qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
274,465
<p>I have some question:</p> <p>How to make a role based web application? Such as in forum sites, there is many user types, admin, moderator etc... is the roles of these user types stored in database or web.config? And when a user login to our site, how to control this users roles? In short I want to learn about authorization and authentication. </p> <p>Thanks..</p>
[ { "answer_id": 274486, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 1, "selected": true, "text": "TblUsers:\n-----------------------------------------------------------------\n| UserID (PK) | UserName | HashedPassword | PermissionLevel (FK)|\n|---------------------------------------------------------------|\n| 1 | BobTables| adfafs2312 | 2 |\n-----------------------------------------------------------------\n\nTblPermissions\n-------------------------------------\n| PermissionID (PK) | Description |\n--------------------------------------\n| 1 | User |\n| 2 | SuperUser |\n| 3 | Admin |\n--------------------------------------\n SELECT TblUser.Username, TblPermissions.Description \n FROM TblUsers, TblPermissions \n WHERE TblUser.UserID = @UserID \n AND TblUser.PermissionLevel = TblPermission.PermissionID;\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/439507/" ]
274,469
<p>This works (prints, for example, “3 arguments”):</p> <pre><code>to run argv do shell script "echo " &amp; (count argv) &amp; " arguments" end run </code></pre> <p>This doesn't (prints only “Argument 3: three”, and not the previous two arguments):</p> <pre><code>to run argv do shell script "echo " &amp; (count argv) &amp; " arguments" repeat with i from 1 to (count argv) do shell script "echo 'Argument " &amp; i &amp; ": " &amp; (item i of argv) &amp; "'" end repeat end run </code></pre> <p>In both cases, I'm running the script using <code>osascript</code> on Mac OS X 10.5.5. Example invocation:</p> <pre><code>osascript 'Script that takes arguments.applescript' Test argument three </code></pre> <p>I'm not redirecting the output, so I know that the script is not throwing an error.</p> <p>If I add a <code>display dialog</code> statement above the <code>do shell script</code>, it throws a “no user interaction allowed” error, so I know that it is executing the loop body.</p> <p>What am I doing wrong? What is it about this loop that causes osascript to not print anything?</p>
[ { "answer_id": 274526, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 0, "selected": false, "text": "do shell script do shell script \"echo foo\"\ndelay 2\ndo shell script \"echo bar\"\n to run argv\n do shell script \"echo \" & (count argv) & \" arguments > /test.txt\"\n \n repeat with i from 1 to (count argv)\n do shell script \"echo 'Argument \" & i & \": \" & (item i of argv) & \"' >> /test.txt\"\n end repeat\nend run\n test.txt 3 arguments\nArgument 1: foo\nArgument 2: bar\nArgument 3: baz\n to run argv\n do shell script \"echo \" & (count argv) & \" arguments > /tmp/foo.txt\"\n \n repeat with i from 1 to (count argv)\n do shell script \"echo 'Argument \" & i & \": \" & (item i of argv) & \"' >> /tmp/foo.txt\"\n end repeat\n \n do shell script \"cat /tmp/foo.txt\"\n do shell script \"rm /tmp/foo.txt\"\nend run\n" }, { "answer_id": 274541, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 3, "selected": true, "text": "to run argv\n set accumulator to do shell script \"echo \" & (count argv) & \" arguments\" altering line endings false\n repeat with i from 1 to (count argv)\n set ln to do shell script \"echo 'Argument \" & i & \": \" & (item i of argv) & \"'\" altering line endings false\n set accumulator to accumulator & ln\n end repeat\n return accumulator\nend run\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30461/" ]
274,474
<p>My usage case is compiling generated source files from a java program using the ToolProvider and JavaCompiler classes provided in JDK 6. The source files contain references to classes in the context classloader (it runs in a J2EE container), but not in the system classloader. My understanding is that by default the ToolProvider will create the JavaCompiler instance with the system classloader.</p> <p>Is there a way to specify a classloader for JavaCompiler to use?</p> <p>I tried this approach, modified from something on IBM DeveloperWorks:</p> <pre><code>FileManagerImpl fm = new FileManagerImpl(compiler.getStandardFileManager(null, null, null);); </code></pre> <p>with FileManagerImpl defined as:</p> <pre><code>static final class FileManagerImpl extends ForwardingJavaFileManager&lt;JavaFileManager&gt; { public FileManagerImpl(JavaFileManager fileManager) { super(fileManager); } @Override public ClassLoader getClassLoader(JavaFileManager.Location location) { new Exception().printStackTrace(); return Thread.currentThread().getContextClassLoader(); } } </code></pre> <p>The stacktrace indicates it's only called once during annotation processing. I verified the class referenced in the source file to be compiled is not on the system classpath but is available from the context classloader.</p>
[ { "answer_id": 665896, "author": "Leihca", "author_id": 74289, "author_profile": "https://Stackoverflow.com/users/74289", "pm_score": 3, "selected": false, "text": " StandardJavaFileManager fileManager = compiler.getStandardFileManager(this /* diagnosticlistener */, null, null);\n// get compilationunits from somewhere, for instance via fileManager.getJavaFileObjectsFromFiles(List<file> files)\nList<String> options = new ArrayList<String>();\noptions.add(\"-classpath\");\nStringBuilder sb = new StringBuilder();\nURLClassLoader urlClassLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader();\nfor (URL url : urlClassLoader.getURLs())\n sb.append(url.getFile()).append(File.pathSeparator);\noptions.add(sb.toString());\nCompilationTask task = compiler.getTask(null, fileManager, this /* diagnosticlistener */, options, null, compilationUnits);\ntask.call();\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33897/" ]
274,482
<p>I am just getting started with CodeIgniter, and I am trying to hash out my regular modules/functions to get them working properly within the MVC framework. I have a few specific questions for anyone who has a strong CodeIgniter background:</p> <p><strong>SESSIONS</strong></p> <p>The CodeIgniter session stores session data on the client side in a cookie, which just isn't going to work for me. I know there are a few replacements for it, or I could build my own library/helper; but I just don't see any benefit over just using <code>$_SESSION</code>.</p> <p>If I just use <code>$_SESSION</code>, will I have any problems with the rest of the framework? Does any other part of the framework depend on using the CodeIgniter session?</p> <p>I feel a bit weird about stepping outside the framework for something so basic, but I am pretty comfortable with plain PHP. I am basically just looking to use CodeIgniter for MVC, and to enforce a more modular aspect for my projects.</p> <p><strong>CODE FLOW &amp; CONFIG</strong></p> <p>I have a few config items that need to be done before almost anything else. </p> <p>For example, say I have a constant <code>APP_LIVE</code>, which is set true/false based on the name of the current server. This has to happen really early as paths, error reporting, the CodeIgniter system, and application folders, etc. will be set based on it.</p> <p>The problem is that the <code>system_folder</code>, and <code>application_folder</code> (which will be set based on which server the code is running on) are set first thing in the <code>index.php</code> file, before any of the configs have loaded.</p> <p>Also, I have a functions that check for things in the URL, and may redirect before the page ever loads. For example, some pages need to enfore the presence of <code>www.</code> in the URL (for SEO), track affiliates, visitor sources, marketing flags, etc.</p> <p>Where is the best place to put things like this that have to happen really early? I know there is a config file, an autoload file, a constants file, etc., but those are too late for some items. Is it a bad practice to simply put these things into the top of the main <code>index.php</code> file, or to make an include there to a global config file? Again, I feel like I am stepping outside the framework, and wonder if I'm just doing that because I don't have a solid understanding of it yet?</p> <p><strong>LAYOUT / HEADER FOOTER</strong></p> <p>Like most people, I have a top header, navigation, footer, etc. I am used to just having them in files, which are included into my page template. I believe I can do that the same way by just making them views and including them into my main page view. Is that the best way to go? Some of them need a bit of data; like what page they are on for the navigation, etc. What's the best way to handle navigation, shared header/footer, etc.?</p>
[ { "answer_id": 274506, "author": "John McCollum", "author_id": 22946, "author_profile": "https://Stackoverflow.com/users/22946", "pm_score": 2, "selected": false, "text": "$data['title'] = 'about us';\n$data['content'] = 'hello world!';\n\n$this->load->view('headerview', $data);\n$this->load->view('contentview', $data);\n$this->load->view('footerview');\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27580/" ]
274,493
<p>When copying large files using <code>shutil.copy()</code>, you get no indication of how the operation is progressing..</p> <p>I have put together something that works - it uses a simple ProgressBar class (which simple returns a simple ASCII progress bar, as a string), and a loop of <code>open().read()</code> and <code>.write()</code> to do the actual copying. It displays the progress bar using <code>sys.stdout.write("\r%s\r" % (the_progress_bar))</code> which is a little hackish, but it works.</p> <p>You can see the code (in context) <a href="http://github.com/dbr/checktveps/tree/1be8f4445fbf766eba25f98f78ec52e955571608/autoPathTv.py#L64-153" rel="noreferrer">on github here</a></p> <p>Is there any built-in module that will do this better? Is there any improvements that can be made to this code?</p>
[ { "answer_id": 274497, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 5, "selected": true, "text": "copy_with_prog def copy_with_prog(src, dest, callback = None):\n while True:\n # copy loop stuff\n if callback:\n callback(pos, total)\n\nprog = ProgressBar(...)\ncopy_with_prog(src, dest, lambda pos, total: prog.update(pos, total))\n" }, { "answer_id": 275945, "author": "Jim Carroll", "author_id": 35922, "author_profile": "https://Stackoverflow.com/users/35922", "pm_score": 3, "selected": false, "text": "\"\"\"\nThreaded Jobs.\n\nAny class that does a long running process can inherit\nfrom ThreadedJob. This enables running as a background\nthread, progress notification, pause and cancel. The\ntime remaining is also calculated by the ThreadedJob class.\n\"\"\"\nimport wx.lib.newevent\nimport thread\nimport exceptions\nimport time\n\n(RunEvent, EVT_RUN) = wx.lib.newevent.NewEvent()\n(CancelEvent, EVT_CANCEL) = wx.lib.newevent.NewEvent()\n(DoneEvent, EVT_DONE) = wx.lib.newevent.NewEvent()\n(ProgressStartEvent, EVT_PROGRESS_START) = wx.lib.newevent.NewEvent()\n(ProgressEvent, EVT_PROGRESS) = wx.lib.newevent.NewEvent()\n\nclass InterruptedException(exceptions.Exception):\n def __init__(self, args = None):\n self.args = args\n #\n#\n\nclass ThreadedJob:\n def __init__(self):\n # tell them ten seconds at first\n self.secondsRemaining = 10.0\n self.lastTick = 0\n\n # not running yet\n self.isPaused = False\n self.isRunning = False\n self.keepGoing = True\n\n def Start(self):\n self.keepGoing = self.isRunning = True\n thread.start_new_thread(self.Run, ())\n\n self.isPaused = False\n #\n\n def Stop(self):\n self.keepGoing = False\n #\n\n def WaitUntilStopped(self):\n while self.isRunning:\n time.sleep(0.1)\n wx.SafeYield()\n #\n #\n\n def IsRunning(self):\n return self.isRunning\n #\n\n def Run(self):\n # this is overridden by the\n # concrete ThreadedJob\n print \"Run was not overloaded\"\n self.JobFinished()\n\n pass\n #\n\n def Pause(self):\n self.isPaused = True\n pass\n #\n\n def Continue(self):\n self.isPaused = False\n pass\n #\n\n def PossibleStoppingPoint(self):\n if not self.keepGoing:\n raise InterruptedException(\"process interrupted.\")\n wx.SafeYield()\n\n # allow cancel while paused\n while self.isPaused:\n if not self.keepGoing:\n raise InterruptedException(\"process interrupted.\")\n\n # don't hog the CPU\n time.sleep(0.1)\n #\n #\n\n def SetProgressMessageWindow(self, win):\n self.win = win\n #\n\n def JobBeginning(self, totalTicks):\n\n self.lastIterationTime = time.time()\n self.totalTicks = totalTicks\n\n if hasattr(self, \"win\") and self.win:\n wx.PostEvent(self.win, ProgressStartEvent(total=totalTicks))\n #\n #\n\n def JobProgress(self, currentTick):\n dt = time.time() - self.lastIterationTime\n self.lastIterationTime = time.time()\n dtick = currentTick - self.lastTick\n self.lastTick = currentTick\n\n alpha = 0.92\n if currentTick > 1:\n self.secondsPerTick = dt * (1.0 - alpha) + (self.secondsPerTick * alpha)\n else:\n self.secondsPerTick = dt\n #\n\n if dtick > 0:\n self.secondsPerTick /= dtick\n\n self.secondsRemaining = self.secondsPerTick * (self.totalTicks - 1 - currentTick) + 1\n\n if hasattr(self, \"win\") and self.win:\n wx.PostEvent(self.win, ProgressEvent(count=currentTick))\n #\n #\n\n def SecondsRemaining(self):\n return self.secondsRemaining\n #\n\n def TimeRemaining(self):\n\n if 1: #self.secondsRemaining > 3:\n minutes = self.secondsRemaining // 60\n seconds = int(self.secondsRemaining % 60.0)\n return \"%i:%02i\" % (minutes, seconds)\n else:\n return \"a few\"\n #\n\n def JobFinished(self):\n if hasattr(self, \"win\") and self.win:\n wx.PostEvent(self.win, DoneEvent())\n #\n\n # flag we're done before we post the all done message\n self.isRunning = False\n #\n#\n\nclass EggTimerJob(ThreadedJob):\n \"\"\" A sample Job that demonstrates the mechanisms and features of the Threaded Job\"\"\"\n def __init__(self, duration):\n self.duration = duration\n ThreadedJob.__init__(self)\n #\n\n def Run(self):\n \"\"\" This can either be run directly for synchronous use of the job,\n or started as a thread when ThreadedJob.Start() is called.\n\n It is responsible for calling JobBeginning, JobProgress, and JobFinished.\n And as often as possible, calling PossibleStoppingPoint() which will \n sleep if the user pauses, and raise an exception if the user cancels.\n \"\"\"\n self.time0 = time.clock()\n self.JobBeginning(self.duration)\n\n try:\n for count in range(0, self.duration):\n time.sleep(1.0)\n self.JobProgress(count)\n self.PossibleStoppingPoint()\n #\n except InterruptedException:\n # clean up if user stops the Job early\n print \"canceled prematurely!\"\n #\n\n # always signal the end of the job\n self.JobFinished()\n #\n #\n\n def __str__(self):\n \"\"\" The job progress dialog expects the job to describe its current state.\"\"\"\n response = []\n if self.isPaused:\n response.append(\"Paused Counting\")\n elif not self.isRunning:\n response.append(\"Will Count the seconds\")\n else:\n response.append(\"Counting\")\n #\n return \" \".join(response)\n #\n#\n\nclass FileCopyJob(ThreadedJob):\n \"\"\" A common file copy Job. \"\"\"\n\n def __init__(self, orig_filename, copy_filename, block_size=32*1024):\n\n self.src = orig_filename\n self.dest = copy_filename\n self.block_size = block_size\n ThreadedJob.__init__(self)\n #\n\n def Run(self):\n \"\"\" This can either be run directly for synchronous use of the job,\n or started as a thread when ThreadedJob.Start() is called.\n\n It is responsible for calling JobBeginning, JobProgress, and JobFinished.\n And as often as possible, calling PossibleStoppingPoint() which will \n sleep if the user pauses, and raise an exception if the user cancels.\n \"\"\"\n self.time0 = time.clock()\n\n try:\n source = open(self.src, 'rb')\n\n # how many blocks?\n import os\n (st_mode, st_ino, st_dev, st_nlink, st_uid, st_gid, st_size, st_atime, st_mtime, st_ctime) = os.stat(self.src)\n num_blocks = st_size / self.block_size\n current_block = 0\n\n self.JobBeginning(num_blocks)\n\n dest = open(self.dest, 'wb')\n\n while 1:\n copy_buffer = source.read(self.block_size)\n if copy_buffer:\n dest.write(copy_buffer)\n current_block += 1\n self.JobProgress(current_block)\n self.PossibleStoppingPoint()\n else:\n break\n\n source.close()\n dest.close()\n\n except InterruptedException:\n # clean up if user stops the Job early\n dest.close()\n # unlink / delete the file that is partially copied\n os.unlink(self.dest)\n print \"canceled, dest deleted!\"\n #\n\n # always signal the end of the job\n self.JobFinished()\n #\n #\n\n def __str__(self):\n \"\"\" The job progress dialog expects the job to describe its current state.\"\"\"\n response = []\n if self.isPaused:\n response.append(\"Paused Copy\")\n elif not self.isRunning:\n response.append(\"Will Copy a file\")\n else:\n response.append(\"Copying\")\n #\n return \" \".join(response)\n #\n#\n\nclass JobProgress(wx.Dialog):\n \"\"\" This dialog shows the progress of any ThreadedJob.\n\n It can be shown Modally if the main application needs to suspend\n operation, or it can be shown Modelessly for background progress\n reporting.\n\n app = wx.PySimpleApp()\n job = EggTimerJob(duration = 10)\n dlg = JobProgress(None, job)\n job.SetProgressMessageWindow(dlg)\n job.Start()\n dlg.ShowModal()\n\n\n \"\"\"\n def __init__(self, parent, job):\n self.job = job\n\n wx.Dialog.__init__(self, parent, -1, \"Progress\", size=(350,200))\n\n # vertical box sizer\n sizeAll = wx.BoxSizer(wx.VERTICAL)\n\n # Job status text\n self.JobStatusText = wx.StaticText(self, -1, \"Starting...\")\n sizeAll.Add(self.JobStatusText, 0, wx.EXPAND|wx.ALL, 8)\n\n # wxGague\n self.ProgressBar = wx.Gauge(self, -1, 10, wx.DefaultPosition, (250, 15))\n sizeAll.Add(self.ProgressBar, 0, wx.EXPAND|wx.ALL, 8)\n\n # horiz box sizer, and spacer to right-justify\n sizeRemaining = wx.BoxSizer(wx.HORIZONTAL)\n sizeRemaining.Add((2,2), 1, wx.EXPAND)\n\n # time remaining read-only edit\n # putting wide default text gets a reasonable initial layout.\n self.remainingText = wx.StaticText(self, -1, \"???:??\")\n sizeRemaining.Add(self.remainingText, 0, wx.LEFT|wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, 8)\n\n # static text: remaining\n self.remainingLabel = wx.StaticText(self, -1, \"remaining\")\n sizeRemaining.Add(self.remainingLabel, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 8)\n\n # add that row to the mix\n sizeAll.Add(sizeRemaining, 1, wx.EXPAND)\n\n # horiz box sizer & spacer\n sizeButtons = wx.BoxSizer(wx.HORIZONTAL)\n sizeButtons.Add((2,2), 1, wx.EXPAND|wx.ADJUST_MINSIZE)\n\n # Pause Button\n self.PauseButton = wx.Button(self, -1, \"Pause\")\n sizeButtons.Add(self.PauseButton, 0, wx.ALL, 4)\n self.Bind(wx.EVT_BUTTON, self.OnPauseButton, self.PauseButton)\n\n # Cancel button\n self.CancelButton = wx.Button(self, wx.ID_CANCEL, \"Cancel\")\n sizeButtons.Add(self.CancelButton, 0, wx.ALL, 4)\n self.Bind(wx.EVT_BUTTON, self.OnCancel, self.CancelButton)\n\n # Add all the buttons on the bottom row to the dialog\n sizeAll.Add(sizeButtons, 0, wx.EXPAND|wx.ALL, 4)\n\n self.SetSizer(sizeAll)\n #sizeAll.Fit(self)\n sizeAll.SetSizeHints(self)\n\n # jobs tell us how they are doing\n self.Bind(EVT_PROGRESS_START, self.OnProgressStart)\n self.Bind(EVT_PROGRESS, self.OnProgress)\n self.Bind(EVT_DONE, self.OnDone)\n\n self.Layout()\n #\n\n def OnPauseButton(self, event):\n if self.job.isPaused:\n self.job.Continue()\n self.PauseButton.SetLabel(\"Pause\")\n self.Layout()\n else:\n self.job.Pause()\n self.PauseButton.SetLabel(\"Resume\")\n self.Layout()\n #\n #\n\n def OnCancel(self, event):\n self.job.Stop()\n #\n\n def OnProgressStart(self, event):\n self.ProgressBar.SetRange(event.total)\n self.statusUpdateTime = time.clock()\n #\n\n def OnProgress(self, event):\n # update the progress bar\n self.ProgressBar.SetValue(event.count)\n\n self.remainingText.SetLabel(self.job.TimeRemaining())\n\n # update the text a max of 20 times a second\n if time.clock() - self.statusUpdateTime > 0.05:\n self.JobStatusText.SetLabel(str(self.job))\n self.statusUpdateTime = time.clock()\n self.Layout()\n #\n #\n\n # when a job is done\n def OnDone(self, event):\n self.ProgressBar.SetValue(0)\n self.JobStatusText.SetLabel(\"Finished\")\n self.Destroy()\n #\n#\n\nif __name__ == \"__main__\":\n app = wx.PySimpleApp()\n #job = EggTimerJob(duration = 10)\n job = FileCopyJob(\"VeryBigFile.mp4\", \"/tmp/test_junk.mp4\", 1024*1024*10)\n dlg = JobProgress(None, job)\n job.SetProgressMessageWindow(dlg)\n job.Start()\n dlg.ShowModal()\n#\n" }, { "answer_id": 51088330, "author": "Gabriel Coutinho De Miranda", "author_id": 8479907, "author_profile": "https://Stackoverflow.com/users/8479907", "pm_score": 2, "selected": false, "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n'''\nCPprogress(SOURCE, DESTINATION)\n\nI made this to give shutil.copy() [or shutil.copy2() in this case] a progress bar.\n\nYou can use CPprogress(SOURCE, DESTINATION) just like shutil.copy(src, dst). SOURCE must be a file path and DESTINATION a file or folder path.\n\nIt will give you a progress bar for each file copied. Just copy this code above the place where you want to use CPprogress(SOURCE, DESTINATION) in your code.\n\nYou can easily change the look of the progress bar:\n - To keep the style and just change the colors, replace the colors values of progressCOLOR and finalCOLOR (orange code at the end of the lines).\n - The use a solid block progress bar, # -*- coding: utf-8 -*- is required. Otherwise, you will get an encoding error. Some basic terminals, like xterm, may not show the progress bar because of the utf-8 characters.\n To use this style, remove the comments #STYLE# in lines ###COLORS### - BlueCOLOR and endBLOCK.\n In def getPERCECENTprogress() remove the comments #STYLE# AND COMMENT THE PREVIOUS line. Do the same in def CPprogress()\n If you don't want the utf-8 encoding, delete the four lines beginning with #STYLE#.\n\nNOTE: If you want to copy lots of small files, the copy process for file is so fast \n that all you will see is a lot of lines scrolling in you terminal window - not enough time for a 'progress'.\n In that case, I use an overall progress that shows only one progress bar to the complete job. nzX\n'''\nimport os\nimport shutil\nimport sys\nimport threading\nimport time\n\n######## COLORS ######\nprogressCOLOR = '\\033[38;5;33;48;5;236m' #\\033[38;5;33;48;5;236m# copy inside '' for colored progressbar| orange:#\\033[38;5;208;48;5;235m\nfinalCOLOR = '\\033[38;5;33;48;5;33m' #\\033[38;5;33;48;5;33m# copy inside '' for colored progressbar| orange:#\\033[38;5;208;48;5;208m\n#STYLE#BlueCOLOR = '\\033[38;5;33m'#\\033[38;5;33m# copy inside '' for colored progressbar Orange#'\\033[38;5;208m'# # BG progress# #STYLE# \n#STYLE#endBLOCK = '' # ▌ copy OR '' for none # BG progress# #STYLE# requires utf8 coding header\n########\n\nBOLD = '\\033[1m'\nUNDERLINE = '\\033[4m'\nCEND = '\\033[0m'\n\ndef getPERCECENTprogress(source_path, destination_path):\n time.sleep(.24)\n if os.path.exists(destination_path):\n while os.path.getsize(source_path) != os.path.getsize(destination_path):\n sys.stdout.write('\\r')\n percentagem = int((float(os.path.getsize(destination_path))/float(os.path.getsize(source_path))) * 100)\n steps = int(percentagem/5)\n copiado = int(os.path.getsize(destination_path)/1000000)# Should be 1024000 but this get's equal to Thunar file manager report (Linux - Xfce)\n sizzz = int(os.path.getsize(source_path)/1000000)\n sys.stdout.write((\" {:d} / {:d} Mb \".format(copiado, sizzz)) + (BOLD + progressCOLOR + \"{:20s}\".format('|'*steps) + CEND) + (\" {:d}% \".format(percentagem))) # BG progress\n #STYLE#sys.stdout.write((\" {:d} / {:d} Mb \".format(copiado, sizzz)) + (BOLD + BlueCOLOR + \"▐\" + \"{:s}\".format('█'*steps) + CEND) + (\"{:s}\".format(' '*(20-steps))+ BOLD + BlueCOLOR + endBLOCK+ CEND) +(\" {:d}% \".format(percentagem))) #STYLE# # BG progress# closer to GUI but less compatible (no block bar with xterm) # requires utf8 coding header\n sys.stdout.flush()\n time.sleep(.01)\n\ndef CPprogress(SOURCE, DESTINATION):\n if os.path.isdir(DESTINATION):\n dst_file = os.path.join(DESTINATION, os.path.basename(SOURCE))\n else: dst_file = DESTINATION\n print \" \"\n print (BOLD + UNDERLINE + \"FROM:\" + CEND + \" \"), SOURCE\n print (BOLD + UNDERLINE + \"TO:\" + CEND + \" \"), dst_file\n print \" \"\n threading.Thread(name='progresso', target=getPERCECENTprogress, args=(SOURCE, dst_file)).start()\n shutil.copy2(SOURCE, DESTINATION)\n time.sleep(.02)\n sys.stdout.write('\\r')\n sys.stdout.write((\" {:d} / {:d} Mb \".format((int(os.path.getsize(dst_file)/1000000)), (int(os.path.getsize(SOURCE)/1000000)))) + (BOLD + finalCOLOR + \"{:20s}\".format('|'*20) + CEND) + (\" {:d}% \".format(100))) # BG progress 100%\n #STYLE#sys.stdout.write((\" {:d} / {:d} Mb \".format((int(os.path.getsize(dst_file)/1000000)), (int(os.path.getsize(SOURCE)/1000000)))) + (BOLD + BlueCOLOR + \"▐\" + \"{:s}{:s}\".format(('█'*20), endBLOCK) + CEND) + (\" {:d}% \".format(100))) #STYLE# # BG progress 100%# closer to GUI but less compatible (no block bar with xterm) # requires utf8 coding header\n sys.stdout.flush()\n print \" \"\n print \" \"\n\n'''\n#Ex. Copy all files from root of the source dir to destination dir\n\nfolderA = '/path/to/SOURCE' # SOURCE\nfolderB = '/path/to/DESTINATION' # DESTINATION\nfor FILE in os.listdir(folderA):\n if not os.path.isdir(os.path.join(folderA, FILE)):\n if os.path.exists(os.path.join(folderB, FILE)): continue # as we are using shutil.copy2() that overwrites destination, this skips existing files\n CPprogress(os.path.join(folderA, FILE), folderB) # use the command as if it was shutil.copy2() but with progress\n\n\n 75 / 150 Mb |||||||||| | 50%\n'''\n" }, { "answer_id": 51088424, "author": "Gabriel Coutinho De Miranda", "author_id": 8479907, "author_profile": "https://Stackoverflow.com/users/8479907", "pm_score": 0, "selected": false, "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n'''\nEx.\nCopyProgress('/path/to/SOURCE', '/path/to/DESTINATION')\n\n\nI think this 'copy with overall progress' is very 'plastic' and can be easily adapted.\nBy default, it will RECURSIVELY copy the CONTENT of 'path/to/SOURCE' to 'path/to/DESTINATION/' keeping the directory tree.\n\nPaying attention to comments, there are 4 main options that can be immediately change:\n\n1 - The LOOK of the progress bar: see COLORS and the PAIR of STYLE lines in 'def getPERCECENTprogress'(inside and after the 'while' loop);\n\n2 - The DESTINATION path: to get 'path/to/DESTINATION/SOURCE_NAME' as target, comment the 2nd 'DST =' definition on the top of the 'def CopyProgress(SOURCE, DESTINATION)' function;\n\n3 - If you don't want to RECURSIVELY copy from sub-directories but just the files in the root source directory to the root of destination, you can use os.listdir() instead of os.walk(). Read the comments inside 'def CopyProgress(SOURCE, DESTINATION)' function to disable RECURSION. Be aware that the RECURSION changes(4x2) must be made in both os.walk() loops;\n\n4 - Handling destination files: if you use this in a situation where the destination filename may already exist, by default, the file is skipped and the loop will jump to the next and so on. On the other way shutil.copy2(), by default, overwrites destination file if exists. Alternatively, you can handle files that exist by overwriting or renaming (according to current date and time). To do that read the comments after 'if os.path.exists(dstFILE): continue' both in the count bytes loop and the main loop. Be aware that the changes must match in both loops (as described in comments) or the progress function will not work properly.\n\n'''\n\nimport os\nimport shutil\nimport sys\nimport threading\nimport time\n\nprogressCOLOR = '\\033[38;5;33;48;5;236m' #BLUEgreyBG\nfinalCOLOR = '\\033[48;5;33m' #BLUEBG\n# check the color codes below and paste above\n\n###### COLORS #######\n# WHITEblueBG = '\\033[38;5;15;48;5;33m'\n# BLUE = '\\033[38;5;33m'\n# BLUEBG = '\\033[48;5;33m'\n# ORANGEBG = '\\033[48;5;208m'\n# BLUEgreyBG = '\\033[38;5;33;48;5;236m'\n# ORANGEgreyBG = '\\033[38;5;208;48;5;236m' # = '\\033[38;5;FOREGROUND;48;5;BACKGROUNDm' # ver 'https://i.stack.imgur.com/KTSQa.png' para 256 color codes\n# INVERT = '\\033[7m'\n###### COLORS #######\n\nBOLD = '\\033[1m'\nUNDERLINE = '\\033[4m'\nCEND = '\\033[0m'\n\nFilesLeft = 0\n\ndef FullFolderSize(path):\n TotalSize = 0\n if os.path.exists(path):# to be safely used # if FALSE returns 0\n for root, dirs, files in os.walk(path):\n for file in files:\n TotalSize += os.path.getsize(os.path.join(root, file))\n return TotalSize\n\ndef getPERCECENTprogress(source_path, destination_path, bytes_to_copy):\n dstINIsize = FullFolderSize(destination_path)\n time.sleep(.25)\n print \" \"\n print (BOLD + UNDERLINE + \"FROM:\" + CEND + \" \"), source_path\n print (BOLD + UNDERLINE + \"TO:\" + CEND + \" \"), destination_path\n print \" \"\n if os.path.exists(destination_path):\n while bytes_to_copy != (FullFolderSize(destination_path)-dstINIsize):\n sys.stdout.write('\\r')\n percentagem = int((float((FullFolderSize(destination_path)-dstINIsize))/float(bytes_to_copy)) * 100)\n steps = int(percentagem/5)\n copiado = '{:,}'.format(int((FullFolderSize(destination_path)-dstINIsize)/1000000))# Should be 1024000 but this get's closer to the file manager report\n sizzz = '{:,}'.format(int(bytes_to_copy/1000000))\n sys.stdout.write((\" {:s} / {:s} Mb \".format(copiado, sizzz)) + (BOLD + progressCOLOR + \"{:20s}\".format('|'*steps) + CEND) + (\" {:d}% \".format(percentagem)) + (\" {:d} ToGo \".format(FilesLeft))) # STYLE 1 progress default # \n #BOLD# sys.stdout.write(BOLD + (\" {:s} / {:s} Mb \".format(copiado, sizzz)) + (progressCOLOR + \"{:20s}\".format('|'*steps) + CEND) + BOLD + (\" {:d}% \".format(percentagem)) + (\" {:d} ToGo \".format(FilesLeft))+ CEND) # STYLE 2 progress BOLD # \n #classic B/W# sys.stdout.write(BOLD + (\" {:s} / {:s} Mb \".format(copiado, sizzz)) + (\"|{:20s}|\".format('|'*steps)) + (\" {:d}% \".format(percentagem)) + (\" {:d} ToGo \".format(FilesLeft))+ CEND) # STYLE 3 progress classic B/W #\n sys.stdout.flush()\n time.sleep(.01)\n sys.stdout.write('\\r')\n time.sleep(.05)\n sys.stdout.write((\" {:s} / {:s} Mb \".format('{:,}'.format(int((FullFolderSize(destination_path)-dstINIsize)/1000000)), '{:,}'.format(int(bytes_to_copy/1000000)))) + (BOLD + finalCOLOR + \"{:20s}\".format(' '*20) + CEND) + (\" {:d}% \".format( 100)) + (\" {:s} \".format(' ')) + \"\\n\") # STYLE 1 progress default # \n #BOLD# sys.stdout.write(BOLD + (\" {:s} / {:s} Mb \".format('{:,}'.format(int((FullFolderSize(destination_path)-dstINIsize)/1000000)), '{:,}'.format(int(bytes_to_copy/1000000)))) + (finalCOLOR + \"{:20s}\".format(' '*20) + CEND) + BOLD + (\" {:d}% \".format( 100)) + (\" {:s} \".format(' ')) + \"\\n\" + CEND ) # STYLE 2 progress BOLD # \n #classic B/W# sys.stdout.write(BOLD + (\" {:s} / {:s} Mb \".format('{:,}'.format(int((FullFolderSize(destination_path)-dstINIsize)/1000000)), '{:,}'.format(int(bytes_to_copy/1000000)))) + (\"|{:20s}|\".format('|'*20)) + (\" {:d}% \".format( 100)) + (\" {:s} \".format(' ')) + \"\\n\" + CEND ) # STYLE 3 progress classic B/W # \n sys.stdout.flush()\n print \" \"\n print \" \"\n\ndef CopyProgress(SOURCE, DESTINATION):\n global FilesLeft\n DST = os.path.join(DESTINATION, os.path.basename(SOURCE))\n # <- the previous will copy the Source folder inside of the Destination folder. Result Target: path/to/Destination/SOURCE_NAME\n # -> UNCOMMENT the next (# DST = DESTINATION) to copy the CONTENT of Source to the Destination. Result Target: path/to/Destination\n DST = DESTINATION # UNCOMMENT this to specify the Destination as the target itself and not the root folder of the target \n #\n if DST.startswith(SOURCE):\n print \" \"\n print BOLD + UNDERLINE + 'Source folder can\\'t be changed.' + CEND\n print 'Please check your target path...'\n print \" \"\n print BOLD + ' CANCELED' + CEND\n print \" \"\n exit()\n #count bytes to copy\n Bytes2copy = 0\n for root, dirs, files in os.walk(SOURCE): # USE for filename in os.listdir(SOURCE): # if you don't want RECURSION #\n dstDIR = root.replace(SOURCE, DST, 1) # USE dstDIR = DST # if you don't want RECURSION #\n for filename in files: # USE if not os.path.isdir(os.path.join(SOURCE, filename)): # if you don't want RECURSION #\n dstFILE = os.path.join(dstDIR, filename)\n if os.path.exists(dstFILE): continue # must match the main loop (after \"threading.Thread\")\n # To overwrite delete dstFILE first here so the progress works properly: ex. change continue to os.unlink(dstFILE)\n # To rename new files adding date and time, instead of deleating and overwriting, \n # comment 'if os.path.exists(dstFILE): continue'\n Bytes2copy += os.path.getsize(os.path.join(root, filename)) # USE os.path.getsize(os.path.join(SOURCE, filename)) # if you don't want RECURSION #\n FilesLeft += 1\n # <- count bytes to copy\n #\n # Treading to call the preogress\n threading.Thread(name='progresso', target=getPERCECENTprogress, args=(SOURCE, DST, Bytes2copy)).start()\n # main loop\n for root, dirs, files in os.walk(SOURCE): # USE for filename in os.listdir(SOURCE): # if you don't want RECURSION #\n dstDIR = root.replace(SOURCE, DST, 1) # USE dstDIR = DST # if you don't want RECURSION #\n if not os.path.exists(dstDIR):\n os.makedirs(dstDIR)\n for filename in files: # USE if not os.path.isdir(os.path.join(SOURCE, filename)): # if you don't want RECURSION #\n srcFILE = os.path.join(root, filename) # USE os.path.join(SOURCE, filename) # if you don't want RECURSION #\n dstFILE = os.path.join(dstDIR, filename)\n if os.path.exists(dstFILE): continue # MUST MATCH THE PREVIOUS count bytes loop \n # <- <- this jumps to the next file without copying this file, if destination file exists. \n # Comment to copy with rename or overwrite dstFILE\n #\n # RENAME part below\n head, tail = os.path.splitext(filename)\n count = -1\n year = int(time.strftime(\"%Y\"))\n month = int(time.strftime(\"%m\"))\n day = int(time.strftime(\"%d\"))\n hour = int(time.strftime(\"%H\"))\n minute = int(time.strftime(\"%M\"))\n while os.path.exists(dstFILE):\n count += 1\n if count == 0:\n dstFILE = os.path.join(dstDIR, '{:s}[{:d}.{:d}.{:d}]{:d}-{:d}{:s}'.format(head, year, month, day, hour, minute, tail))\n else:\n dstFILE = os.path.join(dstDIR, '{:s}[{:d}.{:d}.{:d}]{:d}-{:d}[{:d}]{:s}'.format(head, year, month, day, hour, minute, count, tail))\n # END of RENAME part\n shutil.copy2(srcFILE, dstFILE)\n FilesLeft -= 1\n #\n\n'''\nEx.\nCopyProgress('/path/to/SOURCE', '/path/to/DESTINATION')\n'''\n" }, { "answer_id": 66257068, "author": "JBroadway", "author_id": 9065959, "author_profile": "https://Stackoverflow.com/users/9065959", "pm_score": 0, "selected": false, "text": "ROBOCOPY os import os\n\ndef robocopy(source, destination, extension=''):\n os.system(\"robocopy {} {} {} /xx /njh\".format(source, destination, extension))\n\n# Usage example\nrobocopy(r'C:\\Users\\Example\\Downloads', r'C:\\Users\\Example\\Desktop', '*.mov')\n extension /xx /njh" }, { "answer_id": 70777816, "author": "every skills", "author_id": 15099592, "author_profile": "https://Stackoverflow.com/users/15099592", "pm_score": 0, "selected": false, "text": "#!/usr/bin/python3\n\nimport os\nimport sys\nfrom PySide2.QtWidgets import QProgressBar, QApplication, QDialog, QMainWindow, QPushButton\nfrom PySide2.QtCore import QThread, Signal, Slot\n\n\nclass ProgressDialog(QDialog):\n def __init__(self, parent, source, destination):\n QDialog.__init__(self, parent)\n \n self.resize(400, 50)\n \n self.parent = parent\n self.source = source\n self.destination = destination\n \n self.prog = QProgressBar(self)\n self.prog.setMaximum(100)\n self.prog.setMinimum(0)\n self.prog.setFormat(\"%p%\")\n\n def start(self):\n self.show()\n self.copy()\n\n def copy(self):\n copy_thread = CopyThread(self, self.source, self.destination)\n copy_thread.procPartDone.connect(self.update_progress)\n copy_thread.procDone.connect(self.finished_copy)\n copy_thread.start()\n\n def update_progress(self, progress):\n self.prog.setValue(progress)\n\n def finished_copy(self, state):\n self.close()\n\nclass CopyThread(QThread):\n\n procDone = Signal(bool)\n procPartDone = Signal(int)\n\n def __init__(self, parent, source: str, destination: str):\n QThread.__init__(self, parent)\n \n self.source = source\n self.destination = destination\n\n def run(self):\n self.copy()\n self.procDone.emit(True)\n\n def copy(self):\n source_size = os.stat(self.source).st_size\n copied = 0\n\n with open(self.source, \"rb\") as source, open(self.destination, \"wb\") as target:\n while True:\n chunk = source.read(1024)\n if not chunk:\n break\n\n target.write(chunk)\n copied += len(chunk)\n\n self.procPartDone.emit(copied * 100 / source_size)\n\n\nclass MainWindow(QMainWindow):\n def __init__(self, parent: object = None) -> None:\n super().__init__(parent)\n \n self.src = \"/path/to/file.ext\"\n self.dest = \"/path/to/file.ext\"\n\n self.btn = QPushButton(self)\n self.btn.setText(\"Start copy\")\n self.btn.clicked.connect(self.run)\n \n self.setCentralWidget(self.btn)\n \n def run(self):\n self.prog = ProgressDialog(self, self.src, self.dest)\n self.prog.start()\n\n\ndef main(): \n app = QApplication(sys.argv)\n \n window = MainWindow()\n window.show()\n \n sys.exit(app.exec_())\n\nif __name__ == \"__main__\":\n main()\n python3 main.py\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/745/" ]
274,496
<p>I've built web apps before that utilize phpBB session, and user data. The common move is to use code like this:</p> <pre><code>define('IN_PHPBB', true); //replace $phpbb_root_path with path to your forum $phpbb_root_path = '../forum/'; $phpEx = substr(strrchr(__FILE__, '.'), 1); include($phpbb_root_path . 'common.' . $phpEx); // Start session management $user-&gt;session_begin(); $auth-&gt;acl($user-&gt;data); $user-&gt;setup(); </code></pre> <p>However, by including <code>common.php</code>, I bring along a crap-load of other methods that run into other methods I've got setup.</p> <p>In my example, I'm running the application using CodeIgniter, which already has a "redirect" method. This question should apply to anyone who has pre-built methods that may run into the phpBB methods.</p> <p>Basically, all I need to do is:</p> <ol> <li>Make sure the user is logged in <code>$user-&gt;data[username] == Anonymous</code></li> <li>Utilize data from '$user->data' such as the user's ID, screenname, etc.</li> </ol> <p>Could I grab the <code>$user-&gt;data</code> array, and somehow save it to my own session? Does anyone have any ideas on this? Thanks in advance!</p>
[ { "answer_id": 274497, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 5, "selected": true, "text": "copy_with_prog def copy_with_prog(src, dest, callback = None):\n while True:\n # copy loop stuff\n if callback:\n callback(pos, total)\n\nprog = ProgressBar(...)\ncopy_with_prog(src, dest, lambda pos, total: prog.update(pos, total))\n" }, { "answer_id": 275945, "author": "Jim Carroll", "author_id": 35922, "author_profile": "https://Stackoverflow.com/users/35922", "pm_score": 3, "selected": false, "text": "\"\"\"\nThreaded Jobs.\n\nAny class that does a long running process can inherit\nfrom ThreadedJob. This enables running as a background\nthread, progress notification, pause and cancel. The\ntime remaining is also calculated by the ThreadedJob class.\n\"\"\"\nimport wx.lib.newevent\nimport thread\nimport exceptions\nimport time\n\n(RunEvent, EVT_RUN) = wx.lib.newevent.NewEvent()\n(CancelEvent, EVT_CANCEL) = wx.lib.newevent.NewEvent()\n(DoneEvent, EVT_DONE) = wx.lib.newevent.NewEvent()\n(ProgressStartEvent, EVT_PROGRESS_START) = wx.lib.newevent.NewEvent()\n(ProgressEvent, EVT_PROGRESS) = wx.lib.newevent.NewEvent()\n\nclass InterruptedException(exceptions.Exception):\n def __init__(self, args = None):\n self.args = args\n #\n#\n\nclass ThreadedJob:\n def __init__(self):\n # tell them ten seconds at first\n self.secondsRemaining = 10.0\n self.lastTick = 0\n\n # not running yet\n self.isPaused = False\n self.isRunning = False\n self.keepGoing = True\n\n def Start(self):\n self.keepGoing = self.isRunning = True\n thread.start_new_thread(self.Run, ())\n\n self.isPaused = False\n #\n\n def Stop(self):\n self.keepGoing = False\n #\n\n def WaitUntilStopped(self):\n while self.isRunning:\n time.sleep(0.1)\n wx.SafeYield()\n #\n #\n\n def IsRunning(self):\n return self.isRunning\n #\n\n def Run(self):\n # this is overridden by the\n # concrete ThreadedJob\n print \"Run was not overloaded\"\n self.JobFinished()\n\n pass\n #\n\n def Pause(self):\n self.isPaused = True\n pass\n #\n\n def Continue(self):\n self.isPaused = False\n pass\n #\n\n def PossibleStoppingPoint(self):\n if not self.keepGoing:\n raise InterruptedException(\"process interrupted.\")\n wx.SafeYield()\n\n # allow cancel while paused\n while self.isPaused:\n if not self.keepGoing:\n raise InterruptedException(\"process interrupted.\")\n\n # don't hog the CPU\n time.sleep(0.1)\n #\n #\n\n def SetProgressMessageWindow(self, win):\n self.win = win\n #\n\n def JobBeginning(self, totalTicks):\n\n self.lastIterationTime = time.time()\n self.totalTicks = totalTicks\n\n if hasattr(self, \"win\") and self.win:\n wx.PostEvent(self.win, ProgressStartEvent(total=totalTicks))\n #\n #\n\n def JobProgress(self, currentTick):\n dt = time.time() - self.lastIterationTime\n self.lastIterationTime = time.time()\n dtick = currentTick - self.lastTick\n self.lastTick = currentTick\n\n alpha = 0.92\n if currentTick > 1:\n self.secondsPerTick = dt * (1.0 - alpha) + (self.secondsPerTick * alpha)\n else:\n self.secondsPerTick = dt\n #\n\n if dtick > 0:\n self.secondsPerTick /= dtick\n\n self.secondsRemaining = self.secondsPerTick * (self.totalTicks - 1 - currentTick) + 1\n\n if hasattr(self, \"win\") and self.win:\n wx.PostEvent(self.win, ProgressEvent(count=currentTick))\n #\n #\n\n def SecondsRemaining(self):\n return self.secondsRemaining\n #\n\n def TimeRemaining(self):\n\n if 1: #self.secondsRemaining > 3:\n minutes = self.secondsRemaining // 60\n seconds = int(self.secondsRemaining % 60.0)\n return \"%i:%02i\" % (minutes, seconds)\n else:\n return \"a few\"\n #\n\n def JobFinished(self):\n if hasattr(self, \"win\") and self.win:\n wx.PostEvent(self.win, DoneEvent())\n #\n\n # flag we're done before we post the all done message\n self.isRunning = False\n #\n#\n\nclass EggTimerJob(ThreadedJob):\n \"\"\" A sample Job that demonstrates the mechanisms and features of the Threaded Job\"\"\"\n def __init__(self, duration):\n self.duration = duration\n ThreadedJob.__init__(self)\n #\n\n def Run(self):\n \"\"\" This can either be run directly for synchronous use of the job,\n or started as a thread when ThreadedJob.Start() is called.\n\n It is responsible for calling JobBeginning, JobProgress, and JobFinished.\n And as often as possible, calling PossibleStoppingPoint() which will \n sleep if the user pauses, and raise an exception if the user cancels.\n \"\"\"\n self.time0 = time.clock()\n self.JobBeginning(self.duration)\n\n try:\n for count in range(0, self.duration):\n time.sleep(1.0)\n self.JobProgress(count)\n self.PossibleStoppingPoint()\n #\n except InterruptedException:\n # clean up if user stops the Job early\n print \"canceled prematurely!\"\n #\n\n # always signal the end of the job\n self.JobFinished()\n #\n #\n\n def __str__(self):\n \"\"\" The job progress dialog expects the job to describe its current state.\"\"\"\n response = []\n if self.isPaused:\n response.append(\"Paused Counting\")\n elif not self.isRunning:\n response.append(\"Will Count the seconds\")\n else:\n response.append(\"Counting\")\n #\n return \" \".join(response)\n #\n#\n\nclass FileCopyJob(ThreadedJob):\n \"\"\" A common file copy Job. \"\"\"\n\n def __init__(self, orig_filename, copy_filename, block_size=32*1024):\n\n self.src = orig_filename\n self.dest = copy_filename\n self.block_size = block_size\n ThreadedJob.__init__(self)\n #\n\n def Run(self):\n \"\"\" This can either be run directly for synchronous use of the job,\n or started as a thread when ThreadedJob.Start() is called.\n\n It is responsible for calling JobBeginning, JobProgress, and JobFinished.\n And as often as possible, calling PossibleStoppingPoint() which will \n sleep if the user pauses, and raise an exception if the user cancels.\n \"\"\"\n self.time0 = time.clock()\n\n try:\n source = open(self.src, 'rb')\n\n # how many blocks?\n import os\n (st_mode, st_ino, st_dev, st_nlink, st_uid, st_gid, st_size, st_atime, st_mtime, st_ctime) = os.stat(self.src)\n num_blocks = st_size / self.block_size\n current_block = 0\n\n self.JobBeginning(num_blocks)\n\n dest = open(self.dest, 'wb')\n\n while 1:\n copy_buffer = source.read(self.block_size)\n if copy_buffer:\n dest.write(copy_buffer)\n current_block += 1\n self.JobProgress(current_block)\n self.PossibleStoppingPoint()\n else:\n break\n\n source.close()\n dest.close()\n\n except InterruptedException:\n # clean up if user stops the Job early\n dest.close()\n # unlink / delete the file that is partially copied\n os.unlink(self.dest)\n print \"canceled, dest deleted!\"\n #\n\n # always signal the end of the job\n self.JobFinished()\n #\n #\n\n def __str__(self):\n \"\"\" The job progress dialog expects the job to describe its current state.\"\"\"\n response = []\n if self.isPaused:\n response.append(\"Paused Copy\")\n elif not self.isRunning:\n response.append(\"Will Copy a file\")\n else:\n response.append(\"Copying\")\n #\n return \" \".join(response)\n #\n#\n\nclass JobProgress(wx.Dialog):\n \"\"\" This dialog shows the progress of any ThreadedJob.\n\n It can be shown Modally if the main application needs to suspend\n operation, or it can be shown Modelessly for background progress\n reporting.\n\n app = wx.PySimpleApp()\n job = EggTimerJob(duration = 10)\n dlg = JobProgress(None, job)\n job.SetProgressMessageWindow(dlg)\n job.Start()\n dlg.ShowModal()\n\n\n \"\"\"\n def __init__(self, parent, job):\n self.job = job\n\n wx.Dialog.__init__(self, parent, -1, \"Progress\", size=(350,200))\n\n # vertical box sizer\n sizeAll = wx.BoxSizer(wx.VERTICAL)\n\n # Job status text\n self.JobStatusText = wx.StaticText(self, -1, \"Starting...\")\n sizeAll.Add(self.JobStatusText, 0, wx.EXPAND|wx.ALL, 8)\n\n # wxGague\n self.ProgressBar = wx.Gauge(self, -1, 10, wx.DefaultPosition, (250, 15))\n sizeAll.Add(self.ProgressBar, 0, wx.EXPAND|wx.ALL, 8)\n\n # horiz box sizer, and spacer to right-justify\n sizeRemaining = wx.BoxSizer(wx.HORIZONTAL)\n sizeRemaining.Add((2,2), 1, wx.EXPAND)\n\n # time remaining read-only edit\n # putting wide default text gets a reasonable initial layout.\n self.remainingText = wx.StaticText(self, -1, \"???:??\")\n sizeRemaining.Add(self.remainingText, 0, wx.LEFT|wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, 8)\n\n # static text: remaining\n self.remainingLabel = wx.StaticText(self, -1, \"remaining\")\n sizeRemaining.Add(self.remainingLabel, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 8)\n\n # add that row to the mix\n sizeAll.Add(sizeRemaining, 1, wx.EXPAND)\n\n # horiz box sizer & spacer\n sizeButtons = wx.BoxSizer(wx.HORIZONTAL)\n sizeButtons.Add((2,2), 1, wx.EXPAND|wx.ADJUST_MINSIZE)\n\n # Pause Button\n self.PauseButton = wx.Button(self, -1, \"Pause\")\n sizeButtons.Add(self.PauseButton, 0, wx.ALL, 4)\n self.Bind(wx.EVT_BUTTON, self.OnPauseButton, self.PauseButton)\n\n # Cancel button\n self.CancelButton = wx.Button(self, wx.ID_CANCEL, \"Cancel\")\n sizeButtons.Add(self.CancelButton, 0, wx.ALL, 4)\n self.Bind(wx.EVT_BUTTON, self.OnCancel, self.CancelButton)\n\n # Add all the buttons on the bottom row to the dialog\n sizeAll.Add(sizeButtons, 0, wx.EXPAND|wx.ALL, 4)\n\n self.SetSizer(sizeAll)\n #sizeAll.Fit(self)\n sizeAll.SetSizeHints(self)\n\n # jobs tell us how they are doing\n self.Bind(EVT_PROGRESS_START, self.OnProgressStart)\n self.Bind(EVT_PROGRESS, self.OnProgress)\n self.Bind(EVT_DONE, self.OnDone)\n\n self.Layout()\n #\n\n def OnPauseButton(self, event):\n if self.job.isPaused:\n self.job.Continue()\n self.PauseButton.SetLabel(\"Pause\")\n self.Layout()\n else:\n self.job.Pause()\n self.PauseButton.SetLabel(\"Resume\")\n self.Layout()\n #\n #\n\n def OnCancel(self, event):\n self.job.Stop()\n #\n\n def OnProgressStart(self, event):\n self.ProgressBar.SetRange(event.total)\n self.statusUpdateTime = time.clock()\n #\n\n def OnProgress(self, event):\n # update the progress bar\n self.ProgressBar.SetValue(event.count)\n\n self.remainingText.SetLabel(self.job.TimeRemaining())\n\n # update the text a max of 20 times a second\n if time.clock() - self.statusUpdateTime > 0.05:\n self.JobStatusText.SetLabel(str(self.job))\n self.statusUpdateTime = time.clock()\n self.Layout()\n #\n #\n\n # when a job is done\n def OnDone(self, event):\n self.ProgressBar.SetValue(0)\n self.JobStatusText.SetLabel(\"Finished\")\n self.Destroy()\n #\n#\n\nif __name__ == \"__main__\":\n app = wx.PySimpleApp()\n #job = EggTimerJob(duration = 10)\n job = FileCopyJob(\"VeryBigFile.mp4\", \"/tmp/test_junk.mp4\", 1024*1024*10)\n dlg = JobProgress(None, job)\n job.SetProgressMessageWindow(dlg)\n job.Start()\n dlg.ShowModal()\n#\n" }, { "answer_id": 51088330, "author": "Gabriel Coutinho De Miranda", "author_id": 8479907, "author_profile": "https://Stackoverflow.com/users/8479907", "pm_score": 2, "selected": false, "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n'''\nCPprogress(SOURCE, DESTINATION)\n\nI made this to give shutil.copy() [or shutil.copy2() in this case] a progress bar.\n\nYou can use CPprogress(SOURCE, DESTINATION) just like shutil.copy(src, dst). SOURCE must be a file path and DESTINATION a file or folder path.\n\nIt will give you a progress bar for each file copied. Just copy this code above the place where you want to use CPprogress(SOURCE, DESTINATION) in your code.\n\nYou can easily change the look of the progress bar:\n - To keep the style and just change the colors, replace the colors values of progressCOLOR and finalCOLOR (orange code at the end of the lines).\n - The use a solid block progress bar, # -*- coding: utf-8 -*- is required. Otherwise, you will get an encoding error. Some basic terminals, like xterm, may not show the progress bar because of the utf-8 characters.\n To use this style, remove the comments #STYLE# in lines ###COLORS### - BlueCOLOR and endBLOCK.\n In def getPERCECENTprogress() remove the comments #STYLE# AND COMMENT THE PREVIOUS line. Do the same in def CPprogress()\n If you don't want the utf-8 encoding, delete the four lines beginning with #STYLE#.\n\nNOTE: If you want to copy lots of small files, the copy process for file is so fast \n that all you will see is a lot of lines scrolling in you terminal window - not enough time for a 'progress'.\n In that case, I use an overall progress that shows only one progress bar to the complete job. nzX\n'''\nimport os\nimport shutil\nimport sys\nimport threading\nimport time\n\n######## COLORS ######\nprogressCOLOR = '\\033[38;5;33;48;5;236m' #\\033[38;5;33;48;5;236m# copy inside '' for colored progressbar| orange:#\\033[38;5;208;48;5;235m\nfinalCOLOR = '\\033[38;5;33;48;5;33m' #\\033[38;5;33;48;5;33m# copy inside '' for colored progressbar| orange:#\\033[38;5;208;48;5;208m\n#STYLE#BlueCOLOR = '\\033[38;5;33m'#\\033[38;5;33m# copy inside '' for colored progressbar Orange#'\\033[38;5;208m'# # BG progress# #STYLE# \n#STYLE#endBLOCK = '' # ▌ copy OR '' for none # BG progress# #STYLE# requires utf8 coding header\n########\n\nBOLD = '\\033[1m'\nUNDERLINE = '\\033[4m'\nCEND = '\\033[0m'\n\ndef getPERCECENTprogress(source_path, destination_path):\n time.sleep(.24)\n if os.path.exists(destination_path):\n while os.path.getsize(source_path) != os.path.getsize(destination_path):\n sys.stdout.write('\\r')\n percentagem = int((float(os.path.getsize(destination_path))/float(os.path.getsize(source_path))) * 100)\n steps = int(percentagem/5)\n copiado = int(os.path.getsize(destination_path)/1000000)# Should be 1024000 but this get's equal to Thunar file manager report (Linux - Xfce)\n sizzz = int(os.path.getsize(source_path)/1000000)\n sys.stdout.write((\" {:d} / {:d} Mb \".format(copiado, sizzz)) + (BOLD + progressCOLOR + \"{:20s}\".format('|'*steps) + CEND) + (\" {:d}% \".format(percentagem))) # BG progress\n #STYLE#sys.stdout.write((\" {:d} / {:d} Mb \".format(copiado, sizzz)) + (BOLD + BlueCOLOR + \"▐\" + \"{:s}\".format('█'*steps) + CEND) + (\"{:s}\".format(' '*(20-steps))+ BOLD + BlueCOLOR + endBLOCK+ CEND) +(\" {:d}% \".format(percentagem))) #STYLE# # BG progress# closer to GUI but less compatible (no block bar with xterm) # requires utf8 coding header\n sys.stdout.flush()\n time.sleep(.01)\n\ndef CPprogress(SOURCE, DESTINATION):\n if os.path.isdir(DESTINATION):\n dst_file = os.path.join(DESTINATION, os.path.basename(SOURCE))\n else: dst_file = DESTINATION\n print \" \"\n print (BOLD + UNDERLINE + \"FROM:\" + CEND + \" \"), SOURCE\n print (BOLD + UNDERLINE + \"TO:\" + CEND + \" \"), dst_file\n print \" \"\n threading.Thread(name='progresso', target=getPERCECENTprogress, args=(SOURCE, dst_file)).start()\n shutil.copy2(SOURCE, DESTINATION)\n time.sleep(.02)\n sys.stdout.write('\\r')\n sys.stdout.write((\" {:d} / {:d} Mb \".format((int(os.path.getsize(dst_file)/1000000)), (int(os.path.getsize(SOURCE)/1000000)))) + (BOLD + finalCOLOR + \"{:20s}\".format('|'*20) + CEND) + (\" {:d}% \".format(100))) # BG progress 100%\n #STYLE#sys.stdout.write((\" {:d} / {:d} Mb \".format((int(os.path.getsize(dst_file)/1000000)), (int(os.path.getsize(SOURCE)/1000000)))) + (BOLD + BlueCOLOR + \"▐\" + \"{:s}{:s}\".format(('█'*20), endBLOCK) + CEND) + (\" {:d}% \".format(100))) #STYLE# # BG progress 100%# closer to GUI but less compatible (no block bar with xterm) # requires utf8 coding header\n sys.stdout.flush()\n print \" \"\n print \" \"\n\n'''\n#Ex. Copy all files from root of the source dir to destination dir\n\nfolderA = '/path/to/SOURCE' # SOURCE\nfolderB = '/path/to/DESTINATION' # DESTINATION\nfor FILE in os.listdir(folderA):\n if not os.path.isdir(os.path.join(folderA, FILE)):\n if os.path.exists(os.path.join(folderB, FILE)): continue # as we are using shutil.copy2() that overwrites destination, this skips existing files\n CPprogress(os.path.join(folderA, FILE), folderB) # use the command as if it was shutil.copy2() but with progress\n\n\n 75 / 150 Mb |||||||||| | 50%\n'''\n" }, { "answer_id": 51088424, "author": "Gabriel Coutinho De Miranda", "author_id": 8479907, "author_profile": "https://Stackoverflow.com/users/8479907", "pm_score": 0, "selected": false, "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n'''\nEx.\nCopyProgress('/path/to/SOURCE', '/path/to/DESTINATION')\n\n\nI think this 'copy with overall progress' is very 'plastic' and can be easily adapted.\nBy default, it will RECURSIVELY copy the CONTENT of 'path/to/SOURCE' to 'path/to/DESTINATION/' keeping the directory tree.\n\nPaying attention to comments, there are 4 main options that can be immediately change:\n\n1 - The LOOK of the progress bar: see COLORS and the PAIR of STYLE lines in 'def getPERCECENTprogress'(inside and after the 'while' loop);\n\n2 - The DESTINATION path: to get 'path/to/DESTINATION/SOURCE_NAME' as target, comment the 2nd 'DST =' definition on the top of the 'def CopyProgress(SOURCE, DESTINATION)' function;\n\n3 - If you don't want to RECURSIVELY copy from sub-directories but just the files in the root source directory to the root of destination, you can use os.listdir() instead of os.walk(). Read the comments inside 'def CopyProgress(SOURCE, DESTINATION)' function to disable RECURSION. Be aware that the RECURSION changes(4x2) must be made in both os.walk() loops;\n\n4 - Handling destination files: if you use this in a situation where the destination filename may already exist, by default, the file is skipped and the loop will jump to the next and so on. On the other way shutil.copy2(), by default, overwrites destination file if exists. Alternatively, you can handle files that exist by overwriting or renaming (according to current date and time). To do that read the comments after 'if os.path.exists(dstFILE): continue' both in the count bytes loop and the main loop. Be aware that the changes must match in both loops (as described in comments) or the progress function will not work properly.\n\n'''\n\nimport os\nimport shutil\nimport sys\nimport threading\nimport time\n\nprogressCOLOR = '\\033[38;5;33;48;5;236m' #BLUEgreyBG\nfinalCOLOR = '\\033[48;5;33m' #BLUEBG\n# check the color codes below and paste above\n\n###### COLORS #######\n# WHITEblueBG = '\\033[38;5;15;48;5;33m'\n# BLUE = '\\033[38;5;33m'\n# BLUEBG = '\\033[48;5;33m'\n# ORANGEBG = '\\033[48;5;208m'\n# BLUEgreyBG = '\\033[38;5;33;48;5;236m'\n# ORANGEgreyBG = '\\033[38;5;208;48;5;236m' # = '\\033[38;5;FOREGROUND;48;5;BACKGROUNDm' # ver 'https://i.stack.imgur.com/KTSQa.png' para 256 color codes\n# INVERT = '\\033[7m'\n###### COLORS #######\n\nBOLD = '\\033[1m'\nUNDERLINE = '\\033[4m'\nCEND = '\\033[0m'\n\nFilesLeft = 0\n\ndef FullFolderSize(path):\n TotalSize = 0\n if os.path.exists(path):# to be safely used # if FALSE returns 0\n for root, dirs, files in os.walk(path):\n for file in files:\n TotalSize += os.path.getsize(os.path.join(root, file))\n return TotalSize\n\ndef getPERCECENTprogress(source_path, destination_path, bytes_to_copy):\n dstINIsize = FullFolderSize(destination_path)\n time.sleep(.25)\n print \" \"\n print (BOLD + UNDERLINE + \"FROM:\" + CEND + \" \"), source_path\n print (BOLD + UNDERLINE + \"TO:\" + CEND + \" \"), destination_path\n print \" \"\n if os.path.exists(destination_path):\n while bytes_to_copy != (FullFolderSize(destination_path)-dstINIsize):\n sys.stdout.write('\\r')\n percentagem = int((float((FullFolderSize(destination_path)-dstINIsize))/float(bytes_to_copy)) * 100)\n steps = int(percentagem/5)\n copiado = '{:,}'.format(int((FullFolderSize(destination_path)-dstINIsize)/1000000))# Should be 1024000 but this get's closer to the file manager report\n sizzz = '{:,}'.format(int(bytes_to_copy/1000000))\n sys.stdout.write((\" {:s} / {:s} Mb \".format(copiado, sizzz)) + (BOLD + progressCOLOR + \"{:20s}\".format('|'*steps) + CEND) + (\" {:d}% \".format(percentagem)) + (\" {:d} ToGo \".format(FilesLeft))) # STYLE 1 progress default # \n #BOLD# sys.stdout.write(BOLD + (\" {:s} / {:s} Mb \".format(copiado, sizzz)) + (progressCOLOR + \"{:20s}\".format('|'*steps) + CEND) + BOLD + (\" {:d}% \".format(percentagem)) + (\" {:d} ToGo \".format(FilesLeft))+ CEND) # STYLE 2 progress BOLD # \n #classic B/W# sys.stdout.write(BOLD + (\" {:s} / {:s} Mb \".format(copiado, sizzz)) + (\"|{:20s}|\".format('|'*steps)) + (\" {:d}% \".format(percentagem)) + (\" {:d} ToGo \".format(FilesLeft))+ CEND) # STYLE 3 progress classic B/W #\n sys.stdout.flush()\n time.sleep(.01)\n sys.stdout.write('\\r')\n time.sleep(.05)\n sys.stdout.write((\" {:s} / {:s} Mb \".format('{:,}'.format(int((FullFolderSize(destination_path)-dstINIsize)/1000000)), '{:,}'.format(int(bytes_to_copy/1000000)))) + (BOLD + finalCOLOR + \"{:20s}\".format(' '*20) + CEND) + (\" {:d}% \".format( 100)) + (\" {:s} \".format(' ')) + \"\\n\") # STYLE 1 progress default # \n #BOLD# sys.stdout.write(BOLD + (\" {:s} / {:s} Mb \".format('{:,}'.format(int((FullFolderSize(destination_path)-dstINIsize)/1000000)), '{:,}'.format(int(bytes_to_copy/1000000)))) + (finalCOLOR + \"{:20s}\".format(' '*20) + CEND) + BOLD + (\" {:d}% \".format( 100)) + (\" {:s} \".format(' ')) + \"\\n\" + CEND ) # STYLE 2 progress BOLD # \n #classic B/W# sys.stdout.write(BOLD + (\" {:s} / {:s} Mb \".format('{:,}'.format(int((FullFolderSize(destination_path)-dstINIsize)/1000000)), '{:,}'.format(int(bytes_to_copy/1000000)))) + (\"|{:20s}|\".format('|'*20)) + (\" {:d}% \".format( 100)) + (\" {:s} \".format(' ')) + \"\\n\" + CEND ) # STYLE 3 progress classic B/W # \n sys.stdout.flush()\n print \" \"\n print \" \"\n\ndef CopyProgress(SOURCE, DESTINATION):\n global FilesLeft\n DST = os.path.join(DESTINATION, os.path.basename(SOURCE))\n # <- the previous will copy the Source folder inside of the Destination folder. Result Target: path/to/Destination/SOURCE_NAME\n # -> UNCOMMENT the next (# DST = DESTINATION) to copy the CONTENT of Source to the Destination. Result Target: path/to/Destination\n DST = DESTINATION # UNCOMMENT this to specify the Destination as the target itself and not the root folder of the target \n #\n if DST.startswith(SOURCE):\n print \" \"\n print BOLD + UNDERLINE + 'Source folder can\\'t be changed.' + CEND\n print 'Please check your target path...'\n print \" \"\n print BOLD + ' CANCELED' + CEND\n print \" \"\n exit()\n #count bytes to copy\n Bytes2copy = 0\n for root, dirs, files in os.walk(SOURCE): # USE for filename in os.listdir(SOURCE): # if you don't want RECURSION #\n dstDIR = root.replace(SOURCE, DST, 1) # USE dstDIR = DST # if you don't want RECURSION #\n for filename in files: # USE if not os.path.isdir(os.path.join(SOURCE, filename)): # if you don't want RECURSION #\n dstFILE = os.path.join(dstDIR, filename)\n if os.path.exists(dstFILE): continue # must match the main loop (after \"threading.Thread\")\n # To overwrite delete dstFILE first here so the progress works properly: ex. change continue to os.unlink(dstFILE)\n # To rename new files adding date and time, instead of deleating and overwriting, \n # comment 'if os.path.exists(dstFILE): continue'\n Bytes2copy += os.path.getsize(os.path.join(root, filename)) # USE os.path.getsize(os.path.join(SOURCE, filename)) # if you don't want RECURSION #\n FilesLeft += 1\n # <- count bytes to copy\n #\n # Treading to call the preogress\n threading.Thread(name='progresso', target=getPERCECENTprogress, args=(SOURCE, DST, Bytes2copy)).start()\n # main loop\n for root, dirs, files in os.walk(SOURCE): # USE for filename in os.listdir(SOURCE): # if you don't want RECURSION #\n dstDIR = root.replace(SOURCE, DST, 1) # USE dstDIR = DST # if you don't want RECURSION #\n if not os.path.exists(dstDIR):\n os.makedirs(dstDIR)\n for filename in files: # USE if not os.path.isdir(os.path.join(SOURCE, filename)): # if you don't want RECURSION #\n srcFILE = os.path.join(root, filename) # USE os.path.join(SOURCE, filename) # if you don't want RECURSION #\n dstFILE = os.path.join(dstDIR, filename)\n if os.path.exists(dstFILE): continue # MUST MATCH THE PREVIOUS count bytes loop \n # <- <- this jumps to the next file without copying this file, if destination file exists. \n # Comment to copy with rename or overwrite dstFILE\n #\n # RENAME part below\n head, tail = os.path.splitext(filename)\n count = -1\n year = int(time.strftime(\"%Y\"))\n month = int(time.strftime(\"%m\"))\n day = int(time.strftime(\"%d\"))\n hour = int(time.strftime(\"%H\"))\n minute = int(time.strftime(\"%M\"))\n while os.path.exists(dstFILE):\n count += 1\n if count == 0:\n dstFILE = os.path.join(dstDIR, '{:s}[{:d}.{:d}.{:d}]{:d}-{:d}{:s}'.format(head, year, month, day, hour, minute, tail))\n else:\n dstFILE = os.path.join(dstDIR, '{:s}[{:d}.{:d}.{:d}]{:d}-{:d}[{:d}]{:s}'.format(head, year, month, day, hour, minute, count, tail))\n # END of RENAME part\n shutil.copy2(srcFILE, dstFILE)\n FilesLeft -= 1\n #\n\n'''\nEx.\nCopyProgress('/path/to/SOURCE', '/path/to/DESTINATION')\n'''\n" }, { "answer_id": 66257068, "author": "JBroadway", "author_id": 9065959, "author_profile": "https://Stackoverflow.com/users/9065959", "pm_score": 0, "selected": false, "text": "ROBOCOPY os import os\n\ndef robocopy(source, destination, extension=''):\n os.system(\"robocopy {} {} {} /xx /njh\".format(source, destination, extension))\n\n# Usage example\nrobocopy(r'C:\\Users\\Example\\Downloads', r'C:\\Users\\Example\\Desktop', '*.mov')\n extension /xx /njh" }, { "answer_id": 70777816, "author": "every skills", "author_id": 15099592, "author_profile": "https://Stackoverflow.com/users/15099592", "pm_score": 0, "selected": false, "text": "#!/usr/bin/python3\n\nimport os\nimport sys\nfrom PySide2.QtWidgets import QProgressBar, QApplication, QDialog, QMainWindow, QPushButton\nfrom PySide2.QtCore import QThread, Signal, Slot\n\n\nclass ProgressDialog(QDialog):\n def __init__(self, parent, source, destination):\n QDialog.__init__(self, parent)\n \n self.resize(400, 50)\n \n self.parent = parent\n self.source = source\n self.destination = destination\n \n self.prog = QProgressBar(self)\n self.prog.setMaximum(100)\n self.prog.setMinimum(0)\n self.prog.setFormat(\"%p%\")\n\n def start(self):\n self.show()\n self.copy()\n\n def copy(self):\n copy_thread = CopyThread(self, self.source, self.destination)\n copy_thread.procPartDone.connect(self.update_progress)\n copy_thread.procDone.connect(self.finished_copy)\n copy_thread.start()\n\n def update_progress(self, progress):\n self.prog.setValue(progress)\n\n def finished_copy(self, state):\n self.close()\n\nclass CopyThread(QThread):\n\n procDone = Signal(bool)\n procPartDone = Signal(int)\n\n def __init__(self, parent, source: str, destination: str):\n QThread.__init__(self, parent)\n \n self.source = source\n self.destination = destination\n\n def run(self):\n self.copy()\n self.procDone.emit(True)\n\n def copy(self):\n source_size = os.stat(self.source).st_size\n copied = 0\n\n with open(self.source, \"rb\") as source, open(self.destination, \"wb\") as target:\n while True:\n chunk = source.read(1024)\n if not chunk:\n break\n\n target.write(chunk)\n copied += len(chunk)\n\n self.procPartDone.emit(copied * 100 / source_size)\n\n\nclass MainWindow(QMainWindow):\n def __init__(self, parent: object = None) -> None:\n super().__init__(parent)\n \n self.src = \"/path/to/file.ext\"\n self.dest = \"/path/to/file.ext\"\n\n self.btn = QPushButton(self)\n self.btn.setText(\"Start copy\")\n self.btn.clicked.connect(self.run)\n \n self.setCentralWidget(self.btn)\n \n def run(self):\n self.prog = ProgressDialog(self, self.src, self.dest)\n self.prog.start()\n\n\ndef main(): \n app = QApplication(sys.argv)\n \n window = MainWindow()\n window.show()\n \n sys.exit(app.exec_())\n\nif __name__ == \"__main__\":\n main()\n python3 main.py\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24708/" ]
274,512
<p>I'm going to have my website hosted soon on a VPS or dedicated server (with Windows 2008), so I'm trying to plan ahead. I wonder whether the built-in SMTP server that comes with IIS7 is reliable enough for a production server or should I look for an alternative? I heard good things about hmailserver and best of all it's free, do you have any experience with using the bulit-in SMTP on a high traffic website.</p> <p>Thanks a lot for any suggestions</p>
[ { "answer_id": 10336338, "author": "Jess Coburn", "author_id": 489393, "author_profile": "https://Stackoverflow.com/users/489393", "pm_score": 2, "selected": false, "text": "VPS/Dedicated" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/676066/" ]
274,523
<p>if Form.Release is called after using the form, it will free all related memory but not set the form variable to nil.</p> <pre><code>if not assigned (Form1) then begin Application.CreateForm(Tform1, Form1); try // Do something finally Form1.Release end; end; </code></pre> <p>To be able to call the same code again, Form1 would have to be set to nil at some point. From the description of Release I cannot do</p> <pre><code>Form1 := nil; </code></pre> <p>right after Release, because the Release procedure will return directly after being called and before the form is actually freed. I cannot detect when Form.Release is finished to set the form var to nil.</p> <p>What is the best way to do this?</p>
[ { "answer_id": 274535, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 1, "selected": false, "text": "FreeAndNil(Form1)\n" }, { "answer_id": 274546, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": true, "text": " Form1 := nil; \n" }, { "answer_id": 275106, "author": "Jim McKeeth", "author_id": 255, "author_profile": "https://Stackoverflow.com/users/255", "pm_score": 2, "selected": false, "text": "procedure FreeOrReleaseAndNil(var Obj);\nvar\n Temp: TObject;\nbegin\n Temp := TObject(Obj);\n Pointer(Obj) := nil;\n if Temp is TCustomForm then\n TCustomForm(Temp).Release\n else\n Temp.Free;\nend;\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5015/" ]
274,529
<p>Am working with django Publisher example, I want to list all the publishers in the db via my list_publisher.html template, my template looks like;</p> <pre><code>{% extends "admin/base_site.html" %} {% block title %}List of books by publisher{% endblock %} {% block content %} &lt;div id="content-main"&gt; &lt;h1&gt;List of publisher:&lt;/h1&gt; {%regroup publisher by name as pub_list %} {% for pub in pub_list %} &lt;li&gt;{{ pub.name }}&lt;/li&gt; {% endfor %} &lt;/div&gt; {% endblock %} </code></pre> <p>but when I run "<a href="http://127.0.0.1:8000/list_publisher/" rel="nofollow noreferrer">http://127.0.0.1:8000/list_publisher/</a>" the template just prints the page title with no error! What am I doing wrong?</p>
[ { "answer_id": 274537, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 3, "selected": true, "text": "{% block content %}{% endblock %} {%regroup publisher by name as pub_list %}{{ pub_list|length }} {% regroup publisher|dictsort:\"name\" by name as pub_list %} publisher = Publisher.objects.all().order_by(\"name\")\n" }, { "answer_id": 274975, "author": "Peter Rowell", "author_id": 17017, "author_profile": "https://Stackoverflow.com/users/17017", "pm_score": 0, "selected": false, "text": "[{{pub_list}}] [,,,,,]" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26143/" ]
274,560
<p>Is there an easy way to verify that a given private key matches a given public key? I have a few <code>*.pub</code>and a few <code>*.key</code> files, and I need to check which go with which.</p> <p>Again, these are pub/key files, DSA.</p> <p>I would really prefer a one-liner of some sort...</p>
[ { "answer_id": 274570, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 4, "selected": false, "text": " openssl x509 -in certfile -modulus -noout\n openssl rsa -in keyfile -modulus -noout\n" }, { "answer_id": 274622, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 6, "selected": false, "text": " openssl dsa -pubin -in dsa.pub -modulus -noout\n openssl dsa -in dsa.key -modulus -noout\n" }, { "answer_id": 274662, "author": "Loki", "author_id": 17324, "author_profile": "https://Stackoverflow.com/users/17324", "pm_score": 9, "selected": true, "text": "ssh-keygen -y -f <private key file>\n" }, { "answer_id": 280912, "author": "Robert", "author_id": 35675, "author_profile": "https://Stackoverflow.com/users/35675", "pm_score": 6, "selected": false, "text": "Certificate: openssl x509 -noout -modulus -in server.crt | openssl md5\nPrivate Key: openssl rsa -noout -modulus -in server.key | openssl md5\nCSR: openssl req -noout -modulus -in server.csr | openssl md5\n" }, { "answer_id": 22595408, "author": "John D.", "author_id": 2763030, "author_profile": "https://Stackoverflow.com/users/2763030", "pm_score": 4, "selected": false, "text": "diff <(ssh-keygen -y -f $private_key_file) $public_key_file\n" }, { "answer_id": 49099046, "author": "Bradley Allen", "author_id": 5318106, "author_profile": "https://Stackoverflow.com/users/5318106", "pm_score": 3, "selected": false, "text": "ssh-keygen -y -f ~/.ssh/id_rsa | diff -s - <(cut -d ' ' -f 1,2 ~/.ssh/id_rsa.pub)\n Files - and /dev/fd/63 are identical\n\nFiles - and /dev/fd/63 differ\n" }, { "answer_id": 55571763, "author": "RoutesMaps.com", "author_id": 2085768, "author_profile": "https://Stackoverflow.com/users/2085768", "pm_score": 0, "selected": false, "text": "cat $HOME/.ssh/id_rsa.pub >> $HOME/.ssh/authorized_keys\nssh -i $HOME/.ssh/id_rsa localhost\n" }, { "answer_id": 67423640, "author": "Oliver", "author_id": 869951, "author_profile": "https://Stackoverflow.com/users/869951", "pm_score": 2, "selected": false, "text": "ssh-keygen -l -f PRIVATE_KEY; ssh-keygen -l -f PUBLIC_KEY\n diff -s <(ssh-keygen -l -f PRIVATE_KEY | cut -d' ' -f2) <(ssh-keygen -l -f PUBLIC_KEY | cut -d' ' -f2)\n" }, { "answer_id": 72229472, "author": "Mikko Tuominen", "author_id": 1312559, "author_profile": "https://Stackoverflow.com/users/1312559", "pm_score": 0, "selected": false, "text": "-l' Show fingerprint of specified public key file. Private RSA1 keys are also supported. For RSA and DSA keys ssh-keygen tries to find the matching public key file and prints its fingerprint.\n" }, { "answer_id": 73365000, "author": "Blockchain Office", "author_id": 15125291, "author_profile": "https://Stackoverflow.com/users/15125291", "pm_score": 1, "selected": false, "text": " #!/bin/bash\n\n PRKEY=mysshkey\n PUKEY=mysshkey.pub\n\n echo \"1. OUTPUT\"\n diff <( ssh-keygen -y -e -f \"${PRKEY}\" ) <( ssh-keygen -y -e -f \"${PUKEY}\")\n echo -e \"\\n\"\n\n echo \"2. OUTPUT\"\n diff <( cut -d' ' -f 2 ${PUKEY} ) <( ssh-keygen -y -f \"${PRKEY}\" | cut -d' ' -f 2)\n echo -e \"\\n\"\n\n echo \"3. OUTPUT\"\n DIFF=$(diff <( cut -d' ' -f 2 ${PUKEY} ) <( ssh-keygen -y -f \"${PRKEY}\" | cut -d' ' -f 2) )\n if [ \"$DIFF\" != \"\" ]; then\n echo \"ERROR KEY\"\n else\n echo \"TRUE KEY\"\n fi\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17324/" ]
274,567
<p>Can someone please derive a concrete example from the following:</p> <p><a href="http://www.urdalen.com/blog/?p=210" rel="nofollow noreferrer">http://www.urdalen.com/blog/?p=210</a></p> <p>..that shows how to deal with <code>one-to-many</code> and <code>many-to-many</code> relationships?</p> <p>I've emailed the author some time ago but received no reply. I like his idea, but can't figure out how to implement it beyond simple single table relations.</p> <p>Note: I don't want to use a full-blown ORM. I like doing my SQL by hand. I would like to improve the design of my app code though. Right now each domain object has its own class full of queries wrapped in static methods. They just return scalar, 1d-array (record) or 2d-array (recordset) depending on the query.</p>
[ { "answer_id": 274684, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 4, "selected": true, "text": "$car42 = $car_gateway->fetch(42);\n$wheels = $wheel_gateway->selectByCar($car42);\n $car42 = $car_gateway->fetch(42);\n$wheels = $car42->selectWheels();\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
274,575
<p>While LOC (# lines of code) is a problematic measurement of a code's complexity, it is the most popular one, and when used very carefully, can provide a rough estimate of at least relative complexities of code bases (i.e. if one program is 10KLOC and another is 100KLOC, written in the same language, by teams of roughly the same competence, the second program is almost certainly much more complex).</p> <p>When counting lines of code, do you prefer to count comments in ? What about tests? </p> <p>I've seen various approaches to this. Tools like cloc and sloccount allow to either include or exclude comments. Other people consider comments part of the code and its complexity. </p> <p>The same dilemma exists for unit tests, that can sometimes reach the size of the tested code itself, and even exceed it.</p> <p>I've seen approaches all over the spectrum, from counting only "operational" non-comment non-blank lines, to "XXX lines of tested, commented code", which is more like running "wc -l on all code files in the project".</p> <p>What is your personal preference, and why?</p>
[ { "answer_id": 274600, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": 1, "selected": false, "text": "for (int i = 0; i < list.count; i++)\n{\n // do some stuff\n}\n\nfor (int i = 0; i < list.count; i++){\n // do some stuff\n}\n" }, { "answer_id": 274683, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 3, "selected": false, "text": "Lines of Code: 75,000\nLines of Comments: 10,000\nLines of Tests: 15,000\n ---------\nTotal: 100,000\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
274,586
<p>In ASP.NET MVC, I'm trying to create a link that includes an anchor tag (that is, directing the user to a page, and a specific section of the page).</p> <p>The URL I am trying to create should look like the following:</p> <pre><code>&lt;a href="/category/subcategory/1#section12"&gt;Title for a section on the page&lt;/a&gt; </code></pre> <p>My routing is set up with the standard: </p> <pre><code>routes.MapRoute("Default", "{controller}/{action}/{categoryid}"); </code></pre> <p>The action link syntax that I am using is: </p> <pre><code>&lt;%foreach (Category parent in ViewData.Model) { %&gt; &lt;h3&gt;&lt;%=parent.Name %&gt;&lt;/h3&gt; &lt;ul&gt; &lt;%foreach (Category child in parent.SubCategories) { %&gt; &lt;li&gt;&lt;%=Html.ActionLink&lt;CategoryController&gt;(x =&gt; x.Subcategory(parent.ID), child.Name) %&gt;&lt;/li&gt; &lt;%} %&gt; &lt;/ul&gt; &lt;%} %&gt; </code></pre> <p>My controller method is as follows:</p> <pre><code>public ActionResult Subcategory(int categoryID) { //return itemList return View(itemList); } </code></pre> <p>The above correctly returns a URL as follows:</p> <pre><code>&lt;a href="/category/subcategory/1"&gt;Title for a section on the page&lt;/a&gt; </code></pre> <p>I can't figure out how to add the <strong>#section12</strong> part. The "section" word is just the convention I am using to break up the page sections, and the 12 is the ID of the subcategory, i.e., child.ID.</p> <p>How can I do this?</p>
[ { "answer_id": 274637, "author": "LorenzCK", "author_id": 3118, "author_profile": "https://Stackoverflow.com/users/3118", "pm_score": 8, "selected": true, "text": "<a href=\"<%=Url.Action(\"Subcategory\", \"Category\", new { categoryID = parent.ID }) %>#section12\">link text</a>\n" }, { "answer_id": 275499, "author": "Brad Wilson", "author_id": 1554, "author_profile": "https://Stackoverflow.com/users/1554", "pm_score": 8, "selected": false, "text": "<%= Html.ActionLink(\"Link Text\", \"Action\", \"Controller\", null, null, \"section12-the-anchor\", new { categoryid = \"blah\"}, null) %>\n" }, { "answer_id": 26088408, "author": "PussInBoots", "author_id": 687549, "author_profile": "https://Stackoverflow.com/users/687549", "pm_score": 4, "selected": false, "text": "@Html.ActionLink(\"Some link text\", \"MyAction\", \"MyController\", protocol: null, hostName: null, fragment: \"MyAnchor\", routeValues: null, htmlAttributes: null)\n" }, { "answer_id": 27249511, "author": "NoWar", "author_id": 196919, "author_profile": "https://Stackoverflow.com/users/196919", "pm_score": 1, "selected": false, "text": "@Html.Grid(Model).Columns(columns =>\n {\n columns.Add()\n .Encoded(false)\n .Sanitized(false)\n .SetWidth(10)\n .Titled(string.Empty)\n .RenderValueAs(x => @Html.ActionLink(\"Edit\", \"UserDetails\", \"Membership\", null, null, \"discount\", new { @id = @x.Id }, new { @target = \"_blank\" }));\n\n }).WithPaging(200).EmptyText(\"There Are No Items To Display\")\n <ul id=\"myTab\" class=\"nav nav-tabs\" role=\"tablist\">\n\n <li class=\"active\"><a href=\"#discount\" role=\"tab\" data-toggle=\"tab\">Discount</a></li>\n </ul>\n" }, { "answer_id": 35956305, "author": "Ahmed Samir", "author_id": 3209817, "author_profile": "https://Stackoverflow.com/users/3209817", "pm_score": 0, "selected": false, "text": "<a class=\"btn yellow\" href=\"/users/Create/@Model.Id\" target=\"_blank\">\n Add As User\n </a>\n" }, { "answer_id": 37894890, "author": "Zapnologica", "author_id": 1331971, "author_profile": "https://Stackoverflow.com/users/1331971", "pm_score": 4, "selected": false, "text": "<a href=\"@Url.Action(\"Index\",\"Home\")#features\">Features</a>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29092/" ]
274,619
<p>My platform: Visual C# 2008 Express Edition with NUnit 2.2.7</p> <p>I have a solution with my code in one project and my NUnit unit tests in a different project in the same solution.</p> <p>I have been struggling hard to debug and single-step through the NUnit tests. I found some references online that suggested calling the following:</p> <pre><code>NUnit.ConsoleRunner.Runner.Main(args); </code></pre> <p>But this doesn't even compile - it has the compiler error:</p> <blockquote> <p>Error 1 The type or namespace name 'Runner' does not exist in the namespace 'NUnit.ConsoleRunner' (are you missing an assembly reference?)</p> </blockquote> <p>I've added every assembly reference I could find, to no effect.</p> <p>Finally, this is what I have hacked together and it works, but perhaps you good readers could suggest a better solution:</p> <p>1) In my test project, the class name of a test case that I want to debug is MyTestClass. It has a [TestFixtureSetUp] method named Init() and the actual test case is in [Test] function MyTest()</p> <p>2) In my code project, I have a console program TestProgram.cs which compiles to an EXE.</p> <p>In TestProgram.cs, I call the test cases in the following way</p> <pre><code>// First instantiate the test class MyTestClass tc = new MyTestClass(); // Call the TestFixtureSetup method tc.Init(); // Now call the actual test tc.MyTest(); </code></pre> <p>This works and I can debug and single step through the test cases.</p> <p>If anyone has any better suggestions using Visual Studio 2008 Express <em>without paying for additional plugins</em>, I appreciate your advice.</p>
[ { "answer_id": 274628, "author": "Kent Boogaart", "author_id": 5380, "author_profile": "https://Stackoverflow.com/users/5380", "pm_score": 2, "selected": false, "text": "Runner Debugger.Attach()" }, { "answer_id": 274701, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 0, "selected": false, "text": "NUnit.ConsoleRunner.Runner.Main(args); NUnit.ConsoleRunner.ConsoleUi.Main(args);\n" }, { "answer_id": 274707, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 2, "selected": false, "text": "Start External Program Enable unmanaged code debugging" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18542/" ]
274,626
<p>In c++ what is object slicing and when does it occur?</p>
[ { "answer_id": 274634, "author": "David Dibben", "author_id": 5022, "author_profile": "https://Stackoverflow.com/users/5022", "pm_score": 9, "selected": false, "text": "class A {\n int foo;\n};\n\nclass B : public A {\n int bar;\n};\n B foo bar B b;\n\nA a = b;\n b bar a" }, { "answer_id": 274636, "author": "Black", "author_id": 25234, "author_profile": "https://Stackoverflow.com/users/25234", "pm_score": 7, "selected": false, "text": "A B void wantAnA(A myA)\n{\n // work with myA\n}\n\nB derived;\n// work with the object \"derived\"\nwantAnA(derived);\n wantAnA derived derived B A wantAnA A B" }, { "answer_id": 9047531, "author": "haberdar", "author_id": 1154908, "author_profile": "https://Stackoverflow.com/users/1154908", "pm_score": 3, "selected": false, "text": "class Pet\n{\n public:\n string name;\n};\nclass Dog : public Pet\n{\npublic:\n string breed;\n};\n\nint main()\n{ \n Dog dog;\n Pet pet;\n\n dog.name = \"Tommy\";\n dog.breed = \"Kangal Dog\";\n pet = dog;\n cout << pet.breed; //ERROR\n Pet *ptrP;\nDog *ptrD;\nptrD = new Dog; \nptrD->name = \"Tommy\";\nptrD->breed = \"Kangal Dog\";\nptrP = ptrD;\ncout << ((Dog *)ptrP)->breed; \n" }, { "answer_id": 13625934, "author": "quidkid", "author_id": 1863203, "author_profile": "https://Stackoverflow.com/users/1863203", "pm_score": 0, "selected": false, "text": "class A \n{ \n int x; \n}; \n\nclass B \n{ \n B( ) : x(1), c('a') { } \n int x; \n char c; \n}; \n\nint main( ) \n{ \n A a; \n B b; \n a = b; // b.c == 'a' is \"sliced\" off\n return 0; \n}\n" }, { "answer_id": 14461532, "author": "fgp", "author_id": 1582403, "author_profile": "https://Stackoverflow.com/users/1582403", "pm_score": 9, "selected": false, "text": "A B B A B A B const A& B b;\nA a = b;\n A B a b A B B b1;\nB b2;\nA& a_ref = b2;\na_ref = b1;\n//b2 now contains a mixture of b1 and b2!\n b2 b1 b2 b1 B A b2 B virtual a_ref = b1 A B A& B a_ref B A A B dynamic_cast assign() B assign() A assign() A class A {\npublic:\n virtual A& operator= (const A& a) {\n assign(a);\n return *this;\n }\n\nprotected:\n void assign(const A& a) {\n // copy members of A from a to this\n }\n};\n\nclass B : public A {\npublic:\n virtual B& operator= (const A& a) {\n if (const B* b = dynamic_cast<const B*>(&a))\n assign(*b);\n else\n throw bad_assignment();\n return *this;\n }\n\nprotected:\n void assign(const B& b) {\n A::assign(b); // Let A's assign() copy members of A from b to this\n // copy members of B from b to this\n }\n};\n B operator= B" }, { "answer_id": 22360211, "author": "Santosh", "author_id": 3240133, "author_profile": "https://Stackoverflow.com/users/3240133", "pm_score": 2, "selected": false, "text": " class baseclass\n {\n ...\n baseclass & operator =(const baseclass&);\n baseclass(const baseclass&);\n }\n void function( )\n {\n baseclass obj1=m;\n obj1=m;\n }\n" }, { "answer_id": 25453490, "author": "geh", "author_id": 2916579, "author_profile": "https://Stackoverflow.com/users/2916579", "pm_score": 6, "selected": false, "text": "#include <iostream>\n\nusing namespace std;\n\n// Base class\nclass A {\npublic:\n A() {}\n A(const A& a) {\n cout << \"'A' copy constructor\" << endl;\n }\n virtual void run() const { cout << \"I am an 'A'\" << endl; }\n};\n\n// Derived class\nclass B: public A {\npublic:\n B():A() {}\n B(const B& a):A(a) {\n cout << \"'B' copy constructor\" << endl;\n }\n virtual void run() const { cout << \"I am a 'B'\" << endl; }\n};\n\nvoid g(const A & a) {\n a.run();\n}\n\nvoid h(const A a) {\n a.run();\n}\n\nint main() {\n cout << \"Call by reference\" << endl;\n g(B());\n cout << endl << \"Call by copy\" << endl;\n h(B());\n}\n Call by reference\nI am a 'B'\n\nCall by copy\n'A' copy constructor\nI am an 'A'\n" }, { "answer_id": 37156090, "author": "Varun Kumar", "author_id": 3514002, "author_profile": "https://Stackoverflow.com/users/3514002", "pm_score": -1, "selected": false, "text": "class Base { \nint x;\n };\n\nclass Derived : public Base { \n int z; \n };\n\n int main() \n{\nDerived d;\nBase b = d; // Object Slicing, z of d is sliced off\n}\n" }, { "answer_id": 45184425, "author": "Ghulam Moinul Quadir", "author_id": 7857932, "author_profile": "https://Stackoverflow.com/users/7857932", "pm_score": -1, "selected": false, "text": "#include<bits/stdc++.h>\nusing namespace std;\nclass Base\n{\n public:\n int a;\n int b;\n int c;\n Base()\n {\n a=10;\n b=20;\n c=30;\n }\n};\nclass Derived : public Base\n{\n public:\n int d;\n int e;\n Derived()\n {\n d=40;\n e=50;\n }\n};\nint main()\n{\n Derived d;\n cout<<d.a<<\"\\n\";\n cout<<d.b<<\"\\n\";\n cout<<d.c<<\"\\n\";\n cout<<d.d<<\"\\n\";\n cout<<d.e<<\"\\n\";\n\n\n Base b = d;\n cout<<b.a<<\"\\n\";\n cout<<b.b<<\"\\n\";\n cout<<b.c<<\"\\n\";\n cout<<b.d<<\"\\n\";\n cout<<b.e<<\"\\n\";\n return 0;\n}\n [Error] 'class Base' has no member named 'd'\n[Error] 'class Base' has no member named 'e'\n" }, { "answer_id": 46725480, "author": "Martin B.", "author_id": 7917910, "author_profile": "https://Stackoverflow.com/users/7917910", "pm_score": -1, "selected": false, "text": "Action Action std::string name std::function<void()> f void activate() f std::vector<Action> void push_back(Action toAdd);\n Action Action push_back f A B" }, { "answer_id": 49148511, "author": "Kartik Maheshwari", "author_id": 5213931, "author_profile": "https://Stackoverflow.com/users/5213931", "pm_score": 4, "selected": false, "text": "class Base { int x, y; };\n\nclass Derived : public Base { int z, w; };\n\nint main() \n{\n Derived d;\n Base b = d; // Object Slicing, z and w of d are sliced off\n}\n" }, { "answer_id": 63859829, "author": "Sorush", "author_id": 2543510, "author_profile": "https://Stackoverflow.com/users/2543510", "pm_score": 4, "selected": false, "text": "class A{\npublic:\n virtual void Say(){\n std::cout<<\"I am A\"<<std::endl;\n }\n};\n\nclass B: public A{\npublic:\n void Say() override{\n std::cout<<\"I am B\"<<std::endl;\n }\n};\n\nint main(){\n B b;\n A a1;\n A a2=b;\n\n b.Say(); // I am B\n a1.Say(); // I am A\n a2.Say(); // I am A why???\n}\n A& a2=b;\n a2.Say(); // I am B\n A* a2 = &b;\na2->Say(); // I am B\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35737/" ]
274,639
<p>What the minimum basic setup required to begin developing a Firefox extension?</p>
[ { "answer_id": 274647, "author": "Balaji Sowmyanarayanan", "author_id": 35738, "author_profile": "https://Stackoverflow.com/users/35738", "pm_score": 4, "selected": false, "text": "firefox.exe -profilemanager\n content 1mffext chrome/\n <?xml version=\"1.0\"?>\n<RDF:RDF xmlns:em=\"http://www.mozilla.org/2004/em-rdf#\"\n xmlns:NC=\"http://home.netscape.com/NC-rdf#\"\n xmlns:RDF=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n <RDF:Description RDF:about=\"rdf:#$Fsv+Z3\"\n em:id=\"{ec8030f7-c20a-464f-9b0e-13a3a9e97384}\"\n em:minVersion=\"2.0\"\n em:maxVersion=\"3.0.*\" />\n <RDF:Description RDF:about=\"urn:mozilla:install-manifest\"\n em:id=\"1m-ff-ext@ec29.com\"\n em:type=\"2\"\n em:name=\"OneMinuteFirefoxExtension@ec29.com\"\n em:version=\"0.0.1\"\n em:description=\"One Minute FireFox extension\"\n em:creator=\"labsji \"\n em:homepageURL=\"http://labsji.wordpress.com\">\n <em:contributor>Venkat83</em:contributor>\n <em:targetApplication RDF:resource=\"rdf:#$Fsv+Z3\"/>\n </RDF:Description>\n firefox.exe -profile <path of the newly created profile> -no-remote\n" }, { "answer_id": 274663, "author": "rogeriopvl", "author_id": 28388, "author_profile": "https://Stackoverflow.com/users/28388", "pm_score": 1, "selected": false, "text": "firefox -P My_test_profile -no-remote\n" }, { "answer_id": 24900267, "author": "Max Heiber", "author_id": 2482570, "author_profile": "https://Stackoverflow.com/users/2482570", "pm_score": 0, "selected": false, "text": "source bin/activate mkdir plugin_name cd plugin_name cfx init" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35738/" ]
274,646
<p>I am getting the following error while loading a page.</p> <p>[HttpException (0x80004005): Cannot use a leading .. to exit above the top directory.]</p> <p>No idea what to do ? Can anyone help me ?</p>
[ { "answer_id": 274688, "author": "Martin Brown", "author_id": 20553, "author_profile": "https://Stackoverflow.com/users/20553", "pm_score": 2, "selected": false, "text": "Response.Redirect(\"../SomePage.aspx\");\n ../ http://www.example.com/SomePage.aspx" }, { "answer_id": 932170, "author": "salle55", "author_id": 39636, "author_profile": "https://Stackoverflow.com/users/39636", "pm_score": 0, "selected": false, "text": "<authentication>\n <forms cookieless=\"UseCookies\" />\n</authentication>\n" }, { "answer_id": 10507277, "author": "PerryM", "author_id": 69097, "author_profile": "https://Stackoverflow.com/users/69097", "pm_score": 0, "selected": false, "text": "[HttpException (0x80004005): Cannot use a leading .. to exit above the top directory.]\n System.Web.Util.UrlPath.ReduceVirtualPath(String path) +11496719\n System.Web.Util.UrlPath.Reduce(String path) +171\n System.Web.Configuration.**AuthenticationConfig**.GetCompleteLoginUrl(HttpContext context, String loginUrl) +218\n System.Web.Security.FormsAuthenticationModule.OnEnter(Object source, EventArgs eventArgs) +156\n System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +80\n System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +270 <authentication mode=\"Forms\">\n <forms loginUrl=\"../home.aspx\" timeout=\"2880\" />\n </authentication>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29982/" ]
274,656
<p>I've been trying to build subversion (on a limited account) for a long time but without any luck :(</p> <p>The instructions I'm following: <a href="http://wiki.dreamhost.com/Subversion_Installation" rel="nofollow noreferrer">http://wiki.dreamhost.com/Subversion_Installation</a></p> <p>Running this:</p> <pre><code>./configure --prefix=${RUN} --without-berkeley-db --with-ssl --with-zlib --enable-shared </code></pre> <p>Gives me this error:</p> <pre><code>checking for library containing RSA_new... not found configure: error: could not find library containing RSA_new configure failed for neon </code></pre> <p>Can someone explain to me:</p> <ol> <li>Possible reasons for this</li> <li>Possible ways to circumvent it</li> <li>Optional: What these modules are and what their purpose is (Neon/RSA_new)</li> </ol> <p>Thanks!</p> <h2>Log file contents:</h2> <p>Trying to find interesting bits from the neon config.log file:</p> <pre><code>configure:27693: gcc -o conftest -g -O2 conftest.c &gt;&amp;5 /tmp/ccazXdJz.o: In function `main': /home/stpinst/soft/subversion-1.5.4/neon/conftest.c:93: undefined reference to `RSA_new' collect2: ld returned 1 exit status configure:27699: $? = 1 configure: failed program was: ... | int | main () | { | RSA_new(); | ; | return 0; | } configure:27742: gcc -o conftest -g -O2 conftest.c -lcrypto -lz &gt;&amp;5 /usr/bin/ld: cannot find -lcrypto collect2: ld returned 1 exit status configure:27748: $? = 1 </code></pre> <p>--</p>
[ { "answer_id": 274661, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 3, "selected": false, "text": "aptitude install libssl-dev" }, { "answer_id": 274666, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 1, "selected": false, "text": "setenv CC \"gcc -I/usr/local/ssl/include -L/usr/local/ssl/lib\"\nsetenv CFLAGS \"-O2 -g -I/usr/local/ssl/include\"\nsetenv LDFLAGS \"-L/usr/local/ssl/lib\"\nsetenv CPP \"gcc -E -I/usr/local/ssl/include\"\n" }, { "answer_id": 274889, "author": "AtliB", "author_id": 18274, "author_profile": "https://Stackoverflow.com/users/18274", "pm_score": 0, "selected": false, "text": "apt-get install libssl-dev\n E: Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)\nE: Unable to lock the administration directory (/var/lib/dpkg/), are you root?\n E: Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied) \nE: Unable to lock the administration directory (/var/lib/dpkg/), are you root\n" }, { "answer_id": 274936, "author": "AtliB", "author_id": 18274, "author_profile": "https://Stackoverflow.com/users/18274", "pm_score": 1, "selected": false, "text": "./configure --prefix=${RUN} --without-ssl\n checking for openssl/opensslv.h... no\nconfigure: error: We require OpenSSL; try --with-openssl\nconfigure failed for serf\n ./configure --prefix=${RUN} --with-openssl\n configure: WARNING: Unrecognized options: --with-openssl\n...\nconfigure: error: '--with-openssl requires a path to a directory'\nconfigure failed for serf\n" }, { "answer_id": 275296, "author": "AtliB", "author_id": 18274, "author_profile": "https://Stackoverflow.com/users/18274", "pm_score": 0, "selected": false, "text": "wget http://www.openssl.org/source/openssl-0.9.8a.tar.gz\ntar zxvf openssl-0.9.8a.tar.gz\ncd openssl-0.9.8a\n./configure --prefix=${RUN}\nmake\nmake install\n ./configure --prefix=${RUN} --without-berkeley-db --with-openssl=$HOME/soft/openssl-0.9.8a\n configure: WARNING: Unrecognized options: --with-openssl\n link: warning: `/usr/lib/gcc/x86_64-linux-gnu/4.1.2/../../..//libsqlite 3.la' seems to be moved\nlibtool: link: warning: `/usr/lib/gcc/x86_64-linux-gnu/4.1.2/../../..//libsqlite .la' seems to be moved\nlibtool: link: warning: `/usr/lib/gcc/x86_64-linux-gnu/4.1.2/../../..//libexpat. la' seems to be moved\n/usr/bin/ld: cannot find -lssl\ncollect2: ld returned 1 exit status\nmake[1]: *** [libserf-0.la] Error 1\nmake[1]: Leaving directory `/mnt/local/home/stpinst/soft/subversion-1.5.4/serf'\nmake: *** [external-all] Error 1\n" }, { "answer_id": 2044428, "author": "rogerdpack", "author_id": 32453, "author_profile": "https://Stackoverflow.com/users/32453", "pm_score": 2, "selected": false, "text": "$ ./config shared --prefix=$HOME/installs && make clean && make && make install\n\n$ export CFLAGS= \"-O2 -g -I/root/installs/include\"\n$ export CFLAGS=\"-O2 -g -I/root/installs/include\"\n$ export LDFLAGS=\"-L/root/installs/lib\"\n$ export CPP=\"gcc -E -I/root/installs/include\"\n $ ./configure --with-ssl=openssl --prefix=$HOME/installs && make clean && make && make install\n $ ./configure --with-ssl --prefix=$HOME/installs --with-neon=/root/installs/bin/neon-config && make clean && make && make install\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18274/" ]
274,668
<p>I want to be able to change the status message for Live Messenger, but everything I've found only works for the music message (see <a href="http://coldacid.net/images/screenshots/live-messenger-status-and-music-messages" rel="nofollow noreferrer">this screenshot</a> to see the difference between the two).</p> <p>It is possible to do this, as there are programs that have the ability to change it, and some alternate clients for Live Messenger can also set the status message themselves. I just need to know how to do this myself.</p> <p><strong>Clarification:</strong> The solution needs to work with the latest versions of Live Messenger (i.e. the wave 3 beta). Working with older versions is good too, but it's the 14.x versions that I'm working with.</p>
[ { "answer_id": 274676, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 1, "selected": false, "text": "/psm new message Attribute VB_Name = \"Form1\"\nAttribute VB_GlobalNameSpace = False\nAttribute VB_Creatable = False\nAttribute VB_PredeclaredId = True\nAttribute VB_Exposed = False\nPrivate Declare Function FindWindow Lib \"user32\" Alias \"FindWindowA\" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long\nPrivate Declare Function FindWindowEx Lib \"user32\" Alias \"FindWindowExA\" (ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, ByVal lpsz2 As String) As Long\nPrivate Declare Function PostMessage Lib \"user32\" Alias \"PostMessageA\" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long\nPrivate Const WM_COMMAND = &H111\nPrivate Const WM_CHAR = &H102\nPrivate Const VK_RETURN = &HD\n\nPrivate Function SetPSM(ByVal text As String) As Boolean\n Dim hParentWnd, hChildWnd As Long\n SetPSM = False\n hParentWnd = FindWindow(\"MSBLWindowClass\", vbNullString)\n If hParentWnd <> 0 Then\n hChildWnd = FindWindowEx(hParentWnd, 0, \"DirectUIHWND\", vbNullString)\n If hChildWnd <> 0 Then\n PostMessage hParentWnd, WM_COMMAND, 56606, 0\n Dim i As Integer\n For i = 1 To Len(text)\n Call PostMessage(hChildWnd, WM_CHAR, Asc(Mid$(text, i, 1)), 0)\n Next i\n PostMessage hChildWnd, WM_CHAR, VK_RETURN, 0\n SetPSM = True\n End If\n End If\nEnd Function\n\nPrivate Sub cmdSetPSM_Click()\n SetPSM txtPSM.text\nEnd Sub\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5697/" ]
274,753
<p>There seem to be 3 ways of telling GCC to weak link a symbol:</p> <ul> <li><code>__attribute__((weak_import))</code></li> <li><code>__attribute__((weak))</code></li> <li><code>#pragma weak symbol_name</code></li> </ul> <p>None of these work for me:</p> <pre><code>#pragma weak asdf extern void asdf(void) __attribute__((weak_import, weak)); ... { if(asdf != NULL) asdf(); } </code></pre> <p>I always get a link error like this:</p> <pre>Undefined symbols: "_asdf", referenced from: _asdf$non_lazy_ptr in ccFA05kN.o ld: symbol(s) not found collect2: ld returned 1 exit status</pre> <p>I am using GCC 4.0.1 on OS X 10.5.5. What am I doing wrong?</p>
[ { "answer_id": 730267, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "-Wl,-flat_namespace,-undefined,dynamic_lookup" }, { "answer_id": 3749780, "author": "Jeffrey Scofield", "author_id": 452488, "author_profile": "https://Stackoverflow.com/users/452488", "pm_score": 5, "selected": false, "text": "int f(int n)\n{\n return n * 7;\n}\n #include <stdio.h>\n#include <stdlib.h>\n\nextern int f (int) __attribute__((weak_import));\n\nint main() {\n if(f == NULL)\n printf(\"what, no f?\\n\");\n else\n printf(\"f(8) is %d\\n\", f(8));\n exit(0);\n}\n $ cc -dynamiclib -o f.dylib f.c\n $ cc -o whatnof whatnof.c f.dylib\n$ otool -L whatnof\nwhatnof:\n f.dylib (compatibility version 0.0.0, current version 0.0.0)\n /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.0)\n $ whatnof\nf(8) is 56\n $ mv f.dylib f.dylib.real\n$ touch null.c\n$ cc -dynamiclib -o f.dylib null.c\n $ whatnof\nwhat, no f?\n" }, { "answer_id": 54601464, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 3, "selected": false, "text": "#include <stdio.h>\n\nint my_weak_var __attribute__((weak)) = 1;\n\nint main(void) {\n printf(\"%d\\n\", my_weak_var);\n}\n int my_weak_var = 2;\n gcc -c -std=c99 -Wall -Wextra -pedantic -o main.o main.c\ngcc -c -std=c99 -Wall -Wextra -pedantic -o notmain.o notmain.c\ngcc -std=c99 -Wall -Wextra -pedantic -o main.out main.o notmain.o\n./main.out\n 2\n notmain.o gcc -std=c99 -Wall -Wextra -pedantic -o main.out main.o\n./main.out\n 1\n notmain.o nm main.o notmain.o\n main.o:\n U _GLOBAL_OFFSET_TABLE_\n0000000000000000 T main\n0000000000000000 V my_weak_var\n U printf\n\nnotmain.o:\n0000000000000000 D my_weak_var\n man nm\n .a -Wl,--whole-archive" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
274,762
<p>I read somewhere in the Microsoft documentation that the content of the ASP.NET's <strong>web.config is cached</strong>. If that is true, <strong>where</strong> is it cached - in <strong>memory or on disk</strong>?</p> <p>And a follow-up question: are there any performance considerations I have to make, if I have to access the web.config intensively?</p>
[ { "answer_id": 274851, "author": "AnthonyWJones", "author_id": 17516, "author_profile": "https://Stackoverflow.com/users/17516", "pm_score": 4, "selected": true, "text": "GetSection ConfigurationSection GetSection GetSection" }, { "answer_id": 67498636, "author": "Shirish Patel", "author_id": 9733212, "author_profile": "https://Stackoverflow.com/users/9733212", "pm_score": 0, "selected": false, "text": "<appSettings>\n <add key=\"ProductImageFileType\" value=\".jpg|.jpeg|.gif|.png\" />\n</appSettings>\n string ValidateType = ConfigurationManager.AppSettings[\"ProductImageFileType\"].ToString();\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6461/" ]
274,785
<p>I would like to provide two different versions of my iPhone app on the App Store -- one free that is limited by the number of items displayed through the application, and another one completely unlimited.</p> <p>The source code for both apps will be exactly the same, the only difference would be the SQLite database that stores the items in the app.</p> <p>I understand that both versions of the app will need to have different bundle names, and different icons. I'm trying to find a way to avoid completely copying the source code directory to be able to customize some of these things: database, icons, nib strings, etc.</p> <p>Is there a good way to do this without duplicating everything?</p>
[ { "answer_id": 274956, "author": "mxg", "author_id": 11157, "author_profile": "https://Stackoverflow.com/users/11157", "pm_score": 3, "selected": false, "text": "#ifdef FULL_APP\n // unlimited size\n #define SIZE -1\n#else\n #define SIZE 100\n#endif\n gcc program.cc -o program.o -DFULL_APP\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35478/" ]
274,796
<p>I have the following code which plays a video clip but when it is finished it does not release the form but instead leaves the last frame of the video. how do I get it to clear when playback ends so that I can see the orignal contents of the form it took over to play the video?</p> <pre><code>_video = new Video("video.wmv"); _video.Owner = frmVideoWindow; _video.Play(); </code></pre>
[ { "answer_id": 274847, "author": "user38275", "author_id": 38275, "author_profile": "https://Stackoverflow.com/users/38275", "pm_score": 1, "selected": false, "text": "_video.Ending += new System.EventHandler(this.video_stopped);\n\nprivate void video_stopped(object sender, EventArgs e)\n{\n _video.Owner = null;\n}\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38275/" ]
274,806
<p>I have an app built against MVC Preview 3 (referencing local copies of the MVC assemblies) that I'm trying to modify/test on a machine with the ASP.NET MVC beta installed. I am not interesting in updating this app to run against MVC beta yet - I just need to make a few small changes.</p> <p>It's failing with MissingMethodExceptions on RouteCollection.IgnoreRoutes (in global.asax.cs) because at runtime, the CLR is always finding the beta version of System.Web.Mvc in the GAC and loading this instead of the preview 3 version in my site's \bin directory.</p> <p>Since the assemblies have the same name, version and public key, I believe there's no way of distinguishing between them within web.config, so I think the only solution here is to remove the ASP.NET MVC beta assemblies from the GAC.</p> <p>Only - I can't do this, because they're installed by Windows Installer, so I can't remove them using gacutil.exe /u, and I'm getting "Access is denied" when I try and remove them directly.</p> <p>Anyone know how I can remove this assembly - or, failing that, how to run/host an app that needs System.Web.Mvc preview 3 on a system that has System.Web.Mvc beta in the GAC?</p>
[ { "answer_id": 297717, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": 0, "selected": false, "text": "System.Web.Mvc,version=\"1.0.0.0\",culture=\"neutral\",publicKeyToken=\"31BF3856AD364E35\",processorArchitecture=\"MSIL\"\n HKEY_CLASSES_ROOT\\Installer\\Assemblies\\Global\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5017/" ]
274,814
<p>How do I get a list of all the headings in a word document by using VBA?</p>
[ { "answer_id": 274830, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 6, "selected": true, "text": "astrHeadings = docSource.GetCrossReferenceItems(wdRefTypeHeading) Public Sub CreateOutline()\n Dim docOutline As Word.Document\n Dim docSource As Word.Document\n Dim rng As Word.Range\n \n Dim astrHeadings As Variant\n Dim strText As String\n Dim intLevel As Integer\n Dim intItem As Integer\n \n Set docSource = ActiveDocument\n Set docOutline = Documents.Add\n \n ' Content returns only the main body of the document, not the headers/footer. \n Set rng = docOutline.Content\n ' GetCrossReferenceItems(wdRefTypeHeading) returns an array with references to all headings in the document\n astrHeadings = docSource.GetCrossReferenceItems(wdRefTypeHeading)\n \n For intItem = LBound(astrHeadings) To UBound(astrHeadings)\n ' Get the text and the level.\n strText = Trim$(astrHeadings(intItem))\n intLevel = GetLevel(CStr(astrHeadings(intItem)))\n \n ' Add the text to the document.\n rng.InsertAfter strText & vbNewLine\n \n ' Set the style of the selected range and\n ' then collapse the range for the next entry.\n rng.Style = \"Heading \" & intLevel\n rng.Collapse wdCollapseEnd\n Next intItem\nEnd Sub\n\nPrivate Function GetLevel(strItem As String) As Integer\n ' Return the heading level of a header from the\n ' array returned by Word.\n \n ' The number of leading spaces indicates the\n ' outline level (2 spaces per level: H1 has\n ' 0 spaces, H2 has 2 spaces, H3 has 4 spaces.\n \n Dim strTemp As String\n Dim strOriginal As String\n Dim intDiff As Integer\n \n ' Get rid of all trailing spaces.\n strOriginal = RTrim$(strItem)\n \n ' Trim leading spaces, and then compare with\n ' the original.\n strTemp = LTrim$(strOriginal)\n \n ' Subtract to find the number of\n ' leading spaces in the original string.\n intDiff = Len(strOriginal) - Len(strTemp)\n GetLevel = (intDiff / 2) + 1\nEnd Function\n astrHeadings IsArray True TypeName String() type mismatch For Each Paragraph In Doc.TablesOfContents(1).Range.Paragraphs\n WScript.Echo Paragraph.Range.Text\nNext\n" }, { "answer_id": 276397, "author": "JonnyGold", "author_id": 2665, "author_profile": "https://Stackoverflow.com/users/2665", "pm_score": 4, "selected": false, "text": " Sub ReadPara()\n\n Dim DocPara As Paragraph\n\n For Each DocPara In ActiveDocument.Paragraphs\n\n If Left(DocPara.Range.Style, Len(\"Heading\")) = \"Heading\" Then\n\n Debug.Print DocPara.Range.Text\n\n End If\n\n Next\n\n\nEnd Sub\n Left(DocPara.Range.Text, len(DocPara.Range.Text)-1)\n" }, { "answer_id": 11839209, "author": "joshoff", "author_id": 1420823, "author_profile": "https://Stackoverflow.com/users/1420823", "pm_score": 2, "selected": false, "text": "Public Sub CreateOutline()\n' from http://stackoverflow.com/questions/274814/getting-the-headings-from-a-word-document\n Dim docOutline As Word.Document\n Dim docSource As Word.Document\n Dim rng As Word.Range\n\n Dim astrHeadings As Variant\n Dim strText As String\n Dim intLevel As Integer\n Dim intItem As Integer\n Dim minLevel As Integer\n\n Set docSource = ActiveDocument\n Set docOutline = Documents.Add\n\n minLevel = 1 'levels above this value won't be copied.\n minLevel = CInt(InputBox(\"This macro will generate a new document that contains only the headers from the existing document. What is the lowest level heading you want?\", \"2\"))\n\n ' Content returns only the\n ' main body of the document, not\n ' the headers and footer.\n Set rng = docOutline.Content\n astrHeadings = _\n docSource.GetCrossReferenceItems(wdRefTypeHeading)\n\n For intItem = LBound(astrHeadings) To UBound(astrHeadings)\n ' Get the text and the level.\n strText = Trim$(astrHeadings(intItem))\n intLevel = GetLevel(CStr(astrHeadings(intItem)))\n\n If intLevel <= minLevel Then\n\n ' Add the text to the document.\n rng.InsertAfter strText & vbNewLine\n\n ' Set the style of the selected range and\n ' then collapse the range for the next entry.\n rng.Style = \"Heading \" & intLevel\n rng.Collapse wdCollapseEnd\n End If\n Next intItem\nEnd Sub\n\nPrivate Function GetLevel(strItem As String) As Integer\n ' from http://stackoverflow.com/questions/274814/getting-the-headings-from-a-word-document\n ' Return the heading level of a header from the\n ' array returned by Word.\n\n ' The number of leading spaces indicates the\n ' outline level (2 spaces per level: H1 has\n ' 0 spaces, H2 has 2 spaces, H3 has 4 spaces.\n\n Dim strTemp As String\n Dim strOriginal As String\n Dim intDiff As Integer\n\n ' Get rid of all trailing spaces.\n strOriginal = RTrim$(strItem)\n\n ' Trim leading spaces, and then compare with\n ' the original.\n strTemp = LTrim$(strOriginal)\n\n ' Subtract to find the number of\n ' leading spaces in the original string.\n intDiff = Len(strOriginal) - Len(strTemp)\n GetLevel = (intDiff / 2) + 1\nEnd Function\n" }, { "answer_id": 21383033, "author": "dxc", "author_id": 2804729, "author_profile": "https://Stackoverflow.com/users/2804729", "pm_score": 1, "selected": false, "text": "Sub EXTRACT_HDNGS()\nDim WDApp As Word.Application 'WORD APP\nDim WDDoc As Word.Document 'WORD DOC\n\nSet WDApp = Word.Application\nSet WDDoc = WDApp.ActiveDocument\n\nFor Head_n = 1 To 5\nHead = (\"Heading \" & Head_n)\nWDApp.Selection.HomeKey wdStory, wdMove\n\n Do\n With WDApp.selection\n .MoveStart Unit:=wdLine, Count:=1 \n .Collapse Direction:=wdCollapseEnd\n End with\n With WDApp.Selection.Find\n .ClearFormatting: .text = \"\": \n .MatchWildcards = False: .Forward = True\n .Style = WDDoc.Styles(Head)\n If .Execute = False Then GoTo Level_exit\n .ClearFormatting\n End With\n\n Heading_txt = RemoveSpecialChar(WDApp.Selection.Range.text, 1): Debug.Print Heading_txt\n Heading_lvl = WDApp.Selection.Range.ListFormat.ListLevelNumber: Debug.Print Heading_lvl\n Heading_lne = WDDoc.Range(0, WDApp.Selection.Range.End).Paragraphs.Count: Debug.Print Heading_lne\n Heading_pge = WDApp.Selection.Information(wdActiveEndPageNumber): Debug.Print Heading_pge\n\n If Wdapp.Selection.Style = \"Heading 1\" Then GoTo Level_exit\n Wdapp.Selection.Collapse Direction:=wdCollapseStart\n Loop\nLevel_exit:\nNext Head_n\n\nEnd Sub\n" }, { "answer_id": 28363925, "author": "MagTun", "author_id": 3154274, "author_profile": "https://Stackoverflow.com/users/3154274", "pm_score": 1, "selected": false, "text": "Public Sub CopyHeadingsInNewDoc()\n Dim docOutline As Word.Document\n Dim docSource As Word.Document\n Dim rng As Word.Range\n\n Dim astrHeadings As Variant\n Dim strText As String\n Dim longLevel As Integer\n Dim longItem As Integer\n\n Set docSource = ActiveDocument\n Set docOutline = Documents.Add\n\n ' Content returns only the\n ' main body of the document, not\n ' the headers and footer.\n Set rng = docOutline.Content\n astrHeadings = _\n docSource.GetCrossReferenceItems(wdRefTypeHeading)\n\n For intItem = LBound(astrHeadings) To UBound(astrHeadings)\n ' Get the text and the level.\n strText = Trim$(astrHeadings(intItem))\n intLevel = GetLevel(CStr(astrHeadings(intItem)))\n\n ' Add the text to the document.\n rng.InsertAfter strText & vbNewLine\n\n ' Set the style of the selected range and\n ' then collapse the range for the next entry.\n rng.Style = \"Heading \" & intLevel\n rng.Collapse wdCollapseEnd\n Next intItem\nEnd Sub\n\nPrivate Function GetLevel(strItem As String) As Integer\n ' Return the heading level of a header from the\n ' array returned by Word.\n\n ' The number of leading spaces indicates the\n ' outline level (2 spaces per level: H1 has\n ' 0 spaces, H2 has 2 spaces, H3 has 4 spaces.\n\n Dim strTemp As String\n Dim strOriginal As String\n Dim longDiff As Integer\n\n ' Get rid of all trailing spaces.\n strOriginal = RTrim$(strItem)\n\n ' Trim leading spaces, and then compare with\n ' the original.\n strTemp = LTrim$(strOriginal)\n\n ' Subtract to find the number of\n ' leading spaces in the original string.\n longDiff = Len(strOriginal) - Len(strTemp)\n GetLevel = (longDiff / 2) + 1\nEnd Function\n" }, { "answer_id": 41630198, "author": "jumpjack", "author_id": 1635670, "author_profile": "https://Stackoverflow.com/users/1635670", "pm_score": 1, "selected": false, "text": "Sub Macro1()\n ActiveDocument.TablesOfContents.Add Range:=Selection.Range, _\n RightAlignPageNumbers:=True, _\n UseHeadingStyles:=True, _\n UpperHeadingLevel:=1, _\n LowerHeadingLevel:=5, _\n IncludePageNumbers:=True, _\n AddedStyles:=\"\", _\n UseHyperlinks:=True, _\n HidePageNumbersInWeb:=True, _\n UseOutlineLevels:=True\nEnd Sub\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35762/" ]
274,822
<p>How do I check for an open connection in jdbc for oracle database?</p> <p>Note: <code>conn.isClosed()</code> cannot be used for this.</p>
[ { "answer_id": 274870, "author": "RealHowTo", "author_id": 25122, "author_profile": "https://Stackoverflow.com/users/25122", "pm_score": 3, "selected": false, "text": "Statement stmt = null;\nResultSet rs =null;\ntry {\n stmt = conn.createStatement();\n // oracle\n rs = stmt.executeQuery(\"SELECT 1 FROM Dual\");\n // others\n // rs = stmt.executeQuery(\"SELECT 1\");\n if (rs.next())\n return true; // connection is valid\n}\ncatch (SQLException e) {\n // TODO : log the exception ...\n return false;\n}\nfinally {\n if (stmt != null) stmt.close();\n if (rs != null) rs.close();\n} \n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/450206/" ]
274,823
<p>(This is a question about the UI rather than the technology required to do it)</p> <p>What is the clearest way to display a time for events occurring in different timezones to a user? Does your "average" user understand UTC and timezones?</p> <p>We capture the local time and UTC offset and store it in the database (SQL 2008 DateTimeOffset) for events happening in different timezones. Users are also in a variety of timezones.</p> <p>I'll suggest a couple of answers below so they can be rated but I'd appreciate alternative suggestions.</p> <p>EDIT: I'd like to avoid displaying the time in the user's timezone. Users in different timezones will be discussing the same events and if they're local to different timezones, there'll be confusion.</p> <p>EDIT: I wanted to make the question generic and hopefully useful to more people but for some specific context, this is a web application for tracking parcels (think FedEx). Parcels will cross timezones. Customer support is in the UK but the recipient may be elsewhere.</p>
[ { "answer_id": 274832, "author": "Toby Allen", "author_id": 6244, "author_profile": "https://Stackoverflow.com/users/6244", "pm_score": 2, "selected": false, "text": "15:18 GMT+1\n 15:18 CET \n" }, { "answer_id": 327294, "author": "benc", "author_id": 2910, "author_profile": "https://Stackoverflow.com/users/2910", "pm_score": 1, "selected": false, "text": "CU: \"When will it arrive?\" \nCS: \"Based on your phone number, I am assuming you are in EST. The ETA is 8pm\". \nCU: \"I am traveling in Chicago right now. Can you tell me when I should check back?\"\n(Phone rep taps a \"CST\" button on the screen, and the displays convert.) \nCS: \"Sir, if the package does not arrive before 9:10pm, your local time, please call us.\"\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1456/" ]
274,826
<p>When I use <code>DateTime.Now</code> I get the date and time from the server point of view. Is there any way to get the <em>client</em> date and time in ASP.NET?</p>
[ { "answer_id": 274987, "author": "Ryan", "author_id": 29762, "author_profile": "https://Stackoverflow.com/users/29762", "pm_score": 4, "selected": false, "text": "<script language=\"javascript\">\nfunction checkClientTimeZone()\n{\n // Set the client time zone\n var dt = new Date();\n SetCookieCrumb(\"ClientDateTime\", dt.toString());\n\n var tz = -dt.getTimezoneOffset();\n SetCookieCrumb(\"ClientTimeZone\", tz.toString());\n\n // Expire in one year\n dt.setYear(dt.getYear() + 1);\n SetCookieCrumb(\"expires\", dt.toUTCString());\n}\n\n// Attach to the document onload event\ncheckClientTimeZone();\n</script>\n /// <summary>\n/// Returns the client (if available in cookie) or server timezone.\n/// </summary>\npublic static int GetTimeZoneOffset(HttpRequest Request)\n{\n // Default to the server time zone\n TimeZone tz = TimeZone.CurrentTimeZone;\n TimeSpan ts = tz.GetUtcOffset(DateTime.Now);\n int result = (int) ts.TotalMinutes;\n // Then check for client time zone (minutes) in a cookie\n HttpCookie cookie = Request.Cookies[\"ClientTimeZone\"];\n if (cookie != null)\n {\n int clientTimeZone;\n if (Int32.TryParse(cookie.Value, out clientTimeZone))\n result = clientTimeZone;\n }\n return result;\n}\n http://host/page.aspx?tz=-360\n" }, { "answer_id": 11232562, "author": "Yoshida Hiro", "author_id": 1486566, "author_profile": "https://Stackoverflow.com/users/1486566", "pm_score": -1, "selected": false, "text": "Dim strLanguage As String = Request.UserLanguages(0)\nDim currentCulture As CultureInfo = CultureInfo.CreateSpecificCulture(strLanguage)\nDim dateformat As String = currentCulture.DateTimeFormat.ShortDatePattern\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34096/" ]
274,840
<p>I have a Perl module that I would like to use from Java. Is there a way to call this code using either ActiveState Perl on Windows or the generic Perl that comes with Linux? I have found references to JPL but it doesn’t appear to be maintained anymore.</p>
[ { "answer_id": 274849, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 5, "selected": true, "text": "org.perl.inline.java.InlinePerlCaller use Inline Java => <<END ;\nimport java.util.* ;\nimport org.perl.inline.java.* ;\n\nclass Pod_regexp extends InlineJavaPerlCaller {\n public Pod_regexp() throws InlineJavaException {\n }\n\n public boolean match(String target, String pattern)\n throws InlineJavaException {\n try {\n String m = (String)CallPerlSub(\"main::regexp\",\n new Object [] {target, pattern}) ;\n\n if (m.equals(\"1\")){\n return true ;\n }\n }\n catch (InlineJavaPerlException pe){\n // $@ is in pe.GetObject()\n }\n\n return false ;\n }\n}\nEND\n\nmy $re = new Pod_regexp() ;\nmy $match = $re->match(\"Inline::Java\", \"^Inline\") ;\nprint($match . \"n\") ; # prints 1\n\nsub regexp {\n my $target = shift ;\n my $pattern = shift ;\n\n return ($target =~ /$pattern/) ;\n} \n" }, { "answer_id": 274886, "author": "Olie", "author_id": 34820, "author_profile": "https://Stackoverflow.com/users/34820", "pm_score": 3, "selected": false, "text": "Runtime.getRuntime().exec(\"/usr/bin/perl myPerl.pl\");\n" }, { "answer_id": 6824368, "author": "wulfgarpro", "author_id": 512994, "author_profile": "https://Stackoverflow.com/users/512994", "pm_score": 0, "selected": false, "text": "Inline::Java::PerlInterpreter" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14744/" ]
274,841
<p>I am writing multi-thread socket chat in C++Builder 2009.<br> It is almost complete in accordance with what I need to do but I have a little problem. I need to pass the TMemo* pointer into CreateThread WinAPI function which upcasts it to void*.</p> <p>I tryed this way:<br></p> <pre><code>HANDLE xxx = MemoChat-&gt;Handle; hNetThread = CreateThread(NULL, 0, NetThread, xxx, 0, &amp;dwNetThreadId); //... </code></pre> <p>and then, in NetThread function,</p> <pre><code>TMemo* MyMemo((HANDLE)lpParam); TMemo* MyMemo((TMemo*)lpParam); </code></pre> <p>but it didn`t work:(</p> <p>The question is how I can really downcast it correctly so I can use my Memo Component in this new thread?</p>
[ { "answer_id": 274856, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 2, "selected": false, "text": "hNetThread = CreateThread(NULL, 0, NetThread, MemoChat, 0, &dwNetThreadId);\n" }, { "answer_id": 275036, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 3, "selected": true, "text": "TMemo* MemoChat = // You defined that somewhere I assume\nHANDLE hNetThread = CreateThread(NULL, 0, NetThread, MemoChat, 0, &dwNetThreadId);\n DWORD NetThread(LPVOID lpParameter)\n{\n TMemo* MemoChat = reinterpret_cast<TMemo*>(lpParameter);\n // Do your thread stuff here.\n}\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28298/" ]
274,843
<p>I have some elements on a page which are draggable. These same elements have a click event which navigates to another page. I'm trying to determine the best way of preventing the click event from firing if the user is dragging but still allow the click event if not dragging. Anyone have any ideas of the best way to accomplish this?</p>
[ { "answer_id": 274875, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 0, "selected": false, "text": "new Draggable('tag', \n {\n revert:function()\n {\n $('tag').onclick = function(){return false;};\n setTimeout('$(\\'tag\\').onclick = function(){return true;}','500'); \n return true;\n }\n }\n);\n" }, { "answer_id": 276080, "author": "digitalsanctum", "author_id": 22436, "author_profile": "https://Stackoverflow.com/users/22436", "pm_score": 2, "selected": true, "text": "new Draggable('id', {\n onStart: function() {\n dPhoto = $('id');\n Event.stopObserving('id', 'click');\n },\n onEnd : function() {\n setTimeout(\"Event.observe('id', 'click', function() { location.href = 'url'; });\", 500);\n },\n revert: true\n});\n" }, { "answer_id": 364164, "author": "Tony", "author_id": 45849, "author_profile": "https://Stackoverflow.com/users/45849", "pm_score": 1, "selected": false, "text": "var click_func;\nfunction onDragStart(drgObj,mouseEvent){\n click_func = mouseEvent.target.onclick;\n\n mouseEvent.target.onclick = function(e){\n mouseEvent.target.onclick = click_func;\n return false;\n }\n}\n" }, { "answer_id": 2675063, "author": "Stanley85", "author_id": 321286, "author_profile": "https://Stackoverflow.com/users/321286", "pm_score": 0, "selected": false, "text": "function onDragStart() {\n Event.stopObserving(this.OBJECT,'click');\n Event.observe(this.OBJECT,'click',this.onDragEnd.bindAsEventListener(this));\n}\n\nfunction onDragEnd() {\n Event.stopObserving(this.OBJECT,'click');\n Event.observe(this.OBJECT,'click',this.PREVIOUSFUNCTION.bindAsEventListener(this));\n}\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22436/" ]
274,857
<p>is there an easy way to reset ALL text fields in an asp.net form - like the reset button for html controls?</p>
[ { "answer_id": 274866, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "document.forms[0].reset();\n theForm.reset(); // at least with ASP.NET 2.0\n <input type='button' id='resetButton' value='Reset' onclick='theForm.reset();return false;' //>\n" }, { "answer_id": 274871, "author": "aanund", "author_id": 7335, "author_profile": "https://Stackoverflow.com/users/7335", "pm_score": 3, "selected": false, "text": "Response.Redirect(Request.Url.PathAndQuery, true);\n" }, { "answer_id": 274929, "author": "Stefan", "author_id": 30604, "author_profile": "https://Stackoverflow.com/users/30604", "pm_score": 0, "selected": false, "text": "function resetForm() \n{ \n var inputs = document.getElementsByTagName('input'); \n for(var i=0;i<inputs.length;i++) \n { \n if(input[i].type == 'text')\n input[i].value = \"\";\n }\n}\n" }, { "answer_id": 11346965, "author": "Dubs", "author_id": 2842, "author_profile": "https://Stackoverflow.com/users/2842", "pm_score": -1, "selected": false, "text": "form1.Controls.Clear()\n" }, { "answer_id": 13510529, "author": "ocean4dream", "author_id": 1550794, "author_profile": "https://Stackoverflow.com/users/1550794", "pm_score": 3, "selected": false, "text": "<asp:Button ID=\"btnReset\" runat=\"server\" Text=\"Reset\" \nOnClientClick=\"this.form.reset();return false;\" />\n" }, { "answer_id": 14347701, "author": "Bat_Programmer", "author_id": 475709, "author_profile": "https://Stackoverflow.com/users/475709", "pm_score": 3, "selected": false, "text": "<input type=\"reset\" value=\"Clear\" />\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
274,861
<p>If I have a date, how do I calculate the week number for that date within that year?</p> <p>For example, in 2008, January 1st to January 6th are in week 1 and January 7th to the 13th are in week 2, so if my date was January 10th 2008, my week number would be 2.</p> <p>An algorithm would be great to get me started and sample code would also help - I'm developing in C++ on Windows.</p> <h3>Related:</h3> <blockquote> <p><a href="https://stackoverflow.com/questions/348880/getting-week-number-off-a-date-in-ms-sql-server-2005">Getting week number off a date in MS SQL Server 2005?</a></p> </blockquote>
[ { "answer_id": 274913, "author": "Olie", "author_id": 34820, "author_profile": "https://Stackoverflow.com/users/34820", "pm_score": 6, "selected": true, "text": "int julian = getDayOfYear(myDate) // Jan 1 = 1, Jan 2 = 2, etc...\nint dow = getDayOfWeek(myDate) // Sun = 0, Mon = 1, etc...\nint dowJan1 = getDayOfWeek(\"1/1/\" + thisYear) // find out first of year's day\n// int badWeekNum = (julian / 7) + 1 // Get our week# (wrong! Don't use this)\nint weekNum = ((julian + 6) / 7) // probably better. CHECK THIS LINE. (See comments.)\nif (dow < dowJan1) // adjust for being after Saturday of week #1\n ++weekNum;\nreturn (weekNum)\n S M T W R F S\n 1 2 3 <-- week #1\n4 5 6 7 8 9 10 <-- week #2\n[etc.]\n" }, { "answer_id": 274914, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 2, "selected": false, "text": "int firstdays[7] = { 0, -1, -2, -3, -4, 2, 1 }; // or some other Week 1 rule\nstruct tm breakdown;\ntime_t target = time_you_care_about();\n_gmtime_s(&breakdown,&target);\nint dayofweek = breakdown.tm_wday;\nint dayofyear = breakdown.tm_yday;\n\nint jan1wday = (dayofweek - dayofyear) % 7;\nif (jan1wday < 0) jan1wday += 7;\n\nint week1first = firstdays[jan1wday];\nif (dayofyear < week1first) return 0;\nreturn ((dayofyear - week1first)/7) + 1;\n" }, { "answer_id": 275024, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 5, "selected": false, "text": "-- { } -- @(#)$Id: iso8601_weekday.spl,v 1.1 2001/04/03 19:34:43 jleffler Exp $\n--\n-- Calculate ISO 8601 Week Number for given date\n-- Defines procedure: iso8601_weekday().\n-- Uses procedure: iso8601_weeknum().\n\n{\nAccording to a summary of the ISO 8601:1988 standard \"Data Elements and\nInterchange Formats -- Information Interchange -- Representation of\ndates and times\":\n\n The week notation can also be extended by a number indicating the\n day of the week. For example the day 1996-12-31 which is the\n Tuesday (day 2) of the first week of 1997 can also be written as\n\n 1997-W01-2 or 1997W012\n\n for applications like industrial planning where many things like\n shift rotations are organized per week and knowing the week number\n and the day of the week is more handy than knowing the day of the\n month.\n\nThis procedure uses iso8601_weeknum() to format the YYYY-Www part of the\ndate, and appends '-d' to the result, allowing for Informix's coding of\nSunday as day 0 rather than day 7 as required by ISO 8601.\n}\n\nCREATE PROCEDURE iso8601_weekday(dateval DATE DEFAULT TODAY) RETURNING CHAR(10);\n DEFINE rv CHAR(10);\n DEFINE dw CHAR(4);\n LET dw = WEEKDAY(dateval);\n IF dw = 0 THEN\n LET dw = 7;\n END IF;\n RETURN iso8601_weeknum(dateval) || '-' || dw;\nEND PROCEDURE;\n-- @(#)$Id: iso8601_weeknum.spl,v 1.1 2001/02/27 20:36:25 jleffler Exp $\n--\n-- Calculate ISO 8601 Week Number for given date\n-- Defines procedures: day_one_week_one() and iso8601_weeknum().\n\n{\nAccording to a summary of the ISO 8601:1988 standard \"Data Elements and\nInterchange Formats -- Information Interchange -- Representation of\ndates and times\":\n\n In commercial and industrial applications (delivery times,\n production plans, etc.), especially in Europe, it is often required\n to refer to a week of a year. Week 01 of a year is per definition\n the first week which has the Thursday in this year, which is\n equivalent to the week which contains the fourth day of January. In\n other words, the first week of a new year is the week which has the\n majority of its days in the new year. Week 01 might also contain\n days from the previous year and the week before week 01 of a year is\n the last week (52 or 53) of the previous year even if it contains\n days from the new year. A week starts with Monday (day 1) and ends\n with Sunday (day 7). For example, the first week of the year 1997\n lasts from 1996-12-30 to 1997-01-05 and can be written in standard\n notation as\n\n 1997-W01 or 1997W01\n\n The week notation can also be extended by a number indicating the\n day of the week. For example the day 1996-12-31 which is the\n Tuesday (day 2) of the first week of 1997 can also be written as\n\n 1997-W01-2 or 1997W012\n\n for applications like industrial planning where many things like\n shift rotations are organized per week and knowing the week number\n and the day of the week is more handy than knowing the day of the\n month.\n\nReferring to the standard itself, section 3.17 defines a calendar week:\n\n week, calendar: A seven day period within a calendar year, starting\n on a Monday and identified by its ordinal number within the year;\n the first calendar week of the year is the one that includes the\n first Thursday of that year. In the Gregorian calendar, this is\n equivalent to the week which includes 4 January.\n\nSection 5.2.3 \"Date identified by Calendar week and day numbers\" states:\n\n Calendar week is represented by two numeric digits. The first\n calendar week of a year shall be identified as 01 [...]\n\n Day of the week is represented by one decimal digit. Monday\n shall be identified as day 1 of any calendar week [...]\n\nSection 5.2.3.1 \"Complete representation\" states:\n\n When the application clearly identifies the need for a complete\n representation of a date identified by calendar week and day\n numbers, it shall be one of the alphanumeric representations as\n follows, where CCYY represents a calendar year, W is the week\n designator, ww represents the ordinal number of a calendar week\n within the year, and D represents the ordinal number within the\n calendar week.\n\n Basic format: CCYYWwwD\n Example: 1985W155\n Extended format: CCYY-Www-D\n Example: 1985-W15-5\n\nBoth the summary and the formal definition are intuitively clear, but it\nis not obvious how to translate it into an algorithm. However, we can\ndeal with the problem by exhaustively enumerating the seven options for\nthe day of the week on which 1st January falls (with actual year values\nfor concreteness):\n\n 1st January 2001 is Monday => Week 1 starts on 2001-01-01\n 1st January 2002 is Tuesday => Week 1 starts on 2001-12-31\n 1st January 2003 is Wednesday => Week 1 starts on 2002-12-30\n 1st January 2004 is Thursday => Week 1 starts on 2003-12-29\n 1st January 2010 is Friday => Week 1 starts on 2010-01-04\n 1st January 2005 is Saturday => Week 1 starts on 2005-01-03\n 1st January 2006 is Sunday => Week 1 starts on 2006-01-02\n\n(Cross-check: 1st January 1997 was a Wednesday; the summary notes state\nthat week 1 of 1997 started on 1996-12-30, which is consistent with the\ntable derived for dates in the first decade of the third millennium\nabove).\n\nWhen working with the Informix DATE types, bear in mind that Informix\nuses WEEKDAY values 0 = Sunday, 1 = Monday, 6 = Saturday. When the\nweekday of the first of January has the value in the LH column, you need\nto add the value in the RH column to the 1st of January to obtain the\ndate of the first day of the first week of the year.\n\n Weekday Offset to\n 1st January 1st day of week 1\n\n 0 +1\n 1 0\n 2 -1\n 3 -2\n 4 -3\n 5 +3\n 6 +2\n\nThis can be written as MOD(11-w,7)-3 where w is the (Informix encoding\nof the) weekday of 1st January and the value 11 is used to ensure that\nno negative values are presented to the MOD operator. Hence, the\nexpression for the date corresponding to the 1st day (Monday) of the 1st\nweek of a given year, yyyy, is:\n\n d1w1 = MDY(1, 1, yyyy) + MOD(11 - WEEKDAY(MDY(1,1,yyyy)), 7) - 3\n\nThis expression is encapsulated in stored procedure day_one_week_one:\n}\n\nCREATE PROCEDURE day_one_week_one(yyyy INTEGER) RETURNING DATE;\n DEFINE jan1 DATE;\n LET jan1 = MDY(1, 1, yyyy);\n RETURN jan1 + MOD(11 - WEEKDAY(jan1), 7) - 3;\nEND PROCEDURE;\n\n{\nGiven this date d1w1, we can calculate the week number of any other date\nin the same year as:\n\n TRUNC((dateval - d1w1) / 7) + 1\n\nThe residual issues are ensuring that the wraparounds are correct. If\nthe given date is earlier than the start of the first week of the year\nthat contains it, then the date belongs to the last week of the previous\nyear. If the given date is on or after the start of the first week of\nthe next year, then the date belongs to the first week of the next year.\n\nGiven these observations, we can write iso8601_weeknum as shown below.\n(Beware: iso8601_week_number() is too long for servers with the\n18-character limit; so is day_one_of_week_one()).\n\nThen comes the interesting testing phase -- when do you get week 53?\nOne answer is on Friday 1st January 2010, which is in 2009-W53 (as,\nindeed, is Sunday 3rd January 2010). Similarly, Saturday 1st January\n2005 is in 2004-W53, but Sunday 1st January 2006 is in 2005-W52.\n}\n\nCREATE PROCEDURE iso8601_weeknum(dateval DATE DEFAULT TODAY) RETURNING CHAR(8);\n DEFINE rv CHAR(8);\n DEFINE yyyy CHAR(4);\n DEFINE ww CHAR(2);\n DEFINE d1w1 DATE;\n DEFINE tv DATE;\n DEFINE wn INTEGER;\n DEFINE yn INTEGER;\n -- Calculate year and week number.\n LET yn = YEAR(dateval);\n LET d1w1 = day_one_week_one(yn);\n IF dateval < d1w1 THEN\n -- Date is in early January and is in last week of prior year\n LET yn = yn - 1;\n LET d1w1 = day_one_week_one(yn);\n ELSE\n LET tv = day_one_week_one(yn + 1);\n IF dateval >= tv THEN\n -- Date is in late December and is in the first week of next year\n LET yn = yn + 1;\n LET d1w1 = tv;\n END IF;\n END IF;\n LET wn = TRUNC((dateval - d1w1) / 7) + 1;\n -- Calculation complete: yn is year number and wn is week number.\n -- Format result.\n LET yyyy = yn;\n IF wn < 10 THEN\n LET ww = '0' || wn;\n ELSE\n LET ww = wn;\n END IF\n LET rv = yyyy || '-W' || ww;\n RETURN rv;\nEND PROCEDURE;\n day_one_week_one() -- @(#)$Id: ywd_date.spl,v 1.1 2012/12/29 05:13:27 jleffler Exp $\n-- @(#)Create ywd_date() and ywdstr_date() stored procedures\n\n-- Convert a date in format year, week, day (ISO 8601) to DATE.\n-- Two variants:\n-- ywd_date(yyyy SMALLINT, ww SMALLINT, dd SMALLINT) RETURNING DATE;\n-- ywdstr_date(ywd CHAR(10)) RETURNING DATE;\n\n-- NB: If week 53 is supplied, there is no check that the year had week\n-- 53 (GIGO).\n-- NB: If year yyyy is a leap year and yyyy-01-01 falls on Wed (3) or\n-- Thu (4), there are 53 weeks in the year.\n-- NB: If year yyyy is not a leap year and yyyy-01-01 falls on Thu (4),\n-- there are 53 weeks in the year.\n\nCREATE PROCEDURE ywd_date(yyyy SMALLINT, ww SMALLINT, dd SMALLINT) RETURNING DATE AS date;\n DEFINE d DATE;\n -- Check ranges\n IF yyyy < 1 OR yyyy > 9999 OR ww < 1 OR ww > 53 OR dd < 1 OR dd > 7 THEN\n RETURN NULL;\n END IF;\n LET d = day_one_week_one(yyyy);\n LET d = d + (ww - 1) * 7 + (dd - 1);\n RETURN d;\nEND PROCEDURE;\n\n-- Input: 2012-W52-5\nCREATE PROCEDURE ywdstr_date(ywd CHAR(10)) RETURNING DATE AS date;\n DEFINE yyyy SMALLINT;\n DEFINE ww SMALLINT;\n DEFINE dd SMALLINT;\n LET yyyy = SUBSTR(ywd, 1, 4);\n LET ww = SUBSTR(ywd, 7, 2);\n LET dd = SUBSTR(ywd, 10, 1);\n RETURN ywd_date(yyyy, ww, dd);\nEND PROCEDURE;\n\nCREATE TEMP TABLE test_dates(d DATE);\nINSERT INTO test_dates VALUES('2011-12-28');\nINSERT INTO test_dates VALUES('2011-12-29');\nINSERT INTO test_dates VALUES('2011-12-30');\nINSERT INTO test_dates VALUES('2011-12-31');\nINSERT INTO test_dates VALUES('2012-01-01');\nINSERT INTO test_dates VALUES('2012-01-02');\nINSERT INTO test_dates VALUES('2012-01-03');\nINSERT INTO test_dates VALUES('2012-01-04');\nINSERT INTO test_dates VALUES('2012-01-05');\nINSERT INTO test_dates VALUES('2012-01-06');\nINSERT INTO test_dates VALUES('2012-01-07');\n\nSELECT d, iso8601_weeknum(d), iso8601_weekday(d), ywdstr_date(iso8601_weekday(d))\n FROM test_dates\n ORDER BY d;\n" }, { "answer_id": 275067, "author": "Emerick Rogul", "author_id": 33837, "author_profile": "https://Stackoverflow.com/users/33837", "pm_score": 3, "selected": false, "text": "strftime struct tm #include <stdio.h>\n#include <string.h>\n#include <time.h>\n\nint\nmain(void)\n{\n struct tm tm;\n char timebuf[64];\n\n // Zero out struct tm\n memset(&tm, 0, sizeof tm);\n\n // November 4, 2008 11:00 pm\n tm.tm_sec = 0;\n tm.tm_min = 0;\n tm.tm_hour = 23;\n tm.tm_mday = 4;\n tm.tm_mon = 10;\n tm.tm_year = 108;\n tm.tm_isdst = -1;\n\n // Call mktime to recompute tm.tm_wday and tm.tm_yday\n mktime(&tm);\n\n if (strftime(timebuf, sizeof timebuf, \"%W\", &tm) != 0) {\n printf(\"Week number is: %s\\n\", timebuf);\n }\n\n return 0;\n}\n Week number is: 44\n" }, { "answer_id": 1017188, "author": "Pascalo", "author_id": 121941, "author_profile": "https://Stackoverflow.com/users/121941", "pm_score": 2, "selected": false, "text": "int julian = getDayOfYear(myDate) // Jan 1 = 1, Jan 2 = 2, etc...\nint dow = getDayOfWeek(myDate) // Sun = 0, Mon = 1, etc...\nint dowJan1 = getDayOfWeek(\"1/1/\" + thisYear) // find out first of year's day\nint weekNum = (julian / 7) + 1 // Get our week#\nif (dow < dowJan1) // adjust for being after Saturday of week #1\n ++weekNum;\nreturn (weekNum)\n getDayOfWeek(\"12/31/\" + thisYear-1)\n getDayOfWeek(\"1/1/\" + thisYear) \n" }, { "answer_id": 2814420, "author": "Marius", "author_id": 174650, "author_profile": "https://Stackoverflow.com/users/174650", "pm_score": 1, "selected": false, "text": "// week number of the year\n// (Monday as the first day of the week) as a decimal number [00,53].\n// All days in a new year preceding the first Monday are considered to be in week 0.\nint GetWeek(const struct tm& ts)\n{\n return (ts.tm_yday + 7 - (ts.tm_wday ? (ts.tm_wday - 1) : 6)) / 7;\n}\n" }, { "answer_id": 12608103, "author": "pasx", "author_id": 683319, "author_profile": "https://Stackoverflow.com/users/683319", "pm_score": 0, "selected": false, "text": "tm t = ... //the date on which to find week of year\n\nint wy = -1;\n\nstruct tm t1;\nt1.tm_year = t.tm_year;\nt1.tm_mday = t1.tm_mon = 1; //set to 1st of January\ntime_t tt = mktime(&t1); //compute tm\n\n//remove days for 1st week\nint yd = t.tm_yday - (7 - t1.tm_wday);\nif(yd <= 0 ) //first week is now negative\n wy = 0;\nelse\n wy = (int)std::ceil( (double) ( yd/7) ); //second week will be 1 \n" }, { "answer_id": 16536256, "author": "raghu", "author_id": 2380353, "author_profile": "https://Stackoverflow.com/users/2380353", "pm_score": 2, "selected": false, "text": "public int GetWeekOfYear(DateTime todayDate)\n{\n int days = todayDate.DayOfYear;\n float result = days / 7;\n result=result+1;\n Response.Write(result.ToString());\n return Convert.ToInt32(result);\n}\n" }, { "answer_id": 24907972, "author": "MINH_NV", "author_id": 3458028, "author_profile": "https://Stackoverflow.com/users/3458028", "pm_score": 0, "selected": false, "text": "time_t t = time(NULL);\ntm* timePtr = localtime(&t);\ndouble day_of_year=timePtr->tm_yday +1 ; // 1-365\nint week_of_year =(int) ceill(day_of_year/7.0);\n" }, { "answer_id": 34437838, "author": "Leslie Satenstein", "author_id": 1445782, "author_profile": "https://Stackoverflow.com/users/1445782", "pm_score": -1, "selected": false, "text": "/**\n * @brief WeekNo\n * @param yr\n * @param mon\n * @param day\n * @param iso\n * @return\n *\n * Given a date, return the week number\n * Note. The first week of the year begins on the Monday\n * following the previous Thursday\n * Follows ISO 8601\n *\n * Mutually equivalent definitions for week 01 are:\n *\n * the week with the year's first Thursday in it (the ISO 8601 definition)\n * the week with the Thursday in the period 1 – 7 January\n * the week starting with the Monday in the period 29 December – 4 January\n * the week starting with the Monday which is nearest in time to 1 January\n * the week ending with the Sunday in the period 4 – 10 January\n * the week with 4 January in it\n * the first week with the majority (four or more) of its days in the starting year\n * If 1 January is on a Monday, Tuesday, Wednesday or Thursday, it is in week 01.\n * If 1 January is on a Friday, Saturday or Sunday, it is part of week 52 or 53 of the previous year.\n * the week with the year's first working day in it (if Saturdays, Sundays, and 1 January are not working days).\n *** strftime has a conversion of struct tm to weeknumber. strptime fills in tm struct**\n * Code uses strptime, strftime functions.\n */\n\nint WeekNo( int yr,int mon, int day, int iso)\n{\n struct tm tm;\n char format[32];\n //memset(tm,0,sizeof(tm));\n sprintf(format,\"%d-%02d-%02d\",yr,mon,day);\n strptime(format, \"%Y-%m-%d\", &tm);\n // structure tm is now filled in for strftime\n\n strftime(format, sizeof(format), iso? \"%V\":\"%U\", &tm);\n\n //puts(format);\n return atoi(format);\n}\n" }, { "answer_id": 49425030, "author": "Arun Rao", "author_id": 9533750, "author_profile": "https://Stackoverflow.com/users/9533750", "pm_score": 1, "selected": false, "text": "NoOfDays = (CurrentDate - YearStartDate)+1\nIF NoOfDays MOD 7 = 0 Then\n WeekNo = INT(NoOfDays/7)\nELSE\n WeekNo = INT(NoOfDays/7)+1\nEND \n" }, { "answer_id": 55987057, "author": "Remis", "author_id": 3737891, "author_profile": "https://Stackoverflow.com/users/3737891", "pm_score": 1, "selected": false, "text": "iso_week.h #include <iostream>\n#include \"iso_week.h\"\n\nint main() {\n using namespace iso_week;\n using namespace std::chrono;\n // Get the current time_point and floor to convert to the sys_days:\n auto today = floor<days>(system_clock::now());\n // Convert from sys_days to iso_week::year_weeknum_weekday format\n auto yww = year_weeknum_weekday{today};\n // Print current week number of the year\n std::cout << \"The current week of \" << yww.year() << \" is: \" \n << yww.weeknum() << std::endl;\n\n // Set any day\n auto any_day = 2014_y/9/28;\n // Get week of `any_day`\n std::cout << \"The week of \" << any_day.year() << \" on `any day` was: \" \n << any_day.weeknum() << std::endl; \n}\n The current week of 2019 is: W18\nThe week in 2014 on `any day` was: W09\n" }, { "answer_id": 60531141, "author": "afull", "author_id": 13007429, "author_profile": "https://Stackoverflow.com/users/13007429", "pm_score": 2, "selected": false, "text": "/**********************************************************************************\nFunction Name: rtcCalcYearWeek\nDescription : Function to calculate the working week of the year (changing on a Monday)\nArguments : IN iYear - The year 2000...\n IN iMonth - The month 1..12\n IN iDay - The day 1..31\n IN iWeekDay - The week day 0 = Monday ... 6 = Sunday\nReturn Value : The year week 1..52\n***********************************************************************************/\nint rtcCalcYearWeek(int iYear, int iMonth, int iDay, int iWeekDay)\n{\n int iLeap = 0;\n static const int ppiYearDays[2][13] =\n {\n /* Normal year */\n {0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334},\n /* Leap year */\n {0, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335}\n };\n /* Check for leap year */\n if (((iYear % 4) == 0) && (((iYear % 100) != 0) || ((iYear % 400) == 0)))\n {\n iLeap = 1;\n }\n /* Calculate the year week */\n return (((ppiYearDays[iLeap][iMonth] + iDay) - (iWeekDay + 7) % 7 + 7) / 7) + 1;\n}\n/***********************************************************************************\nEnd of function rtcCalcYearWeek\n***********************************************************************************/\n\n/**********************************************************************************\n* Function Name: rtcCalcWeekDay\n* Description : Function to calculate the week day for a given date from 2000\n* to 2099.\n* Arguments : IN iDay - The day 1..31\n* IN iMonth - The month 1..12\n* IN iYear - The year 2000..2099\n* Return Value : The weekday 0 = Monday ... 6 = Sunday\n***********************************************************************************/\nint rtcCalcWeekDay(int iDay, int iMonth, int iYear)\n{\n if (iMonth < 3)\n {\n iMonth += 12;\n iYear -= 1;\n }\n return (iDay + (2 * iMonth) + (6 * (iMonth + 1) / 10) + iYear \n + (iYear / 4)- (iYear / 100) + (iYear / 400)) % 7;\n}\n/***********************************************************************************\nEnd of function rtcCalcWeekDay\n***********************************************************************************/\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15669/" ]
274,865
<p>I am modifying some code and came across a declaration that I am having trouble understanding:</p> <pre><code>int *userMask[3][4] = {0}; </code></pre> <p>What exactly is this pointing to? Is it a matrix where every element is a pointer? Or is it pointing to a matrix of size [3][4]?</p> <p>Thanks</p> <hr> <p>I guess my question is how <code>userMask[2][maskElement][user]</code> can work when it is declared as <code>int</code>. Wouldn't userMask have to be <code>int[]</code> for that to work properly? I must not be understanding this right...</p> <p>On a side note, thanks for your suggestion about cdecl Robert. However, does anyone know how to use it in an XP command prompt? All I can get is syntax error :(</p>
[ { "answer_id": 274869, "author": "ChrisN", "author_id": 3853, "author_profile": "https://Stackoverflow.com/users/3853", "pm_score": 4, "selected": false, "text": "int if(userMask[2][maskElement][user] && blah)\n result = true;\n userMask int int* int int userMask int userArray[2] = { 10, 20 };\n\nuserMask[0][0] = userArray; // userMask[0][0] points to the\n // first element of userArray.\n userArray int value = userMask[0][0][1]; // sets value = userArray[1], giving 20.\n" }, { "answer_id": 274874, "author": "martjno", "author_id": 3373, "author_profile": "https://Stackoverflow.com/users/3373", "pm_score": -1, "selected": false, "text": "int userMask[3][4]={0};\n" }, { "answer_id": 274878, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 4, "selected": false, "text": "int *userMask[3][4] = {0};\n int (*userMask)[3][4];\n cdecl cdecl> explain int *userMask[3][4]\ndeclare userMask as array 3 of array 4 of pointer to int\n cdecl> declare userMask as pointer to array 3 of array 4 of int\nint (*userMask)[3][4]\n" }, { "answer_id": 274897, "author": "pdc", "author_id": 8925, "author_profile": "https://Stackoverflow.com/users/8925", "pm_score": 0, "selected": false, "text": "userMask[2] int*[] userMask[2][maskElement] int* userMask[2][maskElement][user] int int *userMask[3][4] = {0};\n int *userMask[3][4] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}};\n (int*)0" }, { "answer_id": 274943, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 6, "selected": true, "text": "int *userMask[3][4];\n userMask int*[3][4] int* userMask[2][maskElement][user]\n int * p = userMask[2][maskElement];\n p[user]\n userMask[2][maskElement][user] int * userMask[3][4] = { { 0 } };\nint ** pa = userMask[2]; /* int*[4] becomes int** implicitly */\nint * pi = pa[maskElement];\nint i = pi[user];\n\nassert(i == userMask[2][maskElement][user]);\n int array[5][4][3];\n/* int[4][3] implicitly converts to int(*)[3] (pointer to first element) */\nint (*parray)[3] = array[0]; \nint ** pint = (int**) array[0]; /* wrong!! */\n parray[1] pint[1] sizeof(int[3]) 3 * sizeof(int) sizeof( int* ) array[0][1] ( char * )array[0] + sizeof( int* ) pint[1] int* 0x00 pint[1][0]" }, { "answer_id": 274944, "author": "tabdamage", "author_id": 28022, "author_profile": "https://Stackoverflow.com/users/28022", "pm_score": 0, "selected": false, "text": "type variablename[array_spec];\n int* i;\nint the_int_behind_i = *(i+1);\nint also_the_int_behind_i = i[1];\n" }, { "answer_id": 274971, "author": "Charlie Martin", "author_id": 35092, "author_profile": "https://Stackoverflow.com/users/35092", "pm_score": 2, "selected": false, "text": "int *userMask[3][4] = {0};\n userMask\n userMask[3] \n userMask[3][4] \n userMask[3] int *\n userMask int = {0} 0 int *userMask[3][4] = {0};\n" }, { "answer_id": 274985, "author": "Charlie Martin", "author_id": 35092, "author_profile": "https://Stackoverflow.com/users/35092", "pm_score": 2, "selected": false, "text": "if(userMask[2][maskElement][user] && blah)\n result = true;\n p[i] *(p+i) userMask[2][maskElement][user]\n *((userMask[2][maskElement])+user)\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35767/" ]
274,892
<p>I have information spread out across a few databases and want to put all the information onto one webpage using PHP. I was wondering how I can connect to multiple databases on a single PHP webpage.</p> <p>I know how to connect to a single database using:</p> <pre><code>$dbh = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL"); </code></pre> <p>However, can I just use multiple "mysql_connect" commands to open the other databases, and how would PHP know what database I want the information pulled from if I do have multiple databases connected.</p>
[ { "answer_id": 274919, "author": "Tom Haigh", "author_id": 22224, "author_profile": "https://Stackoverflow.com/users/22224", "pm_score": 9, "selected": true, "text": "mysql_xx mysqli_xx mysql_connect() $new_link $dbh1 = mysql_connect($hostname, $username, $password); \n$dbh2 = mysql_connect($hostname, $username, $password, true); \n\nmysql_select_db('database1', $dbh1);\nmysql_select_db('database2', $dbh2);\n mysql_query('select * from tablename', $dbh1);\n mysql_query('select * from tablename', $dbh2);\n $dbh2 mysql_query('select * from tablename');\n mysql_select_db() SELECT * FROM database2.tablename" }, { "answer_id": 275013, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 7, "selected": false, "text": "try {\n $db = new PDO('mysql:dbname=databasename;host=127.0.0.1', 'username', 'password');\n} catch (PDOException $ex) {\n echo 'Connection failed: ' . $ex->getMessage();\n}\n $result = $db->query(\"select * from tablename\");\nforeach ($result as $row) {\n echo $row['foo'] . \"\\n\";\n}\n $stmt = $db->prepare(\"select * from tablename where id = :id\");\n$stmt->execute(array(':id' => 42));\n$row = $stmt->fetch();\n try {\n $db1 = new PDO('mysql:dbname=databas1;host=127.0.0.1', 'username', 'password');\n $db2 = new PDO('mysql:dbname=databas2;host=127.0.0.1', 'username', 'password');\n} catch (PDOException $ex) {\n echo 'Connection failed: ' . $ex->getMessage();\n}\n" }, { "answer_id": 11681005, "author": "Michael Ratcliffe", "author_id": 1233967, "author_profile": "https://Stackoverflow.com/users/1233967", "pm_score": 2, "selected": false, "text": "$con = new PDO('mysql:host=localhost', $username, $password, \n array(PDO::ATTR_PERSISTENT => true));\n dbname= USE dbname PDO::exec() $con->exec(\"USE someDatabase\");\n$con->exec(\"USE anotherDatabase\");\n" }, { "answer_id": 15000921, "author": "Paks", "author_id": 2095172, "author_profile": "https://Stackoverflow.com/users/2095172", "pm_score": 3, "selected": false, "text": " $conn = mysql_connect(\"hostname\",\"username\",\"password\");\n mysql_select_db(\"db1\",$conn);\n mysql_select_db(\"db2\",$conn);\n\n $query1 = \"SELECT * FROM db1.table\";\n $query2 = \"SELECT * FROM db2.table\";\n $rs = mysql_query($query1);\nwhile($row = mysql_fetch_assoc($rs)) {\n $data1[] = $row;\n}\n\n$rs = mysql_query($query2);\nwhile($row = mysql_fetch_assoc($rs)) {\n $data2[] = $row;\n}\n\nprint_r($data1);\nprint_r($data2);\n" }, { "answer_id": 18506596, "author": "Lazy Fellow", "author_id": 1578851, "author_profile": "https://Stackoverflow.com/users/1578851", "pm_score": 2, "selected": false, "text": "$dbh1 = mysql_connect($hostname, $username, $password); \n$dbh2 = mysql_connect($hostname, $username, $password, true); \n\nmysql_select_db('database1', $dbh1); \nmysql_select_db('database2',$dbh2); \n\nmysql_query('select * from tablename', $dbh1);\nmysql_query('select * from tablename', $dbh2);\n" }, { "answer_id": 19010747, "author": "Ihsan Kusasi", "author_id": 2720077, "author_profile": "https://Stackoverflow.com/users/2720077", "pm_score": 3, "selected": false, "text": "CREATE VIEW another_table AS SELECT * FROM another_database.another_table;\n" }, { "answer_id": 25114222, "author": "user3857891", "author_id": 3857891, "author_profile": "https://Stackoverflow.com/users/3857891", "pm_score": 2, "selected": false, "text": "$Db1 = new mysqli('$DB_HOST','USERNAME','PASSWORD'); // 1st database connection \n$Db2 = new mysqli('$DB_HOST','USERNAME','PASSWORD'); // 2nd database connection\n $query = $Db1->query(\"select * from tablename\")\n$query2 = $Db2->query(\"select * from tablename\")\ndie(\"$Db1->error\");\n" }, { "answer_id": 29739049, "author": "kaushik", "author_id": 2206657, "author_profile": "https://Stackoverflow.com/users/2206657", "pm_score": 3, "selected": false, "text": "$Db1 = new mysqli($hostname,$username,$password,$db_name1); \n// this is connection 1 for DB 1\n\n$Db2 = new mysqli($hostname,$username,$password,$db_name2); \n// this is connection 2 for DB 2\n" }, { "answer_id": 42818799, "author": "Kamal Bunkar", "author_id": 1302648, "author_profile": "https://Stackoverflow.com/users/1302648", "pm_score": 1, "selected": false, "text": "define('HOST','localhost');\ndefine('USER','user');\ndefine('PASS','passs');\ndefine('**DB1**','database_name1');\n\n$connMitra = new mysqli(HOST, USER, PASS, **DB1**);\n define('HOST','localhost');\n define('USER','user');\n define('PASS','passs');\n define(**'DB2**','database_name1');\n\n $connMitra = new mysqli(HOST, USER, PASS, **DB2**);\n" }, { "answer_id": 45688265, "author": "Nagibaba", "author_id": 6170191, "author_profile": "https://Stackoverflow.com/users/6170191", "pm_score": 2, "selected": false, "text": "select_db DB1 DB2 GRANT select ON DB2.* TO DB1@localhost; FLUSH PRIVILEGES; SELECT DB1.TABLE1.id, DB2.TABLE1.username FROM DB1,DB2" }, { "answer_id": 55899580, "author": "htngapi", "author_id": 4010310, "author_profile": "https://Stackoverflow.com/users/4010310", "pm_score": -1, "selected": false, "text": "<?php\n // Sapan Mohanty\n // Skype:sapan.mohannty\n //***********************************\n $oldData = mysql_connect('localhost', 'DBUSER', 'DBPASS');\n echo mysql_error();\n $NewData = mysql_connect('localhost', 'DBUSER', 'DBPASS');\n echo mysql_error();\n mysql_select_db('OLDDBNAME', $oldData );\n mysql_select_db('NEWDBNAME', $NewData );\n $getAllTablesName = \"SELECT table_name FROM information_schema.tables WHERE table_type = 'base table'\";\n $getAllTablesNameExe = mysql_query($getAllTablesName);\n //echo mysql_error();\n while ($dataTableName = mysql_fetch_object($getAllTablesNameExe)) {\n\n $oldDataCount = mysql_query('select count(*) as noOfRecord from ' . $dataTableName->table_name, $oldData);\n $oldDataCountResult = mysql_fetch_object($oldDataCount);\n\n\n $newDataCount = mysql_query('select count(*) as noOfRecord from ' . $dataTableName->table_name, $NewData);\n $newDataCountResult = mysql_fetch_object($newDataCount);\n\n if ( $oldDataCountResult->noOfRecord != $newDataCountResult->noOfRecord ) {\n echo \"<br/><b>\" . $dataTableName->table_name . \"</b>\";\n echo \" | Old: \" . $oldDataCountResult->noOfRecord;\n echo \" | New: \" . $newDataCountResult->noOfRecord;\n\n if ($oldDataCountResult->noOfRecord < $newDataCountResult->noOfRecord) {\n echo \" | <font color='green'>*</font>\";\n\n } else {\n echo \" | <font color='red'>*</font>\";\n }\n\n echo \"<br/>----------------------------------------\";\n\n } \n\n }\n ?>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33194/" ]
274,894
<p>I have a bit of an unusual question. I'm running an old DOS game in dosbox under windows xp and i'm trying to determine when and where it access it's data file.</p> <p>what can i use that will give me a log of all read requests made to a file? I want to know the "when", "from" and "size" of each file read.</p> <p>I know my basic 8086/8088 assembly but nothing more. so if there's no shortcut tool available, a recommendation of a debugging tool / tutorial that can help me get on the right track can be great also.</p> <p>the game's "below the roots", if anyone can shed some light about this game's internals, it will be a great help :)</p>
[ { "answer_id": 277194, "author": "Artelius", "author_id": 31945, "author_profile": "https://Stackoverflow.com/users/31945", "pm_score": 2, "selected": false, "text": "fread()" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11813/" ]
274,899
<p>How have you guys handled working with jQuery includes </p> <pre><code>&lt;script type="text/javascript" src="jquery.js"&gt;&lt;/script&gt; </code></pre> <p>in Asp.Net MVC when working with partial views/view controls? Basically, I don't want to make the jquery include in the master page because I am not using jquery in all of my views, but I also want an easy way for a user control to be able to create the jquery include in the right location ('head') without creating duplicate jquery includes.</p> <p>The best way would be to use a ScriptManaager, but I do not want to rely on ASP.Net Ajax for this in my application. Is there a 'lightweight' ScriptManager that I could use that would also allow the newly released intellisense for jquery? </p> <p>I've created a WebControl that provides this functionality, but I don't get the intellisense support for VS2008, which I would really like.</p> <p>Hope this makes sense.</p>
[ { "answer_id": 274906, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "function loadJSInclude(scriptPath, callback)\n{\n var scriptNode = document.createElement('SCRIPT');\n scriptNode.type = 'text/javascript';\n scriptNode.src = scriptPath;\n\n var headNode = document.getElementsByTagName('HEAD');\n if (headNode[0] != null)\n headNode[0].appendChild(scriptNode);\n\n if (callback != null) \n {\n scriptNode.onreadystagechange = callback; \n scriptNode.onload = callback;\n }\n}\n <script type='text/javascript'>\n if(typeof(someJqueryObject) == \"undefined\") \n loadJSInclude('jquery.js', doYourStuff); \n else \n doYourStuff();\n\n function doYourStuff()\n {\n // jQuery will be loaded now, so you can do your stuff here.\n }\n</script>\n" }, { "answer_id": 4465079, "author": "Sean", "author_id": 545305, "author_profile": "https://Stackoverflow.com/users/545305", "pm_score": 1, "selected": false, "text": "<script src=\"<%=Url.Content(\"~/Content/js/jquery-1.2.3.min.js\") %>\" type=\"text/javascript\"></script>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8534/" ]
274,915
<p>What is the best way to call C/C++ from other languages such as Java, Python, Perl, PHP, etc?</p>
[ { "answer_id": 274924, "author": "Ned Batchelder", "author_id": 14343, "author_profile": "https://Stackoverflow.com/users/14343", "pm_score": 2, "selected": false, "text": "os.system(\"myccode -v args etc\")\n" }, { "answer_id": 274979, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 3, "selected": false, "text": "use Inline C => <<'END_C';\n\n void greet() {\n printf(\"Hello, world\\n\");\n }\nEND_C\n\ngreet;\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14744/" ]
274,918
<p>The CSS Friendly Control Adapters for ASP.NET are great for creating markup that is easy to style. A big benefit of the GridView adapter is that it generates THEAD, TBODY, and TFOOT tags, which allow you to do some really great things with libraries like jQuery - for instance, <a href="http://tablesorter.com/docs/" rel="nofollow noreferrer">Tablesorter</a> for client-side table sorting.</p> <p>The problem is that it seems to be a global on/off for the adapters through the CSSFriendlyAdapters.browser file. What do I do if I already have a slew of GridViews currently in production and only want to use the CSS Friendly Adapters for a new one?</p> <p>So I would be interested in two types of solutions:</p> <p>1) A way to extend or modify GridView (a new tag is acceptable) to output THEAD and TBODY tags.</p> <p>2) A way to conditionally apply or disable CSS Friendly Control Adapters.</p>
[ { "answer_id": 279464, "author": "David Boike", "author_id": 10039, "author_profile": "https://Stackoverflow.com/users/10039", "pm_score": 0, "selected": false, "text": "myGrid.UseAccessibleHeader = true;\nmyGrid.HeaderRow.TableSection = TableRowSection.TableHeader;\nmyGrid.FooterRow.TableSection = TableRowSection.TableFooter;\n" }, { "answer_id": 1158060, "author": "ChrisCa", "author_id": 17194, "author_profile": "https://Stackoverflow.com/users/17194", "pm_score": 3, "selected": true, "text": "public class UlRadioButtonList : RadioButtonList\n {\n protected override void Render(System.Web.UI.HtmlTextWriter writer)\n {\n // Call the base RenderContents method.\n base.Render(writer);\n }\n }\n <browsers>\n <browser refID=\"Default\">\n <controlAdapters>\n <adapter controlType=\"FM.Web.Source.WebControls.UlRadioButtonList\" adapterType=\"FM.Web.Source.ControlAdapters.RadioButtonListAdapter\" />\n </controlAdapters>\n </browser>\n</browsers>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10039/" ]
274,951
<p>You can pass a function pointer, function object (or boost lambda) to std::sort to define a strict weak ordering of the elements of the container you want sorted.</p> <p>However, sometimes (enough that I've hit this several times), you want to be able to chain "primitive" comparisons.</p> <p>A trivial example would be if you were sorting a collection of objects that represent contact data. Sometimes you will want to sort by <pre>last name, first name, area code</pre>. Other times <pre>first name, last name</pre> - yet other times <pre>age, first name, area code</pre>... etc</p> <p>Now, you can certainly write an additional function object for each case, but that violates the DRY principle - especially if each comparison is less trivial.</p> <p>It seems like you should be able to write a hierarchy of comparison functions - the low level ones do the single, primitive, comparisons (e.g. first name &lt; first name), then higher level ones call the lower level ones in succession (probably chaining with &amp;&amp; to make use of short circuit evaluation) to generate the composite functions.</p> <p>The trouble with this approach is that std::sort takes a binary predicate - the predicate can only return a bool. So if you're composing them you can't tell if a "false" indicates equality or greater than. You can make your lower level predicates return an int, with three states - but then you would have to wrap those in higher level predicates before they could be used with std::sort on their own.</p> <p>In all, these are not insurmountable problems. It just seems harder than it should be - and certainly invites a helper library implementation.</p> <p>Therefore, does anyone know of any pre-existing library (esp. if it's a std or boost library) that can help here - of have any other thoughts on the matter?</p> <p>[Update]</p> <p>As mentioned in some of the comments - I've gone ahead and written my own implementation of a class to manage this. It's fairly minimal, and probably has some issues with it in general. but on that basis, for anyone interested, the class is here:</p> <p><a href="http://pastebin.com/f52a85e4f" rel="noreferrer">http://pastebin.com/f52a85e4f</a></p> <p>And some helper functions (to avoid the need to specify template args) is here:</p> <p><a href="http://pastebin.com/fa03d66e" rel="noreferrer">http://pastebin.com/fa03d66e</a></p>
[ { "answer_id": 274963, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "std::sort std::stable_sort" }, { "answer_id": 275014, "author": "siukurnin", "author_id": 35273, "author_profile": "https://Stackoverflow.com/users/35273", "pm_score": 2, "selected": false, "text": "std::sort" }, { "answer_id": 275033, "author": "Jesse Beder", "author_id": 112, "author_profile": "https://Stackoverflow.com/users/112", "pm_score": 4, "selected": true, "text": "struct Type {\n string first, last;\n int age;\n};\n\nstruct CmpFirst {\n bool operator () (const Type& lhs, const Type& rhs) { return lhs.first < rhs.first; }\n};\n\nstruct CmpLast {\n bool operator () (const Type& lhs, const Type& rhs) { return lhs.last < rhs.last; }\n};\n\nstruct CmpAge {\n bool operator () (const Type& lhs, const Type& rhs) { return lhs.age < rhs.age; }\n};\n\ntemplate <typename First, typename Second>\nstruct Chain {\n Chain(const First& f_, const Second& s_): f(f_), s(s_) {}\n\n bool operator () (const Type& lhs, const Type& rhs) {\n if(f(lhs, rhs))\n return true;\n if(f(rhs, lhs))\n return false;\n\n return s(lhs, rhs);\n }\n\n template <typename Next>\n Chain <Chain, Next> chain(const Next& next) const {\n return Chain <Chain, Next> (*this, next);\n }\n\n First f;\n Second s;\n};\n\nstruct False { bool operator() (const Type& lhs, const Type& rhs) { return false; } };\n\ntemplate <typename Op>\nChain <False, Op> make_chain(const Op& op) { return Chain <False, Op> (False(), op); }\n vector <Type> v; // fill this baby up\n\nsort(v.begin(), v.end(), make_chain(CmpLast()).chain(CmpFirst()).chain(CmpAge()));\n" }, { "answer_id": 11167563, "author": "Voivoid", "author_id": 309265, "author_profile": "https://Stackoverflow.com/users/309265", "pm_score": 2, "selected": false, "text": "struct Citizen {\n std::wstring iFirstName;\n std::wstring iLastName;\n};\n\nChainComparer<Citizen> cmp;\ncmp.Chain<std::less>( boost::bind( &Citizen::iLastName, _1 ) );\ncmp.Chain<std::less>( boost::bind( &Citizen::iFirstName, _1 ) );\n\nstd::vector<Citizen> vec;\nstd::sort( vec.begin(), vec.end(), cmp );\n template <typename T>\nclass ChainComparer {\npublic:\n\n typedef boost::function<bool(const T&, const T&)> TComparator;\n typedef TComparator EqualComparator;\n typedef TComparator CustomComparator;\n\n template <template <typename> class TComparer, typename TValueGetter>\n void Chain( const TValueGetter& getter ) {\n\n iComparers.push_back( std::make_pair( \n boost::bind( getter, _1 ) == boost::bind( getter, _2 ), \n boost::bind( TComparer<TValueGetter::result_type>(), boost::bind( getter, _1 ), boost::bind( getter, _2 ) ) \n ) );\n }\n\n bool operator()( const T& lhs, const T& rhs ) {\n BOOST_FOREACH( const auto& comparer, iComparers ) {\n if( !comparer.first( lhs, rhs ) ) {\n return comparer.second( lhs, rhs );\n }\n }\n\n return false;\n }\n\nprivate:\n std::vector<std::pair<EqualComparator, CustomComparator>> iComparers;\n};\n" }, { "answer_id": 15014633, "author": "Alexander Oh", "author_id": 887836, "author_profile": "https://Stackoverflow.com/users/887836", "pm_score": 1, "selected": false, "text": " #include <iostream>\n using namespace std;\n\n struct vec { int x,y,z; };\n\n struct CmpX {\n bool operator() (const vec& lhs, const vec& rhs) const \n { return lhs.x < rhs.x; }\n };\n\n struct CmpY {\n bool operator() (const vec& lhs, const vec& rhs) const \n { return lhs.y < rhs.y; }\n };\n\n struct CmpZ {\n bool operator() (const vec& lhs, const vec& rhs) const \n { return lhs.z < rhs.z; }\n };\n\n template <typename T>\n bool chained(const T &, const T &) {\n return false;\n }\n\n template <typename CMP, typename T, typename ...P>\n bool chained(const T &t1, const T &t2, const CMP &c, P...p) {\n if (c(t1,t2)) { return true; }\n if (c(t2,t1)) { return false; }\n else { return chained(t1, t2, p...); }\n }\n\n int main(int argc, char **argv) {\n vec x = { 1,2,3 }, y = { 2,2,3 }, z = { 1,3,3 };\n cout << chained(x,x,CmpX(),CmpY(),CmpZ()) << endl;\n return 0;\n }\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32136/" ]
274,958
<p>According to <a href="http://www.scalabium.com/faq/dct0150.htm" rel="noreferrer">this page,</a> it's possible to use <code>TClientDataset</code> as an in-memory dataset, completely independent of any actual databases or files. It describes how to setup the dataset's table structure and how to load data into it at runtime. But when I tried to follow its instructions in D2009, step 4 (<code>table.Open</code>) raised an exception. It said that it didn't have a provider specified.</p> <p>The entire point of the example on that page is to build a dataset that doesn't need a provider. Is the page wrong, is it outdated, or am I missing a step somewhere? And if the page is wrong, what do I need to use instead to create a completely independent in-memory dataset? I've been using <code>TJvMemoryData</code>, but if possible I'd like to reduce the amount of extra dependencies that my dataset adds into my project.</p>
[ { "answer_id": 274976, "author": "Tom", "author_id": 13219, "author_profile": "https://Stackoverflow.com/users/13219", "pm_score": 3, "selected": false, "text": "table.CreateDataSet" }, { "answer_id": 274989, "author": "MikeJ", "author_id": 10676, "author_profile": "https://Stackoverflow.com/users/10676", "pm_score": 6, "selected": true, "text": "table.CreateDataset" }, { "answer_id": 275132, "author": "jrodenhi", "author_id": 25315, "author_profile": "https://Stackoverflow.com/users/25315", "pm_score": 4, "selected": false, "text": "procedure TfrmPRMain.ConfigureDataset;\nbegin\n With cdsMain do begin\n FieldDefs.Add('bDelete', ftBoolean);\n FieldDefs.Add('sSource', ftString, 10);\n FieldDefs.Add('iSection', ftInteger);\n FieldDefs.Add('iOrder', ftInteger);\n FieldDefs.Add('sBranch', ftString, 10);\n FieldDefs.Add('sPulseCode', ftString, 10);\n FieldDefs.Add('sCode', ftString, 10);\n FieldDefs.Add('dtWorkDate', ftDate);\n FieldDefs.Add('iWorkWeek', ftInteger);\n FieldDefs.Add('sName', ftString, 50);\n CreateDataSet;\n LogChanges := False;\n Open;\n end;\nend;\n" }, { "answer_id": 295271, "author": "vrad", "author_id": 12891, "author_profile": "https://Stackoverflow.com/users/12891", "pm_score": 3, "selected": false, "text": "TClientDataSet" }, { "answer_id": 764686, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "CreateDataset XXXClientDataSet.Close;\nXXXClientDataSet.Open;\n Open xxxClientDataSet.CreateDataset;\n" }, { "answer_id": 908653, "author": "Tim Sullivan", "author_id": 722, "author_profile": "https://Stackoverflow.com/users/722", "pm_score": 2, "selected": false, "text": "TClientDataset" }, { "answer_id": 16329126, "author": "avra", "author_id": 368260, "author_profile": "https://Stackoverflow.com/users/368260", "pm_score": 0, "selected": false, "text": "TClientDataset unit Unit1;\n\ninterface\n\nuses\n Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,\n Dialogs, DB, DBClient, Grids, DBGrids, StdCtrls, MidasLib;\n\ntype\n TForm1 = class(TForm)\n MemTable: TClientDataSet;\n Button1: TButton;\n Button2: TButton;\n DBGrid1: TDBGrid;\n DataSource1: TDataSource;\n procedure Button1Click(Sender: TObject);\n procedure Button2Click(Sender: TObject);\n procedure FormCreate(Sender: TObject);\n private\n { Private declarations }\n public\n { Public declarations }\n end;\n\nvar\n Form1: TForm1;\n\nimplementation\n\n{$R *.dfm}\n\nprocedure TForm1.Button1Click(Sender: TObject);\nvar\n i: word;\nbegin\n MemTable.DisableControls;\n for i := 1 to 20000 do\n begin\n MemTable.Append;\n MemTable.FieldByName('ID').AsInteger := i;\n MemTable.FieldByName('Status').AsString := 'Code'+IntToStr(i);\n MemTable.FieldByName('Created').AsDateTime := Date();\n MemTable.FieldByName('Volume').AsFloat := Random(10000);\n MemTable.Post;\n end;\n MemTable.EnableControls;\nend;\n\nprocedure TForm1.Button2Click(Sender: TObject);\nbegin\n MemTable.IndexFieldNames := 'Volume';\nend;\n\nprocedure TForm1.FormCreate(Sender: TObject);\nbegin\n MemTable.FieldDefs.Add('ID', ftInteger, 0, False);\n MemTable.FieldDefs.Add('Status', ftString, 10, False);\n MemTable.FieldDefs.Add('Created', ftDate, 0, False);\n MemTable.FieldDefs.Add('Volume', ftFloat, 0, False);\n MemTable.CreateDataSet;\nend;\n\nend.\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32914/" ]
274,984
<p>How can I correctly serve WSDL of a WCF webservice located in a private LAN from behind a reverse proxy listening on public IP?</p> <p>I have an Apache webserver configured in reverse proxy mode which listens for requests on a public IP address and serves them from the internal IIS host. WCF webservice generates WSDL using the FQDN address of the LAN host which, of course, cannot be read by an internet web service client.</p> <p>Is there any setting that can be configured in wcf application's web.config or in IIS in order to customize the WSDL generated containing host address and put public address instead?</p>
[ { "answer_id": 947276, "author": "Richard Collette", "author_id": 107683, "author_profile": "https://Stackoverflow.com/users/107683", "pm_score": 4, "selected": false, "text": "<ServiceBehavior(AddressFilterMode:=AddressFilterMode.Any)>\n https://... http://..... AddressFilterMode.Any web.config listenUri serviceMetaData httpGetEnabled=true <serviceBehaviors>\n <behavior name=\"myBehavior\">\n <serviceMetadata httpGetEnabled=\"true\" />\n </behavior>\n</serviceBehaviors>\n<!-- ... -->\n<services>\n <service name=\"NamespaceQualifiedServiceClass\" behavior=\"myBehavior\" >\n <endpoint listenUri=\"http://www.servicehost.com\" \n address=\"https://www.sslloadbalancer.com\" \n binding=\"someBinding\" \n contract=\"IMyServiceInterface\" ... />\n </service>\n</services>\n basicHttpBinding security mode=none BehaviorExtensionElement Public Overrides ReadOnly Property BehaviorType() As System.Type\n Get\n Return GetType(InlineXsdInWsdlBehavior)\n End Get\nEnd Property\n\nProtected Overrides Function CreateBehavior() As Object\n Return New InlineXsdInWsdlBehavior()\nEnd Function\n system.servicemodel <behaviors>\n <endpointBehaviors>\n <behavior name=\"SSLLoadBalancerBehavior\"> \n <flattenXsdImports/>\n </behavior>\n </endpointBehaviors>\n</behaviors>\n<extensions>\n <behaviorExtensions>\n <!--The full assembly name must be specified in the type attribute as of WCF 3.5sp1-->\n <add name=\"flattenXsdImports\" type=\"Org.ServiceModel.Description.FlattenXsdImportsEndpointBehavior, Org.ServiceModel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\"/> \n </behaviorExtensions>\n</extensions>\n <endpoint address=\"\" binding=\"basicHttpBinding\" contract=\"WCFWsdlFlatten.IService1\" behaviorConfiguration=\"SSLLoadBalancerBehavior\">\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5970/" ]
274,994
<p>I know we are <em>really</em> behind the times here, but we are just about to upgrade from .NET 1.1 to .NET 2.0. </p> <p>Thank you for your sympathy. </p> <p>Anyhow, are there any gotchas we should look out for?<br> Do you have any general advice before we jump in? </p> <p>Please do not post telling me to go straight to 3.5: 2.0 is all we're allowed! </p> <p>We're using mostly C#. </p>
[ { "answer_id": 275020, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 1, "selected": false, "text": "ctl0_ ctl00_..." } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7211/" ]
274,996
<p>First, I am Linq to Sql newbie, so please be gentle :).</p> <p>I have existing ASP.Net application developed over last 3.5 years. It has pretty big data model underneath, around 350 tables. I am trying to do some new things with Linq to SQL. </p> <p>First impression is that linq designer and SqlMetal are built for databases not bigger than NorthWind example. Here are some problems I have:</p> <ol> <li>I have table <code>Products</code> that is needed in lots of places (inventory, invoicing, production, ...). If I put table <code>Products</code> in each dbml file, linq designer is going to create <code>Product</code> class in each of them. I don't want that. I want to only one <code>Product</code> class.</li> <li>I have DataContext about shipping. It needs around 40 tables. This makes dbml file very hard to manage. Is there a way to create smaller dbml files and then include them (as reference) into some "major" dbml?</li> </ol> <p>For now, I really like Linq, but I think it is still seriously lacking design tool for anything bigger than 10 tables.</p> <p>My solution now is building smaller models with Linq designer and then manually merging them (adding properties and references), so lots of code will be generated, but there will also be lots of manual work. </p> <p>Did I miss something big or is this current state of affair with Linq to Sql?</p>
[ { "answer_id": 3675696, "author": "James McCormack", "author_id": 71906, "author_profile": "https://Stackoverflow.com/users/71906", "pm_score": 2, "selected": false, "text": "/code" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25732/" ]
275,004
<p>I wish to calculate the time it took for an API to return a value. The time taken for such an action is in the space of nanoseconds. As the API is a C++ class/function, I am using the timer.h to calculate the same:</p> <pre><code> #include &lt;ctime&gt; #include &lt;iostream&gt; using namespace std; int main(int argc, char** argv) { clock_t start; double diff; start = clock(); diff = ( std::clock() - start ) / (double)CLOCKS_PER_SEC; cout&lt;&lt;&quot;printf: &quot;&lt;&lt; diff &lt;&lt;'\n'; return 0; } </code></pre> <p>The above code gives the time in seconds. How do I get the same in nano seconds and with more precision?</p>
[ { "answer_id": 275031, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 5, "selected": false, "text": "inline __int64 GetCpuClocks()\n{\n\n // Counter\n struct { int32 low, high; } counter;\n\n // Use RDTSC instruction to get clocks count\n __asm push EAX\n __asm push EDX\n __asm __emit 0fh __asm __emit 031h // RDTSC\n __asm mov counter.low, EAX\n __asm mov counter.high, EDX\n __asm pop EDX\n __asm pop EAX\n\n // Return result\n return *(__int64 *)(&counter);\n\n}\n" }, { "answer_id": 275231, "author": "grieve", "author_id": 34329, "author_profile": "https://Stackoverflow.com/users/34329", "pm_score": 7, "selected": true, "text": "#include <sys/time.h>\n\nint main()\n{\n timespec ts;\n // clock_gettime(CLOCK_MONOTONIC, &ts); // Works on FreeBSD\n clock_gettime(CLOCK_REALTIME, &ts); // Works on Linux\n}\n" }, { "answer_id": 275543, "author": "Walter Bright", "author_id": 33949, "author_profile": "https://Stackoverflow.com/users/33949", "pm_score": 3, "selected": false, "text": "unsigned long long rdtsc()\n{\n #define rdtsc(low, high) \\\n __asm__ __volatile__(\"rdtsc\" : \"=a\" (low), \"=d\" (high))\n\n unsigned int low, high;\n rdtsc(low, high);\n return ((ulonglong)high << 32) | low;\n}\n unsigned long long rdtsc()\n{\n _asm\n {\n rdtsc\n }\n}\n" }, { "answer_id": 283584, "author": "gagneet", "author_id": 35416, "author_profile": "https://Stackoverflow.com/users/35416", "pm_score": 5, "selected": false, "text": "#include <time.h>\n#include <iostream>\nusing namespace std;\n\nint main (int argc, char** argv)\n{\n // reset the clock\n timespec tS;\n tS.tv_sec = 0;\n tS.tv_nsec = 0;\n clock_settime(CLOCK_PROCESS_CPUTIME_ID, &tS);\n ...\n ... <code to check for the time to be put here>\n ...\n clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &tS);\n cout << \"Time taken is: \" << tS.tv_sec << \" \" << tS.tv_nsec << endl;\n\n return 0;\n}\n" }, { "answer_id": 3205738, "author": "Marius", "author_id": 174650, "author_profile": "https://Stackoverflow.com/users/174650", "pm_score": 5, "selected": false, "text": "RDTSC clock_gettime() RDTSC inline uint64_t rdtsc()\n{\n uint32_t lo, hi;\n __asm__ __volatile__ (\n \"xorl %%eax, %%eax\\n\"\n \"cpuid\\n\"\n \"rdtsc\\n\"\n : \"=a\" (lo), \"=d\" (hi)\n :\n : \"%ebx\", \"%ecx\" );\n return (uint64_t)hi << 32 | lo;\n}\n #include <time.h>\n#include <sys/timeb.h>\n// needs -lrt (real-time lib)\n// 1970-01-01 epoch UTC time, 1 mcs resolution (divide by 1M to get time_t)\nuint64_t ClockGetTime()\n{\n timespec ts;\n clock_gettime(CLOCK_REALTIME, &ts);\n return (uint64_t)ts.tv_sec * 1000000LL + (uint64_t)ts.tv_nsec / 1000LL;\n}\n Absolute values:\nrdtsc = 4571567254267600\nclock_gettime = 1278605535506855\n\nProcessing time: (10000000 runs)\nrdtsc = 2292547353\nclock_gettime = 1031119636\n" }, { "answer_id": 4720448, "author": "Paul J Moesman", "author_id": 579402, "author_profile": "https://Stackoverflow.com/users/579402", "pm_score": 2, "selected": false, "text": "#include <dos.h>\n\nvoid main() \n{\nstruct time t;\nint Hour,Min,Sec,Hun;\ngettime(&t);\nHour=t.ti_hour;\nMin=t.ti_min;\nSec=t.ti_sec;\nHun=t.ti_hund;\nprintf(\"Start time is: %2d:%02d:%02d.%02d\\n\",\n t.ti_hour, t.ti_min, t.ti_sec, t.ti_hund);\n....\nyour code to time\n...\n\n// read the time here remove Hours and min if the time is in sec\n\ngettime(&t);\nprintf(\"\\nTid Hour:%d Min:%d Sec:%d Hundreds:%d\\n\",t.ti_hour-Hour,\n t.ti_min-Min,t.ti_sec-Sec,t.ti_hund-Hun);\nprintf(\"\\n\\nAlt Ferdig Press a Key\\n\\n\");\ngetch();\n} // end main\n" }, { "answer_id": 11242363, "author": "Thomas", "author_id": 1392778, "author_profile": "https://Stackoverflow.com/users/1392778", "pm_score": 2, "selected": false, "text": "int get_cpu_ticks()\n{\n LARGE_INTEGER ticks;\n QueryPerformanceFrequency(&ticks);\n return ticks.LowPart;\n}\n\n__int64 get_cpu_clocks()\n{\n struct { int32 low, high; } counter;\n\n __asm cpuid\n __asm push EDX\n __asm rdtsc\n __asm mov counter.low, EAX\n __asm mov counter.high, EDX\n __asm pop EDX\n __asm pop EAX\n\n return *(__int64 *)(&counter);\n}\n\nclass cbench\n{\npublic:\n cbench(const char *desc_in) \n : desc(strdup(desc_in)), start(get_cpu_clocks()) { }\n ~cbench()\n {\n printf(\"%s took: %.4f ms\\n\", desc, (float)(get_cpu_clocks()-start)/get_cpu_ticks());\n if(desc) free(desc);\n }\nprivate:\n char *desc;\n __int64 start;\n};\n int main()\n{\n {\n cbench c(\"test\");\n ... code ...\n }\n return 0;\n}\n" }, { "answer_id": 11485388, "author": "Howard Hinnant", "author_id": 576911, "author_profile": "https://Stackoverflow.com/users/576911", "pm_score": 6, "selected": false, "text": "<chrono> <chrono> <chrono> RDTSC RDTSC <chrono> RDTSC clock() clock_gettime() QueryPerformanceCounter RDTSC QueryPerformanceCounter clock_gettime() std::chrono::high_resolution_clock std::chrono::system_clock rdtsc x::clock #include <chrono>\n\nnamespace x\n{\n\nstruct clock\n{\n typedef unsigned long long rep;\n typedef std::ratio<1, 2'800'000'000> period; // My machine is 2.8 GHz\n typedef std::chrono::duration<rep, period> duration;\n typedef std::chrono::time_point<clock> time_point;\n static const bool is_steady = true;\n\n static time_point now() noexcept\n {\n unsigned lo, hi;\n asm volatile(\"rdtsc\" : \"=a\" (lo), \"=d\" (hi));\n return time_point(duration(static_cast<rep>(hi) << 32 | lo));\n }\n};\n\n} // x\n now() {return __rdtsc();} x::clock #include <iostream>\n\ntemplate <class clock>\nvoid\ntest_empty_loop()\n{\n // Define real time units\n typedef std::chrono::duration<unsigned long long, std::pico> picoseconds;\n // or:\n // typedef std::chrono::nanoseconds nanoseconds;\n // Define double-based unit of clock tick\n typedef std::chrono::duration<double, typename clock::period> Cycle;\n using std::chrono::duration_cast;\n const int N = 100000000;\n // Do it\n auto t0 = clock::now();\n for (int j = 0; j < N; ++j)\n asm volatile(\"\");\n auto t1 = clock::now();\n // Get the clock ticks per iteration\n auto ticks_per_iter = Cycle(t1-t0)/N;\n std::cout << ticks_per_iter.count() << \" clock ticks per iteration\\n\";\n // Convert to real time units\n std::cout << duration_cast<picoseconds>(ticks_per_iter).count()\n << \"ps per iteration\\n\";\n}\n std::chrono::nanoseconds Cycle clock::now() typename clock::time_point t0 = clock::now();\n x::clock count() std::chrono::duration_cast Cycle picoseconds int main()\n{\n std::cout << \"\\nUsing rdtsc:\\n\";\n test_empty_loop<x::clock>();\n\n std::cout << \"\\nUsing std::chrono::high_resolution_clock:\\n\";\n test_empty_loop<std::chrono::high_resolution_clock>();\n\n std::cout << \"\\nUsing std::chrono::system_clock:\\n\";\n test_empty_loop<std::chrono::system_clock>();\n}\n x::clock std::chrono::high_resolution_clock std::chrono::system_clock Using rdtsc:\n1.72632 clock ticks per iteration\n616ps per iteration\n\nUsing std::chrono::high_resolution_clock:\n0.620105 clock ticks per iteration\n620ps per iteration\n\nUsing std::chrono::system_clock:\n0.00062457 clock ticks per iteration\n624ps per iteration\n x::clock" }, { "answer_id": 12176835, "author": "ice", "author_id": 1482174, "author_profile": "https://Stackoverflow.com/users/1482174", "pm_score": 2, "selected": false, "text": " int iceu_system_GetTimeNow(long long int *res)\n {\n static struct timespec buffer;\n // \n #ifdef __CYGWIN__\n if (clock_gettime(CLOCK_REALTIME, &buffer))\n return 1;\n #else\n if (clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &buffer))\n return 1;\n #endif\n *res=(long long int)buffer.tv_sec * 1000000000LL + (long long int)buffer.tv_nsec;\n return 0;\n }\n" }, { "answer_id": 13305395, "author": "Mi-La", "author_id": 1809845, "author_profile": "https://Stackoverflow.com/users/1809845", "pm_score": 2, "selected": false, "text": "EProfilerTimer timer;\ntimer.Start();\n\n... // Your code here\n\nconst uint64_t number_of_elapsed_cycles = timer.Stop();\nconst uint64_t nano_seconds_elapsed =\n mumber_of_elapsed_cycles / (double) timer.GetCyclesPerSecond() * 1000000000;\n" }, { "answer_id": 19471677, "author": "gongzhitaao", "author_id": 1429714, "author_profile": "https://Stackoverflow.com/users/1429714", "pm_score": 3, "selected": false, "text": "#include <iostream>\n#include <chrono>\n\nclass Timer\n{\npublic:\n Timer() : beg_(clock_::now()) {}\n void reset() { beg_ = clock_::now(); }\n double elapsed() const {\n return std::chrono::duration_cast<second_>\n (clock_::now() - beg_).count(); }\n\nprivate:\n typedef std::chrono::high_resolution_clock clock_;\n typedef std::chrono::duration<double, std::ratio<1> > second_;\n std::chrono::time_point<clock_> beg_;\n};\n class Timer\n{\npublic:\n Timer() { clock_gettime(CLOCK_REALTIME, &beg_); }\n\n double elapsed() {\n clock_gettime(CLOCK_REALTIME, &end_);\n return end_.tv_sec - beg_.tv_sec +\n (end_.tv_nsec - beg_.tv_nsec) / 1000000000.;\n }\n\n void reset() { clock_gettime(CLOCK_REALTIME, &beg_); }\n\nprivate:\n timespec beg_, end_;\n};\n int main()\n{\n Timer tmr;\n double t = tmr.elapsed();\n std::cout << t << std::endl;\n\n tmr.reset();\n t = tmr.elapsed();\n std::cout << t << std::endl;\n return 0;\n}\n" }, { "answer_id": 23260069, "author": "Patrick K", "author_id": 3212800, "author_profile": "https://Stackoverflow.com/users/3212800", "pm_score": 2, "selected": false, "text": "//Stopwatch.hpp\n\n#ifndef STOPWATCH_HPP\n#define STOPWATCH_HPP\n\n//Boost\n#include <boost/chrono.hpp>\n//Std\n#include <cstdint>\n\nclass Stopwatch\n{\npublic:\n Stopwatch();\n virtual ~Stopwatch();\n void Restart();\n std::uint64_t Get_elapsed_ns();\n std::uint64_t Get_elapsed_us();\n std::uint64_t Get_elapsed_ms();\n std::uint64_t Get_elapsed_s();\nprivate:\n boost::chrono::high_resolution_clock::time_point _start_time;\n};\n\n#endif // STOPWATCH_HPP\n\n\n//Stopwatch.cpp\n\n#include \"Stopwatch.hpp\"\n\nStopwatch::Stopwatch():\n _start_time(boost::chrono::high_resolution_clock::now()) {}\n\nStopwatch::~Stopwatch() {}\n\nvoid Stopwatch::Restart()\n{\n _start_time = boost::chrono::high_resolution_clock::now();\n}\n\nstd::uint64_t Stopwatch::Get_elapsed_ns()\n{\n boost::chrono::nanoseconds nano_s = boost::chrono::duration_cast<boost::chrono::nanoseconds>(boost::chrono::high_resolution_clock::now() - _start_time);\n return static_cast<std::uint64_t>(nano_s.count());\n}\n\nstd::uint64_t Stopwatch::Get_elapsed_us()\n{\n boost::chrono::microseconds micro_s = boost::chrono::duration_cast<boost::chrono::microseconds>(boost::chrono::high_resolution_clock::now() - _start_time);\n return static_cast<std::uint64_t>(micro_s.count());\n}\n\nstd::uint64_t Stopwatch::Get_elapsed_ms()\n{\n boost::chrono::milliseconds milli_s = boost::chrono::duration_cast<boost::chrono::milliseconds>(boost::chrono::high_resolution_clock::now() - _start_time);\n return static_cast<std::uint64_t>(milli_s.count());\n}\n\nstd::uint64_t Stopwatch::Get_elapsed_s()\n{\n boost::chrono::seconds sec = boost::chrono::duration_cast<boost::chrono::seconds>(boost::chrono::high_resolution_clock::now() - _start_time);\n return static_cast<std::uint64_t>(sec.count());\n}\n" }, { "answer_id": 35312966, "author": "Yeti", "author_id": 1009901, "author_profile": "https://Stackoverflow.com/users/1009901", "pm_score": 2, "selected": false, "text": "#include nanoseconds microseconds milliseconds seconds minutes hours #include <chrono>\nstruct MeasureTime\n{\n using precision = std::chrono::microseconds;\n std::vector<std::chrono::steady_clock::time_point> times;\n std::chrono::steady_clock::time_point oneLast;\n void p() {\n std::cout << \"Mark \" \n << times.size()/2\n << \": \" \n << std::chrono::duration_cast<precision>(times.back() - oneLast).count() \n << std::endl;\n }\n void m() {\n oneLast = times.back();\n times.push_back(std::chrono::steady_clock::now());\n }\n void t() {\n m();\n p();\n m();\n }\n MeasureTime() {\n times.push_back(std::chrono::steady_clock::now());\n }\n};\n MeasureTime m; // first time is already in memory\ndoFnc1();\nm.t(); // Mark 1: next time, and print difference with previous mark\ndoFnc2();\nm.t(); // Mark 2: next time, and print difference with previous mark\ndoStuff = doMoreStuff();\nandDoItAgain = doStuff.aoeuaoeu();\nm.t(); // prints 'Mark 3: 123123' etc...\n Mark 1: 123\nMark 2: 32\nMark 3: 433234\n void s() { // summary\n int i = 0;\n std::chrono::steady_clock::time_point tprev;\n for(auto tcur : times)\n {\n if(i > 0)\n {\n std::cout << \"Mark \" << i << \": \"\n << std::chrono::duration_cast<precision>(tprev - tcur).count()\n << std::endl;\n }\n tprev = tcur;\n ++i;\n }\n}\n MeasureTime m;\ndoFnc1();\nm.m();\ndoFnc2();\nm.m();\ndoStuff = doMoreStuff();\nandDoItAgain = doStuff.aoeuaoeu();\nm.m();\nm.s();\n m.s() m.t()" }, { "answer_id": 65118386, "author": "metamorphosis", "author_id": 3454889, "author_profile": "https://Stackoverflow.com/users/3454889", "pm_score": 0, "selected": false, "text": " #include \"plf_nanotimer.h\"\n #include <iostream>\n\n int main(int argc, char** argv)\n {\n plf::nanotimer timer;\n\n timer.start()\n\n // Do something here\n\n double results = timer.get_elapsed_ns();\n std::cout << \"Timing: \" << results << \" nanoseconds.\" << std::endl; \n return 0;\n }\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35416/" ]
275,005
<p>I am writing a program that will draw a solid along the curve of a spline. I am using visual studio 2005, and writing in C++ for OpenGL. I'm using FLTK to open my windows (fast and light toolkit).</p> <p>I currently have an algorithm that will draw a Cardinal Cubic Spline, given a set of control points, by breaking the intervals between the points up into subintervals and drawing linesegments between these sub points. The number of subintervals is variable.</p> <p>The line drawing code works wonderfully, and basically works as follows: I generate a set of points along the spline curve using the spline equation and store them in an array (as a special datastructure called Pnt3f, where the coordinates are 3 floats and there are some handy functions such as distance, length, dot and crossproduct). Then i have a single loop that iterates through the array of points and draws them as so:</p> <pre><code>glBegin(GL_LINE_STRIP); for(pt = 0; pt&lt;=numsubsegements ; ++pt) { glVertex3fv(pt.v()); } glEnd(); </code></pre> <p>As stated, this code works great. Now what i want to do is, instead of drawing a line, I want to extrude a solid. My current exploration is using a 'cylinder' quadric to create a tube along the line. This is a bit trickier, as I have to orient openGL in the direction i want to draw the cylinder. My idea is to do this:</p> <p>Psuedocode:</p> <pre><code>Push the current matrix, translate to the first control point rotate to face the next point draw a cylinder (length = distance between the points) Pop the matrix repeat </code></pre> <p>My problem is getting the angles between the points. I only need yaw and pitch, roll isnt important. I know take the arc-cosine of the dot product of the two points divided by the magnitude of both points, will return the angle between them, but this is not something i can feed to OpenGL to rotate with. I've tried doing this in 2d, using the XZ plane to get x rotation, and making the points vectors from the origin, but it does not return the correct angle.</p> <p>My current approach is much simpler. For each plane of rotation (X and Y), find the angle by:</p> <p>arc-cosine( (difference in 'x' values)/distance between the points)</p> <p>the 'x' value depends on how your set your plane up, though for my calculations I always use world x.</p> <p>Barring a few issues of it making it draw in the correct quadrant that I havent worked out yet, I want to get advice to see if this was a good implementation, or to see if someone knew a better way.</p>
[ { "answer_id": 275040, "author": "Sunlight", "author_id": 33650, "author_profile": "https://Stackoverflow.com/users/33650", "pm_score": 0, "selected": false, "text": "gluLookAt" }, { "answer_id": 275152, "author": "shoosh", "author_id": 9611, "author_profile": "https://Stackoverflow.com/users/9611", "pm_score": 1, "selected": false, "text": "for(pt = 0; pt<=numsubsegements ; ++pt) {\n glBegin(GL_LINE_STRIP);\n glVertex3fv(pt.v());\n}\nglEnd();\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33583/" ]
275,011
<p>I am having a problem displaying a Javascript string with embedded Unicode character escape sequences (\uXXXX) where the initial "\" character is itself escaped as "&amp;#92;" What do I need to do to transform the string so that it properly evaluates the escape sequences and produces output with the correct Unicode character?</p> <p>For example, I am dealing with input such as:</p> <p><pre><code>"this is a &amp;#92;u201ctest&amp;#92;u201d";</code></pre></p> <p>attempting to decode the "&amp;#92;" using a regex expression, e.g.:</p> <p><pre><code>var out = text.replace('/&amp;#92;/g','\');</code></pre></p> <p>results in the output text:</p> <p><pre><code>"this is a \u201ctest\u201d";</code></pre></p> <p>that is, the Unicode escape sequences are displayed as actual escape sequences, not the double quote characters I would like.</p>
[ { "answer_id": 275032, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "eval(new String(\"this is a &#92;u201ctest&#amp;92;u201d\")); eval(new String(\"this is a &#92;u201ctest&#amp;92;u201d\".replace('/&#92;/g','\\'))); \"this is a \\u201ctest\\u201d\"; \"this is a &#92;u201ctest&#amp;92;u201d\"" }, { "answer_id": 275057, "author": "JW.", "author_id": 4321, "author_profile": "https://Stackoverflow.com/users/4321", "pm_score": 1, "selected": false, "text": "var x = \"this is a &#92;u201ctest&#92;u201d\".replace(/&#92;/g,'\\\\')\n// x is now \"this is a \\u201ctest\\u201d\"\neval('x = \"' + x + '\"')\n// x is now \"this is a “test”\"\n" }, { "answer_id": 275518, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 1, "selected": false, "text": "var el= document.createElement('div');\nel.innerHTML= s;\nreturn eval('\"'+el.firstChild.data+'\"');\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
275,018
<p>How do I remove the last character of a string if it is a newline?</p> <pre><code>&quot;abc\n&quot; --&gt; &quot;abc&quot; </code></pre>
[ { "answer_id": 275025, "author": "Rich Bradshaw", "author_id": 16511, "author_profile": "https://Stackoverflow.com/users/16511", "pm_score": 11, "selected": false, "text": "rstrip() >>> 'test string\\n'.rstrip()\n'test string'\n rstrip() chomp >>> 'test string \\n \\r\\n\\n\\r \\n\\n'.rstrip()\n'test string'\n >>> 'test string \\n \\r\\n\\n\\r \\n\\n'.rstrip('\\n')\n'test string \\n \\r\\n\\n\\r '\n rstrip() strip() lstrip() >>> s = \" \\n\\r\\n \\n abc def \\n\\r\\n \\n \"\n>>> s.strip()\n'abc def'\n>>> s.lstrip()\n'abc def \\n\\r\\n \\n '\n>>> s.rstrip()\n' \\n\\r\\n \\n abc def'\n" }, { "answer_id": 275401, "author": "Mike", "author_id": 19215, "author_profile": "https://Stackoverflow.com/users/19215", "pm_score": 7, "selected": false, "text": ">>> 'Mac EOL\\r'.rstrip('\\r\\n')\n'Mac EOL'\n>>> 'Windows EOL\\r\\n'.rstrip('\\r\\n')\n'Windows EOL'\n>>> 'Unix EOL\\n'.rstrip('\\r\\n')\n'Unix EOL'\n chomp >>> \"Hello\\n\\n\\n\".rstrip(\"\\n\")\n\"Hello\"\n" }, { "answer_id": 275659, "author": "Ryan Ginstrom", "author_id": 10658, "author_profile": "https://Stackoverflow.com/users/10658", "pm_score": 8, "selected": false, "text": ">>> text = \"line 1\\nline 2\\r\\nline 3\\nline 4\"\n>>> text.splitlines()\n['line 1', 'line 2', 'line 3', 'line 4']\n" }, { "answer_id": 326279, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": false, "text": "$x=\"a\\n\";\n\nchomp $x\n $x \"a\" x=\"a\\n\"\n\nx.rstrip()\n x \"a\\n\" x=x.rstrip()" }, { "answer_id": 2396894, "author": "Jamie", "author_id": 288263, "author_profile": "https://Stackoverflow.com/users/288263", "pm_score": 6, "selected": false, "text": "import os\ns = s.rstrip(os.linesep)\n rstrip(\"\\n\") \"\\r\\n\" rstrip os.linesep" }, { "answer_id": 5764202, "author": "ingydotnet", "author_id": 721703, "author_profile": "https://Stackoverflow.com/users/721703", "pm_score": 4, "selected": false, "text": ">>> 'foo\\n\\n'.rstrip(os.linesep)\n'foo'\n >>> re.sub(os.linesep + r'\\Z','','foo\\n\\n')\n'foo\\n'\n" }, { "answer_id": 5803510, "author": "Carlos Valiente", "author_id": 179149, "author_profile": "https://Stackoverflow.com/users/179149", "pm_score": 4, "selected": false, "text": "\"foo\".rstrip(os.linesep) $ python\nPython 2.7.1 (r271:86832, Mar 18 2011, 09:09:48) \n[GCC 4.5.0 20100604 [gcc-4_5-branch revision 160292]] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import os, sys\n>>> sys.platform\n'linux2'\n>>> \"foo\\r\\n\".rstrip(os.linesep)\n'foo\\r'\n>>>\n \"foo\".rstrip(\"\\r\\n\")" }, { "answer_id": 8327143, "author": "Chij", "author_id": 1073506, "author_profile": "https://Stackoverflow.com/users/1073506", "pm_score": 3, "selected": false, "text": "foobar= foobar[:-1]\n" }, { "answer_id": 9507807, "author": "mihaicc", "author_id": 648904, "author_profile": "https://Stackoverflow.com/users/648904", "pm_score": 5, "selected": false, "text": "\"line 1\\nline 2\\r\\n...\".replace('\\n', '').replace('\\r', '')\n>>> 'line 1line 2...'\n" }, { "answer_id": 16527062, "author": "kiriloff", "author_id": 1141493, "author_profile": "https://Stackoverflow.com/users/1141493", "pm_score": 5, "selected": false, "text": "line = line.rstrip('\\n')" }, { "answer_id": 19317570, "author": "Leozj", "author_id": 2870855, "author_profile": "https://Stackoverflow.com/users/2870855", "pm_score": 3, "selected": false, "text": "newstr = \"\".join(oldstr.split('\\n'))" }, { "answer_id": 19531239, "author": "minopret", "author_id": 931925, "author_profile": "https://Stackoverflow.com/users/931925", "pm_score": 4, "selected": false, "text": "line.strip() chomp process import os\nsep_pos = -len(os.linesep)\nwith open(\"file.txt\") as f:\n for line in f:\n if line[sep_pos:] == os.linesep:\n line = line[:sep_pos]\n process(line)\n" }, { "answer_id": 21242117, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "import re\n\nr_unwanted = re.compile(\"[\\n\\t\\r]\")\nr_unwanted.sub(\"\", your_text)\n" }, { "answer_id": 26554128, "author": "user4178860", "author_id": 4178860, "author_profile": "https://Stackoverflow.com/users/4178860", "pm_score": -1, "selected": false, "text": "line = line.rstrip('\\r|\\n')\n" }, { "answer_id": 27054136, "author": "Hackaholic", "author_id": 2294755, "author_profile": "https://Stackoverflow.com/users/2294755", "pm_score": 5, "selected": false, "text": "line = line.strip()\n >>> \"\\n\\n hello world \\n\\n\".strip()\n'hello world'\n" }, { "answer_id": 27890752, "author": "kuzzooroo", "author_id": 2829764, "author_profile": "https://Stackoverflow.com/users/2829764", "pm_score": 3, "selected": false, "text": "def chomped_lines(it):\n return map(operator.methodcaller('rstrip', '\\r\\n'), it)\n with open(\"file.txt\") as infile:\n for line in chomped_lines(infile):\n process(line)\n" }, { "answer_id": 28937424, "author": "slec", "author_id": 508792, "author_profile": "https://Stackoverflow.com/users/508792", "pm_score": 5, "selected": false, "text": "s = s.rstrip()\n s rstrip" }, { "answer_id": 32882948, "author": "Alien Life Form", "author_id": 279600, "author_profile": "https://Stackoverflow.com/users/279600", "pm_score": 5, "selected": false, "text": "def chomp(x):\n if x.endswith(\"\\r\\n\"): return x[:-2]\n if x.endswith(\"\\n\") or x.endswith(\"\\r\"): return x[:-1]\n return x\n" }, { "answer_id": 33392998, "author": "Stephen Miller", "author_id": 5366724, "author_profile": "https://Stackoverflow.com/users/5366724", "pm_score": 1, "selected": false, "text": "import time\n\nloops = 50000000\n\ndef method1(loops=loops):\n test_string = 'num\\n'\n t0 = time.time()\n for num in xrange(loops):\n out_sting = test_string[:-1]\n t1 = time.time()\n print('Method 1: ' + str(t1 - t0))\n\ndef method2(loops=loops):\n test_string = 'num\\n'\n t0 = time.time()\n for num in xrange(loops):\n out_sting = test_string.rstrip()\n t1 = time.time()\n print('Method 2: ' + str(t1 - t0))\n\nmethod1()\nmethod2()\n Method 1: 3.92700004578\nMethod 2: 6.73000001907\n" }, { "answer_id": 37346773, "author": "Help me", "author_id": 6361076, "author_profile": "https://Stackoverflow.com/users/6361076", "pm_score": 2, "selected": false, "text": "line = line.rstrip(\"\\n\")\n line = line.strip(\"\\n\")\n" }, { "answer_id": 40749138, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": ">>> ' spacious '.rstrip()\n' spacious'\n>>> \"AABAA\".rstrip(\"A\")\n 'AAB'\n>>> \"ABBA\".rstrip(\"AB\") # both AB and BA are stripped\n ''\n>>> \"ABCABBA\".rstrip(\"AB\")\n 'ABC'\n" }, { "answer_id": 40750864, "author": "internetional", "author_id": 7057076, "author_profile": "https://Stackoverflow.com/users/7057076", "pm_score": 2, "selected": false, "text": "\\n \\r \\r\\n re.sub r\"\\r?\\n?$\" import re\n\nre.sub(r\"\\r?\\n?$\", \"\", the_text, 1)\n import re\n\ntext_1 = \"hellothere\\n\\n\\n\"\ntext_2 = \"hellothere\\n\\n\\r\"\ntext_3 = \"hellothere\\n\\n\\r\\n\"\n\na = re.sub(r\"\\r?\\n?$\", \"\", text_1, 1)\nb = re.sub(r\"\\r?\\n?$\", \"\", text_2, 1)\nc = re.sub(r\"\\r?\\n?$\", \"\", text_3, 1)\n a == b == c True" }, { "answer_id": 43641376, "author": "teichert", "author_id": 3780389, "author_profile": "https://Stackoverflow.com/users/3780389", "pm_score": 3, "selected": false, "text": "\\r\\n s ''.join(s.splitlines())\n True keepends def chomp(s):\n if len(s):\n lines = s.splitlines(True)\n last = lines.pop()\n return ''.join(lines + last.splitlines())\n else:\n return ''\n" }, { "answer_id": 45342003, "author": "Taylor D. Edmiston", "author_id": 149428, "author_profile": "https://Stackoverflow.com/users/149428", "pm_score": 3, "selected": false, "text": "re str.rstrip >>> import re\n >>> re.sub(r'[\\n\\r]+$', '', '\\nx\\r\\n')\n'\\nx'\n >>> re.sub(r'[\\n\\r]+', '', '\\nx\\r\\n')\n'x'\n \\r \\n \\r\\n \\n\\r \\r\\r \\n\\n >>> re.sub(r'[\\n\\r]{1,2}$', '', '\\nx\\r\\n\\r\\n')\n'\\nx\\r'\n>>> re.sub(r'[\\n\\r]{1,2}$', '', '\\nx\\r\\n\\r')\n'\\nx\\r'\n>>> re.sub(r'[\\n\\r]{1,2}$', '', '\\nx\\r\\n')\n'\\nx'\n \\r\\n \\n >>> re.sub(r'(?:\\r\\n|\\n)$', '', '\\nx\\n\\n', count=1)\n'\\nx\\n'\n>>> re.sub(r'(?:\\r\\n|\\n)$', '', '\\nx\\r\\n\\r\\n', count=1)\n'\\nx\\r\\n'\n>>> re.sub(r'(?:\\r\\n|\\n)$', '', '\\nx\\r\\n', count=1)\n'\\nx'\n>>> re.sub(r'(?:\\r\\n|\\n)$', '', '\\nx\\n', count=1)\n'\\nx'\n ?: '...'.rstrip('\\n', '').rstrip('\\r', '') str.rstrip foo\\n\\n\\n foo" }, { "answer_id": 50870896, "author": "Venfah Nazir", "author_id": 3383819, "author_profile": "https://Stackoverflow.com/users/3383819", "pm_score": 0, "selected": false, "text": "import re \nif re.search(\"(\\\\r|)\\\\n$\", line):\n line = re.sub(\"(\\\\r|)\\\\n$\", \"\", line)\n" }, { "answer_id": 58499321, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "s = '''Hello World \\t\\n\\r\\tHi There'''\n# import the module string \nimport string\n# use the method translate to convert \ns.translate({ord(c): None for c in string.whitespace}\n>>'HelloWorldHiThere'\n s = ''' Hello World \n\\t\\n\\r\\tHi '''\nprint(re.sub(r\"\\s+\", \"\", s), sep='') # \\s matches all white spaces\n>HelloWorldHi\n s.replace('\\n', '').replace('\\t','').replace('\\r','')\n>' Hello World Hi '\n s = '''Hello World \\t\\n\\r\\tHi There'''\nregex = re.compile(r'[\\n\\r\\t]')\nregex.sub(\"\", s)\n>'Hello World Hi There'\n s = '''Hello World \\t\\n\\r\\tHi There'''\n' '.join(s.split())\n>'Hello World Hi There'\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
275,022
<p>With squid, we can cache webpages. I am not sure if it provides the same number of caching methods as ASP.NET caching (I primarily use ASP.NET), but it's a tool to cache webpages.</p> <p>Then we have memcached, which can cache database tables. I believe this is correct, and it is like SqlCacheDependency (correct me if I am wrong).</p> <p>However, is there any situation in a large web application where one would find room to use memcached, squid, AND ASP.NET (or PHP, JSP - application framework-level) caching.</p> <p>Thanks!</p>
[ { "answer_id": 275025, "author": "Rich Bradshaw", "author_id": 16511, "author_profile": "https://Stackoverflow.com/users/16511", "pm_score": 11, "selected": false, "text": "rstrip() >>> 'test string\\n'.rstrip()\n'test string'\n rstrip() chomp >>> 'test string \\n \\r\\n\\n\\r \\n\\n'.rstrip()\n'test string'\n >>> 'test string \\n \\r\\n\\n\\r \\n\\n'.rstrip('\\n')\n'test string \\n \\r\\n\\n\\r '\n rstrip() strip() lstrip() >>> s = \" \\n\\r\\n \\n abc def \\n\\r\\n \\n \"\n>>> s.strip()\n'abc def'\n>>> s.lstrip()\n'abc def \\n\\r\\n \\n '\n>>> s.rstrip()\n' \\n\\r\\n \\n abc def'\n" }, { "answer_id": 275401, "author": "Mike", "author_id": 19215, "author_profile": "https://Stackoverflow.com/users/19215", "pm_score": 7, "selected": false, "text": ">>> 'Mac EOL\\r'.rstrip('\\r\\n')\n'Mac EOL'\n>>> 'Windows EOL\\r\\n'.rstrip('\\r\\n')\n'Windows EOL'\n>>> 'Unix EOL\\n'.rstrip('\\r\\n')\n'Unix EOL'\n chomp >>> \"Hello\\n\\n\\n\".rstrip(\"\\n\")\n\"Hello\"\n" }, { "answer_id": 275659, "author": "Ryan Ginstrom", "author_id": 10658, "author_profile": "https://Stackoverflow.com/users/10658", "pm_score": 8, "selected": false, "text": ">>> text = \"line 1\\nline 2\\r\\nline 3\\nline 4\"\n>>> text.splitlines()\n['line 1', 'line 2', 'line 3', 'line 4']\n" }, { "answer_id": 326279, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": false, "text": "$x=\"a\\n\";\n\nchomp $x\n $x \"a\" x=\"a\\n\"\n\nx.rstrip()\n x \"a\\n\" x=x.rstrip()" }, { "answer_id": 2396894, "author": "Jamie", "author_id": 288263, "author_profile": "https://Stackoverflow.com/users/288263", "pm_score": 6, "selected": false, "text": "import os\ns = s.rstrip(os.linesep)\n rstrip(\"\\n\") \"\\r\\n\" rstrip os.linesep" }, { "answer_id": 5764202, "author": "ingydotnet", "author_id": 721703, "author_profile": "https://Stackoverflow.com/users/721703", "pm_score": 4, "selected": false, "text": ">>> 'foo\\n\\n'.rstrip(os.linesep)\n'foo'\n >>> re.sub(os.linesep + r'\\Z','','foo\\n\\n')\n'foo\\n'\n" }, { "answer_id": 5803510, "author": "Carlos Valiente", "author_id": 179149, "author_profile": "https://Stackoverflow.com/users/179149", "pm_score": 4, "selected": false, "text": "\"foo\".rstrip(os.linesep) $ python\nPython 2.7.1 (r271:86832, Mar 18 2011, 09:09:48) \n[GCC 4.5.0 20100604 [gcc-4_5-branch revision 160292]] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import os, sys\n>>> sys.platform\n'linux2'\n>>> \"foo\\r\\n\".rstrip(os.linesep)\n'foo\\r'\n>>>\n \"foo\".rstrip(\"\\r\\n\")" }, { "answer_id": 8327143, "author": "Chij", "author_id": 1073506, "author_profile": "https://Stackoverflow.com/users/1073506", "pm_score": 3, "selected": false, "text": "foobar= foobar[:-1]\n" }, { "answer_id": 9507807, "author": "mihaicc", "author_id": 648904, "author_profile": "https://Stackoverflow.com/users/648904", "pm_score": 5, "selected": false, "text": "\"line 1\\nline 2\\r\\n...\".replace('\\n', '').replace('\\r', '')\n>>> 'line 1line 2...'\n" }, { "answer_id": 16527062, "author": "kiriloff", "author_id": 1141493, "author_profile": "https://Stackoverflow.com/users/1141493", "pm_score": 5, "selected": false, "text": "line = line.rstrip('\\n')" }, { "answer_id": 19317570, "author": "Leozj", "author_id": 2870855, "author_profile": "https://Stackoverflow.com/users/2870855", "pm_score": 3, "selected": false, "text": "newstr = \"\".join(oldstr.split('\\n'))" }, { "answer_id": 19531239, "author": "minopret", "author_id": 931925, "author_profile": "https://Stackoverflow.com/users/931925", "pm_score": 4, "selected": false, "text": "line.strip() chomp process import os\nsep_pos = -len(os.linesep)\nwith open(\"file.txt\") as f:\n for line in f:\n if line[sep_pos:] == os.linesep:\n line = line[:sep_pos]\n process(line)\n" }, { "answer_id": 21242117, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "import re\n\nr_unwanted = re.compile(\"[\\n\\t\\r]\")\nr_unwanted.sub(\"\", your_text)\n" }, { "answer_id": 26554128, "author": "user4178860", "author_id": 4178860, "author_profile": "https://Stackoverflow.com/users/4178860", "pm_score": -1, "selected": false, "text": "line = line.rstrip('\\r|\\n')\n" }, { "answer_id": 27054136, "author": "Hackaholic", "author_id": 2294755, "author_profile": "https://Stackoverflow.com/users/2294755", "pm_score": 5, "selected": false, "text": "line = line.strip()\n >>> \"\\n\\n hello world \\n\\n\".strip()\n'hello world'\n" }, { "answer_id": 27890752, "author": "kuzzooroo", "author_id": 2829764, "author_profile": "https://Stackoverflow.com/users/2829764", "pm_score": 3, "selected": false, "text": "def chomped_lines(it):\n return map(operator.methodcaller('rstrip', '\\r\\n'), it)\n with open(\"file.txt\") as infile:\n for line in chomped_lines(infile):\n process(line)\n" }, { "answer_id": 28937424, "author": "slec", "author_id": 508792, "author_profile": "https://Stackoverflow.com/users/508792", "pm_score": 5, "selected": false, "text": "s = s.rstrip()\n s rstrip" }, { "answer_id": 32882948, "author": "Alien Life Form", "author_id": 279600, "author_profile": "https://Stackoverflow.com/users/279600", "pm_score": 5, "selected": false, "text": "def chomp(x):\n if x.endswith(\"\\r\\n\"): return x[:-2]\n if x.endswith(\"\\n\") or x.endswith(\"\\r\"): return x[:-1]\n return x\n" }, { "answer_id": 33392998, "author": "Stephen Miller", "author_id": 5366724, "author_profile": "https://Stackoverflow.com/users/5366724", "pm_score": 1, "selected": false, "text": "import time\n\nloops = 50000000\n\ndef method1(loops=loops):\n test_string = 'num\\n'\n t0 = time.time()\n for num in xrange(loops):\n out_sting = test_string[:-1]\n t1 = time.time()\n print('Method 1: ' + str(t1 - t0))\n\ndef method2(loops=loops):\n test_string = 'num\\n'\n t0 = time.time()\n for num in xrange(loops):\n out_sting = test_string.rstrip()\n t1 = time.time()\n print('Method 2: ' + str(t1 - t0))\n\nmethod1()\nmethod2()\n Method 1: 3.92700004578\nMethod 2: 6.73000001907\n" }, { "answer_id": 37346773, "author": "Help me", "author_id": 6361076, "author_profile": "https://Stackoverflow.com/users/6361076", "pm_score": 2, "selected": false, "text": "line = line.rstrip(\"\\n\")\n line = line.strip(\"\\n\")\n" }, { "answer_id": 40749138, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": ">>> ' spacious '.rstrip()\n' spacious'\n>>> \"AABAA\".rstrip(\"A\")\n 'AAB'\n>>> \"ABBA\".rstrip(\"AB\") # both AB and BA are stripped\n ''\n>>> \"ABCABBA\".rstrip(\"AB\")\n 'ABC'\n" }, { "answer_id": 40750864, "author": "internetional", "author_id": 7057076, "author_profile": "https://Stackoverflow.com/users/7057076", "pm_score": 2, "selected": false, "text": "\\n \\r \\r\\n re.sub r\"\\r?\\n?$\" import re\n\nre.sub(r\"\\r?\\n?$\", \"\", the_text, 1)\n import re\n\ntext_1 = \"hellothere\\n\\n\\n\"\ntext_2 = \"hellothere\\n\\n\\r\"\ntext_3 = \"hellothere\\n\\n\\r\\n\"\n\na = re.sub(r\"\\r?\\n?$\", \"\", text_1, 1)\nb = re.sub(r\"\\r?\\n?$\", \"\", text_2, 1)\nc = re.sub(r\"\\r?\\n?$\", \"\", text_3, 1)\n a == b == c True" }, { "answer_id": 43641376, "author": "teichert", "author_id": 3780389, "author_profile": "https://Stackoverflow.com/users/3780389", "pm_score": 3, "selected": false, "text": "\\r\\n s ''.join(s.splitlines())\n True keepends def chomp(s):\n if len(s):\n lines = s.splitlines(True)\n last = lines.pop()\n return ''.join(lines + last.splitlines())\n else:\n return ''\n" }, { "answer_id": 45342003, "author": "Taylor D. Edmiston", "author_id": 149428, "author_profile": "https://Stackoverflow.com/users/149428", "pm_score": 3, "selected": false, "text": "re str.rstrip >>> import re\n >>> re.sub(r'[\\n\\r]+$', '', '\\nx\\r\\n')\n'\\nx'\n >>> re.sub(r'[\\n\\r]+', '', '\\nx\\r\\n')\n'x'\n \\r \\n \\r\\n \\n\\r \\r\\r \\n\\n >>> re.sub(r'[\\n\\r]{1,2}$', '', '\\nx\\r\\n\\r\\n')\n'\\nx\\r'\n>>> re.sub(r'[\\n\\r]{1,2}$', '', '\\nx\\r\\n\\r')\n'\\nx\\r'\n>>> re.sub(r'[\\n\\r]{1,2}$', '', '\\nx\\r\\n')\n'\\nx'\n \\r\\n \\n >>> re.sub(r'(?:\\r\\n|\\n)$', '', '\\nx\\n\\n', count=1)\n'\\nx\\n'\n>>> re.sub(r'(?:\\r\\n|\\n)$', '', '\\nx\\r\\n\\r\\n', count=1)\n'\\nx\\r\\n'\n>>> re.sub(r'(?:\\r\\n|\\n)$', '', '\\nx\\r\\n', count=1)\n'\\nx'\n>>> re.sub(r'(?:\\r\\n|\\n)$', '', '\\nx\\n', count=1)\n'\\nx'\n ?: '...'.rstrip('\\n', '').rstrip('\\r', '') str.rstrip foo\\n\\n\\n foo" }, { "answer_id": 50870896, "author": "Venfah Nazir", "author_id": 3383819, "author_profile": "https://Stackoverflow.com/users/3383819", "pm_score": 0, "selected": false, "text": "import re \nif re.search(\"(\\\\r|)\\\\n$\", line):\n line = re.sub(\"(\\\\r|)\\\\n$\", \"\", line)\n" }, { "answer_id": 58499321, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "s = '''Hello World \\t\\n\\r\\tHi There'''\n# import the module string \nimport string\n# use the method translate to convert \ns.translate({ord(c): None for c in string.whitespace}\n>>'HelloWorldHiThere'\n s = ''' Hello World \n\\t\\n\\r\\tHi '''\nprint(re.sub(r\"\\s+\", \"\", s), sep='') # \\s matches all white spaces\n>HelloWorldHi\n s.replace('\\n', '').replace('\\t','').replace('\\r','')\n>' Hello World Hi '\n s = '''Hello World \\t\\n\\r\\tHi There'''\nregex = re.compile(r'[\\n\\r\\t]')\nregex.sub(\"\", s)\n>'Hello World Hi There'\n s = '''Hello World \\t\\n\\r\\tHi There'''\n' '.join(s.split())\n>'Hello World Hi There'\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32484/" ]
275,034
<p>One of the features of the modern (64 bit OS X and iPhone OS) Objective C runtime is the ability for properties to dynamically synthesize ivars without explicitly declaring them in the class:</p> <pre><code>@interface MyClass : NSObject { // NSString *name; unnecessary on modern runtimes } @property (retain) NSStrng *name; @end @implementation MyClass @synthesize name; @end </code></pre> <p>In quite a bit of my code I use custom getter implementations in order to initialize the properties:</p> <pre><code>- (NSString *) name { if (!name) { name = @"Louis"; } return name; } </code></pre> <p>The above is incompatible with synthesized ivars since it needs to access a an ivar that is not declared in the header. For various reasons I would like to update a number of my personal frameworks to use synthesized ivars when built on the modern runtimes, the above code needs to be modified to work with synthesized ivars in order to achieve that goal.</p> <p>While the Objective C 2.0 documentation states that the synthesized accessors on the modern runtime will synthesize the ivar on first use. It does not specify what low level mechanism is used to do this. Is it done by class_getInstanceVariable(), are the restrictions on class_addIvar() loosened, is it an undocumented function int he objective C 2.0 runtime? While I could implement my own side storage for the data backing my properties, I would much rather use the mechanism that synthesized accessors are using.</p>
[ { "answer_id": 5542886, "author": "JD Brennan", "author_id": 304712, "author_profile": "https://Stackoverflow.com/users/304712", "pm_score": -1, "selected": false, "text": "[myObject setValue:@\"whatever\" forKey:@\"foo\"];\n" }, { "answer_id": 9045742, "author": "Farcaller", "author_id": 151652, "author_profile": "https://Stackoverflow.com/users/151652", "pm_score": 0, "selected": false, "text": "@synthesize name = _name;\n\n...\n\n- (NSString *) name {\n if (!name) {\n _name = @\"Louis\";\n }\n\n return _name;\n}\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30506/" ]
275,038
<p>I wish to convert a single string with multiple delimiters into a key=>value hash structure. Is there a simple way to accomplish this? My current implementation is:</p> <pre><code>sub readConfigFile() { my %CONFIG; my $index = 0; open(CON_FILE, "config"); my @lines = &lt;CON_FILE&gt;; close(CON_FILE); my @array = split(/&gt;/, $lines[0]); my $total = @array; while($index &lt; $total) { my @arr = split(/=/, $array[$index]); chomp($arr[1]); $CONFIG{$arr[0]} = $arr[1]; $index = $index + 1; } while ( ($k,$v) = each %CONFIG ) { print "$k =&gt; $v\n"; } return; } </code></pre> <p>where 'config' contains:</p> <pre><code>pub=3&gt;rec=0&gt;size=3&gt;adv=1234 123 4.5 6.00 pub=1&gt;rec=1&gt;size=2&gt;adv=111 22 3456 .76 </code></pre> <p>The last digits need to be also removed, and kept in a separate key=>value pair whose name can be 'ip'. (I have not been able to accomplish this without making the code too lengthy and complicated).</p>
[ { "answer_id": 275127, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 3, "selected": true, "text": "$." }, { "answer_id": 275163, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 1, "selected": false, "text": "#!/bin/perl -w\nuse strict;\nuse constant debug => 0;\n\nsub readConfigFile()\n{\n my %CONFIG;\n open(CON_FILE, \"config\") or die \"failed to open file ($!)\\n\";\n\n while (my $line = <CON_FILE>)\n {\n chomp $line;\n $line =~ s/#.*//; # Remove comments\n next if $line =~ /^\\s*$/; # Ignore blank lines\n\n foreach my $field (split(/>/, $line))\n {\n my @arr = split(/=/, $field);\n $CONFIG{$arr[0]} = $arr[1];\n print \":: $arr[0] => $arr[1]\\n\" if debug;\n }\n }\n close(CON_FILE);\n\n while (my($k,$v) = each %CONFIG)\n {\n print \"$k => $v\\n\";\n }\n return %CONFIG;\n}\n\nreadConfigFile; # Ignores returned hash\n pub=3;rec=0;size=3;adv=(1234,123,4.5);ip=6.00\n" }, { "answer_id": 277717, "author": "Altreus", "author_id": 2386199, "author_profile": "https://Stackoverflow.com/users/2386199", "pm_score": 1, "selected": false, "text": "my @hashes;\n\nfor my $line (@config) {\n my $hash; # config line will end up here\n\n my @pairs = split />/, $line;\n\n # Do the ip first. Split the last element of @pairs and put the second half into the\n # hash, overwriting the element with the first half at the same time.\n # This means we don't have to do anything special with the for loop below.\n ($pairs[-1], $hash->{ip}) = (split / /, $pairs[-1], 2);\n\n for (@pairs) {\n my ($k, $v) = split /=/;\n $hash->{$k} = $v;\n }\n\n push @hashes, $hash;\n}\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35416/" ]
275,039
<p>I got an image with which links to another page using <code>&lt;a href="..."&gt; &lt;img ...&gt; &lt;/a&gt;</code>.</p> <p>How can I make it make a post like if it was a button <code>&lt;input type="submit"...&gt;</code>?</p>
[ { "answer_id": 275048, "author": "Shawn", "author_id": 26, "author_profile": "https://Stackoverflow.com/users/26", "pm_score": 3, "selected": false, "text": "<form action=\"page-you're-submitting-to.html\" method=\"POST\">\n <a href=\"#\" onclick=\"document.forms[0].submit();return false;\"><img src=\"whatever.jpg\" /></a>\n</form>\n" }, { "answer_id": 275049, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 5, "selected": false, "text": "<input type=\"image\" src=\"...\"> <a href=\"#\" onclick=\"document.forms['myFormName'].submit(); return false;\">...</a>" }, { "answer_id": 275051, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 6, "selected": true, "text": "<input type=\"image\" name=\"your_image_name\" src=\"your_image_url.png\" />\n your_image_name.x your_image_name.y" }, { "answer_id": 275052, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 1, "selected": false, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"fr\">\n<head>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n <title>BSO Communication</title>\n\n<style type=\"text/css\">\n.submit {\n border : 0;\n background : url(ok.gif) left top no-repeat;\n height : 24px;\n width : 24px;\n cursor : pointer;\n text-indent : -9999px;\n}\nhtml:first-child .submit {\n padding-left : 1000px;\n}\n</style>\n<!--[if IE]>\n<style type=\"text/css\">\n.submit {\n text-indent : 0;\n color : expression(this.value = '');\n}\n</style>\n<![endif]-->\n</head>\n\n<body>\n <h1>Display input submit as image with CSS</h1>\n\n <p>Take a look at <a href=\"/2007/07/26/afficher-un-input-submit-comme-une-image/\">the related article</a> (in french).</p>\n <form action=\"\" method=\"get\">\n <fieldset>\n <legend>Some form</legend>\n <p class=\"field\">\n <label for=\"input\">Some value</label>\n\n <input type=\"text\" id=\"input\" name=\"value\" />\n <input type=\"submit\" class=\"submit\" />\n </p>\n </fieldset>\n </form>\n\n <hr />\n <p>This page is part of the <a href=\"http://www.bsohq.fr\">BSO Communication blog</a>.</p>\n\n</body>\n</html>\n" }, { "answer_id": 2593346, "author": "Jiky1", "author_id": 311080, "author_profile": "https://Stackoverflow.com/users/311080", "pm_score": 3, "selected": false, "text": " <html>\n\n <?php\n\n echo $_POST['c'].\" | \".$_POST['d'].\" | \".$_POST['e'];\n\n ?>\n\n <form action=\"test.php\" method=\"POST\">\n <input type=\"hidden\" name=\"c\" value=\"toto98\">\n <input type=\"hidden\" name=\"d\" value=\"toto97\">\n <input type=\"hidden\" name=\"e\" value=\"toto aaaaaaaaaaaaaaaaaaaa\">\n\n <a href=\"\" onclick=\"document.forms[0].submit();return false;\">Click</a> \n </form>\n\n</html>\n\n\nSo easy.\n\n\n\n\nSo easy.\n" }, { "answer_id": 7997472, "author": "Paulius Zaliaduonis", "author_id": 314454, "author_profile": "https://Stackoverflow.com/users/314454", "pm_score": 7, "selected": false, "text": "<a href=\"#\" onclick=\"$(this).closest('form').submit()\">Submit Link</a>\n" }, { "answer_id": 14408553, "author": "Kateriana", "author_id": 1991753, "author_profile": "https://Stackoverflow.com/users/1991753", "pm_score": 0, "selected": false, "text": "<form method=\"post\" action=\"whatever.asp\">\n<input type=...n\n\n<input type=\"image\" name=\"Submit\" src=\"/graphics/continue.gif\" align=\"middle\" border=\"0\" alt=\"Continue\">\n</form>\n" }, { "answer_id": 15088641, "author": "Grit", "author_id": 1353668, "author_profile": "https://Stackoverflow.com/users/1353668", "pm_score": 2, "selected": false, "text": "$('#[href button name]').click(function(e) {\n e.preventDefault();\n $('#[form name]').attr('action', 'alternateurl.php');\n $('#[form name]').submit();\n});\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26004/" ]
275,062
<p>So I was hoping that some old school Vim'ers could help me out. These are all separate questions and normally I would put them up each on their own but I'm not sure if that qualifies as question whoring here. </p> <p>Plus I think if you know enough to be asking any of these questions they will all be coming up in the near future:</p> <ol> <li>I have a library I'm writing and a series of applications that use that library. There doesn't seem to be an easy way(from what I can tell) to build a <strong>ctags file</strong> for the library and build one for each of my applications and make sure one references the other when I'm in vim.</li> <li>Using gf to open files from command mode is awesome, but a lot of my include files don't contain the full path. They refer to an include directory I set in the IDE. How can I set this directory as another point for Vim to start looking for files?</li> <li>Is there a way to compile a file inside Vim and send the output to a buffer? I'm currently using MSVS 2k3 but I'll be porting over to Linux in a few weeks so if this is possible on either system I'd appreciate it.</li> </ol>
[ { "answer_id": 275108, "author": "Ali Afshar", "author_id": 28380, "author_profile": "https://Stackoverflow.com/users/28380", "pm_score": 0, "selected": false, "text": ":cd {path}\n :he cd\n :lcd" }, { "answer_id": 275167, "author": "Luc Hermitte", "author_id": 15934, "author_profile": "https://Stackoverflow.com/users/15934", "pm_score": 2, "selected": false, "text": ":h 'tags' :h 'path :h :make" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23829/" ]
275,063
<p>I would like to be able to set "Extend my Windows desktop onto this monitor" via code. A PowerShell script would be ideal. WMI seems the way forward but I have zero knowledge in WMI.</p>
[ { "answer_id": 275123, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 2, "selected": false, "text": "Option Explicit\nDim WshShell, Dummy, Splash\n\nOn Error Resume Next\n\nSet WshShell = WScript.CreateObject(\"WScript.Shell\")\n\n'Main\nCall DoIt\nWScript.Quit\n\nSub DoIt\nwshshell.Run(\"%systemroot%\\system32\\control.exe desk.cpl,@0,3\")\n\n' Give Display Properties time to load\nWScript.Sleep 1000\nWshShell.SendKeys \"2\"\nWScript.Sleep 10\nWshShell.SendKeys \"%E\"\nWScript.Sleep 500\nWshShell.SendKeys \"%A\"\nWshShell.SendKeys \"{TAB}\"\nWshShell.SendKeys \"{TAB}\"\nWshShell.SendKeys \"{TAB}\"\nWshShell.SendKeys \"{TAB}\"\nWshShell.SendKeys \"{TAB}\"\nWshShell.SendKeys \"{TAB}\"\nWshShell.SendKeys \"{TAB}\"\nWshShell.SendKeys \"{TAB}\"\nWshShell.SendKeys \"{TAB}\"\nWshShell.SendKeys \"{TAB}\"\nWshShell.SendKeys \"{ENTER}\"\nEnd Sub 'DoIt\n ;\n; — toggle-screen.au3\n;\n\n; exec cpanel app `display settings`\nRun(”C:\\WINDOWS\\system32\\control.exe desk.cpl,@0,3?”)\n\n; wait for window to be active\nWinWaitActive(”Display Settings”)\n\n; select 2nd display\nSend(”{TAB}”)\nSend(”{DOWN}”)\n\n; work back to the ‘extend desktop’ control\nSend(”+{TAB}”)\nSend(”+{TAB}”)\nSend(”+{TAB}”)\nSend(”+{TAB}”)\nSend(”+{TAB}”)\nSend(”+{TAB}”)\nSend(”+{TAB}”)\nSend(”+{TAB}”)\nSend(”+{TAB}”)\n\n; toggle ‘extend desktop’ control and apply\nSend(”{SPACE}”)\nSend(”{ENTER}”)\n\n; wait for window to be active\nWinWaitActive(”Display Settings”)\n\n; accept\nSend(”{TAB}”)\nSend(”{ENTER}”)\n\n;\n; — E.O.F.\n; \n" }, { "answer_id": 275597, "author": "halr9000", "author_id": 6637, "author_profile": "https://Stackoverflow.com/users/6637", "pm_score": 2, "selected": false, "text": "param ( \n $ControllerName = \"$( throw 'ControllerName is a mandatory parameter' )\"\n)\n$regPath = \"HKLM:\\system\\CurrentControlSet\\control\\video\"\n$devDescStr = \"Device Description\"\n\nSet-Location -path $regPath\n$regSubKey = Get-ChildItem -recurse -include 0000\n$devDescProperty = $regSubKey | Get-ItemProperty -name $devDescStr -erroraction SilentlyContinue \n$priDescProperty = $devDescProperty | Where-Object { $_.$devDescStr -match $ControllerName }\nSet-Location -path $priDescProperty.PSPath\nGet-ItemProperty -path . -name \"Attach.ToDesktop\"\n" }, { "answer_id": 891694, "author": "David Resnick", "author_id": 3904, "author_profile": "https://Stackoverflow.com/users/3904", "pm_score": 0, "selected": false, "text": ";\n; — toggle-screen2.au3\n;\n\n#include <WinAPI.au3>\n; exec cpanel app `display settings`\nRun(_WinAPI_ExpandEnvironmentStrings(\"%windir%\") & \"\\system32\\control.exe desk.cpl,@0,3?\")\n\n; wait for window to be active\nWinWaitActive(\"Display Properties\")\n\n; select 2nd display\nSend(\"!d\")\nSend(\"{DOWN}\")\n\n; toggle the ‘extend desktop’ checkbox\nSend(\"!e\")\n\n; close the dialog\nSend(\"{ENTER}\")\n" }, { "answer_id": 2462742, "author": "loraderon", "author_id": 22092, "author_profile": "https://Stackoverflow.com/users/22092", "pm_score": 3, "selected": false, "text": "public class DisplayHelper\n{\n [DllImport(\"user32.dll\")]\n static extern DISP_CHANGE ChangeDisplaySettings(uint lpDevMode, uint dwflags);\n [DllImport(\"user32.dll\")]\n static extern bool EnumDisplayDevices(string lpDevice, uint iDevNum, ref DISPLAY_DEVICE lpDisplayDevice, uint dwFlags);\n\n enum DISP_CHANGE : int\n {\n Successful = 0,\n Restart = 1,\n Failed = -1,\n BadMode = -2,\n NotUpdated = -3,\n BadFlags = -4,\n BadParam = -5,\n BadDualView = -1\n }\n\n [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]\n struct DISPLAY_DEVICE\n {\n [MarshalAs(UnmanagedType.U4)]\n public int cb;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]\n public string DeviceName;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]\n public string DeviceString;\n [MarshalAs(UnmanagedType.U4)]\n public DisplayDeviceStateFlags StateFlags;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]\n public string DeviceID;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]\n public string DeviceKey;\n }\n\n [Flags()]\n enum DisplayDeviceStateFlags : int\n {\n /// <summary>The device is part of the desktop.</summary>\n AttachedToDesktop = 0x1,\n MultiDriver = 0x2,\n /// <summary>The device is part of the desktop.</summary>\n PrimaryDevice = 0x4,\n /// <summary>Represents a pseudo device used to mirror application drawing for remoting or other purposes.</summary>\n MirroringDriver = 0x8,\n /// <summary>The device is VGA compatible.</summary>\n VGACompatible = 0x16,\n /// <summary>The device is removable; it cannot be the primary display.</summary>\n Removable = 0x20,\n /// <summary>The device has more display modes than its output devices support.</summary>\n ModesPruned = 0x8000000,\n Remote = 0x4000000,\n Disconnect = 0x2000000\n }\n\n public static void EnableSecondaryDisplay()\n {\n var secondaryIndex = 1;\n var secondary = GetDisplayDevice(secondaryIndex);\n var id = secondary.DeviceKey.Split('\\\\')[7];\n\n using (var key = Registry.CurrentConfig.OpenSubKey(string.Format(@\"System\\CurrentControlSet\\Control\\VIDEO\\{0}\", id), true))\n {\n using (var subkey = key.CreateSubKey(\"000\" + secondaryIndex))\n {\n subkey.SetValue(\"Attach.ToDesktop\", 1, RegistryValueKind.DWord);\n subkey.SetValue(\"Attach.RelativeX\", 1024, RegistryValueKind.DWord);\n subkey.SetValue(\"DefaultSettings.XResolution\", 1024, RegistryValueKind.DWord);\n subkey.SetValue(\"DefaultSettings.YResolution\", 768, RegistryValueKind.DWord);\n subkey.SetValue(\"DefaultSettings.BitsPerPel\", 32, RegistryValueKind.DWord);\n }\n }\n\n ChangeDisplaySettings(0, 0);\n }\n\n private static DISPLAY_DEVICE GetDisplayDevice(int id)\n {\n var d = new DISPLAY_DEVICE();\n d.cb = Marshal.SizeOf(d);\n if (!EnumDisplayDevices(null, (uint)id, ref d, 0))\n throw new NotSupportedException(\"Could not find a monitor with id \" + id);\n return d;\n }\n}\n" }, { "answer_id": 3481380, "author": "MemphiZ", "author_id": 130465, "author_profile": "https://Stackoverflow.com/users/130465", "pm_score": 1, "selected": false, "text": "Run(\"C:\\WINDOWS\\system32\\control.exe desk.cpl\", \"C:\\Windows\\system32\\\")\nWinWait(\"Screen Resolution\")\nControlCommand(\"Screen Resolution\", \"\", \"ComboBox1\", \"SetCurrentSelection\", \"SAMSUNG\")\n\nif (ControlCommand(\"Screen Resolution\", \"\", \"ComboBox3\", \"GetCurrentSelection\", \"\") = \"Disconnect this display\") Then\n ControlCommand(\"Screen Resolution\", \"\", \"ComboBox1\", \"SetCurrentSelection\", \"2\")\n ControlCommand(\"Screen Resolution\", \"\", \"ComboBox3\", \"SetCurrentSelection\", \"3\")\n ControlCommand(\"Screen Resolution\", \"\", \"ComboBox1\", \"SetCurrentSelection\", \"0\")\n ControlCommand(\"Screen Resolution\", \"\", \"ComboBox3\", \"SetCurrentSelection\", \"1\")\n ControlClick(\"Screen Resolution\", \"\", \"Button4\")\n WinWait(\"Display Settings\")\n ControlClick(\"Display Settings\", \"\", \"Button1\")\nElse\n ControlCommand(\"Screen Resolution\", \"\", \"ComboBox3\", \"SetCurrentSelection\", \"3\")\n ControlCommand(\"Screen Resolution\", \"\", \"ComboBox1\", \"SetCurrentSelection\", \"2\")\n ControlCommand(\"Screen Resolution\", \"\", \"ComboBox3\", \"SetCurrentSelection\", \"1\")\n ControlClick(\"Screen Resolution\", \"\", \"Button4\")\n WinWait(\"Display Settings\")\n ControlClick(\"Display Settings\", \"\", \"Button1\")\nEndIf\n" }, { "answer_id": 25094871, "author": "Communicative Algebra", "author_id": 3611932, "author_profile": "https://Stackoverflow.com/users/3611932", "pm_score": 6, "selected": false, "text": "displayswitch.exe /internal Disconnect projector (same as \"Show only on 1\" from the Display Properties dialog)\ndisplayswitch.exe /clone Duplicate screen\ndisplayswitch.exe /extend Extend screen\ndisplayswitch.exe /external Projector only (disconnect local) (same as \"Show only on 2\" from the Display Properties dialog)\n call displayswitch.exe /extend\n" }, { "answer_id": 49906724, "author": "Bong Gutz", "author_id": 9666019, "author_profile": "https://Stackoverflow.com/users/9666019", "pm_score": 2, "selected": false, "text": "RunWait C:\\Windows\\System32\\DisplaySwitch.exe /extend\n RunWait C:\\Windows\\System32\\DisplaySwitch.exe /internal\n #NoEnv ; Recommended for performance and compatibility with future AutoHotkey releases.\n; #Warn ; Enable warnings to assist with detecting common errors.\nSendMode Input ; Recommended for new scripts due to its superior speed and reliability.\n#Persistent \n\nAny1stKeyUWantToTurnOn::RunWait C:\\Windows\\System32\\DisplaySwitch.exe /extend\nAny2stKeyUWantToTurnOff::RunWait C:\\Windows\\System32\\DisplaySwitch.exe /internal\n" }, { "answer_id": 69096335, "author": "askvictor", "author_id": 224511, "author_profile": "https://Stackoverflow.com/users/224511", "pm_score": 2, "selected": false, "text": "[Flags]\npublic enum SetDisplayConfigFlags : uint\n{\n SDC_TOPOLOGY_INTERNAL = 0x00000001,\n SDC_TOPOLOGY_CLONE = 0x00000002,\n SDC_TOPOLOGY_EXTEND = 0x00000004,\n SDC_TOPOLOGY_EXTERNAL = 0x00000008,\n SDC_APPLY = 0x00000080\n}\n\n[DllImport(\"user32.dll\", CharSet = CharSet.Unicode)]\nprivate static extern long SetDisplayConfig(uint numPathArrayElements,\n IntPtr pathArray, uint numModeArrayElements, IntPtr modeArray, SetDisplayConfigFlags flags);\n\nstatic void CloneDisplays() {\n SetDisplayConfig(0, IntPtr.Zero, 0, IntPtr.Zero, SetDisplayConfigFlags.SDC_TOPOLOGY_CLONE | SetDisplayConfigFlags.SDC_APPLY);\n}\n\nstatic void ExtendDisplays() {\n SetDisplayConfig(0, IntPtr.Zero, 0, IntPtr.Zero, SetDisplayConfigFlags.SDC_TOPOLOGY_EXTEND | SetDisplayConfigFlags.SDC_APPLY);\n}\n\nstatic void ExternalDisplay() {\n SetDisplayConfig(0, IntPtr.Zero, 0, IntPtr.Zero, SetDisplayConfigFlags.SDC_TOPOLOGY_EXTERNAL | SetDisplayConfigFlags.SDC_APPLY);\n}\n\nstatic void InternalDisplay() {\n SetDisplayConfig(0, IntPtr.Zero, 0, IntPtr.Zero, SetDisplayConfigFlags.SDC_TOPOLOGY_INTERNAL | SetDisplayConfigFlags.SDC_APPLY);\n}\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/176626/" ]
275,064
<p>I read a properties-file at the webapplication startup phase (contextInitialized()) and I started to think about how to make these settings 'visible' to the servlets. Do I need to loop through the keys and add each and every one to the context, like this</p> <pre><code>Iterator i = settings.keySet().iterator(); while (i.hasNext()) { key = (String) i.next(); value = (String) settings.get(key); context.setAttribute(key, value); } </code></pre> <p>or are there better methods?</p> <p>Thank you!</p> <p>/Adam</p>
[ { "answer_id": 275065, "author": "Josh", "author_id": 2204759, "author_profile": "https://Stackoverflow.com/users/2204759", "pm_score": 1, "selected": false, "text": "String key = null;\nIterator<String> i = settings.keySet().iterator();\nwhile (i.hasNext())\n context.setAttribute(key = i.next(), settings.get(key));\n" }, { "answer_id": 276498, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 3, "selected": false, "text": "context.setAttribute(\"mySettings\", settings);\n public void setAttribute(String name, Object object)\n" }, { "answer_id": 276582, "author": "Adam Asham", "author_id": 31518, "author_profile": "https://Stackoverflow.com/users/31518", "pm_score": 0, "selected": false, "text": "application.module1.color=black\napplication.module1.font=arial\n" }, { "answer_id": 411415, "author": "Adam Asham", "author_id": 31518, "author_profile": "https://Stackoverflow.com/users/31518", "pm_score": 1, "selected": false, "text": "//ExampleServlet.java\nSettings settings = (Settings)context.getAttribute(\"application.settings\");\n\nString color = settings.getModule1().getColor();\nString font = settings.getModule1().getFont();\n\nint blogs = settings.getModule2().getActiveBlogCount();\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31518/" ]
275,073
<p>I have just noticed that a multidimensional array in C# does not implement <code>IEnumerable&lt;T&gt;</code>, while it does implement <code>IEnumerable</code>. For single-dimensional arrays, both <code>IEnumerable&lt;T&gt;</code> and <code>IEnumerable</code> are implemented.</p> <p>Why this difference? If a multi-dimensional array is <code>IEnumerable</code>, surely it should also implement the generic version? I noticed this because I tried to use an extension method on a multidimensional array, which fails unless you use <code>Cast&lt;T&gt;</code> or similar; so I can definitely see the an argument for making multidimensional arrays implement <code>IEnumerable&lt;T&gt;</code>.</p> <p>To clarify my question in code, I would expect the following code to print <code>true</code> four times, while it actually prints <code>true</code>, <code>false</code>, <code>true</code>, <code>true</code>:</p> <pre><code>int[] singleDimensionArray = new int[10]; int[,] multiDimensional = new int[10, 10]; Debug.WriteLine(singleDimensionArray is IEnumerable&lt;int&gt;); Debug.WriteLine(multiDimensional is IEnumerable&lt;int&gt;); Debug.WriteLine(singleDimensionArray is IEnumerable); Debug.WriteLine(multiDimensional is IEnumerable); </code></pre>
[ { "answer_id": 275107, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 1, "selected": false, "text": "IEnumerable<int> int[] singleDimensionArray = new int[10];\nint[][] multiJagged = new int[10][];\n\nDebug.WriteLine(singleDimensionArray is IEnumerable<int>);\nDebug.WriteLine(multiJagged is IEnumerable<int[]>);\nDebug.WriteLine(singleDimensionArray is IEnumerable);\nDebug.WriteLine(multiJagged is IEnumerable);\n int[,] IEnumerable<int[]>" }, { "answer_id": 275129, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": true, "text": "System.Collections.Generic.IList<U> IEnumerable IEnumerable<T> IList<T> Cast<T>" }, { "answer_id": 1183153, "author": "Jader Dias", "author_id": 48465, "author_profile": "https://Stackoverflow.com/users/48465", "pm_score": 4, "selected": false, "text": "public static class ArrayExtensions\n{\n public static IEnumerable<T> ToEnumerable<T>(this Array target)\n {\n foreach (var item in target)\n yield return (T)item;\n }\n}\n" }, { "answer_id": 27322593, "author": "PEDRO ACOSTA MOLINA", "author_id": 4329858, "author_profile": "https://Stackoverflow.com/users/4329858", "pm_score": 0, "selected": false, "text": "int[] secondmarks = {20, 15, 31, 34, 35, 50, 40, 90, 99, 100, 20};\n\nIEnumerable<int> finallist = secondmarks.OrderByDescending(c => c);\n\nint[,] orderedMarks = new int[2, finallist.Count()];\n\nEnumerable.Range(0, finallist.Count()).ToList().ForEach(k => {orderedMarks[0, k] = (int) finallist.Skip(k).Take(1).Average();\norderedMarks[1, k] = k + 1;}); \n\nEnumerable.Range(0, finallist.Count()).Select(m => new {Score = orderedMarks[0, m], Place = orderedMarks[1, m]}).Dump();\n Score Place\n\n100 1\n99 2 \n90 3 \n50 4 \n40 5 \n35 6 \n34 7 \n31 8 \n20 9 \n20 10 \n15 11 \n" }, { "answer_id": 46997301, "author": "Sergey Teplyakov", "author_id": 250833, "author_profile": "https://Stackoverflow.com/users/250833", "pm_score": 4, "selected": false, "text": "IEnumerable IEnumerable<T> IEnumerable IEnumerable<T> public static class ArrayExtensions\n{\n public static IEnumerable<T> ToEnumerable<T>(this T[,] target)\n {\n foreach (var item in target)\n yield return item;\n }\n}\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13627/" ]
275,092
<p>We have a JavaScript function named "move" which does just "windows.location.href = <em>any given anchor</em>". <br/> This function works on IE, Opera and Safari, but somehow is ignored in Firefox. Researching on Google doesn't produce a satisfactory answer <strong>why</strong> it doesn't work. <br/> Does any JavaScript guru knows about this behavior, and what would be the best practice to jump to an anchor via JavaScript?</p>
[ { "answer_id": 275102, "author": "Dan Herbert", "author_id": 392, "author_profile": "https://Stackoverflow.com/users/392", "pm_score": 6, "selected": true, "text": "window.location = 'url';\n window.location.href location window.location" }, { "answer_id": 275104, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "javascript:window.location.href=\"#2.5\"; alert(window.location.href); javascript:(function () { window.location.href=\"#2.5\"; })();" }, { "answer_id": 275110, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 0, "selected": false, "text": "window.location.replace function navigateNext() \n{\n if (!window.location.hash) \n {\n window.location.replace(window.location.href + unescape(\"#2\"))\n } \n else \n {\n newItem = nextItem(window.location.hash)\n if (document.getElementById(newItem)) \n {\n window.location.replace(stripHash(window.location) + \"#\" + newItem)\n } \n else \n {\n window.location.replace(stripHash(window.location) + \"#1\")\n }\n }\n}\n" }, { "answer_id": 275192, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 1, "selected": false, "text": "<script>\n window.location.href = 'http://www.google.com/';\n</script>\n" }, { "answer_id": 275320, "author": "Mr. Muskrat", "author_id": 2657951, "author_profile": "https://Stackoverflow.com/users/2657951", "pm_score": 0, "selected": false, "text": "Response.Write(\"<script type='text/javaScript'> window.location = '#myAnchor'; </script>\";); \n" }, { "answer_id": 325507, "author": "graffic", "author_id": 15987, "author_profile": "https://Stackoverflow.com/users/15987", "pm_score": 2, "selected": false, "text": "setTimeout( \"location.replace('whatever.html');\", 0 );\n" }, { "answer_id": 326102, "author": "serg", "author_id": 20128, "author_profile": "https://Stackoverflow.com/users/20128", "pm_score": -1, "selected": false, "text": "document.location.href =\"...\"\n" }, { "answer_id": 390162, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "window.location.hash = \"#gallery\";\n" }, { "answer_id": 1334836, "author": "sprite", "author_id": 145211, "author_profile": "https://Stackoverflow.com/users/145211", "pm_score": 4, "selected": false, "text": "function JSNavSomewhere()\n{\n window.location.href = myUrl;\n return false;\n}\n <asp:button ........ onclick=\"return JSNavSomewhere();\" />\n" }, { "answer_id": 2236750, "author": "Ketan Mayangar", "author_id": 270267, "author_profile": "https://Stackoverflow.com/users/270267", "pm_score": 0, "selected": false, "text": "<script type=\"text/javascript\" language=\"javascript\"></script>" }, { "answer_id": 2497437, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "function thisWorks()\n{\n window.location.href = \"http://www.google.com\";\n return false;\n}\n\nfunction thisDoesNotWork()\n{\n window.location.href = \"http://www.google.com\";\n}\n" }, { "answer_id": 12794064, "author": "Awal Istirdja", "author_id": 1687851, "author_profile": "https://Stackoverflow.com/users/1687851", "pm_score": 0, "selected": false, "text": "<a> function sebelum_hapus()\n{\nvar setuju = confirm (\"Anda akan menghapus data...\")\nif (setuju)\nwindow.location = \"index.php\";\n}\n <a href=\"\" onClick=\"sebelum_hapus();\">Klik here</a>\n <a href=\"#\" onClick=\"sebelum_hapus();\">Klik here</a>\n" }, { "answer_id": 13972210, "author": "LCJ", "author_id": 696627, "author_profile": "https://Stackoverflow.com/users/696627", "pm_score": 3, "selected": false, "text": "IE Chrome Firefox window.location.href(\"http://stackoverflow.com\");\n window.location.href = \"http://stackoverflow.com\";\n" }, { "answer_id": 40882141, "author": "VikasChauhan", "author_id": 5793125, "author_profile": "https://Stackoverflow.com/users/5793125", "pm_score": 0, "selected": false, "text": "window.location.assign(\"link to next page\")" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34815/" ]
275,109
<p>I'm writing a url rewrite in django that when a person goes to <a href="http://mysite.com/urlchecker/http://www.google.com" rel="nofollow noreferrer">http://mysite.com/urlchecker/http://www.google.com</a> it sends the url: <a href="http://ww.google.com" rel="nofollow noreferrer">http://ww.google.com</a> to a view as a string variable. </p> <p>I tried doing:</p> <pre><code>(r'^urlchecker/(?P&lt;url&gt;\w+)/$', 'mysite.main.views.urlchecker'), </code></pre> <p>But that didn't work. Anyone know what I'm doing wrong?</p> <p>Also, generally is there a good resource to learn regular expressions specifically for python/django?</p> <p>Thanks guys!</p>
[ { "answer_id": 275117, "author": "Peter Rowell", "author_id": 17017, "author_profile": "https://Stackoverflow.com/users/17017", "pm_score": 3, "selected": true, "text": "(r'^urlchecker/(?P<url>.+)$', 'mysite.main.views.urlchecker')," } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23695/" ]
275,120
<p>Given a class, <a href="http://help.eclipse.org/stable/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/api/org/eclipse/ui/views/navigator/ResourceNavigator.html" rel="noreferrer">org.eclipse.ui.views.navigator.ResourceNavigator</a> for example, how do I find out which jar file to use? I know it's in org.eclipse.ui.ide, but how would I find that out?</p> <p><strong>Edit</strong>: Thank you to all of you who answered. Like many things, there seems to be several ways to skin this cat. I wish javadoc contained this info. So far here are the different methods:</p> <ol> <li><p>Without Internet, Eclipse or NetBeans:</p> <pre><code>for f in `find . -name '*.jar'`; do echo $f &amp;&amp; jar tvf $f | grep -i $1; done </code></pre></li> <li><p>If you want to find out locally using Eclipse:</p> <ul> <li><a href="http://www.alphaworks.ibm.com/tech/jarclassfinder" rel="noreferrer">JAR Class Finder Plug-in</a></li> <li><a href="http://classlocator.sourceforge.net/" rel="noreferrer">Class Locator Plug-in</a></li> </ul></li> <li><p>If you want to find out from Internet or you do not have the jar yet:</p> <ul> <li><a href="http://www.jarfinder.com/" rel="noreferrer">jarFinder</a></li> <li><a href="http://findjar.com/" rel="noreferrer">findjar.com</a></li> </ul></li> </ol>
[ { "answer_id": 275125, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 1, "selected": false, "text": "jar -vtf foo.jar" }, { "answer_id": 275144, "author": "user28791", "author_id": 28791, "author_profile": "https://Stackoverflow.com/users/28791", "pm_score": 3, "selected": false, "text": "for f in `find . -name '*.jar'`; do echo $f && jar tvf $f | grep -i $1; done\n" }, { "answer_id": 8076739, "author": "user1039322", "author_id": 1039322, "author_profile": "https://Stackoverflow.com/users/1039322", "pm_score": 2, "selected": false, "text": "**shell> find . -name \"*.jar\" | xargs -i -t \\jar tvf {} | grep [TheClassNameYouAreLookingFor]**\n shell> find apache-commons/ -name \"*.jar\" | xargs -i -t \\jar tvf {} | grep LogFactory.class\n\njar tvf apache-commons/commons-beanutils-1.7.0.jar\n\njar tvf apache-commons/commons-fileupload-1.2.1.jar\n\njar tvf apache-commons/commons-lang-2.3.jar\n\n**jar tvf apache-commons/commons-logging-1.1.jar**\n\n**21140 Tue May 09 23:08:12 EDT 2006 org/apache/commons/logging/LogFactory.class**\n\njar tvf apache-commons/commons-net-1.3.0.jar\n" }, { "answer_id": 14685373, "author": "user2039378", "author_id": 2039378, "author_profile": "https://Stackoverflow.com/users/2039378", "pm_score": 3, "selected": false, "text": "find * -type f -name '*.jar' -exec grep -l 'TestClass.class' '{}' \\;\n" }, { "answer_id": 46919673, "author": "Geoffrey Ritchey", "author_id": 2831843, "author_profile": "https://Stackoverflow.com/users/2831843", "pm_score": 1, "selected": false, "text": "find . -name \"*.jar\" -print -exec jar -tf {} \\; >outputfile\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3827/" ]
275,128
<p>Is there any way of doing parallel assignment in C++? Currently, the below compiles (with warnings)</p> <pre><code>#include &lt;iostream&gt; int main() { int a = 4; int b = 5; a, b = b, a; std::cout &lt;&lt; "a: " &lt;&lt; a &lt;&lt; endl &lt;&lt; "b: " &lt;&lt; b &lt;&lt; endl; return 0; } </code></pre> <p>and prints:</p> <pre><code>a: 4 b: 5 </code></pre> <p>What I'd like it to print ... if it weren't obvious, is:</p> <pre><code>a: 5 b: 4 </code></pre> <p>As in, say, ruby, or python.</p>
[ { "answer_id": 275146, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 1, "selected": false, "text": "int a = 4;\nint b = 5;\n\n{\n int tmp = a;\n a = b;\n b = tmp;\n}\n { a, b }" }, { "answer_id": 275149, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 5, "selected": true, "text": "a, b = b, a;\n a, (b = b), a\n std::swap(a, b);\n tie(a, b) = make_tuple(b, a);\n" }, { "answer_id": 275155, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 2, "selected": false, "text": "a,b,c a, b a, b = b, a a; b = b; a;" }, { "answer_id": 277954, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 0, "selected": false, "text": "template <typename T1> void ParAssign(T1& Lhs_1, T1 const& Rhs1);\ntemplate <typename T1, typename T2> void ParAssign(T1& Lhs1, T2& Lhs2, T1 const& Rhs1, T2 const& Rhs2);\n// etc.\nParAssign(a,b,\n b,a);\n" }, { "answer_id": 47930129, "author": "Scheff's Cat", "author_id": 7478597, "author_profile": "https://Stackoverflow.com/users/7478597", "pm_score": 1, "selected": false, "text": "#include <iostream>\nusing namespace std;\n\nint main()\n{\n int a = 4, b = 5;\n cout << \"Before assignment: a: \" << a << \", b: \" << b << endl;\n pair<int&, int&> ba(b, a);\n ba = make_pair(a, b); // <===: (b, a) = (a, b)\n cout << \"After assignment : a: \" << a << \", b: \" << b << endl;\n return 0;\n}\n Before assignment: a: 4, b: 5\nAfter assignment : a: 5, b: 4\n a, b std::pair make_pair() -std=c++03 -std=c++11" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35807/" ]
275,150
<p>My website is XHTML Transitional compliant <strong>except for one thing</strong>: the &amp; (ampersand) in the URL are written as it is, instead of <code>&amp;amp;</code></p> <p>That is, all the URLs in my pages are usually like this:</p> <pre><code>&lt;a href=&quot;http://www.example.org/page.aspx?x=1&amp;y=2&quot;&gt;Foo&lt;/a&gt; </code></pre> <p>But <a href="http://validator.w3.org/" rel="nofollow noreferrer">XHTML validator</a> generates this error:</p> <blockquote> <p>cannot generate system identifier for general entity &quot;y&quot;</p> </blockquote> <p>... and it wants the URL to be written like this:</p> <pre><code>&lt;a href=&quot;http://www.example.org/page.aspx?x=1&amp;amp;y=2&quot;&gt;Foo&lt;/a&gt; </code></pre> <p>The problem is that Internet Explorer and Firefox don't handle the URL correctly and ignore the y parameter. <strong>How can I make this link work and validate correctly?</strong></p> <p>It seems to me that it is impossible to write XHTML pages if the browsers don't work with strict encoded XHTML URLs.</p> <p>Do you want to see in action? See the difference between these two links (copy and paste them as they are):</p> <pre><code>http://stackoverflow.com/search?q=ff&amp;sort=newest </code></pre> <p>and</p> <pre><code>http://stackoverflow.com/search?q=ff&amp;amp;sort=newest </code></pre>
[ { "answer_id": 275154, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 3, "selected": false, "text": "&amp; & <a href=\"http://www.example.org/page.aspx?x=1&amp;y=2\">Foo</a>\n /mypath/mypage?b=%26stuff\n" }, { "answer_id": 275252, "author": "pipTheGeek", "author_id": 28552, "author_profile": "https://Stackoverflow.com/users/28552", "pm_score": 7, "selected": true, "text": "& &amp; & %26 <a href=\"Default2.aspx?param1=63&amp;param2=hel\">Click me</a> default2.aspx & &amp; &amp; &amp;" }, { "answer_id": 275371, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "& http://foo?x=1&amp;y=2 http://foo?x=1&amp;amp;y=2 &amp" }, { "answer_id": 280408, "author": "Simon", "author_id": 15371, "author_profile": "https://Stackoverflow.com/users/15371", "pm_score": -1, "selected": false, "text": "&amp;amp; &amp;#38;" }, { "answer_id": 26046095, "author": "kasimir", "author_id": 1005334, "author_profile": "https://Stackoverflow.com/users/1005334", "pm_score": 0, "selected": false, "text": "&#38; &amp;" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
275,153
<p>Basically I have a website. I have a properly setup sitemap so I assume Google knows about all of my pages. And I've seen on some sites, the search form leads to a page with the shell of the original site but the results are clearly provided by Google. Similar to codinghorror.com's search, however his results aren't shown within his website's layout.</p> <p>Any idea what I'm talking about or how to achieve this?</p>
[ { "answer_id": 275157, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 4, "selected": false, "text": "<form method=\"get\" action=\"http://www.google.com/search\">\n\n<div style=\"border:1px solid black;padding:4px;width:20em;\">\n<table border=\"0\" cellpadding=\"0\">\n<tr><td>\n<input type=\"text\" name=\"q\" size=\"25\"\n maxlength=\"255\" value=\"\" />\n<input type=\"submit\" value=\"Google Search\" /></td></tr>\n<tr><td align=\"center\" style=\"font-size:75%\">\n<input type=\"checkbox\" name=\"sitesearch\"\n value=\"askdavetaylor.com\" checked /> only search Ask Dave Taylor<br />\n</td></tr></table>\n</div>\n\n</form>\n <html>\n<head>\n <meta http-equiv=\"Content-Language\" content=\"en-gb\">\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=windows-1252\">\n\n <script language=\"javascript\" type=\"text/javascript\">\n function showFrame () {\n var e = document.getElementById(\"if1\");\n e.style.visibility = \"visible\" ;\n }\n </script>\n</head>\n\n<body>\n <p> </p>\n <p>\n <span id=\"spSearch\" onclick=\"showFrame()\">Search</span>\n </p>\n <p> </p>\n <p><iframe name=\"I1\" id=\"if1\" width=\"100%\" height=\"254\" style=\"visibility:hidden\" src=\"http://www.google.co.uk\">\n Your browser does not support inline frames or is currently configured not to display inline frames.\n </iframe></p>\n</body>\n</html>\n" }, { "answer_id": 289619, "author": "Liam", "author_id": 18333, "author_profile": "https://Stackoverflow.com/users/18333", "pm_score": 3, "selected": false, "text": "site:" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/428190/" ]
275,160
<p>Just starting to explore the 'wonders' of regex. Being someone who learns from trial and error, I'm really struggling because my trials are throwing up a disproportionate amount of errors... My experiments are in PHP using ereg().</p> <p>Anyway. I work with first and last names separately but for now using the same regex. So far I have:</p> <pre><code>^[A-Z][a-zA-Z]+$ </code></pre> <p>Any length string that starts with a capital and has only letters (capital or not) for the rest. But where I fall apart is dealing with the special situations that can pretty much occur anywhere.</p> <ul> <li>Hyphenated Names (Worthington-Smythe) </li> <li>Names with Apostophies (D'Angelo) </li> <li>Names with Spaces (Van der Humpton) - capitals in the middle which may or may not be required is way beyond my interest at this stage.</li> <li>Joint Names (Ben &amp; Jerry)</li> </ul> <p>Maybe there's some other way a name can be that I'm no thinking of, but I suspect if I can get my head around this, I can add to it. I'm pretty sure there will be instances where more than one of these situations comes up in one name.</p> <p>So, I think the bottom line is to have my regex also accept a space, hyphens, ampersands and apostrophes - but not at the start or end of the name to be technically correct.</p>
[ { "answer_id": 275177, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 7, "selected": true, "text": "a-z" }, { "answer_id": 275180, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 1, "selected": false, "text": "^[A-Z][a-zA-Z '&-]*[A-Za-z]$ \n" }, { "answer_id": 275687, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 3, "selected": false, "text": "\\p{L}" }, { "answer_id": 2044909, "author": "Daan", "author_id": 58565, "author_profile": "https://Stackoverflow.com/users/58565", "pm_score": 6, "selected": false, "text": "^([ \\u00c0-\\u01ffa-zA-Z'\\-])+$\n Jérémie O'Co-nor" }, { "answer_id": 4549739, "author": "Abhisek.test", "author_id": 556467, "author_profile": "https://Stackoverflow.com/users/556467", "pm_score": 1, "selected": false, "text": "^[a-zA-Z][a-zA-Z0-9_]*\\.?[a-zA-Z0-9_\\.]*$\n" }, { "answer_id": 5994825, "author": "uke", "author_id": 339661, "author_profile": "https://Stackoverflow.com/users/339661", "pm_score": 2, "selected": false, "text": " +[a-z]{2,3} +[a-z]*|[\\w'-]*\n" }, { "answer_id": 8880713, "author": "Tatarasanu Victor", "author_id": 1169171, "author_profile": "https://Stackoverflow.com/users/1169171", "pm_score": 1, "selected": false, "text": "/([\\u00c0-\\u01ffa-zA-Z'\\-]+[ ]?[*]?[\\u00c0-\\u01ffa-zA-Z'\\-]*)+/;" }, { "answer_id": 11342352, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "//http://support.microsoft.com/kb/177506\nforeach(array('/','\\\\',':','*','?','<','>','|') as $char)\n if(strpos($name,$char)!==false)\n die(\"Not allowed char: '$char'\");\n" }, { "answer_id": 11634636, "author": "paviktherin", "author_id": 667434, "author_profile": "https://Stackoverflow.com/users/667434", "pm_score": 0, "selected": false, "text": "/([\\-'a-z]+\\s?){2,4}/\n" }, { "answer_id": 25826707, "author": "majestic", "author_id": 4038323, "author_profile": "https://Stackoverflow.com/users/4038323", "pm_score": 1, "selected": false, "text": "^([\\u00c0-\\u01ffa-zA-Z]+\\b['\\-]{0,1})+\\b$\n" }, { "answer_id": 27756303, "author": "doncadavona", "author_id": 3936053, "author_profile": "https://Stackoverflow.com/users/3936053", "pm_score": 0, "selected": false, "text": "/^([a-zA-Z]+[\\s'.]?)+\\S$/\n" }, { "answer_id": 31564796, "author": "Taher Ahmed", "author_id": 3436060, "author_profile": "https://Stackoverflow.com/users/3436060", "pm_score": 4, "selected": false, "text": "^([A-Za-z])+$\n ^[A-Za-z]+(((\\'|\\-|\\.)?([A-Za-z])+))?$\n ^[A-Za-z]+((\\s)?((\\'|\\-|\\.)?([A-Za-z])+))*$\n ^[A-Za-z]+((\\s)?([A-Za-z])+)*$\n ^(\\s)*[A-Za-z]+((\\s)?((\\'|\\-|\\.)?([A-Za-z])+))*(\\s)*$\n (\\'|\\-|\\.)\n (\\'|\\-|\\.|\\_)\n" }, { "answer_id": 46262215, "author": "Aominé", "author_id": 7731859, "author_profile": "https://Stackoverflow.com/users/7731859", "pm_score": 0, "selected": false, "text": "^[a-zA-Z'-]{3,}\\s[a-zA-Z'-]{3,}$\n ^ $ \\s [a-zA-Z'-\\s]{3,} ' - jean-luc \\s ^[a-zA-Z'-\\s]{3,}\\s[a-zA-Z'-]{3,}$\n" }, { "answer_id": 46292284, "author": "tk_", "author_id": 3168721, "author_profile": "https://Stackoverflow.com/users/3168721", "pm_score": 3, "selected": false, "text": "^(([A-Za-z]+[,.]?[ ]?|[a-z]+['-]?)+)$\n" }, { "answer_id": 65544550, "author": "Charlie Brown", "author_id": 13941632, "author_profile": "https://Stackoverflow.com/users/13941632", "pm_score": -1, "selected": false, "text": "^[a-zA-Z'-\\s\\.]{3,20}\\s[a-zA-Z'-\\.]{3,20}$\n Jane J. Samuels John Simms Snr. D'amalia Jones \nDavid Silva Jnr. \nJay-Silva Thompson\nShay .J. Muhanned\nBob J. Iverson\n" }, { "answer_id": 66102679, "author": "Jakub Brzezinski", "author_id": 15169257, "author_profile": "https://Stackoverflow.com/users/15169257", "pm_score": 0, "selected": false, "text": "^(?:(?!^\\s|[ \\-']{2}|[\\d\\r\\n\\t\\f\\v!\"#$%&()*+,\\.\\/:;<=>?@[\\\\\\]^_`{|}~€‚ƒ„…†‡ˆ‰‹‘’“”•–—˜™›¡¢£¤¥¦§¨©ª«¬®¯°±²³´¶·¸¹º»¼½¾¿×÷№′″ⁿ⁺⁰‱₁₂₃₄]|\\s$).){1,50}$\n" }, { "answer_id": 69013701, "author": "Aman Godara", "author_id": 12581494, "author_profile": "https://Stackoverflow.com/users/12581494", "pm_score": 1, "selected": false, "text": "^[A-Z][a-z]*(([,.] |[ '-])[A-Za-z][a-z]*)*(\\.?)( [IVXLCDM]+)?$" }, { "answer_id": 71010691, "author": "kkyucon", "author_id": 14774669, "author_profile": "https://Stackoverflow.com/users/14774669", "pm_score": 0, "selected": false, "text": "$pattern = \"/^((\\p{Lu}{1})\\S(\\p{Ll}{1,20})[^0-9])+[-'\\s]((\\p{Lu}{1})\\S(\\p{Ll}{1,20}))*[^0-9]$/u\";\n \"Jane Doe\" \"John Doe\" \"Marie-Josée Côté-Rochon\" \"Bill O'reilly\" 0-9 trim() \"John J. William\" \"Francis O'reilly Jr. III\" \"John\" \"Jane\" \"O'reilly\" \"Smith\" [^0-9] $pattern = \"/^(\\p{Lu}{1}\\S\\p{Ll}{1,20}[-'\\s]\\p{Lu}{1}\\S\\p{Ll}{1,20})+([^\\d]+)$/u\";\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1444/" ]
275,169
<p>I have 2 files:</p> <pre><code>/****demo.cpp****/ #include &lt;iostream.h&gt; #include "gc.h" class foo{}; int main(){ gc&lt;foo&gt; x1; cout&lt;&lt;x1; } /*****gc.h*****/ template &lt;class T&gt; class gc { T* ptr; public: operator T*(){} }; </code></pre> <p>If I don't write <code>operator T*(){}</code> then I get a lot of compiler errors.</p> <p>So plz tell me what is <code>operator T*(void)</code> and when it is invoked?</p>
[ { "answer_id": 275176, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 2, "selected": false, "text": "T*(){} gc<T> T* ptr template <class T>\nstd::ostream& operator<<( std::ostream& os, const gc<T>& x)\n{\n // os << .. something useful here ..\n return os;\n}\n" }, { "answer_id": 275183, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "operator type () type operator T* () operator<< iostream.h iostream iostream.h math.h, stdio.h cmath cstdio namespace std cout std::cout" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
275,174
<p>I have a string that is HTML encoded: </p> <pre><code>'''&amp;lt;img class=&amp;quot;size-medium wp-image-113&amp;quot;\ style=&amp;quot;margin-left: 15px;&amp;quot; title=&amp;quot;su1&amp;quot;\ src=&amp;quot;http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg&amp;quot;\ alt=&amp;quot;&amp;quot; width=&amp;quot;300&amp;quot; height=&amp;quot;194&amp;quot; /&amp;gt;''' </code></pre> <p>I want to change that to:</p> <pre class="lang-html prettyprint-override"><code>&lt;img class="size-medium wp-image-113" style="margin-left: 15px;" title="su1" src="http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg" alt="" width="300" height="194" /&gt; </code></pre> <p>I want this to register as HTML so that it is rendered as an image by the browser instead of being displayed as text. </p> <p>The string is stored like that because I am using a web-scraping tool called <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="noreferrer"><code>BeautifulSoup</code></a>, it "scans" a web-page and gets certain content from it, then returns the string in that format.</p> <p>I've found how to do this in <strong>C#</strong> but not in <strong>Python</strong>. Can someone help me out?</p> <h3>Related</h3> <ul> <li><a href="https://stackoverflow.com/questions/57708/convert-xml-html-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li> </ul>
[ { "answer_id": 275195, "author": "Jake", "author_id": 24730, "author_profile": "https://Stackoverflow.com/users/24730", "pm_score": 2, "selected": false, "text": "htmlCodes = [\n ['&', '&amp;'],\n ['<', '&lt;'],\n ['>', '&gt;'],\n ['\"', '&quot;'],\n]\nhtmlCodesReversed = htmlCodes[:]\nhtmlCodesReversed.reverse()\ndef htmlDecode(s, codes=htmlCodesReversed):\n \"\"\" Returns the ASCII decoded version of the given HTML string. This does\n NOT remove normal HTML tags like <p>. It is the inverse of htmlEncode().\"\"\"\n for code in codes:\n s = s.replace(code[1], code[0])\n return s\n def htmlEncode(s, codes=htmlCodes):\n \"\"\" Returns the HTML encoded version of the given string. This is useful to\n display a plain ASCII text string on a web page.\"\"\"\n for code in codes:\n s = s.replace(code[0], code[1])\n return s\n" }, { "answer_id": 275246, "author": "Daniel Naab", "author_id": 32638, "author_profile": "https://Stackoverflow.com/users/32638", "pm_score": 8, "selected": true, "text": "django.utils.html.escape def escape(html):\n \"\"\"Returns the given HTML with ampersands, quotes and carets encoded.\"\"\"\n return mark_safe(force_unicode(html).replace('&', '&amp;').replace('<', '&l\nt;').replace('>', '&gt;').replace('\"', '&quot;').replace(\"'\", '&#39;'))\n def html_decode(s):\n \"\"\"\n Returns the ASCII decoded version of the given HTML string. This does\n NOT remove normal HTML tags like <p>.\n \"\"\"\n htmlCodes = (\n (\"'\", '&#39;'),\n ('\"', '&quot;'),\n ('>', '&gt;'),\n ('<', '&lt;'),\n ('&', '&amp;')\n )\n for code in htmlCodes:\n s = s.replace(code[1], code[0])\n return s\n\nunescaped = html_decode(my_string)\n django.utils.html.escape # Python 2.x:\nimport HTMLParser\nhtml_parser = HTMLParser.HTMLParser()\nunescaped = html_parser.unescape(my_string)\n\n# Python 3.x:\nimport html.parser\nhtml_parser = html.parser.HTMLParser()\nunescaped = html_parser.unescape(my_string)\n\n# >= Python 3.5:\nfrom html import unescape\nunescaped = unescape(my_string)\n {{ context_var|safe }}\n{% autoescape off %}\n {{ context_var }}\n{% endautoescape %}\n" }, { "answer_id": 275463, "author": "vincent", "author_id": 34871, "author_profile": "https://Stackoverflow.com/users/34871", "pm_score": 4, "selected": false, "text": "from BeautifulSoup import BeautifulStoneSoup\nBeautifulStoneSoup(\"Sacr&eacute; bl&#101;u!\", \n convertEntities=BeautifulStoneSoup.HTML_ENTITIES).contents[0]\n# u'Sacr\\xe9 bleu!'\n" }, { "answer_id": 449169, "author": "user26294", "author_id": 26294, "author_profile": "https://Stackoverflow.com/users/26294", "pm_score": 6, "selected": false, "text": ">> help(cgi.escape)\ncgi.escape = escape(s, quote=None)\n Replace special characters \"&\", \"<\" and \">\" to HTML-safe sequences.\n If the optional flag quote is true, the quotation mark character (\")\n is also translated.\n import re\nfrom htmlentitydefs import name2codepoint\n# for some reason, python 2.5.2 doesn't have this one (apostrophe)\nname2codepoint['#39'] = 39\n\ndef unescape(s):\n \"unescape HTML code refs; c.f. http://wiki.python.org/moin/EscapingHtml\"\n return re.sub('&(%s);' % '|'.join(name2codepoint),\n lambda m: unichr(name2codepoint[m.group(1)]), s)\n" }, { "answer_id": 3271650, "author": "slowkvant", "author_id": 162125, "author_profile": "https://Stackoverflow.com/users/162125", "pm_score": 3, "selected": false, "text": "def decodeHtmlentities(string):\n import re\n entity_re = re.compile(\"&(#?)(\\d{1,5}|\\w{1,8});\")\n\n def substitute_entity(match):\n from htmlentitydefs import name2codepoint as n2cp\n ent = match.group(2)\n if match.group(1) == \"#\":\n return unichr(int(ent))\n else:\n cp = n2cp.get(ent)\n\n if cp:\n return unichr(cp)\n else:\n return match.group()\n\n return entity_re.subn(substitute_entity, string)[0]\n" }, { "answer_id": 7088472, "author": "Jiangge Zhang", "author_id": 718453, "author_profile": "https://Stackoverflow.com/users/718453", "pm_score": 7, "selected": false, "text": "try:\n from html import escape # python 3.x\nexcept ImportError:\n from cgi import escape # python 2.x\n\nprint(escape(\"<\"))\n try:\n from html import unescape # python 3.4+\nexcept ImportError:\n try:\n from html.parser import HTMLParser # python 3.x (<3.4)\n except ImportError:\n from HTMLParser import HTMLParser # python 2.x\n unescape = HTMLParser().unescape\n\nprint(unescape(\"&gt;\"))\n" }, { "answer_id": 8524552, "author": "Mike Samuel", "author_id": 20394, "author_profile": "https://Stackoverflow.com/users/20394", "pm_score": 0, "selected": false, "text": "htmlentitydefs htmlentitydefs &NotEqualTilde; NotEqualTilde; U+02242 U+00338 ≂̸\n def decodeHtmlText(html):\n \"\"\"\n Given a string of HTML that would parse to a single text node,\n return the text value of that node.\n \"\"\"\n # Fast path for common case.\n if html.find(\"&\") < 0: return html\n return re.sub(\n '&(?:#(?:x([0-9A-Fa-f]+)|([0-9]+))|([a-zA-Z0-9]+));',\n _decode_html_entity,\n html)\n\ndef _decode_html_entity(match):\n \"\"\"\n Regex replacer that expects hex digits in group 1, or\n decimal digits in group 2, or a named entity in group 3.\n \"\"\"\n hex_digits = match.group(1) # '&#10;' -> unichr(10)\n if hex_digits: return unichr(int(hex_digits, 16))\n decimal_digits = match.group(2) # '&#x10;' -> unichr(0x10)\n if decimal_digits: return unichr(int(decimal_digits, 10))\n name = match.group(3) # name is 'lt' when '&lt;' was matched.\n if name:\n decoding = (htmlentitydefs.name2codepoint.get(name)\n # Treat &GT; like &gt;.\n # This is wrong for &Gt; and &Lt; which HTML5 adopted from MathML.\n # If htmlentitydefs included mappings for those entities,\n # then this code will magically work.\n or htmlentitydefs.name2codepoint.get(name.lower()))\n if decoding is not None: return unichr(decoding)\n return match.group(0) # Treat \"&noSuchEntity;\" as \"&noSuchEntity;\"\n" }, { "answer_id": 8593583, "author": "Chris Harty", "author_id": 990114, "author_profile": "https://Stackoverflow.com/users/990114", "pm_score": 3, "selected": false, "text": "<html>\n{{ node.description|safe }}\n</html>\n" }, { "answer_id": 9468081, "author": "Seth Gottlieb", "author_id": 561578, "author_profile": "https://Stackoverflow.com/users/561578", "pm_score": 1, "selected": false, "text": "from django.utils.html import escape\n\nsomething_nice = escape(request.POST['something_naughty'])\n" }, { "answer_id": 11273187, "author": "smilitude", "author_id": 439649, "author_profile": "https://Stackoverflow.com/users/439649", "pm_score": 0, "selected": false, "text": "{% autoescape on %}\n {{ body }}\n{% endautoescape %}\n" }, { "answer_id": 28268163, "author": "James", "author_id": 1870013, "author_profile": "https://Stackoverflow.com/users/1870013", "pm_score": 2, "selected": false, "text": "In [1]: from django.utils.text import unescape_entities\nIn [2]: unescape_entities('&lt;img class=&quot;size-medium wp-image-113&quot; style=&quot;margin-left: 15px;&quot; title=&quot;su1&quot; src=&quot;http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg&quot; alt=&quot;&quot; width=&quot;300&quot; height=&quot;194&quot; /&gt;')\nOut[2]: u'<img class=\"size-medium wp-image-113\" style=\"margin-left: 15px;\" title=\"su1\" src=\"http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg\" alt=\"\" width=\"300\" height=\"194\" />'\n" }, { "answer_id": 31282266, "author": "Collin Anderson", "author_id": 131881, "author_profile": "https://Stackoverflow.com/users/131881", "pm_score": 4, "selected": false, "text": "import html\n\nhtml.unescape(your_string)\n" }, { "answer_id": 51404291, "author": "Paolo Melchiorre", "author_id": 755343, "author_profile": "https://Stackoverflow.com/users/755343", "pm_score": 0, "selected": false, "text": "scraped_html clean_html scraped_html = (\n '&lt;img class=&quot;size-medium wp-image-113&quot; '\n 'style=&quot;margin-left: 15px;&quot; title=&quot;su1&quot; '\n 'src=&quot;http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg&quot; '\n 'alt=&quot;&quot; width=&quot;300&quot; height=&quot;194&quot; /&gt;'\n)\nclean_html = (\n '<img class=\"size-medium wp-image-113\" style=\"margin-left: 15px;\" '\n 'title=\"su1\" src=\"http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg\" '\n 'alt=\"\" width=\"300\" height=\"194\" />'\n)\n >>> from django.utils.text import unescape_entities\n>>> clean_html == unescape_entities(scraped_html)\nTrue\n >>> from django.utils.html import escape\n>>> scraped_html == escape(clean_html)\nTrue\n &gt; &#62; &x3e; >>> from html import unescape\n>>> clean_html == unescape(scraped_html)\nTrue\n & < > >>> from html import escape\n>>> scraped_html == escape(clean_html)\nTrue\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23695/" ]
275,178
<p>We are using IIS 6 and ASP.Net, When users make secure page requests using </p> <blockquote> <p><strong><a href="https://somesite.com/securePage.aspx" rel="nofollow noreferrer">https://somesite.com/securePage.aspx</a></strong></p> </blockquote> <p>the user gets an error:</p> <hr> <blockquote> <p><strong>Error code: ssl error bad cert domain</strong></p> </blockquote> <hr> <p>The certificate was issued to <strong>www.somesite.com</strong> and indicates that <strong>somesite.com</strong> uses an invalid security certificate.</p> <p>I was hoping to be able to catch the request in the Application BeginRequest event but the SSL error occurs before this. In order to invoke the Application BeginRequest event the user needs to click through the certificate error message. Is it possible to redirect in code or does this fix need to occur within IIS?</p>
[ { "answer_id": 275210, "author": "djn", "author_id": 9673, "author_profile": "https://Stackoverflow.com/users/9673", "pm_score": -1, "selected": false, "text": "RewriteEngine On\nRewriteCond %{HTTP_HOST} ^example\\.com$ [NC]\nRewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]\n" }, { "answer_id": 20060333, "author": "Nazca", "author_id": 2792592, "author_profile": "https://Stackoverflow.com/users/2792592", "pm_score": 0, "selected": false, "text": "https://mydomain.com - works\nhttps://www.mydomain.com - works\nhttps://www.mysite.com - ERROR\nhttps://mysite.com - works\nhttps://thissite.com - works\nhttps://www.thissite.com - works.\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4814/" ]
275,194
<p>How can I format data coming from a DataBinder.Eval statement in an ASPX page?</p> <p>For example, I want to display the published date of the news items in a particular format in the homepage. I'm using the ASP.NET 2.0 Repeater control to show the list of news items.</p> <p>The code for this goes like this:</p> <pre><code>&lt;asp:Repeater ID="Repeater1" runat="server" DataSourceID="ObjectDataSource1"&gt; &lt;HeaderTemplate&gt;&lt;table cellpadding="0" cellspacing="0" width="255"&gt;&lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;tr&gt;&lt;td &gt; &lt;a href='/content/latestNews.aspx?id=&lt;%#DataBinder.Eval(Container.DataItem, "id") %&gt;'&gt; &lt;asp:Label ID="lblNewsTitle" runat="server" Text='&lt;%# DataBinder.Eval(Container.DataItem, "title") %&gt;'&gt;&lt;/asp:Label&gt; &lt;/a&gt; &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt; &lt;asp:Label ID="lblNewsDate" runat="server" Text='&lt;%# DataBinder.Eval(Container.DataItem, "publishedDate"))%&gt;'&gt;&lt;/asp:Label&gt; &lt;/td&gt;&lt;/tr&gt; &lt;/ItemTemplate&gt; &lt;FooterTemplate&gt;&lt;/table&gt;&lt;/FooterTemplate&gt;&lt;/asp:Repeater&gt; </code></pre> <p>Is there a way I could call a custom method with the DataBinder.Eval value as its parameter (something like below)?</p> <pre><code>&lt;asp:Label ID="lblNewsDate" runat="server" Text='&lt;%# GetDateInHomepageFormat(DataBinder.Eval(Container.DataItem, "publishedDate")) )%&gt;'&gt;&lt;/asp:Label&gt; </code></pre> <p>If yes, then where do I write the GetDateInHomepageFormat method? I tried out in the code behind page but got a run time error? If this is not possible, is there a way to do inline formatting?</p>
[ { "answer_id": 275218, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 7, "selected": true, "text": "<%# DataBinder.Eval(Container.DataItem, \"expression\"[, \"format\"]) %>\n <asp:Label id=\"lblNewsDate\" runat=\"server\" Text='<%# DataBinder.Eval(Container.DataItem, \"publishedDate\", \"{0:dddd d MMMM}\") %>'</label>\n" }, { "answer_id": 275319, "author": "dexter", "author_id": 2703984, "author_profile": "https://Stackoverflow.com/users/2703984", "pm_score": 4, "selected": false, "text": "<%# ((DateTime)DataBinder.Eval(Container.DataItem,\"publishedDate\")).ToString(\"yyyy-MMM-dd\") %>\n <%# ((DateTime)Eval(\"publishedDate\")).ToString(\"yyyy-MMM-dd\") %>\n" }, { "answer_id": 275828, "author": "Nahom Tijnam", "author_id": 11172, "author_profile": "https://Stackoverflow.com/users/11172", "pm_score": 4, "selected": false, "text": "<asp:Label ID=\"lblNewsDate\" runat=\"server\" Text='<%# GetDateInHomepageFormat(DataBinder.Eval(Container.DataItem, \"publishedDate\")) )%>'></asp:Label>\n public partial class _Default : System.Web.UI.Page\n{\n\n protected string GetDateInHomepageFormat(DateTime d)\n {\n\n string retValue = \"\";\n\n // Do all processing required and return value\n\n return retValue;\n }\n}\n" }, { "answer_id": 1211493, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<%#DateTime.Parse(Eval(\"DDDate\").ToString()).ToString(\"dd-MM-yyyy\")%>\n" }, { "answer_id": 1439119, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<asp:Label ID=\"ServiceBeginDate\" runat=\"server\" Text='<%# (DataBinder.Eval(Container.DataItem, \"ServiceBeginDate\", \"{0:yyyy}\") == \"0001\") ? \"\" : DataBinder.Eval(Container.DataItem, \"ServiceBeginDate\", \"{0:MM/dd/yyyy}\") %>'>\n</asp:Label>\n" }, { "answer_id": 1605239, "author": "santosh kumar", "author_id": 194332, "author_profile": "https://Stackoverflow.com/users/194332", "pm_score": 0, "selected": false, "text": "<%# DataBinder.Eval(Container.DataItem, \"DateColoumnName\", \"{0:dd-MMM-yyyy}\") %>\n" }, { "answer_id": 6026812, "author": "Diego C.", "author_id": 80268, "author_profile": "https://Stackoverflow.com/users/80268", "pm_score": 4, "selected": false, "text": "<asp:Label id=\"lblNewsDate\" runat=\"server\" Text='<%# Eval(\"publishedDate\", \"{0:dddd d MMMM}\") %>'</label>\n protected internal string Eval(\nstring expression,\nstring format\n" }, { "answer_id": 7651385, "author": "GMG", "author_id": 978506, "author_profile": "https://Stackoverflow.com/users/978506", "pm_score": 2, "selected": false, "text": "<%#((DateTime)Eval(\"ExpDate\")).ToString(\"d\")%>\n" }, { "answer_id": 7762117, "author": "gaz", "author_id": 892575, "author_profile": "https://Stackoverflow.com/users/892575", "pm_score": 1, "selected": false, "text": "<asp:Label ID=\"Label3\" runat=\"server\" text='<%# Formatlabel(DataBinder.Eval(Container.DataItem, \"psWages1D\")) %>'/>\n Public Function fLabel(ByVal tval) As String\n fLabel = tval.ToString(\"#,##0.00%;(#,##0.00%);Zero\")\nEnd Function\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11172/" ]
275,199
<p>How do you do the following operations in C++?</p> <ol> <li>Opening Files</li> <li>Closing Files</li> <li>Reading Files</li> <li>Writing Files</li> </ol>
[ { "answer_id": 275224, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 4, "selected": false, "text": "#include <fstream>\nint main()\n{\n std::ifstream inputFile(\"MyFileName\") // Opens a File.\n\n int x;\n inputFile >> x; // Reads an integer from a file.\n\n std::string word;\n inputFile >> word; // Reads a space separated word from a file.\n\n double y;\n inputFile >> y; // Reads a floating point number from the file.\n\n // etc..\n } // File AutoMagically closed by going out of scope.\n #include <fstream>\nint main()\n{\n std::ofstream inputFile(\"MyFileName\") // Opens a File.\n\n int x = 5;\n inputFile << x << \" \"; // Writes an integer to a file then a space.\n inputFile << 5 << \" \"; // Same Again.\n\n std::string word(\"This is a line\");\n inputFile << word << \"\\n\"; // Writes a string to a file followed by a newline\n // Notice the difference between reading and\n // writing a string.\n inputFile << \"Write a string constant to a file\\n\";\n\n double y = 15.4;\n inputFile << y << \":\"; // Writes a floating point number \n // to the file followed by \":\".\n\n // etc..\n } // File AutoMagically closed by going out of scope.\n" }, { "answer_id": 275234, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 3, "selected": false, "text": "{ \n std::ifstream in(\"foo.txt\"); /* opens for reading */\n std::ofstream out(\"bar.txt\"); /* opens for writing */\n out << in.rdbuf(); /* streams in into out. writing and reading */\n} /* closes automatically */\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35821/" ]
275,207
<p>My friend produced a small proof-of-concept assembler that worked on x86. I decided to port it for x86_64 as well, but I immediately hit a problem.</p> <p>I wrote a small piece of program in C, then compiled and objdumped the code. After that I inserted it to my python script, therefore the x86_64 code is correct:</p> <pre><code>from ctypes import cast, CFUNCTYPE, c_char_p, c_long buffer = ''.join(map(chr, [ #0000000000000000 &lt;add&gt;: 0x55, # push %rbp 0x48, 0x89, 0xe5, # mov %rsp,%rbp 0x48, 0x89, 0x7d, 0xf8, # mov %rdi,-0x8(%rbp) 0x48, 0x8b, 0x45, 0xf8, # mov -0x8(%rbp),%rax 0x48, 0x83, 0xc0, 0x0a, # add $0xa,%rax 0xc9, # leaveq 0xc3, # retq ])) fptr = cast(c_char_p(buffer), CFUNCTYPE(c_long, c_long)) print fptr(1234) </code></pre> <p>Now, why does this script keeps doing segmentation fault whenever I run it?</p> <p>I have yet a question about mprotect and no execution flag. It is said to protect against most basic security exploits like buffer overruns. But what is the real reason it's in use? You could just keep on writing until you hit the .text, then inject your instructions into a nice, PROT_EXEC -area. Unless, of course, you use a write protection in .text</p> <p>But then, why have that PROT_EXEC everywhere anyway? Wouldn't it just help tremendously that your .text section is write protected?</p>
[ { "answer_id": 275333, "author": "vincent", "author_id": 34871, "author_profile": "https://Stackoverflow.com/users/34871", "pm_score": 2, "selected": false, "text": "mprotect VirtualProtect" }, { "answer_id": 275426, "author": "Cheery", "author_id": 21711, "author_profile": "https://Stackoverflow.com/users/21711", "pm_score": 3, "selected": false, "text": "from ctypes import (\n cast, CFUNCTYPE, c_long, sizeof, addressof, create_string_buffer, pythonapi\n)\n\nPROT_NONE, PROT_READ, PROT_WRITE, PROT_EXEC = 0, 1, 2, 4\nmprotect = pythonapi.mprotect\n\nbuffer = ''.join(map(chr, [ #0000000000000000 <add>:\n 0x55, # push %rbp\n 0x48, 0x89, 0xe5, # mov %rsp,%rbp\n 0x48, 0x89, 0x7d, 0xf8, # mov %rdi,-0x8(%rbp)\n 0x48, 0x8b, 0x45, 0xf8, # mov -0x8(%rbp),%rax\n 0x48, 0x83, 0xc0, 0x0a, # add $0xa,%rax\n 0xc9, # leaveq \n 0xc3, # retq\n]))\n\npagesize = pythonapi.getpagesize()\ncbuffer = create_string_buffer(buffer)#c_char_p(buffer)\naddr = addressof(cbuffer)\nsize = sizeof(cbuffer)\nmask = pagesize - 1\nif mprotect(~mask&addr, mask&addr + size, PROT_READ|PROT_WRITE|PROT_EXEC) < 0:\n print \"mprotect failed?\"\nelse:\n fptr = cast(cbuffer, CFUNCTYPE(c_long, c_long))\n print repr(fptr(1234))\n" }, { "answer_id": 275460, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 4, "selected": true, "text": "libc = CDLL('libc.so')\n\n# Some constants\nPROT_READ = 1\nPROT_WRITE = 2\nPROT_EXEC = 4\n\ndef executable_code(buffer):\n \"\"\"Return a pointer to a page-aligned executable buffer filled in with the data of the string provided.\n The pointer should be freed with libc.free() when finished\"\"\"\n\n buf = c_char_p(buffer)\n size = len(buffer)\n # Need to align to a page boundary, so use valloc\n addr = libc.valloc(size)\n addr = c_void_p(addr)\n\n if 0 == addr: \n raise Exception(\"Failed to allocate memory\")\n\n memmove(addr, buf, size)\n if 0 != libc.mprotect(addr, len(buffer), PROT_READ | PROT_WRITE | PROT_EXEC):\n raise Exception(\"Failed to set protection on buffer\")\n return addr\n\ncode_ptr = executable_code(buffer)\nfptr = cast(code_ptr, CFUNCTYPE(c_long, c_long))\nprint fptr(1234)\nlibc.free(code_ptr)\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21711/" ]
275,213
<p>Previously, I had a class that wrapped an internal <code>System.Collections.Generic.List&lt;Item&gt;</code> (where Item is a class I created). The wrapper class provided several collection-level properties that provided totals, averages, and other computations on items in the list. I was creating a <code>BindingSource</code> around this wrapped <code>List&lt;&gt;</code> and another <code>BindingSource</code> around my class and was able to get at the Items in the wrapped list through the first <code>BindingSource</code> and the collection-level properties of the wrapper class using the second. </p> <p>A simplified example looks like: </p> <pre><code>public class OldClass() { private List&lt;Item&gt; _Items; public OldClass() { _Items = new List&lt;Item&gt;(); } public List&lt;Item&gt; Items { get { return _Items; } } // collection-level properties public float AverageValue { get { return Average() } } public float TotalValue { get { return Total() } } // ... other properties like this } </code></pre> <p>With the binding sources created in this way:</p> <pre><code>_itemsBindingSource = new BindingSource(oldClass.Items); _summaryBindingSource = new BindingSource(oldClass); </code></pre> <p>Recently, I tried to change this class to be derived from <code>System.Collections.Generic.List&lt;Item&gt;</code> instead of keeping a wrapped <code>List&lt;&gt;</code> member. My hope was to get rid of the extra wrapper layer and use only one <code>BindingSource</code> instead of two. However, now I find that I cannot get at the properties that apply to all items in the list (such as <code>AverageValue</code>) when I do data binding. Only the properties of list items are available. </p> <p>Am I forced to go back to using a wrapped <code>List&lt;&gt;</code> of <code>Item</code>s? Or is there a way that I can get at both the properties of <code>Item</code>s stored my new class as well as the properties that apply to the collection itself?</p>
[ { "answer_id": 275392, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": true, "text": "IList IListSource IList DataMember BindingSource TextBox AverageValue DataGridView DataSource DataMember=\"Items\"" }, { "answer_id": 276037, "author": "Keltex", "author_id": 28260, "author_profile": "https://Stackoverflow.com/users/28260", "pm_score": 0, "selected": false, "text": "public static class MyExtensions\n{\n public static float GetAverage(this List<Item>)\n {\n // implementation\n }\n\n public static float GetTotal(this List<Item>)\n {\n // implementation\n }\n}\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4849/" ]
275,214
<p>I am starting again with c++ and was thinking about the scope of variables. If I have a variable inside a function and then I return that variable will the variable not be "dead" when it's returned because the scope it was in has ended?</p> <p>I have tried this with a function returning a string and it did work. Can anyone explain this? Or at least point me to some place that can explain this to me please.</p> <p>Thanks</p>
[ { "answer_id": 275225, "author": "Kieveli", "author_id": 15852, "author_profile": "https://Stackoverflow.com/users/15852", "pm_score": 2, "selected": false, "text": "int funcB() {\n int j = 12;\n return j;\n}\n\nvoid A() {\n int i;\n i = funcB();\n}\n" }, { "answer_id": 275226, "author": "Jason Coco", "author_id": 34218, "author_profile": "https://Stackoverflow.com/users/34218", "pm_score": 2, "selected": false, "text": "int *myBadAddingFunction(int a, int b)\n{\n int result;\n\n result = a + b;\n return &result; // this is very bad and the result is undefined\n}\n\nchar *myOtherBadFunction()\n{\n char myString[256];\n\n strcpy(myString, \"This is my string!\");\n return myString; // also allocated on the stack, also bad\n}\n" }, { "answer_id": 275430, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 2, "selected": false, "text": "std::string someFunc( std::string& const s)\n{\n return s + \"copy\";\n}\n delete new std::string& someFunc2( std::string const& s)\n{\n return s + \"reference to a copy\"; // this is bad - the temp object created will \n // be destroyed after the expression the \n // function call is in finishes.\n // Some, but not all, compilers will warn \n // about this.\n}\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8715/" ]
275,230
<p>I know how to use the OleDbConnection class to open an excel file and select from it, but is there a simple method to read the data from an excel file that has been read into a Stream? And is there also a similar method for QuickBooks?</p>
[ { "answer_id": 275225, "author": "Kieveli", "author_id": 15852, "author_profile": "https://Stackoverflow.com/users/15852", "pm_score": 2, "selected": false, "text": "int funcB() {\n int j = 12;\n return j;\n}\n\nvoid A() {\n int i;\n i = funcB();\n}\n" }, { "answer_id": 275226, "author": "Jason Coco", "author_id": 34218, "author_profile": "https://Stackoverflow.com/users/34218", "pm_score": 2, "selected": false, "text": "int *myBadAddingFunction(int a, int b)\n{\n int result;\n\n result = a + b;\n return &result; // this is very bad and the result is undefined\n}\n\nchar *myOtherBadFunction()\n{\n char myString[256];\n\n strcpy(myString, \"This is my string!\");\n return myString; // also allocated on the stack, also bad\n}\n" }, { "answer_id": 275430, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 2, "selected": false, "text": "std::string someFunc( std::string& const s)\n{\n return s + \"copy\";\n}\n delete new std::string& someFunc2( std::string const& s)\n{\n return s + \"reference to a copy\"; // this is bad - the temp object created will \n // be destroyed after the expression the \n // function call is in finishes.\n // Some, but not all, compilers will warn \n // about this.\n}\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13855/" ]
275,233
<p>What I would like to do is the following. I have a single table, Products, containing a private key ProductID. Instead of having SQL Server auto-increment ProductID on inserts, I want to increment it in the DataContext partial method "InsertProduct":</p> <pre><code>Partial Public Class MyDataContext Private Sub InsertProduct(ByVal instance As Product) Dim id As Integer = Me.Products.Max(Function(p As Product) p.ProductID) + 1 instance.ProductID = id Me.ExecuteDynamicInsert(instance) End Sub End Class </code></pre> <p>However, this will only work when inserting the first Product instance. When attempting to insert a second instance, the id retrieved is the same as for the first,</p> <pre><code>Using context As New MyDataContext Dim product1 As New Product context.Products.InsertOnSubmit(product1) context.SubmitChanges() 'This works Dim product2 As New Product context.Products.InsertOnSubmit(product2) context.SubmitChanges() 'DuplicateKeyException End Using </code></pre> <p>Am I missing something obvious here?</p>
[ { "answer_id": 275350, "author": "valure", "author_id": 9919, "author_profile": "https://Stackoverflow.com/users/9919", "pm_score": 0, "selected": false, "text": "context.SubmitChanges()" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9919/" ]
275,237
<p>i.e. I just want them to be permanently accepted all the time.</p>
[ { "answer_id": 3506961, "author": "Doug K", "author_id": 423329, "author_profile": "https://Stackoverflow.com/users/423329", "pm_score": 3, "selected": false, "text": "* Tools -> Options -> Advanced -> Encryption -> View Certificates\n* Under Authorities tab, enter \"RSA Security 1024\" in the Search textbox.\n* Select RSA Security 1024 V3 and press the Edit button.\n* Uncheck all three options\n* Press OK and close out the rest of the dialogs. \n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34594/" ]
275,249
<p>What is a good use case for uncaught_exception?</p>
[ { "answer_id": 275537, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 2, "selected": false, "text": "uncaught_exception throw; uncaught_exception" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14069/" ]
275,250
<p>I'm writing some disposable Haskell scripts to solve some of the <a href="http://projecteuler.net" rel="nofollow noreferrer">Project Euler</a> problems. I don't really want to have to compile them because of the number of changes I'm constantly having to make, but in a few cases I've found that I've run out of stack space.</p> <p>The documentation for <code>runhaskell</code> says that the following syntax should increase the stack space:</p> <pre><code>runhaskell +RTS -K5M -RTS Script.hs </code></pre> <p>This never, ever works (in any permutation I've tried). The stack size always remains 8,388,608. This is maddening, and I haven't found much help on Google.</p> <p>Any suggestions? What am I doing wrong?</p>
[ { "answer_id": 275623, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 1, "selected": false, "text": "module Main where\nmain = do\n print solution\nsolution = ...\n ghc --make -O3 Problem123.hs\n./Problem123\n" }, { "answer_id": 431989, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "$ ghc -O2 -o 23 23.hs\n$ ./23 +RTS -K128M\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27779/" ]
275,273
<p>I recently downloaded PLT Scheme and DrScheme. When I open DrScheme, I am told to choose a language. However, I'm not familiar with any of my options, and the help guides don't really break it down to help me easily choose which choice.</p> <p>So, first - is DrScheme and PLT Scheme really the tools I need to learn Lisp and/or Scheme? If so, what are the different languages and which one(s) should I be using?</p>
[ { "answer_id": 275313, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 5, "selected": true, "text": "#lang scheme\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
275,314
<p>When using MYSQL C API to query results. The results are returned as a <code>MYSQL_ROW</code> type, which according to the MYSQL C API documentation, I can easily <code>printf("%s", row[0])</code>. But what if I want to transfer the contents of <code>row[0]</code> into a string or a char*?</p>
[ { "answer_id": 54962732, "author": "jww", "author_id": 608639, "author_profile": "https://Stackoverflow.com/users/608639", "pm_score": 0, "selected": false, "text": "mysql_fetch_lengths MYSQL_ROW MYSQL_ROW mysql_fetch_row() mysql_fetch_row MYSQL_ROW row;\nunsigned int num_fields;\nunsigned int i;\n\nnum_fields = mysql_num_fields(result);\nwhile ((row = mysql_fetch_row(result)))\n{\n unsigned long *lengths;\n lengths = mysql_fetch_lengths(result);\n for(i = 0; i < num_fields; i++)\n {\n printf(\"[%.*s] \", (int) lengths[i],\n row[i] ? row[i] : \"NULL\");\n }\n printf(\"\\n\");\n}\n MYSQL_RES* res = NULL;\nMYSQL row;\n\nconst char SELECT_STMT[] = \"SELECT COUNT(*) FROM blacklist_ftc\";\nif (mysql_query(mysql, SELECT_STMT) != 0)\n{\n /* handle error */\n goto finish;\n}\n\nif ((res = mysql_store_result(s_mysql)) == NULL)\n{\n /* handle error */\n goto finish;\n}\n\nif (mysql_num_fields(res) != 1 || mysql_num_rows(res) != 1)\n{\n /* handle error */\n goto finish;\n}\n\nchar buf[32];\nunsigned long* length;\n\nrow = mysql_fetch_row(res);\nlength = mysql_fetch_lengths(res);\n\nif (row == NULL || length == NULL)\n{\n /* handle error */\n goto finish;\n}\n\nsize_t size = length[0] < sizeof(buf)-1 ? length[0] : sizeof(buf)-1;\nmemcpy(buf, row[0], size);\nbuf[size] = '\\0';\n\nunsigned long count = (unsigned long)atoi(buf);\n\nfinish:\n\nif (res)\n{\n mysql_free_result(res);\n res = NULL;\n}\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28462/" ]
275,338
<p>What is the <em>best</em> way to print the cells of a <code>String[][]</code> array as a right-justified table? For example, the input</p> <pre><code>{ { "x", "xxx" }, { "yyy", "y" }, { "zz", "zz" } } </code></pre> <p>should yield the output</p> <pre><code> x xxx yyy y zz zz </code></pre> <p>This seems like something that one <em>should</em> be able to accomplish using <code>java.util.Formatter</code>, but it doesn't seem to allow non-constant field widths. The best answer will use some standard method for padding the table cells, not the manual insertion of space characters.</p>
[ { "answer_id": 275438, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 3, "selected": false, "text": "public static void printTable(String[][] table) {\n // Find out what the maximum number of columns is in any row\n int maxColumns = 0;\n for (int i = 0; i < table.length; i++) {\n maxColumns = Math.max(table[i].length, maxColumns);\n }\n\n // Find the maximum length of a string in each column\n int[] lengths = new int[maxColumns];\n for (int i = 0; i < table.length; i++) {\n for (int j = 0; j < table[i].length; j++) {\n lengths[j] = Math.max(table[i][j].length(), lengths[j]);\n }\n }\n\n // Generate a format string for each column\n String[] formats = new String[lengths.length];\n for (int i = 0; i < lengths.length; i++) {\n formats[i] = \"%1$\" + lengths[i] + \"s\" \n + (i + 1 == lengths.length ? \"\\n\" : \" \");\n }\n\n // Print 'em out\n for (int i = 0; i < table.length; i++) {\n for (int j = 0; j < table[i].length; j++) {\n System.out.printf(formats[j], table[i][j]);\n }\n }\n}\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1412/" ]
275,351
<p>Is there a way to get all methods (private, privileged, or public) of a javascript object from within? Here's the sample object:</p> <pre><code>var Test = function() { // private methods function testOne() {} function testTwo() {} function testThree() {} // public methods function getMethods() { for (i in this) { alert(i); // shows getMethods, but not private methods } } return { getMethods : getMethods } }(); // should return ['testOne', 'testTwo', 'testThree', 'getMethods'] Test.getMethods(); </code></pre> <p>The current issue is the code in <code>getMethods()</code>, the simplified example will return just the public methods, but not to private ones.</p> <p><strong>edit</strong>: my test code may (or may not) be overcomplicating what i'm hoping to get at. given the following:</p> <pre><code>function myFunction() { var test1 = 1; var test2 = 2; var test3 = 3; } </code></pre> <p>is there a way to find out what variables exist in <code>myFunction()</code> from within <code>myFunction()</code>. the pseudo-code would look like this:</p> <pre><code>function myFunction() { var test1 = 1; var test2 = 2; var test3 = 3; alert(current.properties); // would be nice to get ['test1', 'test2', 'test3'] } </code></pre>
[ { "answer_id": 275362, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 0, "selected": false, "text": "this var t = new Test();\nt.getMethods();\n" }, { "answer_id": 275390, "author": "eswald", "author_id": 21229, "author_profile": "https://Stackoverflow.com/users/21229", "pm_score": 1, "selected": false, "text": "{ getMethods : getMethods }" }, { "answer_id": 275457, "author": "Kevin Gorski", "author_id": 35806, "author_profile": "https://Stackoverflow.com/users/35806", "pm_score": 6, "selected": true, "text": "var Test = function() {\n var private = {\n testOne : function () {},\n testTwo : function () {},\n testThree : function () {}\n };\n\n function getMethods() {\n for (i in this) {\n alert(i); // shows getMethods, but not private methods\n }\n for (i in private) {\n alert(i); // private methods\n }\n }\n return { getMethods : getMethods }\n}();\n\n// will return ['getMethods', 'testOne', 'testTwo', 'testThree']\nTest.getMethods();\n" }, { "answer_id": 315635, "author": "small_jam", "author_id": 15752, "author_profile": "https://Stackoverflow.com/users/15752", "pm_score": 1, "selected": false, "text": "var that = this; var Test = function() {\n var that = this;\n function testOne() {}\n function testTwo() {}\n function testThree() {}\n function getMethods() {\n for (i in that) {\n alert(i);\n }\n }\n return { getMethods : getMethods }\n}();\n" }, { "answer_id": 10174525, "author": "Rune FS", "author_id": 112407, "author_profile": "https://Stackoverflow.com/users/112407", "pm_score": 1, "selected": false, "text": "(function() {\n var obj = {\n // private methods\n testOne: function () {},\n testTwo : function () {},\n testThree: function () {},\n // public methods\n getMethods : function () {\n for (i in this) {\n alert(i); // shows getMethods, but not private methods\n }\n }\n };\n return { getMethods : function(){return obj.getMethods();} }\n})();\n" }, { "answer_id": 10538036, "author": "Jay", "author_id": 390720, "author_profile": "https://Stackoverflow.com/users/390720", "pm_score": 3, "selected": false, "text": "//Reflection\n\n~function (extern) {\n\nvar Reflection = this.Reflection = (function () { return Reflection; });\n\nReflection.prototype = Reflection;\n\nReflection.constructor = Reflection;\n\nReflection.getArguments = function (func) {\n var symbols = func.toString(),\n start, end, register;\n start = symbols.indexOf('function');\n if (start !== 0 && start !== 1) return undefined;\n start = symbols.indexOf('(', start);\n end = symbols.indexOf(')', start);\n var args = [];\n symbols.substr(start + 1, end - start - 1).split(',').forEach(function (argument) {\n args.push(argument);\n });\n return args;\n};\n\nextern.Reflection = extern.reflection = Reflection;\n\nFunction.prototype.getArguments = function () { return Reflection.getArguments(this); }\n\nFunction.prototype.getExpectedReturnType = function () { /*ToDo*/ }\n\n} (this);\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4853/" ]
275,355
<p>another request sorry.. Right now I am reading the tokens in one by one and it works, but I want to know when there is a new line..</p> <p>if my file contains</p> <pre><code>Hey Bob Now </code></pre> <p>should give me</p> <pre><code>Hey Bob [NEW LINE] NOW </code></pre> <p>Is there a way to do this without using getline?</p>
[ { "answer_id": 275405, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 5, "selected": true, "text": "std::string line;\nwhile(std::getline(std::cin,line))\n{\n\n // If you then want to tokenize the line use a string stream:\n\n std::stringstream lineStream(line);\n std::string token;\n while(lineStream >> token)\n {\n std::cout << \"Token(\" << token << \")\\n\";\n }\n\n std::cout << \"New Line Detected\\n\";\n}\n #include <iostream>\n#include <fstream>\n\nclass Token\n{\n private:\n friend std::ostream& operator<<(std::ostream&,Token const&);\n friend std::istream& operator>>(std::istream&,Token&);\n std::string value;\n};\nstd::istream& operator>>(std::istream& str,Token& data)\n{\n // Check to make sure the stream is OK.\n if (!str)\n { return str;\n }\n\n char x;\n // Drop leading space\n do\n {\n x = str.get();\n }\n while(str && isspace(x) && (x != '\\n'));\n\n // If the stream is done. exit now.\n if (!str)\n {\n return str;\n }\n\n // We have skipped all white space up to the\n // start of the first token. We can now modify data.\n data.value =\"\";\n\n // If the token is a '\\n' We are finished.\n if (x == '\\n')\n { data.value = \"\\n\";\n return str;\n }\n\n // Otherwise read the next token in.\n str.unget();\n str >> data.value;\n\n return str;\n}\nstd::ostream& operator<<(std::ostream& str,Token const& data)\n{\n return str << data.value;\n}\n\n\nint main()\n{\n std::ifstream f(\"PLOP\");\n Token x;\n\n while(f >> x)\n {\n std::cout << \"Token(\" << x << \")\\n\";\n }\n}\n" }, { "answer_id": 277054, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "std::getline std::string token;\nstd::ifstream file(\"file.txt\");\nwhile(std::getline(file, token)) {\n std::istringstream line(token);\n while(line >> token) {\n std::cout << \"Token :\" << token << std::endl;\n }\n if(file.unget().get() == '\\n') {\n std::cout << \"newline found\" << std::endl;\n }\n}\n" }, { "answer_id": 806542, "author": "the_drow", "author_id": 85140, "author_profile": "https://Stackoverflow.com/users/85140", "pm_score": 1, "selected": false, "text": "vector<string> vec; //we'll put all of the tokens in here \nstring token;\nistringstream iss(\"put text here\"); \n\nwhile ( getline(iss, token, '\\n') ) {\n vec.push_back(token);\n}\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33481/" ]
275,374
<p>I am trying to make a basic API for my website so certain other websites that I approve of can show content from my site. I have a PHP script on my server that the other websites can access to pull content in XML format. How can I make sure that only certain websites can access this php page on my server?</p>
[ { "answer_id": 275379, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 2, "selected": false, "text": "Order allow, deny\nDeny from 192.168.0.10\nDeny from 212.155.\nDeny from 1.2.3.4 5.6.7.8 127.0.0.1\nAllow from all\n Deny from all\nAllow from 1.2.3.4\n <?\n $allowed[0]=\"xxx.xxx.xxx.xxx\";\n $allowed[1]=\"yyy.yyy.yyy.yyy\";\n\n // add as many as you need\n\n if (!in_array($_SERVER['REMOTE_ADDR'],$allowed)) header(\"HTTP/1.1 403 Forbidden\");\n?>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
275,375
<p>From googling around it looks like Xcode (3.1 in my case) should be at least trying to give me a sane debug view of STL containers - or at least vectors.</p> <p>However, whenever I go to look at a vector in the debugger I just see M_impl, with M_start and M_finish members (and a couple of others) - but nothing in-between! (it's a debug build, btw).</p> <p>Am I missing a setting or something somewhere?</p> <p>I've also read that there are macros available that can augment the debug viewer even further to inspect more complex containers - but have been unable to find any.</p> <p>I'd also like to be able to view std::wstrings, without having to drop to the memory viewer. It shows std::string fine. Is there anything I can do to show std::wstring?</p> <p>I realise this is a bit of a composite question - but it's all really part of the same subject.</p>
[ { "answer_id": 275398, "author": "Michel", "author_id": 31122, "author_profile": "https://Stackoverflow.com/users/31122", "pm_score": 2, "selected": true, "text": "template <class T> struct S { T m_t; }\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32136/" ]
275,382
<p>I currently have 2 domain names that I want to setup different websites for. I am currently looking at using some free hosting that works well for my current needs but doesn't give me any way to point "mydomain.com" to the actual site. Instead I have to give users a longer, harder to remember url.</p> <p>My proposed solution is to point my domains to my home ip and host a small ASP.NET app through IIS consisting of a redirect page that simply redirects to the appropriate site. Is there a way in ASP.NET to recognize which domain url was requested in order to know where to redirect the page to?</p>
[ { "answer_id": 275388, "author": "Cristian Libardo", "author_id": 16526, "author_profile": "https://Stackoverflow.com/users/16526", "pm_score": 1, "selected": false, "text": "if(Request.Url.Authority == \"www.site1.com\")\n Response.Redirect(...);\n" }, { "answer_id": 276556, "author": "Jim", "author_id": 681, "author_profile": "https://Stackoverflow.com/users/681", "pm_score": 3, "selected": true, "text": "<%EnableSessionState=False\n\nhost = Request.ServerVariables(\"HTTP_HOST\")\n\nif host = \"website1.com\" or host = \"www.website1.com\" then\nresponse.redirect(\"http://website1.com/website1/default.aspx\")\n\nelseif host = \"website2.com\" or host = \"www.website2.com\" then\nresponse.redirect(\"http://website2.com/website2/default.aspx\")\n\nelse\nresponse.redirect(\"http://website1.com/\")\n\nend if\n%>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20489/" ]
275,386
<p>I'm writing a Linux kernel module that needs to open and read files. What's the best way to accomplish that?</p>
[ { "answer_id": 275396, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 3, "selected": false, "text": "open read close mm_segment_t fs = get_fs();\nset_fs(KERNEL_DS);\n\nfd = (*syscall_open)(file, flags, mode);\nif(fd != -1) {\n (*syscall_read)(fd, buf, size);\n (*syscall_close)(fd);\n}\nset_fs(fs);\n syscall_*" }, { "answer_id": 53622925, "author": "Billy", "author_id": 5849262, "author_profile": "https://Stackoverflow.com/users/5849262", "pm_score": 2, "selected": false, "text": "kernel_read_file_from_path(const char *path, void **buf, loff_t *size, loff_t max_size, enum kernel_read_file_id id)\n include/linux/fs.h id READING_FIRMWARE buf size size + 1 kernel_read_file() kernel_read_file_from_path() fs/exec.c i_size kernel_read_file() kernel_write() kernel_read() kernel_read_file() kernel_read_file_from_path() kernel_write_file() kernel_write_file_from_path() fs/exec.c kernel_read_file() kernel_read_file_from_path() kernel_write_file() kernel_write_file_from_path()" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/275386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28804/" ]
275,404
<p>How do you split a string into tokens in C++?</p>
[ { "answer_id": 275413, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 2, "selected": false, "text": "std::string line(\"A line of tokens\");\nstd::stringstream lineStream(line);\n\nstd::string token;\nwhile(lineStream >> token)\n{\n}\n" }, { "answer_id": 275417, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 4, "selected": false, "text": "elems delim char std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {\n std::stringstream ss(s);\n std::string item;\n while(std::getline(ss, item, delim)) {\n elems.push_back(item);\n }\n return elems;\n}\n" }, { "answer_id": 275674, "author": "Imbue", "author_id": 3175, "author_profile": "https://Stackoverflow.com/users/3175", "pm_score": 2, "selected": false, "text": "/* strtok example */\n#include <stdio.h>\n#include <string.h>\n\nint main ()\n{\n char str[] =\"- This, a sample string.\";\n char * pch;\n printf (\"Splitting string \\\"%s\\\" into tokens:\\n\",str);\n pch = strtok (str,\" ,.-\");\n while (pch != NULL)\n {\n printf (\"%s\\n\",pch);\n pch = strtok (NULL, \" ,.-\");\n }\n return 0;\n}\n #include<iostream>\n#include<boost/tokenizer.hpp>\n#include<string>\n\nint main(){\n using namespace std;\n using namespace boost;\n string s = \"This is, a test\";\n tokenizer<> tok(s);\n for(tokenizer<>::iterator beg=tok.begin(); beg!=tok.end();++beg){\n cout << *beg << \"\\n\";\n }\n}\n" }, { "answer_id": 275702, "author": "Shadow2531", "author_id": 1697, "author_profile": "https://Stackoverflow.com/users/1697", "pm_score": 3, "selected": false, "text": "#include <iostream>\n#include <string>\n#include <vector>\n#include <iterator>\n#include <ostream>\n#include <algorithm>\n#include <boost/algorithm/string.hpp>\nusing namespace std;\nusing namespace boost;\n\nint main() {\n vector<string> v;\n split(v, \"1=2&3=4&5=6\", is_any_of(\"=&\"));\n copy(v.begin(), v.end(), ostream_iterator<string>(cout, \"\\n\"));\n}\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33481/" ]
275,411
<p>I'm writing a php program that pulls from a database source. Some of the varchars have quotes that are displaying as black diamonds with a question mark in them (�, <a href="http://www.fileformat.info/info/unicode/char/fffd/index.htm" rel="noreferrer">REPLACEMENT CHARACTER</a>, I assume from Microsoft Word text).</p> <p>How can I use php to strip these characters out?</p>
[ { "answer_id": 275448, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "header(\"Content-Type: text/html; charset=ISO-8859-1\");\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">\n iconv()" }, { "answer_id": 275449, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 5, "selected": false, "text": "charset=iso-8859-1 header accept-charset <form> Content-Type text/html Content-Type charset http-equiv=\"Content-Type\"" }, { "answer_id": 275467, "author": "Daniel Cassidy", "author_id": 31662, "author_profile": "https://Stackoverflow.com/users/31662", "pm_score": 3, "selected": false, "text": "header('Content-Type: text/html; charset=Windows-1252');\n" }, { "answer_id": 10023664, "author": "ptwiggerl", "author_id": 1057535, "author_profile": "https://Stackoverflow.com/users/1057535", "pm_score": 4, "selected": false, "text": "$con = mysql_connect(\"localhost\",\"username\",\"password\"); \nmysql_set_charset('utf8',$con);\n $con = mysql_connect(\"localhost\",\"username\",\"password\"); \n$charset = mysql_client_encoding($con);\necho \"The current character set is: $charset\\n\"; \n" }, { "answer_id": 15138120, "author": "Avatar", "author_id": 1066234, "author_profile": "https://Stackoverflow.com/users/1066234", "pm_score": 6, "selected": false, "text": "substr() mb_substr($utfstring, 0, 10, 'utf-8'); htmlspecialchars() htmlspecialchars($utfstring, ENT_QUOTES, 'UTF-8'); preg_replace() $string = preg_replace('/[^A-Za-z0-9ÄäÜüÖöß]/', ' ', $string); mb_ereg_replace()" }, { "answer_id": 24352574, "author": "GrafixGuy", "author_id": 1888232, "author_profile": "https://Stackoverflow.com/users/1888232", "pm_score": 0, "selected": false, "text": "&quot; &#34;" }, { "answer_id": 31690375, "author": "DropHit", "author_id": 1656124, "author_profile": "https://Stackoverflow.com/users/1656124", "pm_score": 3, "selected": false, "text": "ini_set('mbstring.substitute_character', \"none\"); \n$text= mb_convert_encoding($text, 'UTF-8', 'UTF-8');\n" }, { "answer_id": 32037413, "author": "Hamlet Kraskian", "author_id": 1531995, "author_profile": "https://Stackoverflow.com/users/1531995", "pm_score": 4, "selected": false, "text": "iso-8859-1 utf8 $text = “string from database”;\n$text = utf8_encode($text);\necho $text;\n" }, { "answer_id": 39338349, "author": "drtechno", "author_id": 6797108, "author_profile": "https://Stackoverflow.com/users/6797108", "pm_score": 0, "selected": false, "text": " include 'dbconnectfile.php';\n\n //// the variable $db comes from my db connect file\n /// inx is my auto increment column\n /// broke_column is the column I need to fix\n\n $qwy = \"select inx,broke_column from Table \";\n $res = $db->query($qwy); \n\n while ($data = $res->fetch_row()) {\n for ($m=0; $m<$res->field_count; $m++) {\n if ($m==0){ \n $id=0;\n $id=$data[$m];\n echo $id;\n }else if ($m==1){ \n $fix=0;\n $fix=$data[$m];\n\n\n $fix = utf8_decode($fix);\n $fixx =str_replace(\"?\",\" \",$fix);\n\n echo $fixx;\n\n ////I echoed the data to the screen because I like to see something as I execute it :)\n }\n }\n $insert= \"UPDATE Table SET broke_column='\".$fixx.\"' where inx='\".$id.\"'\";\n $insresult= $db->query($insert);\n echo\"<br>\";\n }\n\n ?> \n" }, { "answer_id": 41451445, "author": "JacobRossDev", "author_id": 1595997, "author_profile": "https://Stackoverflow.com/users/1595997", "pm_score": 1, "selected": false, "text": "$text = utf8_decode($text)\n $text = str_replace('?', '', utf8_decode($text));\n" }, { "answer_id": 42801565, "author": "asma", "author_id": 7712774, "author_profile": "https://Stackoverflow.com/users/7712774", "pm_score": 1, "selected": false, "text": ".doc/docx if(ini_get('zlib.output_compression'))\n\n ini_set('zlib.output_compression', 'Off');\n ob_clean();\n" }, { "answer_id": 43001066, "author": "javier_domenech", "author_id": 2192660, "author_profile": "https://Stackoverflow.com/users/2192660", "pm_score": 0, "selected": false, "text": "default_charset = \"ISO-8859-1\"" }, { "answer_id": 44410006, "author": "Utmost Creator", "author_id": 6901693, "author_profile": "https://Stackoverflow.com/users/6901693", "pm_score": 1, "selected": false, "text": "md_FUNC_NAME" }, { "answer_id": 46633907, "author": "Prasant Kumar", "author_id": 5231984, "author_profile": "https://Stackoverflow.com/users/5231984", "pm_score": 2, "selected": false, "text": "<head> <meta charset=\"iso-8859-1\">\n" }, { "answer_id": 56009343, "author": "Harshil Kaneria", "author_id": 10949608, "author_profile": "https://Stackoverflow.com/users/10949608", "pm_score": 3, "selected": false, "text": "<?php\nheader(\"Content-Type: text/html; charset=ISO-8859-1\");\n?>\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
275,437
<p>I want to display the "infinity" symbol using </p> <pre><code>CGContextSelectFont(context, "HelveticaNeue", textSize, kCGEncodingMacRoman); CGContextShowTextAtPoint(context, myCenter.x, myCenter.y + textHeight, [sName cStringUsingEncoding:NSMacOSRomanStringEncoding], [sName length]); </code></pre> <p>It is displayed as a square box, or a circle. I have found out this symbol is in decimal 176 and 221E in Hexadecimal format. I am using Helvetica as my font, and have tried others with no luck. Is this a problem with the encoding I am using?</p>
[ { "answer_id": 275447, "author": "Jason Coco", "author_id": 34218, "author_profile": "https://Stackoverflow.com/users/34218", "pm_score": 5, "selected": true, "text": "- (void)drawRect:(CGRect)rect {\n unichar inf = 0x221E; // infinity symbol\n NSString* sName = [[NSString alloc] initWithCharacters:&inf length:1];\n UIFont* font = [UIFont fontWithName:@\"Helvetica\" size:32.0];\n [sName drawInRect:CGRectMake(20, 20, 40, 40)\n withFont:font];\n [sName release];\n}\n" }, { "answer_id": 392612, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "CGContextSaveGState(context);\nCGContextSetRGBFillColor(context, 0, 0, 0, 0.5);\n[self.text drawInRect:targetRect withFont:self.font];\nCGContextRestoreGState(context);\n" }, { "answer_id": 17331764, "author": "Ian Vink", "author_id": 172861, "author_profile": "https://Stackoverflow.com/users/172861", "pm_score": 1, "selected": false, "text": "UIGraphics.PushContext (mBmpContext);\nmBmpContext.SetRGBFillColor(1f,1f,1f,1f);\nvar font = UIFont.FromName (\"Arial\", 30);\nusing (var nsstr = new NSString (\"äöü ÜÖÄ\")){\n nsstr.DrawString (new PointF (10, 400), font);\n}\nUIGraphics.PopContext ()\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29642/" ]
275,442
<p>How can I make a local drive visible to a Windows XP VMWare image?</p> <p>Preferably, I'd like to make local drives available as Drive Letters within the VM Ware Image.</p>
[ { "answer_id": 275451, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "vm > settings > options > shared folders\n" }, { "answer_id": 10649033, "author": "ntg", "author_id": 508907, "author_profile": "https://Stackoverflow.com/users/508907", "pm_score": 0, "selected": false, "text": "VBoxManage internalcommands createrawvmdk -filename mydrive.vmdk -rawdisk \\\\.\\PhysicalDrive0\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9467/" ]
275,444
<p>What are the things that Medium Trust stops you from doing? For example, I've already learned that Medium Trust stops you from using System.IO.Path.GetTempPath(). What other things like that?</p>
[ { "answer_id": 275445, "author": "Shawn", "author_id": 26, "author_profile": "https://Stackoverflow.com/users/26", "pm_score": 2, "selected": false, "text": " <trust level=\"Full|High|Medium|Low|Minimal\" />\n" }, { "answer_id": 275533, "author": "Corey Trager", "author_id": 9328, "author_profile": "https://Stackoverflow.com/users/9328", "pm_score": 3, "selected": true, "text": "<trust level=\"Medium\" originUrl=\"\" />\n" }, { "answer_id": 446909, "author": "edosoft", "author_id": 6399, "author_profile": "https://Stackoverflow.com/users/6399", "pm_score": 0, "selected": false, "text": "[DLLImport]" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9328/" ]
275,453
<p>I can't seem to get a scrollbar to work in an inner stack/flow. Does anyone know how to?</p>
[ { "answer_id": 358198, "author": "user45200", "author_id": 45200, "author_profile": "https://Stackoverflow.com/users/45200", "pm_score": 1, "selected": false, "text": "<div> #my_div {\n width: [some_width]px;\n height: [some_height]px;\n overflow: auto;\n}\n" }, { "answer_id": 610273, "author": "Sergei Silnov", "author_id": 73642, "author_profile": "https://Stackoverflow.com/users/73642", "pm_score": 3, "selected": false, "text": "Shoes.app(:title => \"Scrolll!\" ) do\n flow :margin => 10 do\n stack :width => \"150px\", :height => \"200px\", :scroll => true do\n para \"all you need is love\", \"all you need is love\", \"all you need is love\", \"all you need is love\", \"all you need is love\", \"all you need is love\", \"all you need is love\", \"all you need is love\", \"all you need is love\", \"all you need is love\",\n end\n end\nend\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35852/" ]
275,456
<p>Working with a traditional listener callback model. I have several listeners that collect various stuff. Each listener's collected stuff is inside the listener in internal structures.</p> <p>The problem is that I want some of the listeners to be aware of some of the "stuff" in the other listeners.</p> <p>I enforce listener registration order, so if I knowingly register events in some order a later listener can be sure that a previously listener updated its stuff and somehow access it to do more stuff. </p> <p>My first attempt at this is to have each listener store a reference to the listeners upon which it depends. So I register listeners in the order of those without dependencies to those with prior-registered dependencies, and then set the references between the listeners in various methods.</p> <p>I am starting to realize how bad this feels and I was wondering if somehow has been down this road before. What would be a more appropriate pattern when one of the listeners needs to access stuff in another?</p> <p>Here is some pseudocode to illustrate:</p> <pre><code>interface Listener { onEvent(char e); } class A implements Listener { private int count; public void onEvent(char e) { if(e == 'a') count++; } public int getCount() { return count; } } class B implements Listener { private int count; // private A a; // private void setA(A a) { this.a = a; } public void onEvent(char e) { if(e == 'b') count++; } public int getCount() { return count; } public int getAPlusBCount() { // We know B count, but we don't know A so how would we change this // so B is A aware? Or not even aware, just somehow coupled? This // is the question // return a.getCount() + count; } public void doConditionalHere() { // Do some condition in B that relies on the state of data in A int acount = 0; // a.getCount(); ??? if(acount % 2 == 0) { this.count--; } } } class Run { A a = new A(); B b = new B(); List listeners = new List(); listeners.add(a); listeners.add(b); // The ugly way I add coupling right now is to keep a reference to A // inside B. It's commented out because I am hoping there is a more intelligent approach // b.setA(a); for(char c : "ababbabab") { for(listener : listeners) { listener.onEvent(c); } } } </code></pre>
[ { "answer_id": 275470, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 2, "selected": false, "text": "interface Listener {\n String getId();\n Collection<String> getDependencies();\n onEvent(char e);\n}\n interface Listener {\n Collection<Listener> getDependencies();\n onEvent(char e);\n}\n" }, { "answer_id": 279233, "author": "Sandman", "author_id": 19911, "author_profile": "https://Stackoverflow.com/users/19911", "pm_score": 2, "selected": true, "text": " public interface CountObserver {\n\n public void updateCount(String className);\n public int getCount(String className);\n}\n\npublic class CentralObserver implements CountObserver {\n\n private int aCount;\n private int bCount;\n\n public void updateCount(String className) {\n\n //There's probably a better way to do this than using\n //all these if-elses, but you'll get the idea.\n\n if (className.equals(\"AclassName\")) {\n aCount++;\n }\n else if (className.equals(\"BclassName\")) {\n bCount++;\n }\n }\n\n public int getCount(String className) {\n\n if (className.equals(\"AclassName\")) {\n return aCount;\n }\n else if (className.equals(\"BclassName\")) {\n return bCount;\n }\n}\n\nclass A implements Listener {\n\n CountObserver countObserver;\n\n public void registerObserver (CountObserver countObserver) {\n\n this.countObserver = countObserver;\n }\n\n public void onEvent(char e) {\n\n if(e == 'a') {\n\n countObserver.updateCount (this.getClass.getName);\n }\n }\n\n}\n\n//Same thing for B or any other class implementing Listener. Your Listener interface should, of \n\n//course, have a method signature for the registerObserver method which all the listener classes \n\n//will implement.\n\nclass Run {\n\n private A a;\n private B b; \n private CountObserver centralObserver;\n\n public runProgram () {\n\n centralObserver = new CentralObserver();\n a.registerObserver(centralObserver);\n b.registerObserver(centralObserver);\n\n //run OnEvent method for A a couple of times, then for B\n\n }\n\n public int getAcount () {\n\n return centralObserver.getCount(a.getClass.getName());\n }\n\n public int getBcount () {\n\n return centralObserver.getCount(b.getClass.getName());\n }\n} \n //To get the sum of all the counts just call getAcount + getBcount. Of course, you can always add more listeners and more getXCount methods\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2204759/" ]
275,458
<p>Has anyone converted a large (ours is 550,000 lines) program of Fortran 77 code to C++ ? What pitfalls did you run into ? Was the conversion a success ? Did you use a tool like <code>for_c</code> ( <a href="http://www.cobalt-blue.com/fc/fcmain.htm" rel="noreferrer">http://www.cobalt-blue.com/fc/fcmain.htm</a> ) ? Was the resulting C++ code significantly faster or slower ?</p>
[ { "answer_id": 275488, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": 3, "selected": false, "text": "label10:;\n\n goto label10;\n #define XMAX 10 + 1\n#define YMAX 20 + 1 \nfloat a[XMAX][YMAX];\n for (x = 1; x <= XMAX; x++)\n for (y = 1; y <= YMAX; y++)\n a[x][y] = 0.0f;\n #define A(X,Y) a[Y][X]\ndouble a[XMAX][YMAX];\nA(4,2) = 3.14;\n FILE *fp19 = fopen(\"file\",\"mode\");\n int z;\nfor (z = 1, z <= 20; z++)\n printf(\"%lf \", proj[z][4]);\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35854/" ]
275,464
<p>What does the following error mean? </p> <p>Geeneration of designer file failed: Exception from HRESULT: 0x80042929 </p> <p>It started showing up in my application when building and I'm not sure what's causing it. I'm using VS.Net 2008 and .Net 3.5</p>
[ { "answer_id": 275488, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": 3, "selected": false, "text": "label10:;\n\n goto label10;\n #define XMAX 10 + 1\n#define YMAX 20 + 1 \nfloat a[XMAX][YMAX];\n for (x = 1; x <= XMAX; x++)\n for (y = 1; y <= YMAX; y++)\n a[x][y] = 0.0f;\n #define A(X,Y) a[Y][X]\ndouble a[XMAX][YMAX];\nA(4,2) = 3.14;\n FILE *fp19 = fopen(\"file\",\"mode\");\n int z;\nfor (z = 1, z <= 20; z++)\n printf(\"%lf \", proj[z][4]);\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33633/" ]
275,471
<p>I'm trying to use GDB to debug (to find an annoying segfault). When I run:</p> <pre><code>gdb ./filename </code></pre> <p>from the command line, I get the following error:</p> <pre><code>This GDB was configured as "i686-pc-linux- gnu"..."/path/exec": not in executable format: File format not recognized </code></pre> <p>When I execute:</p> <pre><code>file /path/executable/ </code></pre> <p>I get the following info:</p> <pre><code> ELF 64-bit LSB executable, AMD x86-64, version 1 (SYSV), for GNU/Linux 2.4.0, dynamically linked (uses shared libs), not stripped </code></pre> <p>I am using GDB 6.1, and the executable is compiled with gcc version 3.4.6.</p> <p>I'm a little out of my water in terms of using gdb, but as far as I can tell it should be working in this instance. Any ideas what's going wrong?</p>
[ { "answer_id": 275763, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 2, "selected": false, "text": "gdb executable-file core-file\n gdb executable-file\n executable-file" }, { "answer_id": 1123312, "author": "RandomNickName42", "author_id": 67819, "author_profile": "https://Stackoverflow.com/users/67819", "pm_score": 2, "selected": false, "text": "# objdump -H\n\nobjdump: supported targets: elf32-powerpc aixcoff-rs6000 elf32-powerpcle ppcboot elf64-powerpc elf64-powerpcle elf64-little elf64-big elf32-little elf32-big srec symbolsrec tekhex binary ihex\nobjdump: supported architectures: rs6000:6000 rs6000:rs1 rs6000:rsc rs6000:rs2 powerpc:common powerpc:common64 powerpc:603 powerpc:EC603e powerpc:604 powerpc:403 powerpc:601 powerpc:620 powerpc:630 powerpc:a35 powerpc:rs64ii powerpc:rs64iii powerpc:7400 powerpc:e500 powerpc:MPC8XX powerpc:750\n\nThe following PPC specific disassembler options are supported for use with\nthe -M switch:\n booke|booke32|booke64 Disassemble the BookE instructions\n e300 Disassemble the e300 instructions\n e500|e500x2 Disassemble the e500 instructions\n efs Disassemble the EFS instructions\n power4 Disassemble the Power4 instructions\n power5 Disassemble the Power5 instructions\n power6 Disassemble the Power6 instructions\n 32 Do not disassemble 64-bit instructions\n 64 Allow disassembly of 64-bit instructions\n" }, { "answer_id": 31819274, "author": "kenorb", "author_id": 55075, "author_profile": "https://Stackoverflow.com/users/55075", "pm_score": 1, "selected": false, "text": "gdb lldb sudo apt-get install lldb yum" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1266/" ]
275,484
<p>I'm pretty sure this is a simple question in regards to formatting but here's what I want to accomplish:</p> <p>I want to output data onto the screen using <code>cout</code>. I want to output this in the form of a table format. What I mean by this is the columns and rows should be properly aligned. Example:</p> <pre><code>Test 1 Test2 2 Iamlongverylongblah 2 Etc 1 </code></pre> <p>I am only concerned with the individual line so my line to output now (not working) is</p> <p><code>cout &lt;&lt; var1 &lt;&lt; "\t\t" &lt;&lt; var2 &lt;&lt; endl;</code></p> <p>Which gives me something like:</p> <pre><code>Test 1 Test2 2 Iamlongverylongblah 2 Etc 1 </code></pre>
[ { "answer_id": 275489, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 3, "selected": false, "text": "cout << format(\"%|1$30| %2%\") % var1 % var2;\n" }, { "answer_id": 275494, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 7, "selected": true, "text": "#include <iostream>\n#include <iomanip>\nusing namespace std;\n\nint main () {\n cout << setw(21) << left << \"Test\" << 1 << endl;\n cout << setw(21) << left << \"Test2\" << 2 << endl;\n cout << setw(21) << left << \"Iamlongverylongblah\" << 2 << endl;\n cout << setw(21) << left << \"Etc\" << 1 << endl;\n return 0;\n}\n" }, { "answer_id": 20597035, "author": "avishayhajbi", "author_id": 2580592, "author_profile": "https://Stackoverflow.com/users/2580592", "pm_score": -1, "selected": false, "text": "string str = \"somthing\";\nprintf (\"%10s\",str);\nprintf (\"%10s\\n\",str);\nprintf (\"%10s\",str);\nprintf (\"%10s\\n\",str);\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33481/" ]
275,493
<p>I'm using a RichTextBox in WinForms 3.5 and I found that when I programmatically edit the contained text, those changes are no longer available to the built in undo functionality.</p> <p>Is there a way to make it so these changes are available for undo/redo?</p>
[ { "answer_id": 275621, "author": "BFree", "author_id": 15861, "author_profile": "https://Stackoverflow.com/users/15861", "pm_score": 3, "selected": true, "text": " string buffer = String.Empty;\n string buffer2 = String.Empty;\n public Form3()\n {\n InitializeComponent();\n this.richTextBox1.KeyDown += new KeyEventHandler(richTextBox1_KeyDown);\n this.richTextBox1.TextChanged += new EventHandler(richTextBox1_TextChanged);\n }\n\n void richTextBox1_TextChanged(object sender, EventArgs e)\n {\n buffer2 = buffer;\n buffer = richTextBox1.Text;\n }\n\n void richTextBox1_KeyDown(object sender, KeyEventArgs e)\n {\n if (e.Control && e.KeyCode == Keys.Z)\n {\n this.richTextBox1.Text = buffer2;\n }\n }\n\n private void button1_Click(object sender, EventArgs e)\n {\n richTextBox1.Text = \"Changed\";\n }\n" }, { "answer_id": 59628129, "author": "Morty", "author_id": 1012586, "author_profile": "https://Stackoverflow.com/users/1012586", "pm_score": 1, "selected": false, "text": "richTextBox.SelectAll();\nrichTextBox.SelectedText = NewText;\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194/" ]
275,514
<p>Something is eluding me ... it seems obvious, but I can't quite figure it out.</p> <p>I want to add/remove a couple of HTML controls to a page (plain old html) when a user changes value of a dropdown list. An example is to add or remove a "number of guests in this room" textbox for each (of a number) of rooms requested ... </p> <p>So if a user selects:</p> <p>1 room, there is one text box</p> <p>2 rooms, there are two text boxes</p> <p>3 rooms, three text boxes </p> <p>back to 2 rooms, two text boxes</p> <p>and so on ...</p>
[ { "answer_id": 275521, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 2, "selected": false, "text": "<script>\n //swap $ with applicable lib call (if avail)\n function $(id){\n return document.getElementById(id);\n }\n function adjustTexts(obj){\n var roomTotal = 4;\n var count = obj.selectedIndex;\n //show/hide unrequired text boxes...\n for(var i=0;i<roomTotal;i++){\n if(i < count){\n $('room'+ (i+1)).style.display = 'block';\n } else {\n $('room'+ (i+1)).style.display = 'none';\n }\n }\n }\n</script>\n\n\n<select name=\"rooms\" onchange=\"adjustTexts(this);\">\n <option>1</option>\n <option>2</option>\n <option>3</option>\n <option>4</option>\n</select>\n\n<div id=\"room1\">\n <label>Room 1</label>:<input type=\"text\" name=\"room1text\"/>\n</div>\n\n<div id=\"room2\" style=\"display:none;\">\n <label>Room 2</label>:<input type=\"text\" name=\"room2text\"/>\n</div>\n\n<div id=\"room3\" style=\"display:none;\">\n <label>Room 3</label>:<input type=\"text\" name=\"room3text\"/>\n</div>\n\n<div id=\"room4\" style=\"display:none;\">\n <label>Room 4</label>:<input type=\"text\" name=\"room4text\"/>\n</div>\n" }, { "answer_id": 275527, "author": "ckramer", "author_id": 20504, "author_profile": "https://Stackoverflow.com/users/20504", "pm_score": 3, "selected": true, "text": "var container = document.getElementById(\"myContainerDiv\");\nvar html;\nfor(var i = 0; i < selectedRooms; i++)\n{\n html = html + \"<input type=text ... /><br />\";\n}\ncontainer.innerHtml = html;\n var html;\nfor(var i = 0; i < selectedRooms; i++)\n{\n html = html + \"<input type=text ... /><br />\";\n}\n\n$(\"#myContainerDiv\").append(html);\n" }, { "answer_id": 275528, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 1, "selected": false, "text": "<select name=\"rooms\" id=\"rooms\">\n <option value=\"1\">1 room</option>\n <option value=\"2\">2 rooms</option>\n <option value=\"3\">3 rooms</option>\n</select>\n<div id=\"boxes\"></div>\n document.getElementById('rooms').onchange = function() {\n var e = document.getElementById('boxes');\n var count = parseInt(document.getElementById('rooms').value);\n e.innerHTML = '';\n\n for(i = 1; i <= count; i++) {\n e.innerHTML += 'Room '+i+' <input type=\"text\" name=\"room'+i+'\" /><br />';\n } \n}\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34770/" ]
275,536
<p>Where would the physical files be?</p>
[ { "answer_id": 275538, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 6, "selected": true, "text": "<SYSTEMDRIVE>\\Documents and Settings\\<user>\\Local Settings\\Application Data\\Microsoft\\IsolatedStorage \n <SYSTEMDRIVE>\\Users\\<user>\\AppData\\Roaming\\Microsoft\\IsolatedStorage\n" }, { "answer_id": 9560896, "author": "Mark Sowul", "author_id": 155892, "author_profile": "https://Stackoverflow.com/users/155892", "pm_score": 4, "selected": false, "text": "%LocalAppData%\\IsolatedStorage %AppData%\\IsolatedStorage." }, { "answer_id": 9923679, "author": "arhsim", "author_id": 580092, "author_profile": "https://Stackoverflow.com/users/580092", "pm_score": 3, "selected": false, "text": "System.Diagnostics.Process.Start(\n Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + \n \"\\\\IsolatedStorage\"\n );\n" }, { "answer_id": 13053663, "author": "Joshua", "author_id": 549346, "author_profile": "https://Stackoverflow.com/users/549346", "pm_score": 2, "selected": false, "text": "%ProgramData%\\IsolatedStorage" }, { "answer_id": 22793833, "author": "Mangesh", "author_id": 3273962, "author_profile": "https://Stackoverflow.com/users/3273962", "pm_score": 2, "selected": false, "text": "C:\\Users\\mangesh\\AppData\\LocalLow\\Microsoft\\Silverlight\\<followed by some random folder names>" }, { "answer_id": 50763705, "author": "mybrave", "author_id": 1755565, "author_profile": "https://Stackoverflow.com/users/1755565", "pm_score": 2, "selected": false, "text": "IsolationStorage Local user [LocalApplicationData]\\IsolatedStorage\nRoaming user [ApplicationData]\\IsolatedStorage\nMachine [CommonApplicationData]\\IsolatedStorage\n Environment.GetFolderPath Local user C:\\Users\\<user>\\AppData\\Local\\IsolatedStorage\nRoaming user C:\\Users\\<user>\\AppData\\Roaming\\IsolatedStorage\nMachine C:\\ProgramData\\IsolatedStorage\n" }, { "answer_id": 69397820, "author": "Rodolfo G.", "author_id": 120764, "author_profile": "https://Stackoverflow.com/users/120764", "pm_score": 0, "selected": false, "text": "C:\\Windows\\SysWOW64\\config\\systemprofile\\AppData\\Local\\IsolatedStorage\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9328/" ]
275,540
<p>I would like to call an ejb3 at runtime. The name of the ejb and the method name will only be available at runtime, so I cannot include any remote interfaces at compile time.</p> <pre><code>String bean = 'some/Bean'; String meth = 'doStuff'; //lookup the bean Object remoteInterface = (Object) new InitialContext().lookup(bean); //search the method .. // foreach (methods) // if method == meth, method.invoke(bean); </code></pre> <p>the beans should be distributed accross multiple application servers, and all beans are to be called remotely.</p> <p>Any hints? specifically i do <strong>not</strong> want:</p> <ol> <li>dependency injection</li> <li>inclusion of appliation specific ejb interfaces in the dispatcher (above)</li> <li>webservices, thats like throwing out processing power for nothing, all the xml crap</li> </ol> <p>Is it possible to load an ejb3 remote interface over the network (if yes, how?), so I could cache the interface in some hashmap or something.</p> <p>I have a solution with a remote dispatcher bean, which I can include in the above main dispatcher, which does essentially the same, but just relays the call to a local ejb (which I can lookup how? naming lookup fails). Given the remote dispatcher bean, I can use dependency injection.</p> <p>thanks for any help</p> <p>(netbeans and glassfish btw)</p>
[ { "answer_id": 461625, "author": "Pavel", "author_id": 48340, "author_profile": "https://Stackoverflow.com/users/48340", "pm_score": 0, "selected": false, "text": "Object ejb = ctx.lookup(bean);\nfor (Method m : ejb.getClass().getMethods()) {\n if (m.getName().equals(meth) && m.getParameterTypes().length == 0) {\n m.invoke(service);\n }\n}\n Arrays.equals(m.getParameterTypes(), new Class[]{String.class})\n m.invoke(service, new Object[]{\"arg0\"})\n" } ]
2008/11/09
[ "https://Stackoverflow.com/questions/275540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]