instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>I've been tasked with build an accessible RSS feed for my company's job listings. I already have an RSS feed from our recruiting partner; so I'm transforming their RSS XML to our own proxy RSS feed to add additional data as well limit the number of items in the feed so we list on the latest jobs.</p>
<p>The RSS validates via feedvalidator.org (with warnings); but the problem is this. Unfortunately, no matter how many times I tell them not to; my company's HR team directly copies and pastes their Word documents into our Recruiting partners CMS when inserting new job listings, leaving WordML in my feed. I believe this WordML is causing issues with Feedburner's BrowserFriendly feature; which we want to show up to make it easier for people to subscribe. Therefore, I need to remove the WordML markup in the feed.</p>
<p>Anybody have experience doing this? Can anyone point me to a good solution to this problem?</p>
<p>Preferably; I'd like to be pointed to a solution in .Net (VB or C# is fine) and/or XSL.</p>
<p>Any advice on this is greatly appreciated.</p>
<p>Thanks.</p>
|
<p>I haven't yet worked with WordML, but assuming that its elements are in a different namespace from RSS, it should be quite simple to do with XSLT.</p>
<p>Start with a basic identity transform (a stylesheet that add all nodes from the input doc "as is" to the output tree). You need these two templates:</p>
<pre><code> <!-- Copy all elements, and recur on their child nodes. -->
<xsl:template match="*">
<xsl:copy>
<xsl:apply-templates select="@*"/>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<!-- Copy all non-element nodes. -->
<xsl:template match="@*|text()|comment()|processing-instruction()">
<xsl:copy/>
</xsl:template>
</code></pre>
<p>A transformation using a stylesheet containing just the above two templates would exactly reproduce its input document on output, modulo those things that standards-compliant XML processors are permitted to change, such as entity replacement.</p>
<p>Now, add in a template that matches any element in the WordML namespace. Let's give it the namespace prefix 'wml' for the purposes of this example:</p>
<pre><code> <!-- Do not copy WordML elements or their attributes to the
output tree; just recur on child nodes. -->
<xsl:template match="wml:*">
<xsl:apply-templates/>
</xsl:template>
</code></pre>
<p>The beginning and end of the stylesheet are left as an exercise for the coder.</p>
|
<p>I would do something like this:</p>
<pre><code>char[] charToRemove = { (char)8217, (char)8216, (char)8220, (char)8221, (char)8211 };
char[] charToAdd = { (char)39, (char)39, (char)34, (char)34, '-' };
string cleanedStr = "Your WordML filled Feed Text.";
for (int i = 0; i < charToRemove.Length; i++)
{
cleanedStr = cleanedStr.Replace(charToRemove.GetValue(i).ToString(), charToAdd.GetValue(i).ToString());
}
</code></pre>
<p>This would look for the characters in reference, (Which are the Word special characters that mess up everything and replaces them with their ASCII equivelents.</p>
| 29,895
|
<p>Now, before you say it: I <strong>did</strong> Google and my <code>hbm.xml</code> file <strong>is</strong> an Embedded Resource. </p>
<p>Here is the code I am calling:</p>
<pre><code>ISession session = GetCurrentSession();
var returnObject = session.Get<T>(Id);
</code></pre>
<p>Here is my mapping file for the class:</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="HQData.Objects.SubCategory, HQData" table="SubCategory" lazy="true">
<id name="ID" column="ID" unsaved-value="0">
<generator class="identity" />
</id>
<property name="Name" column="Name" />
<property name="NumberOfBuckets" column="NumberOfBuckets" />
<property name="SearchCriteriaOne" column="SearchCriteriaOne" />
<bag name="_Businesses" cascade="all">
<key column="SubCategoryId"/>
<one-to-many
class="HQData.Objects.Business, HQData"/>
</bag>
<bag name="_Buckets" cascade="all">
<key column="SubCategoryId"/>
<one-to-many
class="HQData.Objects.Bucket, HQData"/>
</bag>
</class>
</hibernate-mapping>
</code></pre>
<p>Has anyone run to this issue before?</p>
<p>Here is the full error message:</p>
<blockquote>
<pre>MappingException: No persister for: HQData.Objects.SubCategory]NHibernate.Impl.SessionFactoryImpl.GetEntityPersister(String entityName, Boolean throwIfNotFound)
in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionFactoryImpl.cs:766 NHibernate.Impl.SessionFactoryImpl.GetEntityPersister(String entityName)
in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionFactoryImpl.cs:752 NHibernate.Event.Default.DefaultLoadEventListener.OnLoad(LoadEvent event, LoadType loadType)
in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Event\Default\DefaultLoadEventListener.cs:37 NHibernate.Impl.SessionImpl.FireLoad(LoadEvent event, LoadType loadType)
in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:2054 NHibernate.Impl.SessionImpl.Get(String entityName, Object id)
in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:1029 NHibernate.Impl.SessionImpl.Get(Type entityClass, Object id)
in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:1020 NHibernate.Impl.SessionImpl.Get(Object id)
in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:985 HQData.DataAccessUtils.NHibernateObjectHelper.LoadDataObject(Int32 Id)
in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQData\DataAccessUtils\NHibernateObjectHelper.cs:42 HQWebsite.LocalSearch.get_subCategory()
in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQWebsite\LocalSearch.aspx.cs:17 HQWebsite.LocalSearch.Page_Load(Object sender, EventArgs e)
in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQWebsite\LocalSearch.aspx.cs:27 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +33 System.Web.UI.Control.OnLoad(EventArgs e) +99 System.Web.UI.Control.LoadRecursive() +47 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1436</pre>
</blockquote>
<p><strong>Update</strong>, here's what the solution for <em>my</em> scenario was: I had changed some code and I wasn't adding the Assembly to the config file during runtime. </p>
|
<p>Sounds like you forgot to add a mapping assembly to the session factory configuration..</p>
<p>If you're using app.config...</p>
<pre><code>.
.
<property name="show_sql">true</property>
<property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
<mapping assembly="Project.DomainModel"/> <!-- Here -->
</session-factory>
.
.
</code></pre>
|
<p>Had a similar problem when find an object by id...
All i did was to use the fully qualified name in the class name. That is
Before it was :</p>
<pre><code>find("Class",id)
</code></pre>
<p>Object so it became like this : </p>
<pre><code>find("assemblyName.Class",id)
</code></pre>
| 8,222
|
<p>Can someone please tell me how to submit an HTML form when the return key is pressed and if there are no buttons in the form?
<strong>The submit button is not there</strong>. I am using a custom div instead of that.</p>
|
<p>To submit the form when the enter key is pressed create a javascript function along these lines.</p>
<pre><code>function checkSubmit(e) {
if(e && e.keyCode == 13) {
document.forms[0].submit();
}
}
</code></pre>
<p>Then add the event to whatever scope you need eg on the div tag:</p>
<p><code><div onKeyPress="return checkSubmit(event)"/></code></p>
<p>This is also the default behaviour of Internet Explorer 7 anyway though (probably earlier versions as well).</p>
|
<p>Similar to Chris Marasti-Georg's example, instead using inline javascript.
Essentially add onkeypress to the fields you want the enter key to work with. This example acts on the password field.</p>
<pre><code><html>
<head><title>title</title></head>
<body>
<form action="" method="get">
Name: <input type="text" name="name"/><br/>
Pwd: <input type="password" name="password" onkeypress="if(event.keyCode==13) {javascript:form.submit();}" /><br/>
<input type="submit" onClick="javascript:form.submit();"/>
</form>
</body>
</html>
</code></pre>
| 4,977
|
<p>Currently my code is organized in the following tree structure:</p>
<pre><code>src/
module1.py
module2.py
test_module1.py
test_module2.py
subpackage1/
__init__.py
moduleA.py
moduleB.py
test_moduleA.py
test_moduleB.py
</code></pre>
<p>Where the <code>module*.py</code> files contains the source code and the <code>test_module*.py</code> contains the <code>TestCase</code>s for the relevant module.</p>
<p>With the following comands I can run the tests contained in a single file, for example:</p>
<pre><code>$ cd src
$ nosetests test_filesystem.py
..................
----------------------------------------------------------------------
Ran 18 tests in 0.390s
OK
</code></pre>
<p>How can I run all tests? I tried with <code>nosetests -m 'test_.*'</code> but it doesn't work.</p>
<pre><code>$cd src
$ nosetests -m 'test_.*'
----------------------------------------------------------------------
Ran 0 tests in 0.000s
OK
</code></pre>
<p>Thanks</p>
|
<p>Whether you seperate or mix tests and modules is probably a matter of taste, although I would strongly advocate for keeping them apart (setup reasons, code stats etc).</p>
<p>When you're using nosetests, make sure that all directories with tests are real packages:</p>
<pre><code>src/
module1.py
module2.py
subpackage1/
__init__.py
moduleA.py
moduleB.py
tests/
__init__.py
test_module1.py
test_module2.py
subpackage1/
__init__.py
test_moduleA.py
test_moduleB.py
</code></pre>
<p>This way, you can just run <code>nosetests</code> in the toplevel directory and all tests will be found. You need to make sure that <code>src/</code> is on the <code>PYTHONPATH</code>, however, otherwise all the tests will fail due to missing imports.</p>
|
<p>I'll give a <a href="http://www.testoob.org" rel="nofollow noreferrer">Testoob</a> answer.</p>
<p>Running tests in a single file is like Nose:</p>
<pre><code>testoob test_foo.py
</code></pre>
<p>To run tests in many files you can create suites with the Testoob collectors (in each subpackage)</p>
<pre><code># src/subpackage?/__init__.py
def suite():
import testoob
return testoob.collecting.collect_from_files("test_*.py")
</code></pre>
<p>and</p>
<pre><code># src/alltests.py
test_modules = [
'subpackage1.suite',
'subpackage2.suite',
]
def suite():
import unittest
return unittest.TestLoader().loadTestsFromNames(test_modules)
if __name__ == "__main__":
import testoob
testoob.main(defaultTest="suite")
</code></pre>
<p>I haven't tried your specific scenario.</p>
| 47,865
|
<p>The following error is being thrown:</p>
<pre><code>com.sun.jdi.InternalException: Got error code in reply:35 occurred while retrieving value. for all expressions
</code></pre>
<p>I am getting this error for all expressions and cant find anything on it. My guess is that the debugger isn't correctly connecting to the remote version, but I am not sure.</p>
|
<p>It looks like the problem is related to the new debug feature "Show method result after a step operation":
See the thread <a href="https://www.eclipse.org/forums/index.php?t=msg&th=1088650&goto=1772065&" rel="noreferrer">Eclipse Oxygen - Debugging Issue</a> on the Eclipse forum:</p>
<p><strong>The workaround is to go to
Preferences -> Java -> Debug and disable the option
"Show method result after a step operation (if supported by the VM; may be slow)".</strong></p>
<p>See also the bug report in the Eclipse Bugzilla <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=531706" rel="noreferrer">Bug 531706 - Oygen.2 com.sun.jdi.InternalException: Got error code in reply:35 while debugging</a></p>
|
<p>I am not sure but I have got this plenty of times. It comes when I debug the application, and I think it occurs when the debugger tries to wrap a exception which arises due to code. At one instance while debugging when I see the logs I get some business exception, but while debugging it gave me <code>com.sun.jdi.internalexception</code>.</p>
<p>Yes I do remote debugging the servers JVM so it could also be beacuse the debugger isn't correctly connecting to the remote version as you pointed out</p>
| 37,797
|
<p>It looks like some work has been done to make <a href="http://sourceware.org/pthreads-win32/" rel="noreferrer">pthread-win32</a> work with x64, but there are no build instructions. I have tried simly building with the Visual Studio x64 Cross Tools Command Prompt, but when I try to link to the lib from an x64 application, it can't see any of the function exports. It seems like it is still compiling the lib as x86 or something.</p>
<p>I've even tried adding /MACHINE to the makefile in the appropriate places, but it doesn't help. Has anyone gotten this to work?</p>
|
<p>Until it's officially released, it looks like you have to check out the CVS head to get version 2.9 of the library. Version 2.9 has all the x64 patches, but you will still have problems if you try to compile the static library from the command line.</p>
<p>The only workaround I know of is to use the DLLs instead of statically linking the LIB.</p>
|
<p><a href="http://sources.redhat.com/ml/pthreads-win32/2007/msg00008.html" rel="nofollow noreferrer">This message</a> might help.</p>
| 19,272
|
<p>Is it possible to order results in SQL Server 2005 by the relevance of a freetext match? In MySQL you can use the (roughly equivalent) MATCH function in the ORDER BY section, but I haven't found any equivalence in SQL Server.</p>
<p>From the <a href="http://dev.mysql.com/doc/refman/5.0/en/fulltext-natural-language.html" rel="noreferrer">MySQL docs</a>:</p>
<blockquote>
<p>For each row in the table, MATCH() returns a relevance value; that is, a similarity measure between the search string and the text in that row in the columns named in the MATCH() list.</p>
</blockquote>
<p>So for example you could order by the number of votes, then this relevance, and finally by a creation date. Is this something that can be done, or am I stuck with just returning the matching values and not having this ordering ability?</p>
|
<p>If you are using <code>FREETEXTTABLE</code> then it returns a column name <code>Rank</code>, so <code>order by Rank</code> should work. I don't know if other freetext search methods are also returning this value or not. You can have a try.</p>
|
<p>Both <code>FREETEXTTABLE</code> and <code>CONTAINSTABLE</code> will return the <code>[RANK]</code> column, but make sure you are using either the correct variation or union both of them to get all appropriate results.</p>
| 7,704
|
<p>I tried out printing a "bridge" for the first time using this <a href="https://www.thingiverse.com/thing:284380" rel="nofollow noreferrer">Bridge Calibration model</a>. The model creator suggests printing, tweaking settings, and printing again until it works "properly." </p>
<p>My first try worked reasonably well, but the underside of the bridge is pretty rough and stringy. But I don't know what a "good bridge" is supposed to look like.</p>
<p><a href="https://i.stack.imgur.com/htfAV.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/htfAV.jpg" alt="printed bridge"></a></p>
<p>How smooth should the underside of the bridge be? Any suggestions for what changes I should make to my slicer settings? Here is what I have currently:</p>
<p><a href="https://i.stack.imgur.com/87qVV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/87qVV.png" alt="slicer settings for bridging"></a></p>
<p>Here is a picture of my hotend on my Monoprice Maker Select Plus, as requested:</p>
<p><a href="https://i.stack.imgur.com/JxNbw.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JxNbw.jpg" alt="hotend of Monoprice Maker Select Plus"></a></p>
|
<p>Unless you are using a calibrated temperature sensor, it is a question what the temperature will be. </p>
<p>Actually it doesn't really matter what the temperature exactly is, you just need to find the sweet spot for your filaments on your machine. With respect to reported temperatures by others, your settings may differ a little, but that does not matter. </p>
|
<p>Temperature from thermosensors gets collected as a resistance value that changes with temperature. The chip in your board decides the temperature from this value based on a temperature-resistance table.</p>
<p>If you are using Marlin Firmware, the setting which table is referenced by your machine to get its values is written under the header Thermal Settings inside <code>Confinguration.h</code>.</p>
| 1,126
|
<p>I'm trying to find about ALL the possible options that I can set in <code>web.config</code>.
Surprisingly, I can't find this at all. I expected it to be somewhere inside <a href="http://msdn.microsoft.com" rel="noreferrer">MSDN</a>.</p>
<p>I know I can technically add "anything" to <code>web.config</code>, what I'm looking for is the things that the .NET Framework "as shipped" uses.</p>
<p>In particular, right now I'm interested in the <code><mailsettings></code> section.<br>
For example, in many examples I've found, I noticed that they set <code>DeliveryMethod="Network"</code>.
I'm really curious what other values this attribute can take.</p>
<p>Is there any document on all the attributes and all their values, and all the effects those have?</p>
|
<p>It all starts on <a href="http://msdn.microsoft.com/en-us/library/zeshe0eb(v=vs.100).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/zeshe0eb(v=vs.100).aspx</a> :</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/dayb112d(v=vs.100).aspx" rel="noreferrer"><code><system.web></code></a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/bb546044(v=vs.100).aspx" rel="noreferrer"><code><system.web.extensions></code></a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/ms228154(v=vs.100).aspx" rel="noreferrer"><code><appSettings></code></a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/ms228256(v=vs.100).aspx" rel="noreferrer"><code><configSections></code></a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/bf7sd233(v=vs.100).aspx" rel="noreferrer"><code><connectionStrings></code></a></li>
</ul>
|
<p>This might be what you're after (not all in one page), but the top of the schema - drill down recursively to find it all :)</p>
<p><a href="http://msdn.microsoft.com/en-US/library/b5ysx397(v=vs.100).aspx" rel="nofollow noreferrer">ASP.NET Configuration Settings</a></p>
| 26,167
|
<p>I want to create templates for base new reports on to have common designs. How do you do it?</p>
|
<p>The need to produce reports with a common starting design and format is key to any project involving clients and their reports. I have been working on reports for over 10 years now. This has not been the largest portion of my jobs through the years but it has been a very import one. The key to any report project is not to recreate the mundane aspects of the reports for each but to use templates. The use of templates is not a common task or knowledge for Microsoft's SQL Server Reporting Services. Knowing how to save reports templates so that you and your team can create these shortcuts at the creation of a new report in Visual Studio 2005 will help save time and have all reports use the same layout and design.</p>
<p>Create of a set of reports with the following suggestions:</p>
<ul>
<li>Page size -- 8.5 by 11 (letter) and 8.5 by 14 (legal)</li>
<li>Orientation -- portrait and landscape for all paper sizes </li>
<li>Header -- Text Box for report name, Text Box for report subtitle, client or brand logo</li>
<li>Footer -- page number/total pages, date and time report printed</li>
</ul>
<p>Take all the rdl files for the reports created from the suggestions and copy the files to the following directory:</p>
<p>C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\PrivateAssemblies\ProjectItems\ReportProject</p>
<p>When creating a new report in your Visual Studio 2005 report project through Add|New Item</p>
<p><a href="http://www.cloudsocket.com/images/image-thumb14.png">alt text http://www.cloudsocket.com/images/image-thumb14.png</a></p>
<p>The new report dialog will present the list of items from the directory where the new templates were placed.</p>
<p><a href="http://www.cloudsocket.com/images/image-thumb15.png">alt text http://www.cloudsocket.com/images/image-thumb15.png</a></p>
<p>Select the report that fits the requirement needed and proceed to develop your reports without needing to create the basics.</p>
|
<p>Further more, I would suggest wrapping up your template perhaps with externally linked images into an .msi for easier distribution. It is a lot easier to ask people in a department to run an installer than it is to hope they find the right path to put the reporting template in. Make sure you use the proper program files variables etc to account for "Program Files" vs "Program Files(x86)" and other variations users sometimes do with their environment variable settings.</p>
| 9,058
|
<p>I need a way to detect mouse/keyboard activity on Linux. Something similar to what any IM program would do. If no activity is detected for, say 5 minutes, it will set your IM status to "I'm not here right now".</p>
<p>Any help towards this is appreciated.</p>
<p>Thanks.</p>
|
<p>Complete <a href="/questions/tagged/c" class="post-tag" title="show questions tagged 'c'" rel="tag">c</a> solution : (cut & paste the whole code in a terminal)</p>
<pre><code>cat>/tmp/idletime.c<<EOF
#include <time.h>
#include <stdio.h>
#include <unistd.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/extensions/scrnsaver.h>
int GetIdleTime () {
time_t idle_time;
static XScreenSaverInfo *mit_info;
Display *display;
int screen;
mit_info = XScreenSaverAllocInfo();
if((display=XOpenDisplay(NULL)) == NULL) { return(-1); }
screen = DefaultScreen(display);
XScreenSaverQueryInfo(display, RootWindow(display,screen), mit_info);
idle_time = (mit_info->idle) / 1000;
XFree(mit_info);
XCloseDisplay(display);
return idle_time;
}
int main() {
printf("%d\n", GetIdleTime());
return 0;
}
EOF
gcc -Wall /tmp/idletime.c -o /tmp/idletime -L/usr/X11R6/lib/ -lX11 -lXext -lXss
DISPLAY=:0 /tmp/idletime
</code></pre>
<p>(the main part is coming from X11::IdleTime perl module)</p>
|
<p>I wrote the <a href="https://gist.github.com/siers/3b97d3f84347e8600985ce19bf5fb35b" rel="nofollow">wait-while-idle.rb</a> which does the <em>"detecting keyboard, mouse activity in linux"</em> but the other way around — wait until the user's come back.</p>
<p>Yes, sure — it's polling, but I doubt anyone requires performance here.</p>
<p>Planning to catch pranksters sneaking up on my computer with it and a little scripting.</p>
| 27,468
|
<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>
|
<p>I solved this by using something like the following:</p>
<pre><code>new Draggable('id', {
onStart: function() {
dPhoto = $('id');
Event.stopObserving('id', 'click');
},
onEnd : function() {
setTimeout("Event.observe('id', 'click', function() { location.href = 'url'; });", 500);
},
revert: true
});
</code></pre>
|
<p>Something like the following might do the trick (and prevent the click event to be fired up)</p>
<pre><code>new Draggable('tag',
{
revert:function()
{
$('tag').onclick = function(){return false;};
setTimeout('$(\'tag\').onclick = function(){return true;}','500');
return true;
}
}
);
</code></pre>
| 34,631
|
<p>Anyone know a simple method to swap the background color of a webpage using JavaScript?</p>
|
<p>Modify the JavaScript property <code>document.body.style.background</code>.</p>
<p>For example:</p>
<pre><code>function changeBackground(color) {
document.body.style.background = color;
}
window.addEventListener("load",function() { changeBackground('red') });
</code></pre>
<p>Note: this does depend a bit on how your page is put together, for example if you're using a DIV container with a different background colour you will need to modify the background colour of that instead of the document body.</p>
|
<p>This code makes random color for background every second.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>setInterval(changeColor,1000);
function changeColor(){
let r = Math.random() * 255 ;
let g = Math.random() * 255 ;
let b = Math.random() * 255 ;
document.body.style.backgroundColor = `rgb( ${r}, ${g}, ${b} )`;
}</code></pre>
</div>
</div>
</p>
<p>I hope helps someone.❤</p>
| 24,064
|
<p>I have a migration that runs an SQL script to create a new Postgres schema. When creating a new database in Postgres by default it creates a schema called 'public', which is the main schema we use. The migration to create the new database schema seems to be working fine, however the problem occurs after the migration has run, when rails tries to update the 'schema_info' table that it relies on it says that it does not exist, as if it is looking for it in the new database schema and not the default 'public' schema where the table actually is.</p>
<p>Does anybody know how I can tell rails to look at the 'public' schema for this table?</p>
<p>Example of SQL being executed: ~</p>
<pre><code>CREATE SCHEMA new_schema;
COMMENT ON SCHEMA new_schema IS 'this is the new Postgres database schema to sit along side the "public" schema';
-- various tables, triggers and functions created in new_schema
</code></pre>
<p>Error being thrown: ~</p>
<pre><code>RuntimeError: ERROR C42P01 Mrelation "schema_info" does not exist
L221 RRangeVarGetRelid: UPDATE schema_info SET version = ??
</code></pre>
<p>Thanks for your help</p>
<p>Chris Knight</p>
|
<p>Well that depends what your migration looks like, what your database.yml looks like and what exactly you are trying to attempt. Anyway more information is needed change the names if you have to and post an example database.yml and the migration. does the migration change the search_path for the adapter for example ? </p>
<p>But know that in general rails and postgresql schemas don't work well together (yet?). </p>
<p>There are a few places which have problems. Try and build and app that uses only one pg database with 2 non-default schemas one for dev and one for test and tell me about it. (from thefollowing I can already tell you that you will get burned)</p>
<p>Maybe it was fixed since the last time I played with it but when I see <a href="http://rails.lighthouseapp.com/projects/8994/tickets/390-postgres-adapter-quotes-table-name-breaks-when-non-default-schema-is-used" rel="noreferrer">http://rails.lighthouseapp.com/projects/8994/tickets/390-postgres-adapter-quotes-table-name-breaks-when-non-default-schema-is-used</a> or this <a href="http://rails.lighthouseapp.com/projects/8994/tickets/918-postgresql-tables-not-generating-correct-schema-list" rel="noreferrer">http://rails.lighthouseapp.com/projects/8994/tickets/918-postgresql-tables-not-generating-correct-schema-list</a> or this in postgresql_adapter.rb</p>
<pre><code> # Drops a PostgreSQL database
#
# Example:
# drop_database 'matt_development'
def drop_database(name) #:nodoc:
execute "DROP DATABASE IF EXISTS #{name}"
end
</code></pre>
<p>(yes this is wrong if you use the same database with different schemas for both dev and test, this would drop both databases each time you run the unit tests !)</p>
<p>I actually started writing patches. the first one was for the indexes methods in the adapter which didn't care about the search_path ending up with duplicated indexes in some conditions, then I started getting hurt by the rest and ended up abandonning the idea of using schemas: I wanted to get <em>my</em> app done and I didn't have the extra time needed to fix the problems I had using schemas. </p>
|
<p>You can use <a href="https://github.com/TMXCredit/pg_power" rel="nofollow">pg_power</a>. It provides additional DSL for migration to create PostgreSQL schemas and not only.</p>
| 11,669
|
<p>I have a link on my webpage to print the webpage. However, the link is also visible in the printout itself.</p>
<p>Is there javascript or HTML code which would hide the link button when I click the print link?</p>
<p>Example:</p>
<pre class="lang-none prettyprint-override"><code> "Good Evening"
Print (click Here To Print)
</code></pre>
<p>I want to hide this "Print" label when it prints the text "Good Evening". The "Print" label should not show on the printout itself.</p>
|
<p>In your stylesheet add:</p>
<pre><code>@media print
{
.no-print, .no-print *
{
display: none !important;
}
}
</code></pre>
<p>Then add <code>class='no-print'</code> (or add the no-print class to an existing class statement) in your HTML that you don't want to appear in the printed version, such as your button.</p>
|
<p>As Elias Hasle said, JavaScript can override <code>!important</code>. So, I extended his answer with a theoretical implementation.</p>
<p>This code identifies all elements with the class <code>no-print</code>, hides them with CSS before printing, and restores the original style after printing:</p>
<pre class="lang-js prettyprint-override"><code>var noPrintElements = [];
window.addEventListener("beforeprint", function(event) {
var hideMe = document.getElementsByClassName("no-print");
noPrintElements = [];
Array.prototype.forEach.call(hideMe, function(item, index) {
noPrintElements.push({"element": item, "display": item.style.display });
item.style.display = 'none'; // hide the element
});
});
window.addEventListener("afterprint", function(event) {
Array.prototype.forEach.call(noPrintElements, function(item, index) {
item.element.style.display = item.display; // restore the element
});
noPrintElements = []; // just to be on the safe side
});
</code></pre>
| 46,309
|
<p>(Note: This is for MySQL's SQL, not SQL Server.)</p>
<p>I have a database column with values like "abc def GHI JKL". I want to write a WHERE clause that includes a case-insensitive test for any word that begins with a specific letter. For example, that example would test true for the letters a,c,g,j because there's a 'word' beginning with each of those letters. The application is for a search that offers to find records that have only words beginning with the specified letter. Also note that there is not a fulltext index for this table.</p>
|
<p>Using REGEXP opearator:</p>
<pre><code>SELECT * FROM `articles` WHERE `body` REGEXP '[[:<:]][acgj]'
</code></pre>
<p>It returns records where column body contains words starting with a,c,g or i (case insensitive)</p>
<p>Be aware though: this is not a very good idea if you expect any heavy load (not using index - it scans every row!)</p>
|
<p>Check the <a href="http://dev.mysql.com/doc/refman/5.0/en/pattern-matching.html" rel="nofollow noreferrer">Pattern Matching</a> and <a href="http://dev.mysql.com/doc/refman/5.0/en/regexp.html" rel="nofollow noreferrer">Regular Expressions</a> sections of the MySQL Reference Manual.</p>
| 33,594
|
<p>I'm working with JInternalFrame's under Mac OS X Java 5 and when maximizing a JInternalFrame within a JDesktopPane the window doesn't fully maximize, but the property to allow maximizing is definitely set to true. This is the result I'm getting when maximized:</p>
<p><a href="http://www.kieransenior.co.uk/pics/jinternalframe.png" rel="nofollow noreferrer">Seeing as though the image previews didn't work.</a></p>
<p>I've got no idea why it's happening. Here's my code.</p>
<pre><code> JInternalFrame f = new JInternalFrame("irc.quakenet.org - #overclockers", true, true, true, true);
f.setVisible(true);
f.setSize(300,300);
f.setEnabled(true);
f.setMaximizable(true);
try {
f.setSelected(true);
} catch (PropertyVetoException e) {
e.printStackTrace();
}
</code></pre>
<p>Any ideas?</p>
|
<p>Swing may be respecting the fact that you can't fully maximize a window on the Mac. As in, if you maximize a real window, it will simply become big, but not fill the entire screen. The desktop pane may be emulating this behaviour.</p>
<p>You may be able to override this by listening for maximize events and manually setting the window bounds to precisely fill the desktop pane.</p>
|
<p>True indeed, Mac OS doesn't fully maximize windows. The problem is that I won't achieve the effect of a 'docked' window by just setting the size of the active window, which means a different approach is most probably required. That seems to be a common approach to the problem though.</p>
| 42,348
|
<p>When you attempt to declare an unsigned variable in C#.NET with a value outside its value range it is flagged as a compiler error, but if you produce a negative value at runtime and assign it to that variable at runtime the value wraps.</p>
<pre><code>uint z = -1; // Will not compile
uint a = 5;
uint b = 6;
uint c = a - b; // Will result in uint.MaxValue
</code></pre>
<p>Is there a good reason why unsigned variables wrap in such a situation instead of throwing an exception?</p>
<p>Thanks.</p>
|
<p>Declaring an unassigned variable in C# isn't flagged with an error - trying to assign an invalid value to a variable is. For instance, here's a variable which isn't definitely assigned (assuming it's local) after declaration:</p>
<pre><code>uint z;
</code></pre>
<p>-1 isn't a valid value for a uint any more than 0.5 is, which is why your example wouldn't compile.</p>
<p>Now, as for the rest: integers types just wrap on overflow - just as adding 1 to <code>int.MaxValue</code> returns <code>int.MinValue</code>. This is a significant performance improvement over having the program check each operation for overflow - at the cost of potentially not spotting an error.</p>
<p>That's only if you're in an unchecked context, mind you - if you perform any of these operations in a checked context, you'll get an exception instead. For instance;</p>
<pre><code>class Test
{
static void Main()
{
checked
{
uint a = 5;
uint b = 6;
uint c = a - b;
}
}
}
</code></pre>
<p>Run that and you'll see an <code>OverflowException</code> get thrown. If that's what you want for your whole project, you can set it in the project properties (or compile with the <code>/checked+</code> command line option to <code>csc</code>.)</p>
<p>EDIT: It's worth noting that the other answers have shown that you could put smaller amounts of code in the checked context - just the declaration and assignment of <code>c</code> or even just the calculation. It's all pretty flexible.</p>
|
<p>The reason it wraps to negative is because of <a href="http://en.wikipedia.org/wiki/Two%27s_complement" rel="nofollow noreferrer">Two's Complement</a> math that is used for integer arithmetic. </p>
<p>The short answer is that the most significant bit is used as the sign. A zero is positive; a one is negative.</p>
| 29,519
|
<p>How does one setup DUnit Testing in a Midas/DataSnap project in Delphi 2006 </p>
<p>Edit </p>
<p>How does one set up a Dunit Test into a TRemoteDataModule
The project wizard in Delphi 2006 does not work with TRemoteDataModule </p>
|
<p>The question doesn't entirely make sense. Unit tests are performed in a separate project, not within your DataSnap server. Generally, tests which connect to a database are integration tests rather than unit tests. What is it, exactly that you want to test? If it's utility methods within, say, a TRemoteDataModule, you should extract those out into a separate class as class methods, and test them there. You should not have to instantiate an application server to perform unit tests.</p>
|
<p>Sorry for the terse answer above, the iPad posts whenever I hit return while editing a post.</p>
<p>dUnit is designed to perform unit testing, and what you are trying to do is NOT unit testing.</p>
<p>A test is not a unit test if:</p>
<ul>
<li>It talks to the database</li>
<li>It communicates across the network</li>
<li>It touches the file system</li>
<li>It can't run at the same time as any of your other unit tests</li>
<li>You have to do special things to your environment (such as editing config files) to run it.</li>
<li>It can't run in isolation</li>
</ul>
<p>If you follow the SOLID principles (especially the single responsibility principle), using dUnit to test your class (without testing the Midas/DataSnap related logic) should be reasonably simple. And really, you shouldn't need to test the Midas/DataSnap logic.</p>
<p>But there are ways to perform integration and behavioural tests on Delphi applications.</p>
<p>Personally, I wouldn't use TestComplete because it doesn't integrate well with any sort of CI server and the tests are stored in a proprietary binary format (which makes merging differences or maintaining changes in any source control system problematic).</p>
<p>You could try <a href="http://sourceforge.net/projects/dspec/" rel="nofollow">dSpec</a>, but I'm not sure Jody Dawkins is maintaining it any more.</p>
<p>I have used the <a href="http://www.autoitscript.com/site/autoit/" rel="nofollow">AutoIt</a> BASIC scripting language directly on some projects, and also used its .NET assembly to drive a Delphi application using NUnit and C# on another. While not perfect, the NUnit / C# solution was more elegant than anything I'd seen for performing functional / behavioural testing Delphi applications. It did take some effort to get it setup though.</p>
| 30,812
|
<p>I have HTML code edited by FCKEditor stored in a database and would like to display (well render) it onto a view. So, for instance, something stored as:</p>
<pre><code>&lt;&gt;pre&lt;&gt;This is some sample text&lt;&gt;pre&lt;/&gt
</code></pre>
<p>Will be displayed to the user as:</p>
<pre><code>This is some sample text
</code></pre>
<p>(With the appropriate style for pre-formatted-text)</p>
<p>The view already has the required string to display from <code>ViewData</code>, I'm just not sure what the best way to show it to the user is.</p>
|
<p>Try this:</p>
<pre><code><%= System.Web.HttpUtility.HtmlDecode(yourEncodedHtmlFromYouDatabase) %>
</code></pre>
<p>More info <a href="http://msdn.microsoft.com/en-us/library/system.web.httputility.htmldecode.aspx" rel="nofollow noreferrer">here</a>.</p>
|
<p>You want to use <code>@Html.Raw(str)</code>.</p>
<p>See <a href="https://learn.microsoft.com/en-us/dotnet/api/system.web.mvc.htmlhelper.raw" rel="nofollow noreferrer">MSDN</a> for more information.</p>
<blockquote>
<p>Returns markup that is not HTML encoded.</p>
<p>This method wraps HTML markup using the IHtmlString class, which renders unencoded HTML.</p>
</blockquote>
| 38,509
|
<p>My application allows the user to enter a numeric value (currency) in a <code>UITextField</code> control, but the keyboard layout that I wish was available is unfortunately not one of the built-in options, so I had to choose the "Numbers & Punctuation" option in Interface Builder. Here's the corresponding dialog window in IB:</p>
<p><a href="https://i.stack.imgur.com/FbnvH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FbnvH.png" alt="enter image description here"></a></p>
<p>So when my application asks the user for the input, it is displaying the following:</p>
<p><a href="https://i.stack.imgur.com/u9tbB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/u9tbB.png" alt="enter image description here"></a></p>
<p>Which is perfectly fine, but look at all of the extra keys available to the user! One could easily enter "12;56!" in the text field, and I assume I have to validate that somehow.</p>
<p>So my question is: how do I validate currency values entered into a <code>UITextField</code>?</p>
|
<p>I have the urge to answer because this was the first entry I saw when I googled and the highest ranked answer wouldn't allow me to enter a currency.<br>
I'm german, and in germany (and in many other countries) we use <code>,</code> as the decimalseparator. </p>
<p>I just wrote a similar method and this is what I have right now.</p>
<pre><code>- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
static NSString *numbers = @"0123456789";
static NSString *numbersPeriod = @"01234567890.";
static NSString *numbersComma = @"0123456789,";
//NSLog(@"%d %d %@", range.location, range.length, string);
if (range.length > 0 && [string length] == 0) {
// enable delete
return YES;
}
NSString *symbol = [[NSLocale currentLocale] objectForKey:NSLocaleDecimalSeparator];
if (range.location == 0 && [string isEqualToString:symbol]) {
// decimalseparator should not be first
return NO;
}
NSCharacterSet *characterSet;
NSRange separatorRange = [textField.text rangeOfString:symbol];
if (separatorRange.location == NSNotFound) {
if ([symbol isEqualToString:@"."]) {
characterSet = [[NSCharacterSet characterSetWithCharactersInString:numbersPeriod] invertedSet];
}
else {
characterSet = [[NSCharacterSet characterSetWithCharactersInString:numbersComma] invertedSet];
}
}
else {
// allow 2 characters after the decimal separator
if (range.location > (separatorRange.location + 2)) {
return NO;
}
characterSet = [[NSCharacterSet characterSetWithCharactersInString:numbers] invertedSet];
}
return ([[string stringByTrimmingCharactersInSet:characterSet] length] > 0);
}
</code></pre>
|
<p>Using shouldChangeCharactersInRange screws up the pop-up key board as the backspace button doesn't work.</p>
<p>Number formatter is the way to go. Here's a sample I used to find positive decimals. I call it during the validation check- for e.g. when the user clicks on the save button.</p>
<pre><code> -(BOOL) isPositiveNumber: (NSString *) numberString {
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *aNumber = [numberFormatter numberFromString:numberString];
[numberFormatter release];
if ([aNumber floatValue] > 0) {
NSLog( @"Found positive number %4.2f",[aNumber floatValue] );
return YES;
}
else {
return NO;
}
}
</code></pre>
| 44,483
|
<p>Has anyone used Mono, the open source .NET implementation on a large or medium sized project? I'm wondering if it's ready for real world, production environments. Is it stable, fast, compatible, ... enough to use? Does it take a lot of effort to port projects to the Mono runtime, or is it really, <em>really</em> compatible enough to just take of and run already written code for Microsoft's runtime?</p>
|
<p>There are a couple of scenarios to consider: (a) if you are porting an existing application and wondering if Mono is good enough for this task; (b) you are starting to write some new code, and you want to know if Mono is mature enough.</p>
<p>For the first case, you can use the <a href="http://mono-project.com/MoMA" rel="noreferrer">Mono Migration Analyzer tool</a> (Moma) to evaluate how far your application is from running on Mono. If the evaluation comes back with flying colors, you should start on your testing and QA and get ready to ship.</p>
<p>If your evaluation comes back with a report highlighting features that are missing or differ significantly in their semantics in Mono you will have to evaluate whether the code can be adapted, rewritten or in the worst case whether your application can work with reduced functionality. </p>
<p>According to our Moma statistics based on user submissions (this is from memory) about 50% of the applications work out of the box, about 25% require about a week worth of work (refactoring, adapting) another 15% require a serious commitment to redo chunks of your code, and the rest is just not worth bothering porting since they are so incredibly tied to Win32. At that point, either you start from zero, or a business decision will drive the effort to make your code portable, but we are talking months worth of work (at least from the reports we have).</p>
<p>If you are starting from scratch, the situation is a lot simpler, because you will only be using the APIs that are present in Mono. As long as you stay with the supported stack (which is pretty much .NET 2.0, plus all the core upgrades in 3.5 including LINQ and System.Core, plus any of the Mono cross-platform APIs) you will be fine. </p>
<p>Every once in a while you might run into bugs in Mono or limitations, and you might have to work around them, but that is not different than any other system.</p>
<p>As for portability: ASP.NET applications are the easier ones to port, as those have little to no dependencies on Win32 and you can even use SQL server or other popular databases (there are plenty of bundled database providers with Mono). </p>
<p>Windows.Forms porting is sometimes trickier because developers like to escape the .NET sandbox and P/Invoke their brains out to configure things as useful as the changing the cursor blinking rate expressed as two bezier points encoded in BCD form in a wParam. Or some junk like that.</p>
|
<p>It really depends on the namespaces and classes that you are using from the .NET framework. I had interest in converting one of my windows services to run on my email server, which is Suse, but we ran into several hard roadblocks with APIs that had not been completely implemented. There is a chart somewhere on the Mono website that lists all of the classes and their level of completion. If your application is covered, then go for it.</p>
<p>Like any other application, do prototyping and testing before you make a full commitment, of course.</p>
<p>Another problem we ran into is licensed software: if you are referencing someone else's DLL, you can't code your way around incompatibilities that are buried in that assembly.</p>
| 3,904
|
<p>Is there a way to identify, from within a VM, that your code is running inside a VM?</p>
<p>I guess there are more or less easy ways to identify specific VM systems, especially if the VM has the provider's extensions installed (such as for VirtualBox or VMWare). But is there a general way to identify that you are not running directly on the CPU?</p>
|
<p>A lot of the research on this is dedicated to detecting so-called "blue pill" attacks, that is, a malicious hypervisor that is actively attempting to evade detection. </p>
<p>The classic trick to detect a VM is to populate the ITLB, run an instruction that <strong>must</strong> be virtualized (which necessarily clears out such processor state when it gives control to the hypervisor), then run some more code to detect if the ITLB is still populated. The first paper on it is located <a href="http://www.symantec.com/avcenter/reference/Virtual_Machine_Threats.pdf" rel="noreferrer">here</a>, and a rather colorful explanation from a <a href="http://web.archive.org/web/20080213212608/http://www.matasano.com/log/930/side-channel-detection-attacks-against-unauthorized-hypervisors/" rel="noreferrer">researcher's blog</a> and alternative <a href="http://web.archive.org/web/20080720153608/http://www.matasano.com/log/930/side-channel-detection-attacks-against-unauthorized-hypervisors/" rel="noreferrer">Wayback Machine link to the blog article (images broken)</a>.</p>
<p>Bottom line from discussions on this is that there is always a way to detect a malicious hypervisor, and it's much simpler to detect one that isn't trying to hide.</p>
|
<p>If it VM does the job well, it should be invisible to the client that it's being virtualized. However, one can look at other clues.</p>
<p>I would imagine that looking for known drivers or software specific to the VM environment would be the best possible way.</p>
<p>For example, on a VMWare client running Windows, vmxnet.sys would be the network driver, displayed as VMware accelerated AMD PCNet Adapter.</p>
| 6,061
|
<p>If I open an image with <code>open("image.jpg")</code>, how can I get the RGB values of a pixel assuming I have the coordinates of the pixel?</p>
<p>Then, how can I do the reverse of this? Starting with a blank graphic, 'write' a pixel with a certain RGB value?</p>
<p>I would prefer if I didn't have to download any additional libraries.</p>
|
<p>It's probably best to use the <a href="http://www.pythonware.com/products/pil/" rel="noreferrer">Python Image Library</a> to do this which I'm afraid is a separate download.</p>
<p>The easiest way to do what you want is via the <a href="http://effbot.org/imagingbook/image.htm" rel="noreferrer">load() method on the Image object</a> which returns a pixel access object which you can manipulate like an array:</p>
<pre><code>from PIL import Image
im = Image.open('dead_parrot.jpg') # Can be many different formats.
pix = im.load()
print im.size # Get the width and hight of the image for iterating over
print pix[x,y] # Get the RGBA Value of the a pixel of an image
pix[x,y] = value # Set the RGBA Value of the image (tuple)
im.save('alive_parrot.png') # Save the modified pixels as .png
</code></pre>
<p>Alternatively, look at <a href="http://effbot.org/imagingbook/imagedraw.htm" rel="noreferrer">ImageDraw</a> which gives a much richer API for creating images.</p>
|
<pre><code>import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img=mpimg.imread('Cricket_ACT_official_logo.png')
imgplot = plt.imshow(img)
</code></pre>
| 16,730
|
<p>I have two tables, both with start time and end time fields. I need to find, for each row in the first table, all of the rows in the second table where the time intervals intersect.</p>
<p>For example:</p>
<pre><code> <-----row 1 interval------->
<---find this--> <--and this--> <--and this-->
</code></pre>
<p>Please phrase your answer in the form of a SQL <code>WHERE</code>-clause, AND consider the case where the end time in the second table may be <code>NULL</code>.</p>
<p>Target platform is SQL Server 2005, but solutions from other platforms may be of interest also.</p>
|
<pre><code>SELECT *
FROM table1,table2
WHERE table2.start <= table1.end
AND (table2.end IS NULL OR table2.end >= table1.start)
</code></pre>
|
<p>And what, if you want to analyse such an overlap on a minute precision with 70m+ rows?
the only solution i could make up myself was a time dimension table for the join </p>
<p>else the dublicate-handling became a headache .. and the processing cost where astronomical</p>
| 14,357
|
<p>The WPF control WindowsFormsHost inherits from IDisposable.</p>
<p>If I have a complex WPF visual tree containing some of the above controls what event or method can I use to call IDispose during shutdown?</p>
|
<p>In the case of application shutdown there is nothing you need to do to properly dispose of the WindowsFormsHost. Since it derives from HwndHost disposing is handled when the Dispatcher is shutdown. If you use Reflector you will see that when HwndHost is initialized it creates a WeakEventDispatcherShutdown.</p>
<p>If you are using it in a dialog the best I can suggest is to override OnClosed and dispose of your Host then, otherwise the HwndHost will hang around until until the Dispatcher is shutdown.</p>
<pre><code>public partial class Dialog : Window
{
public Dialog()
{
InitializeComponent();
}
protected override void OnClosed(EventArgs e)
{
if (host != null)
host.Dispose();
base.OnClosed(e);
}
}
</code></pre>
<p>A simple way to test when dispose gets called is to derive a custom class from WindowsFormsHost and play around with different situations. Put a break point in dispose and see when it gets called.</p>
<pre><code>public class CustomWindowsFormsHost : WindowsFormsHost
{
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
}
</code></pre>
|
<p>You don't need to dispose controls when closing a form, the API will do it for you automatically if the control is in the visual tree of the form ( as a child of the form or other control in the form)</p>
| 31,715
|
<p>What install tool can I use to create Virtual Directory on IIS? OpenSource, free or to do in C#. </p>
|
<p><a href="http://wix.sourceforge.net/" rel="nofollow noreferrer">WiX</a> can create IIS virtual directories.</p>
|
<p>You could use <a href="http://blogs.iis.net/msdeploy/archive/2008/01/22/welcome-to-the-web-deployment-team-blog.aspx" rel="nofollow noreferrer">Microsoft Web Deployment Tool</a> to recreate a website structure.</p>
| 14,326
|
<p>In Java, is there a way to have a window that is "Always on top" regardless if the user switches focus to another application? I've searched the web, and all of the solutions lean to some sort of JNI interface with native bindings. Truly this can't be the only way to do it?.. or is it?</p>
|
<p>Try this method of the <code>Window</code> class:</p>
<p><a href="http://java.sun.com/javase/6/docs/api/java/awt/Window.html#setAlwaysOnTop%28boolean%29" rel="noreferrer">Window.setAlwaysOnTop(boolean)</a></p>
<p>It works the same way as the default in the Windows TaskManager: switch to another app but it shows always on top.</p>
<p>This was added in Java 1.5</p>
<p>Sample code:</p>
<pre><code>import javax.swing.JFrame;
import javax.swing.JLabel;
public class Annoying {
public static void main(String[] args) {
JFrame frame = new JFrame("Hello!!");
// Set's the window to be "always on top"
frame.setAlwaysOnTop( true );
frame.setLocationByPlatform( true );
frame.add( new JLabel(" Isn't this annoying?") );
frame.pack();
frame.setVisible( true );
}
}
</code></pre>
<p>
<img src="https://i.stack.imgur.com/od2Zo.png" alt="alt text">
</p>
<p><sub>Window remains on top even when is not active</sub></p>
|
<p>dont use setFullScreenWindow,just get the screen size and then setSize, and everything will be fine.</p>
| 38,124
|
<p>Using Django's built in models, how would one create a triple-join between three models.</p>
<p>For example:</p>
<ul>
<li>Users, Roles, and Events are the models.</li>
<li>Users have many Roles, and Roles many Users. (ManyToMany)</li>
<li>Events have many Users, and Users many Events. (ManyToMany)</li>
<li>But for any given Event, any User may have only one Role.</li>
</ul>
<p>How can this be represented in the model?</p>
|
<p><strong>zacherates</strong> writes:</p>
<blockquote>
<p>I'd model Role as an association class between Users and Roles (...)</p>
</blockquote>
<p>I'd also reccomed this solution, but you can also make use of some syntactical sugar provided by Django: <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships" rel="noreferrer">ManyToMany relation with extra fields</a>.</p>
<p>Example:</p>
<pre><code>class User(models.Model):
name = models.CharField(max_length=128)
class Event(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(User, through='Role')
def __unicode__(self):
return self.name
class Role(models.Model):
person = models.ForeignKey(User)
group = models.ForeignKey(Event)
date_joined = models.DateField()
invite_reason = models.CharField(max_length=64)
</code></pre>
|
<p>I'd model Role as an association class between Users and Roles, thus,</p>
<pre><code>class User(models.Model):
...
class Event(models.Model):
...
class Role(models.Model):
user = models.ForeignKey(User)
event = models.ForeignKey(Event)
</code></pre>
<p>And enforce the one role per user per event in either a manager or SQL constraints.</p>
| 9,856
|
<p>I'm interested in finding online APIs where you could perform a call to some third party service with some print preparation request with my model (i.e. "heal a model" or "set up support") and get in return GCODE file I can send to a 3D printer.
My input will be :</p>
<ul>
<li>The 3d model (obj, stl)</li>
<li>My printer (makerbot, ultimaker, whatever) or a printer profile</li>
<li>A printing profile</li>
</ul>
<p>This is opposed to all the classical 3D printing processes we have right now. Currently when printing in a 3D printer you would need to go through these phases:</p>
<ol>
<li>Create/Download a model</li>
<li>Prepare the model for printing with some 3rd party desktop software</li>
<li>Export the model as gcode</li>
<li>Save the file to some flash drive</li>
<li>Plug the flash drive into the printer</li>
<li>Print the model with the printer interface</li>
</ol>
<p>I would like to know if this process can be simplified to a point where you can just print your model directly from your web browser without going through all these steps.
I know I'm over simplifying things here, but I would still want to see if solutions like I suggested exist?</p>
<p>Thanks</p>
|
<p>There are printers designed for medical use, and the manufacturers supply them with varying levels of <a href="http://www.medicalplasticsnews.com/opinion/passing-the-test_1/" rel="nofollow">certification and testing</a>, however I've not seen a filament manufacturer certify their material as bio-compatible separate from the printer. The printing process changes the material slightly in the best case (and significantly with poor temperature control or badly set parameters), so even if bio-compatible filament were found, the resulting product might not achieve the same level of bio-compatibility.</p>
<p>If your intent is to use hobbyist level machine for medical purposes, you might simply want to use an interface, such as a sock or a molded/cast polymer that you know to be bio-compatible between the printed part and the skin.</p>
|
<p>If you want to know something about what you are questioning, it is interesting to you to read <a href="http://e-nable.org/resources/prosthetics-students-consultation/" rel="nofollow noreferrer">http://e-nable.org/resources/prosthetics-students-consultation/</a></p>
<p>That's a link with complementary information how to print 3D as a volunteer.</p>
<p>I know that is not enough information about products, but I believe Nylon is the best recommend because it is what generally printers are using, though.</p>
<p>This website supports information with Dr. Chang by the e-mail eagle01@rocketmail.com</p>
<p>but there insnt information about the components used in the prosthetics, but I know that Nylon is the best suited to it nowadays. </p>
<p>If you prefer there is a site with makers loging information about PETG:
<a href="https://www.matterhackers.com/news/how-to-succeed-when-printing-with-petg-filament" rel="nofollow noreferrer">https://www.matterhackers.com/news/how-to-succeed-when-printing-with-petg-filament</a></p>
| 118
|
<p>I have an object that starts a thread, opens a file, and waits for input from other classes. As it receives input, it writes it to disk. Basically, it's a thread safe data logging class...</p>
<p>Here's the weird part. When I open a form in the designer (Visual Studio 2008) that uses the object the file gets created. It's obviously running under the design time vhost process...</p>
<p>The odd thing is I've not been able to reproduce the issue in another project. I'm not sure what the rules are for code that gets executed in the designer and code that does not. For example, creating a file in a Windows Forms constructor doesn't actually create the file at design time...</p>
<p>What is the explanation? Is there a reference?</p>
|
<p>You can check the UsageMode of the LicenseManager, to check if the code is in design time or not.</p>
<p>System.ComponentModel.LicenseManager.UsageMode == System.ComponentModel.LicenseUsageMode.Designtime</p>
<p>Here is a quick example:</p>
<pre><code>using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace Test
{
public class ComponentClass : Component
{
public ComponentClass()
{
MessageBox.Show("Runtime!");
}
}
}
</code></pre>
<p>When this component gets add to your form in the designer, you will immediatly get a message box.</p>
<p>To prevent this you can add a simple if statement to check if the code is not in design time</p>
<pre><code>using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace Test
{
public class ComponentClass : Component
{
public ComponentClass()
{
if (LicenseManager.UsageMode != LicenseUsageMode.Designtime)
{
MessageBox.Show("Runtime!");
}
}
}
}
</code></pre>
<p>After adding the if statement, the messagebox no longer appears when the component is added to the form via the designer.</p>
|
<p>There are some things you shouldn't do with the designer. I don't have any hard evidence, but I found that the Windows Forms designer hates it when you take away the default constructor from it. Just go ahead and create new overloads, but leave the empty constructor in place.</p>
<p>Also try to avoid doing <code>Form_Load</code> events in base classes you inherit from.</p>
| 35,700
|
<p>I'm having issues getting the C sockets API to work properly in C++ on z/OS.</p>
<p>Although I am including <code>sys/socket.h</code>, I still get compile time errors telling me that <code>AF_INET</code> is not defined.</p>
<p>Am I missing something obvious, or is this related to the fact that being on z/OS makes my problems much more complicated?</p>
<p>I discovered that there is an <code>#ifdef</code> that I'm hitting. Apparently z/OS isn't happy unless I define which "type" of sockets I'm using with:</p>
<pre><code>#define _OE_SOCKETS
</code></pre>
<p>Now, I personally have no idea what this <code>_OE_SOCKETS</code> is actually for, so if any z/OS sockets programmers are out there (all 3 of you), perhaps you could give me a rundown of how this all works?</p>
<p>Test App</p>
<pre><code>#include <sys/socket.h>
int main()
{
return AF_INET;
}
</code></pre>
<p>Compile/Link Output:</p>
<pre><code>cxx -Wc,xplink -Wl,xplink -o inet_test inet.C
"./inet.C", line 5.16: CCN5274 (S) The name lookup for "AF_INET" did not find a declaration.
CCN0797(I) Compilation failed for file ./inet.C. Object file not created.
</code></pre>
<p>A check of sys/sockets.h does include the definition I need, and as far as I can tell, it is not being blocked by any <code>#ifdef</code> statements.</p>
<p>I have however noticed it contains the following:</p>
<pre><code>#ifdef __cplusplus
extern "C" {
#endif
</code></pre>
<p>which encapsulates basically the whole file? Not sure if it matters.</p>
|
<p>Keep a copy of the IBM manuals handy:</p>
<ul>
<li><a href="http://publibz.boulder.ibm.com/cgi-bin/bookmgr_OS390/BOOKS/CBCPG1A0/CCONTENTS?DT=20090606065305" rel="noreferrer"> z/OS V1R11.0 XL C/C++ Programming Guide</a> </li>
<li><a href="http://publibz.boulder.ibm.com/cgi-bin/bookmgr_OS390/BOOKS/EDCLB1A0/CCONTENTS?DT=20090607203246" rel="noreferrer"> z/OS V1R11.0 XL C/C++ Run-Time Library Reference</a> </li>
</ul>
<p>The IBM publications are generally very good, but you need to get used to their format, as well as knowing where to look for an answer. You'll find quite often that a feature that you want to use is guarded by a "feature test macro"</p>
<p>You should ask your friendly system programmer to install the <a href="http://www-03.ibm.com/servers/eserver/zseries/zos/le/manpgs.html" rel="noreferrer">XL C/C++ Run-Time Library Reference: Man Pages
</a> on your system. Then you can do things like "man connect" to pull up the man page for the socket connect() API. When I do that, this is what I see:</p>
<p>FORMAT</p>
<p>X/Open</p>
<pre><code>#define _XOPEN_SOURCE_EXTENDED 1
#include <sys/socket.h>
int connect(int socket, const struct sockaddr *address, socklen_t address_len);
</code></pre>
<p>Berkeley Sockets</p>
<pre><code>#define _OE_SOCKETS
#include <sys/types.h>
#include <sys/socket.h>
int connect(int socket, struct sockaddr *address, int address_len);
</code></pre>
|
<p>DISCLAIMER: I am not a C++ programmer, however I know C really well. I
adapated these calls from some C code I have.</p>
<p>Also markdown put these strange _ as my underscores.</p>
<p>You should just be able to write an abstraction class around the C sockets with something like this:</p>
<pre><code>class my_sock {
private int sock;
private int socket_type;
private socklen_t sock_len;
private struct sockaddr_in server_addr;
public char *server_ip;
public unsigned short server_port;
};
</code></pre>
<p>Then have methods for opening, closing, and sending packets down the socket.</p>
<p>For example, the open call might look something like this:</p>
<pre><code>int my_socket_connect()
{
int return_code = 0;
if ( this->socket_type != CLIENT_SOCK ) {
cout << "This is a not a client socket!\n";
return -1;
}
return_code = connect( this->local_sock, (struct sockaddr *) &this->server_addr, sizeof(this->server_addr));
if( return_code < 0 ) {
cout << "Connect() failure! %s\n", strerror(errno);
return return_code;
}
return return_code;
}
</code></pre>
| 2,240
|
<p>In Python, you can do this:</p>
<pre><code>print "Hi! I'm %(name)s, and I'm %(age)d years old." % ({"name":"Brian","age":30})
</code></pre>
<p>What's the closest, simplest Ruby idiom to replicate this behavior? (No monkeypatching the String class, please.)</p>
<p>One of the really excellent benefits of this is that you can store the pre-processed string in a variable and use it as a "template", like so:</p>
<pre><code>template = "Hi! I'm %(name)s, and I'm %(age)d years old."
def greet(template,name,age):
print template % ({"name":name,"age":age})
</code></pre>
<p>This is obviously a trivial example, but there is a lot of utility in being able to store such a string for later use. Ruby's <code>"Hi! I'm #{name}"</code> convention is cursorily similar, but the immediate evaluation makes it less versatile.</p>
|
<p>You can also use </p>
<pre><code>printf "1: %<key1>s 2: %<key2>s\n", {:key1 => "value1", :key2 => "value2"}
</code></pre>
<p>or</p>
<pre><code>data = {:key1 => "value1", :key2 => "value2"}
printf "1: %<key1>s 2: %<key2>s\n", data
</code></pre>
<p>or (this needs ruby 1.9, for the other examples I'm not sure)</p>
<pre><code>data = {key1: "value1", key2: "value2"}
printf "1: %<key1>s 2: %<key2>s\n", data
</code></pre>
<p>This prints</p>
<pre><code>1: value1 2: value2
</code></pre>
<p>Important restriction: The used keys of the hash (<em>data</em> in my example) must be symbols.</p>
<hr>
<p>A remark on the example above:
<code>printf</code> takes one format string and optional parameters. But there is also a <code>String#%</code>-method.</p>
<p>The following four calls have all the same result:</p>
<pre><code>printf "1: %<key1>s 2: %<key2>s\n" , {:key1 => "value1", :key2 => "value2"}
printf "1: %<key1>s 2: %<key2>s\n" % {:key1 => "value1", :key2 => "value2"}
print "1: %<key1>s 2: %<key2>s\n" % {:key1 => "value1", :key2 => "value2"}
puts "1: %<key1>s 2: %<key2>s" % {:key1 => "value1", :key2 => "value2"}
</code></pre>
<p>The second version uses first the <code>String#%</code>-method and sends the result to <code>printf</code>.</p>
|
<p>puts "Hi! I'm #{name}, and I'm #{age} years old."</p>
| 23,920
|
<p>At my current job we have a CMS system that is .NET/SQL Server based. While customizing a couple of the modules for some internal use, I was a little surprised to see that instead of having APIs that returned data via your typical result set that was bound to a DataGrid/DataList/Repeater control, that the APIs returned an XML node/collection, that was then passed to an XSLT transformation and rendered on the page that way.</p>
<p>What are the benefits to using a model like this?</p>
|
<p>Keep one integer for each bit, and increment this collection appropriately for each integer in the array.</p>
<p>At the end, some of the bits will have a count higher than half the length of the array - those bits determine N. Of course, the count will be higher than the number of times N occurred, but that doesn't matter. The important thing is that any bit which isn't part of N <em>cannot</em> occur more than half the times (because N has over half the entries) and any bit which is part of N <em>must</em> occur more than half the times (because it will occur every time N occurs, and any extras).</p>
<p>(No code at the moment - about to lose net access. Hopefully the above is clear enough though.)</p>
|
<p>I have recollections of this algorithm, which might or might not follow the 2K rule. It might need to be rewritten with stacks and the like to avoid breaking the memory limits due to function calls, but this might be unneeded since it only ever has a logarithmic number of such calls. Anyhow, I have vague recollections from college or a recursive solution to this which involved divide and conquer, the secret being that when you divide the groups in half, at least one of the halves still has more than half of its values equal to the max. The basic rule when dividing is that you return two candidate top values, one of which is the top value and one of which is some other value (that may or may not be 2nd place). I forget the algorithm itself.</p>
| 35,170
|
<p>I have a table that has a column with a default value:</p>
<pre><code>create table t (
value varchar(50) default ('something')
)
</code></pre>
<p>I'm using a stored procedure to insert values into this table:</p>
<pre><code>create procedure t_insert (
@value varchar(50) = null
)
as
insert into t (value) values (@value)
</code></pre>
<p>The question is, how do I get it to use the default when <code>@value</code> is <code>null</code>? I tried:</p>
<pre><code>insert into t (value) values ( isnull(@value, default) )
</code></pre>
<p>That obviously didn't work. Also tried a <code>case</code> statement, but that didn't fair well either. Any other suggestions? Am I going about this the wrong way?</p>
<p>Update: I'm trying to accomplish this <strong>without</strong> having to:</p>
<ol>
<li>maintain the <code>default</code> value in multiple places, and</li>
<li>use multiple <code>insert</code> statements.</li>
</ol>
<p>If this isn't possible, well I guess I'll just have to live with it. It just seems that something this should be attainable.</p>
<p>Note: my actual table has more than one column. I was just quickly writing an example.</p>
|
<p>Try an if statement ... </p>
<pre><code>if @value is null
insert into t (value) values (default)
else
insert into t (value) values (@value)
</code></pre>
|
<p>The easiest way to do this is to modify the table declaration to be </p>
<pre><code>CREATE TABLE Demo
(
MyColumn VARCHAR(10) NOT NULL DEFAULT 'Me'
)
</code></pre>
<p>Now, in your stored procedure you can do something like.</p>
<pre><code>CREATE PROCEDURE InsertDemo
@MyColumn VARCHAR(10) = null
AS
INSERT INTO Demo (MyColumn) VALUES(@MyColumn)
</code></pre>
<p>However, this method ONLY works if you can't have a null, otherwise, your stored procedure would have to use a different form of insert to trigger a default.</p>
| 28,554
|
<p>I have an Excel spreadsheet with a few thousand entries in it. I want to import the table into a MySQL 4 database (that's what I'm given). I am using SQuirrel for GUI access to the database, which is being hosted remotely. </p>
<p>Is there a way to load the columns from the spreadsheet (which I can name according to the column names in the database table) to the database without copying the contents of a generated CSV file from that table? That is, can I run the LOAD command on a local file instructing it to load the contents into a remote database, and what are the possible performance implications of doing so?</p>
<p>Note, there is a auto-generated field in the table for assigning ids to new values, and I want to make sure that I don't override that id, since it is the primary key on the table (as well as other compound keys).</p>
|
<p>One of the ways GWT was designed to be used is exactly as you've used it. We have done that in many of our apps - where there is one GWT module with multiple 'parts' that are loaded based on whether a given id exists on a page or not. So I don't see that you'll have any issues at all going this way. We often use this approach even for new web applications, where we just want a few 'widgets' on the page, rather than coding the whole application in GWT. </p>
<p>It won't make a huge difference, but one thing I would suggest is not putting the GWT javascript code into your main template, but rather only put it on the pages that need it. It's true that if you're not running HTTPs it is cached basically forever, but it seems wrong to get people to load in the module if it's not actually needed on that page. This of course depends on how people use your site, if they are likely to download it anyway then it won't make any difference.</p>
|
<p>You're doing it right. Avoid avoid avoid the temptation to try to 'minimize' the GWT footprint by breaking it up into multiple separate apps. </p>
<p>The key to GWT performance is to have as few downloads as possible and to make sure they're cached. Loading a 250k bundle once is much better than two 200k bundles and because compression get's better with larger files you really start to reap benefits as things grow. </p>
<p>y-slow & firebug can be really helpful when it comes to convincing yourself of this. </p>
<p>One performance trick you might check out is available in the sample chapter here: <a href="http://www.infoq.com/articles/progwt" rel="nofollow noreferrer">http://www.infoq.com/articles/progwt</a>
It shows a mini-architecture around loading GWT widgets into any number of slots and pre-populating data in JavaScript variables. This allows your GWT widgets to load and not require a second HTTP GET to get the data they use. In practice I found that this was a nice performance boost. </p>
| 47,404
|
<p>I receive HTML pages from our creative team, and then use those to build aspx pages. One challenge I frequently face is getting the HTML I spit out to match theirs exactly. I almost always end up screwing up the nesting of <code><div></code>s between my page and the master pages.</p>
<p>Does anyone know of a tool that will help in this situation -- something that will compare 2 pages and output the structural differences? I can't use a standard diff tool, because IDs change from what I receive from creative, text replaces <i>lorem ipsum</i>, etc.. </p>
|
<p>You can use <a href="http://tidy.sourceforge.net/" rel="nofollow noreferrer">HTMLTidy</a> to convert the HTML to well-formed XML so you can use <a href="http://msdn.microsoft.com/en-us/library/aa302294.aspx" rel="nofollow noreferrer">XML Diff</a>, as Gulzar suggested.</p>
<pre><code>tidy -asxml index.html
</code></pre>
|
<p>winmerge is a good visual diff program</p>
| 7,114
|
<p>I need to copy files using Windows command-line (available on XP Pro or later by default) and show progress during the process.</p>
<p>The progress indicator could be in a terminal or a GUI window. It is intended to be used during batch file scripting.</p>
|
<p>I used the copy command with the /z switch for copying over network drives. Also works for copying between local drives. Tested on XP Home edition.</p>
|
<p>Here is the script I use:</p>
<pre><code>@ECHO off
SETLOCAL ENABLEDELAYEDEXPANSION
mode con:cols=210 lines=50
ECHO Starting 1-way backup of MEDIA(M:) to BACKUP(G:)...
robocopy.exe M:\ G:\ *.* /E /PURGE /SEC /NP /NJH /NJS /XD "$RECYCLE.BIN" "System Volume Information" /TEE /R:5 /COPYALL /LOG:from_M_to_G.log
ECHO Finished with backup.
pause
</code></pre>
| 8,324
|
<p>Are there any good <a href="http://java.sun.com/blueprints/corej2eepatterns/Patterns/ValueListHandler.html" rel="noreferrer">value list handler</a> implementations available?</p>
<p>I've found <a href="http://valuelist.sourceforge.net/" rel="noreferrer">valuelist</a>, but it seems to be stagnating... besides I really need good control of links the taglib generates, because I need to call some JavaScript from it.</p>
<p>Currently I solve it by rewriting the taglib in freemarker and using valuelist's backend.</p>
<p>Does anyone know a better way?</p>
|
<p>Calling MiniMizeMemory() will do a garbage collection, trim the process working size, then compact the process' heap.</p>
<pre><code>public static void MinimizeMemory()
{
GC.Collect(GC.MaxGeneration);
GC.WaitForPendingFinalizers();
SetProcessWorkingSetSize(
Process.GetCurrentProcess().Handle,
(UIntPtr)0xFFFFFFFF,
(UIntPtr)0xFFFFFFFF);
IntPtr heap = GetProcessHeap();
if (HeapLock(heap))
{
try
{
if (HeapCompact(heap, 0) == 0)
{
// error condition ignored
}
}
finally
{
HeapUnlock(heap);
}
}
}
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool SetProcessWorkingSetSize(
IntPtr process,
UIntPtr minimumWorkingSetSize,
UIntPtr maximumWorkingSetSize);
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern IntPtr GetProcessHeap();
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool HeapLock(IntPtr heap);
[DllImport("kernel32.dll")]
internal static extern uint HeapCompact(IntPtr heap, uint flags);
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool HeapUnlock(IntPtr heap);
</code></pre>
|
<p>While this is in C#, look at the source code, it will solve any issues you have:</p>
<p><a href="http://www.codeproject.com/KB/cs/NotifyIconExample.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/cs/NotifyIconExample.aspx</a></p>
| 32,953
|
<p>How can I programmatically remove a (known) password from an Excel VBA project?</p>
<p>To be clear: I want to remove the password from the VBA Project, not the workbook or any worksheets.</p>
|
<p>Another way to remove VBA project password is;</p>
<ul>
<li>Open xls file with a hex editor.
(ie. Hex Edit <a href="http://www.hexedit.com/" rel="noreferrer">http://www.hexedit.com/</a>)</li>
<li>Search for DPB</li>
<li>Replace DPB to DPx</li>
<li>Save file.</li>
<li>Open file in Excel.</li>
<li>Click "Yes" if you get any message box.</li>
<li>Set new password from VBA Project Properties. </li>
<li>Close and open again file, then type your new password to unprotect.</li>
</ul>
<p><strong>UPDATE:</strong> For Excel 2010 (Works for MS Office Pro Plus 2010 [14.0.6023.1000 64bit]), </p>
<ul>
<li>Open the XLSX file with 7zip</li>
</ul>
<p><strong>If workbook is protected:</strong></p>
<ul>
<li>Browse the folder <code>xl</code></li>
<li>If the workbook is protected, right click <code>workbook.xml</code> and select <strong>Edit</strong></li>
<li>Find the portion <code><workbookProtection workbookPassword="XXXX" lockStructure="1"/></code> (<code>XXXX</code> is your encrypted password)</li>
<li>Remove <code>XXXX</code> part. (ie. <code><workbookProtection workbookPassword="" lockStructure="1"/></code>)</li>
<li>Save the file. </li>
<li>When 7zip asks you to update the archive, say <strong>Yes</strong>.</li>
<li>Close 7zip and re-open your XLSX.</li>
<li>Click <strong>Protect Workbook</strong> on <strong>Review</strong> tab.</li>
<li>Optional: Save your file.</li>
</ul>
<p><strong>If worksheets are protected:</strong></p>
<ul>
<li>Browse to <code>xl/worksheets/</code> folder.</li>
<li>Right click the <code>Sheet1.xml</code>, <code>sheet2.xml</code>, etc and select <strong>Edit</strong>.</li>
<li>Find the portion <code><sheetProtection password="XXXX" sheet="1" objects="1" scenarios="1" /></code></li>
<li>Remove the encrypted password (ie. <code><sheetProtection password="" sheet="1" objects="1" scenarios="1" /></code>)</li>
<li>Save the file. </li>
<li>When 7zip asks you to update the archive, say <strong>Yes</strong>.</li>
<li>Close 7zip and re-open your XLSX.</li>
<li>Click <strong>Unprotect Sheet</strong> on <strong>Review</strong> tab.</li>
<li>Optional: Save your file.</li>
</ul>
|
<p>After opening xlsm file with 7 zip, extracting vbaproject.bin and in Notepad ++ replacing DpB with DPx and re-saving I got a Lot of vbaproject errors and vba project password was gone but no code/forms.</p>
<p>I right clicked to export and was able to re-import to a new project.</p>
| 34,297
|
<p>One thing I am concerned with is that I discovered two ways of registering delegates to events.</p>
<ol>
<li>OnStuff += this.Handle; </li>
<li>OnStuff += new StuffEventHandler(this.Handle);</li>
</ol>
<p>The first one is clean, and it makes sense doing "OnStuff -= this.Handle;" to unregister from the event... But with the latter case, should I do "OnStuff -= new StuffEventHandler(this.Handle);"? It feels like I am not removing anything at all, since I'm throwing in another StuffEventHandler reference. Does the event compare the delegate by reference? I am concerned I could start a nasty memory pool here. Get me? I don't have the reference to the "new StuffEventHandler" I previously registered.</p>
<p>What is the downside of doing #1?</p>
<p>What is benefit of doing #2? </p>
|
<p>You don't need to worry about keeping a reference to the originally registered delegate, and you will not start a "nasty memory pool".</p>
<p>When you call "OnStuff -= new StuffEventHandler(this.Handle);" the removal code does <em>not</em> compare the delegate you are removing by reference: it checks for equality by comparing references to the target method(s) that the delegate will call, and removes the matching delegates from "OnStuff".</p>
<p>By the way, "OnStuff" itself is a delegate object (the event keyword that I assume you have in your declaration simply restricts the accessibility of the delegate).</p>
|
<p>If I remember correctly, the first alternative is merely syntactic sugar for the second.</p>
| 12,499
|
<p>This is a bit hypothetical and grossly simplified but...</p>
<p>Assume a program that will be calling functions written by third parties. These parties can be assumed to be non-hostile but can't be assumed to be "competent". Each function will take some arguments, have side effects and return a value. They have no state while they are not running.</p>
<p>The objective is to ensure they can't cause memory leaks by logging all mallocs (and the like) and then freeing everything after the function exits.</p>
<p>Is this possible? Is this practical?</p>
<p>p.s. The important part to me is ensuring that no allocations persist so ways to remove memory leaks without doing that are not useful to me.</p>
|
<p>You don't specify the operating system or environment, this answer assumes Linux, glibc, and C.</p>
<p>You can set __malloc_hook, __free_hook, and __realloc_hook to point to functions which will be called from malloc(), realloc(), and free() respectively. There is a __malloc_hook manpage showing the prototypes. You can add track allocations in these hooks, then return to let glibc handle the memory allocation/deallocation.</p>
<p>It sounds like you want to free any live allocations when the third-party function returns. There are ways to have gcc automatically insert calls at every function entrance and exit using -finstrument-functions, but I think that would be inelegant for what you are trying to do. Can you have your own code call a function in your memory-tracking library after calling one of these third-party functions? You could then check if there are any allocations which the third-party function did not already free.</p>
|
<p>Since you're worried about memory leaks and talking about malloc/free, I assume you're in C. I'm also assuming based on your question that you do not have access to the source code of the third party library.</p>
<p>The only thing I can think of is to examine memory consumption of your app before & after the call, log error messages if they're different and convince the third party vendor to fix any leaks you find.</p>
| 7,366
|
<p>I have a method lets say:</p>
<pre><code>private static String drawCellValue(
int maxCellLength, String cellValue, String align) { }
</code></pre>
<p>and as you can notice, I have a parameter called align. Inside this method I'm going to have some if condition on whether the value is a 'left' or 'right'.. setting the parameter as String, obviously I can pass any string value.. I would like to know if it's possible to have an Enum value as a method parameter, and if so, how?</p>
<p>Just in case someone thinks about this; I thought about using a Boolean value but I don't really fancy it. First, how to associate true/false with left/right ? (Ok, I can use comments but I still find it dirty) and secondly, I might decide to add a new value, like 'justify', so if I have more than 2 possible values, Boolean type is definitely not possible to use.</p>
<p>Any ideas?</p>
|
<p>This should do it:</p>
<pre><code>private enum Alignment { LEFT, RIGHT };
String drawCellValue (int maxCellLength, String cellValue, Alignment align){
if (align == Alignment.LEFT)
{
//Process it...
}
}
</code></pre>
|
<p>Sure, you could use an enum. Would something like the following work?</p>
<pre><code>enum Alignment {
LEFT,
RIGHT
}
</code></pre>
<p>private static String drawCellValue(int maxCellLength, String cellValue, Alignment alignment) { }</p>
<p>If you wanted to use a boolean, you could rename the align parameter to something like alignLeft. I agree that this implementation is not as clean, but if you don't anticipate a lot of changes and this is not a public interface, it might be a good choice.</p>
| 17,214
|
<p>I'm trying to highlight just one specific row in a table using jQuery. The row will have an 'active' status. I have seen plenty of examples online which show how to do zebra striping for alternate row styling. Does anyone know of a jQuery expression which will get a element based on the value of a element in a specific column? </p>
|
<p>check out ":contains" on <a href="http://docs.jquery.com/Selectors" rel="nofollow noreferrer">http://docs.jquery.com/Selectors</a></p>
|
<p>You can use one of them:</p>
<pre><code>$("td").contains("test");
</code></pre>
<p>or</p>
<pre><code>$("div:contains('John')");
</code></pre>
| 22,114
|
<p>I'm trying to set up <a href="http://www.autohotkey.com/" rel="nofollow noreferrer">AutoHotkey</a> macros for some common tasks, and I want the hotkeys to mimic Visual Studio's "two-step shortcut" behaviour - i.e. pressing <kbd>Ctrl</kbd>-<kbd>K</kbd> will enable "macro mode"; within macro mode, pressing certain keys will run a macro and then disable 'macro mode', and any other key will just disable macro mode.</p>
<p>Example - when typing a filename, I want to be able to insert today's date by tapping <kbd>Ctrl</kbd>-<kbd>K</kbd>, then pressing <kbd>D</kbd>.</p>
<p>Does anyone have a good example of a stateful AutoHotkey script that behaves like this?</p>
|
<p>This Autohotkey script, when you press <kbd>ctrl</kbd>+<kbd>k</kbd>, will wait for you to press a key and if you press <kbd>d</kbd>, it will input the current date.</p>
<pre><code>^k::
Input Key, L1
FormatTime, Time, , yyyy-MM-dd
if Key = d
Send %Time%
return
</code></pre>
|
<p>A slight variation on the accepted answer - this is what I've ended up using. I'm capturing Ctrl+LWin (left Windows key) so it doesn't conflict with VS inbuilt Ctrl-K shortcuts.</p>
<pre><code>; Capture Ctrl+Left Windows Key
^LWin::
; Show traytip including shortcut keys
TrayTip, Ctrl-Win pressed - waiting for second key..., t: current time`nd: current date, 1, 1
; Capture next string input (i.e. next key)
Input, Key, L1
; Call TrayTip with no arguments to remove currently-visible traytip
TrayTip
if Key = d
{
FormatTime, Date, , yyyyMMdd
SendInput %Date%
}
else if Key = t
{
FormatTime, Time, , hhmmss
SendInput %Time%
}
return
</code></pre>
| 24,476
|
<p>I've noticed on bank websites, etc, my user IDs aren't saved (they don't appear in a dropdown like other commonly entered stuff does) and there's no prompt for it to remember your password. How is this done? How do the sites notify the browser that they are in 'special' or else exceptions? Just curious.</p>
|
<p>Usually you just need to put the autocomplete="off" into the form or field you want to block.</p>
<p>Keep in mind that users can get around this with a scriptlet, plugin, or grease-monkey script.</p>
<p><a href="https://developer.mozilla.org/en/How_to_Turn_Off_Form_Autocompletion#Exceptions_and_Recommended_Workarounds" rel="noreferrer">https://developer.mozilla.org/en/How_to_Turn_Off_Form_Autocompletion#Exceptions_and_Recommended_Workarounds</a></p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms533032(VS.85).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms533032(VS.85).aspx</a></p>
|
<p>Autocomplete behavior can be controlled at TextBox also. </p>
<p>As suggested in link below, use AutoCompleteType = "Disabled" to disable autocomplete for any textbox.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox.autocompletetype.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox.autocompletetype.aspx</a></p>
| 42,524
|
<p>I know there are tools to get text files to resource files for Visual Studio. But I want to get the text from my resource files to a text file so they can be translated. Or is there a better way to do this? </p>
|
<p>You can use <a href="http://simpleresxeditor.blogspot.com/" rel="nofollow noreferrer">Simple Resx Editor</a>, it has some interesting features that will help you into the translation process.</p>
|
<p>You could use winres.exe from Microsoft, it lets you localize windows forms without having to use Visual Studio. It doesn't save the resources to a text file, but the idea is that the localization expert for each culture could use the tool to generate a localized versions of the application.</p>
<p>Here's a better explanation:
<a href="http://msdn.microsoft.com/en-us/library/8bxdx003(VS.80).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/8bxdx003(VS.80).aspx</a></p>
| 24,225
|
<p>I remember when MS was developing Cassini - I believe they rolled it into VS 05/08, so I think this is a Cassini web server question. </p>
<p>I am using Windows XP with Visual Studio 2008, and find it quite inconvenient when I want to test a web page/styling with multiple browsers and multiple OSes. Right now I have to deploy the code on our server, and if there are any updates that need to happen, the process turns into quite a time drain. Since I am using XP/IIS 5, the option of using IIS is not an option. The use of IIS on XP requires an extra prefix for a project, which breaks all links, css etc. This was also a really quick development project so things like root dir that should be pulled out to config aren't, I am quite on board with this type of solution but it wasn't implemented in this project. It also seems really sketchy that MS wouldn't allow a simple flag somewhere to allow remote connections - its quite simple (<a href="http://www.devx.com/dotnet/Article/11711" rel="noreferrer">http://www.devx.com/dotnet/Article/11711</a>) but I don't want to recompile Cassini.</p>
<p>Does anyone know how to allow the integrated development web server in Visual Studio 2008 to be seen by other computers? This would save loads of time.</p>
|
<p>just figured out a good solution:
1) Set up fiddler on development machine
2) Set up remote machine to use fiddler as proxy
3) browse to <code>http://localhost.:[insert your dev port # here</code>]/ on remote machine</p>
|
<p>Using Fiddler as reverse proxy, development web server could get the request, but it becomes internal request (127.0.0.1), which is useless in my case.</p>
<p>I'm trying to catch remote request to debug it on there.</p>
| 27,125
|
<p>I have a couple of files containing a value in each line.</p>
<p><strong>EDIT :</strong></p>
<p>I figured out the answer to this question while in the midst of writing the post and didn't realize I had posted it by mistake in its incomplete state.</p>
<p>I was trying to do:</p>
<pre><code>paste -d ',' file1 file2 file 3 file 4 > file5.csv
</code></pre>
<p>and was getting a weird output. I later realized that was happening because some files had both a carriage return and a newline character at the end of the line while others had only the newline character. I got to always remember to pay attention to those things.
</p>
|
<p>file 1:</p>
<pre>
1
2
3
</pre>
<p>file2:</p>
<pre>
2
4
6
</pre>
<pre><code>paste --delimiters=\; file1 file2
</code></pre>
<p>Will yield:</p>
<pre>
1;2
3;4
5;6
</pre>
|
<p>you probably need to clarify or retag your question but as it stands the answer is below.</p>
<p>joining two files under Linux</p>
<pre><code>cat filetwo >> fileone
</code></pre>
| 4,485
|
<p>I need to do the following for the purposes of paging a query in nHibernate:</p>
<pre><code>Select count(*) from
(Select e.ID,e.Name from Object as e where...)
</code></pre>
<p>I have tried the following, </p>
<pre><code>select count(*) from Object e where e = (Select distinct e.ID,e.Name from ...)
</code></pre>
<p>and I get an nHibernate Exception saying I cannot convert Object to int32.</p>
<p>Any ideas on the required syntax?</p>
<p><strong>EDIT</strong></p>
<p>The Subquery uses a distinct clause, I cannot replace the e.ID,e.Name with <code>Count(*)</code> because <code>Count(*) distinct</code> is not a valid syntax, and <code>distinct count(*)</code> is meaningless.</p>
|
<pre><code>var session = GetSession();
var criteria = session.CreateCriteria(typeof(Order))
.Add(Restrictions.Eq("Product", product))
.SetProjection(Projections.CountDistinct("Price"));
return (int) criteria.UniqueResult();
</code></pre>
|
<p>If you just need <code>e.Id</code>,<code>e.Name</code>:</p>
<p><code>select count(*) from Object where</code>.....</p>
| 14,159
|
<p>Let's say we have a solution with the following structure:</p>
<ul>
<li>Project.DAL - Data access layer,
depends on a lower-level library,
e.g. Oracle.DataAccess w/copy local
= true </li>
<li>Project.BLL - Business logic layer, references Project.DAL as
project </li>
<li>Project.UI - UI layer,
compiles to executable, references
Project.BLL, default project</li>
</ul>
<p>When Project.UI is compiled, VS is smart enough to copy Project.DAL.dll to the output directory, but it's not smart enough to figure out that I wanted Oracle.DataAccess to be copied to the output directory as well for distribution to clients.</p>
<p>Can anyone explain why this is so? Is it because it sees Oracle.DataAccess in the GAC and assumes that clients will have it in the GAC as well?</p>
<p>It's not that big of a deal, but it's kinda annoying that every time I add a new assembly reference, I have to remember to set it to copy local and add an item to copy it in my build script as well. </p>
|
<p>Yes, Visual Studio will copy a DLL to the output path in any of the two conditions below:</p>
<ol>
<li>The DLL is referenced explicitly with CopyLocal = true</li>
<li>The DLL is referenced without CopyLocal or implicitly through some other referenced DLL <strong>and is not in the GAC</strong></li>
</ol>
<p>The reason why it will not copy-local when the file is in GAC, is that when resolving assembly names the GAC has highest priority, i.e. even if you have a (different) local copy, the version from the GAC will be used.</p>
<p>I suggest you set up a library directory where you put all external assemblies that are referenced. Then you set up an automatic MSBuild script on a computer (or VM) that does not have the Oracle-file gac'ed (nor Visual Studio installed for that sake). That way, the file will be copied to the build, and you will have more control over what is done than when using VS.</p>
|
<p>@RenniePet Here's a link to a blog which describes the method RenniePet described in a comment above (if you don't want to edit your project file manually as @Shaun suggested):</p>
<p><a href="http://blogs.msdn.com/b/jjameson/archive/2009/11/18/the-copy-local-bug-in-visual-studio.aspx" rel="nofollow">http://blogs.msdn.com/b/jjameson/archive/2009/11/18/the-copy-local-bug-in-visual-studio.aspx</a></p>
| 46,062
|
<p>My Prusa Mk3 has been making this sort of rough surface on prints, and I'm not sure what caused this. I am printing with PLA Prusament with 0.2 mm layer height at the preset for PLA. What is this, and how can I fix it?</p>
<p><a href="https://i.stack.imgur.com/qRzOM.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qRzOM.jpg" alt="Print with rough surface finish"></a></p>
<p><strike>Edit: Changed absolutely nothing, tried again and problem solved!</strike></p>
|
<p>The OP was not able to reproduce the problem as can be taken from an edit to his question:</p>
<blockquote>
<p>Changed absolutely nothing, tried again and problem solved!</p>
</blockquote>
<p><em>To honor the Q/A approach used on SE sites, this comment has been converted to a community answer, that once voted for will not make this question pop up once in a while.</em></p>
|
<p>To me this looks like your nozzle is too hot. Try turning the temp down by 5 degrees at a time and see if the issue goes away.</p>
| 1,208
|
<p>I need to create a BAT file to run an application through telnet, but as far as I know there is no way to do this on DOS. Telnet does not allow any command to be sent to the remote machine at the very instant of the connection, and each subsequent command in the BAT file would only be executed after telnet stops. This hypothetical piece of code illustrates what I want to do:</p>
<pre><code>telnet 100.99.98.1 "C:\Application\app.exe -a -b -c"
</code></pre>
<p>And that would run the app.exe on the machine 100.99.98.1 with three parameters. Despite my efforts, nothing worked. Is there a way to do that?</p>
<p>Tks,</p>
<p>Pedrin Batista</p>
|
<p>Have you tried:</p>
<pre><code>echo "c:\application\app.exe -a -b -c" | telnet 100.99.98.1
</code></pre>
<p>this won't work if the remote telnet server requires a username and password, though.</p>
|
<p>Does your telnet app need to run in a command window, or do you only need to <em>start</em> it from the command line? If you want to "launch and forget," you might consider a scriptable terminal program such as the free TeraTerm. You can launch it from the command line with the <code>start</code> command and let it execute a script in the background.</p>
| 35,981
|
<p>Given a source color of any hue by the system or user, I'd like a simple algorithm I can use to work out a lighter or darker variants of the selected color. Similar to effects used on Windows Live Messenger for styling the user interface.</p>
<p>Language is C# with .net 3.5.</p>
<p><strong>Responding to comment:</strong> Color format is (Alpha)RGB. With values as bytes or floats.</p>
<p><strong>Marking answer:</strong> For the context of my use (a few simple UI effects), the answer I'm marking as accepted is actually the most simple for this context. However, I've given up votes to the more complex and accurate answers too. Anyone doing more advanced color operations and finding this thread in future should definitely check those out. Thanks SO. :)</p>
|
<p>Simply multiply the RGB values by the amount you want to modify the level by. If one of the colors is already at the max value, then you can't make it any brighter (using HSV math anyway.)</p>
<p>This gives the exact same result with a lot less math as switching to HSV and then modifying V. This gives the same result as switching to HSL and then modifying L, as long as you don't want to start losing saturation.</p>
|
<p>Assuming you get the color as RGB, first convert it to HSV (hue, saturation, value) color space. Then increase/decrease the value to produce lighter/darker shade of the color. Then convert back to RGB.</p>
| 12,315
|
<p>I have seen some websites use the following tag:</p>
<pre><code><meta type="title" content="Title of the page" />
</code></pre>
<p>Is it needed when you have a <code><title></code>?</p>
<p>Also, what's the best formatting for a page title? Some ideas:</p>
<ul>
<li>Page Description :: Company Name</li>
<li>Page Description - Company Name</li>
<li>Page Description <> Company Name</li>
<li>Company Name: Page Description</li>
<li>...</li>
</ul>
<p>Does it matter to Google/Yahoo/etc? Do you include the company name or a general description of the site in the title on every page? </p>
|
<p>The <code><meta type="title"></code> tag has little rank or relevance to search engine crawlers. The good old <code><title></code> tag is far and away the <a href="http://www.w3.org/QA/Tips/good-titles" rel="nofollow noreferrer">most important element of a good web page</a>.</p>
<p>As for the format of the title, I think there is good advice in <a href="http://www.standards-schmandards.com/2004/title-text-separators/" rel="nofollow noreferrer">this article at Standards Schmandards</a>:</p>
<blockquote>
<p>If the title contains the name of the
site, the name of the site should be
placed at the end of the title. This
makes sure that multiple bookmarks
from the same site are easy to browse
through in the bookmarks folder and
listeners to your page get the most
important information first.</p>
</blockquote>
<p>I would highly suggest that you <em>do</em> include the company name or site name at the end of each title because:</p>
<ol>
<li>Consistency is always a good idea.</li>
<li>Newer browsers like Firefox 3 allow you to search your history and bookmarks by page titles, so users can easily get a view of all the pages they've visited on your site by simply typing in your company name or site name.</li>
<li>People that use screen readers will have no idea what website they are visiting if it isn't listed somewhere on the page.</li>
</ol>
<p>However, I would not put a description of the site anywhere but on the home page because that would make the title unnecessarily long and would frustrate screen reader users because they would have to make an extra effort to skip that information on every page they visit.</p>
<p>If you do decide to put the company name in your title, keep these things in mind (also from <a href="http://www.standards-schmandards.com/2004/title-text-separators/" rel="nofollow noreferrer">Standards Schmandards</a>):</p>
<blockquote>
<ul>
<li>The separator character should be
distinct so that users understand
that it is a separator. (I.e. it
should not appear as part of text
items in the title).</li>
<li>Prime candidates to use as separators are the vertical bar (|),
the dot (·) and the dash (-).</li>
<li>Regardless of the character you pick, <em>it is important to surround it
with whitespace</em>. This will aid both
sighted visitors and listeners as it
will distinguish the character from
the title text.</li>
</ul>
</blockquote>
<p>Based on all the information herein, that essentially makes the second example in your question the obvious choice:</p>
<pre><code><title>
Page Description - Company Name
</title>
</code></pre>
|
<p> is what you want to use, because it stands out more than meta tags to most search engines.</p>
<p>My suggestion is to put the keywords that matter first, and avoid repeating the name of your business other than on the homepage, because this only serves to dilute the value of the title text.</p>
| 29,799
|
<p>Does anyone know the format of the MAPI property <code>PR_SEARCH_KEY</code>?</p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/ms529414(EXCHG.10).aspx" rel="nofollow noreferrer">online documentation</a> has this to say about it:</p>
<blockquote>
<p>The search key is formed by
concatenating the address type (in
uppercase characters), the colon
character ':', the e-mail address in
canonical form, and the terminating
null character.</p>
</blockquote>
<p>And the exchange document <a href="http://msdn.microsoft.com/en-us/library/cc433489(EXCHG.80).aspx" rel="nofollow noreferrer">MS-OXOABK</a> says this:</p>
<blockquote>
<p>The PidTagSearchKey property of type
PtypBinary is a binary value formed by
concatenating the ASCII string "EX: "
followed by the DN for the object
converted to all upper case, followed
by a zero byte value.</p>
</blockquote>
<p>However all the MAPI messages I've seen with this property have it as some sort of binary 16 byte sequence that looks like a GUID. Does anyone else have any more information about it? Is it always 16 bytes?</p>
<p>Thanks!</p>
|
<p>I believe that the property <code>PR_SEARCH_KEY</code> will be of different formats for different objects (as alluded to by Moishe).</p>
<p>A MAPI message object will have a unique value assigned on creation for <code>PR_SEARCH_KEY</code>, however if the object is copied this property value is copied also. I presume when you reply to an e-mail, Exchange will assign the <code>PR_SEARCH_KEY</code> value to be the original message's value.</p>
<p>You will need to inspect each object type to understand how the <code>PR_SEARCH_KEY</code> is formed but I doubt if it's always 16 bytes for all MAPI types.</p>
<p>This link <a href="http://groups.google.com/group/microsoft.public.win32.programmer.messaging/browse_thread/thread/79ff9c1a90fd28b6/93da8a356076e683?lnk=st&q=PR_SEARCH_KEY#93da8a356076e683" rel="nofollow noreferrer">USENET discussion</a> has a good discussion with Dmitry Streblechenko involved who is an expert on Extended MAPI.</p>
|
<p>The sentence before the ones you quoted from the online docs reads, "MAPI uses specific rules for constructing search keys for message recipients" which makes me think that it's talking about the PR_SEARCH_KEY property on MAPI_MAILUSER objects -- or at least not on MAPI_MESSAGE objects.</p>
| 24,891
|
<p>Subject says it all but he background:</p>
<p>I want to trigger some TortoiseSVN action from a batch file? I suspect that I can do this by calling the right exe with the right args but I'd rather find a way to solve the more general problem of doing an arbitrary action.</p>
<p><strong>Edit:</strong> The reason that I don't just use svn directly is that TortoiseSVN doesn't include a command line SVN client (e.i. there is no svn.exe on my computer at all). Also, it would dump it output the stdout and I want the GUI output.</p>
<p>Regarding the Right Click menu, besides a way to directly trigger a right click item, a way to take an arbitrary right click item and (more or less automatically) find out what command line to call would also be good enough. However a solution that amounts to "just find out what it does" is not as I already know how to go there.</p>
<p>I don't have any specific reason to believe this can be done, so if someone <em>knows</em> it can't be, that would be a valid answer as well.</p>
|
<p>Use TortoiseProc.exe /command:
See Appendix E of the TortoiseSVN guide</p>
|
<p>Seems to me as if you answered the question yourself. To trigger an arbitrary action will still require knowing something about the action. I am not sure that you will get any benefit from triggering a right click on a menu over calling the exe with the args in the first place.</p>
| 33,477
|
<p>I have a GSM modem connected via USB. The modem creates 2 serial ports. The first is automatically attached to the modem, the second shows in Device Manager as "HUAWEI Mobile Connect - 3G PC UI Interface (COM6)"</p>
<p>The second port is used to get vital information from the modem, such as signal quality; to send and receive text messages; and a whole host of other functions.</p>
<p>I am writing an application that will wrap up some of the features provided by the second port. What I need is a sure fire method of identifying which COM port is the spare one. Iterating the ports and checking a response to "ATE0" is not sufficient. The modem's port is usually the lower numbered one, and when a dial up connection is not active, it will respond to "ATE0" the same as the second port.</p>
<p>What I was thinking of doing is iterating the ports and checking their friendly name, as it shows in Device Manager. That way I can link the port in my application to the port labelled "HUAWEI Mobile Connect - 3G PC UI Interface (COM6)" in Device Manager. I've just not found any information yet that will allow me to get that name programmatically.</p>
|
<p>A long time ago I wrote a utility for a client to do just this, but for a GPS rather than a modem. </p>
<p>I have just looked at it, and bits that jump-out as being possibly helpful are:</p>
<pre><code> GUID guid = GUID_DEVCLASS_PORTS;
SP_DEVICE_INTERFACE_DATA interfaceData;
ZeroMemory(&interfaceData, sizeof(interfaceData));
interfaceData.cbSize = sizeof(interfaceData);
SP_DEVINFO_DATA devInfoData;
ZeroMemory(&devInfoData, sizeof(devInfoData));
devInfoData.cbSize = sizeof(devInfoData);
if(SetupDiEnumDeviceInfo(
hDeviceInfo, // Our device tree
nDevice, // The member to look for
&devInfoData
))
{
DWORD regDataType;
BYTE hardwareId[300];
if(SetupDiGetDeviceRegistryProperty(hDeviceInfo, &devInfoData, SPDRP_HARDWAREID, &regDataType, hardwareId, sizeof(hardwareId), NULL))
{
...
</code></pre>
<p>(You call this bit in a loop with incrementing nDevice)</p>
<p>and then</p>
<pre><code>BYTE friendlyName[300];
if(SetupDiGetDeviceRegistryProperty(hDeviceInfo, &devInfoData, SPDRP_FRIENDLYNAME, NULL, friendlyName, sizeof(friendlyName), NULL))
{
strFriendlyNames += (LPCTSTR)friendlyName;
strFriendlyNames += '\n';
}
</code></pre>
<p>which finds the name of the device.</p>
<p>Hopefully that will help you in the right direction.</p>
|
<p>Used the method posted by <a href="http://gaiger-programming.blogspot.tw/2015/07/methods-collection-of-enumerating-com.html" rel="nofollow">LiGenChen</a>. The method ComPortSetupAPISetupDiClassGuids gave the best time and friendly name.</p>
| 39,214
|
<p>I first encountered the concept of <a href="http://ajaxpatterns.org/Lazy_Registration" rel="noreferrer">lazy registration</a> the <a href="http://ajaxpatterns.org/Main_Page" rel="noreferrer">Ajax Patterns</a> site, where they define it as accumulating "bits of information about the user as they interact, with formal registration occurring later on." I'm looking at doing something similar for my website, but I'd like to know a little bit more about best practices before I start implementing it. My site is about web development, but general best practices are great too. How have you implemented lazy registration on your sites or projects? Where have you seen it in the wild? What do you like or dislike about it?</p>
|
<p>Have a look at this vid, a very good overview of the lazy registration pattern:
<a href="http://www.90percentofeverything.com/2009/03/16/signup-forms-must-die-heres-how-we-killed-ours/" rel="nofollow noreferrer">http://www.90percentofeverything.com/2009/03/16/signup-forms-must-die-heres-how-we-killed-ours/</a></p>
|
<p>One way that I was thinking about implementing this is when users leave blog comments. A common Wordpress format is to allow site visitors to comment as long as they leave a name and an email address. If I followed a similar pattern and then after they submit their comment, ask them if they would also like to register by having username and password inputs right there, with their email pre-filled in the email address input. There would also be a message saying that if they choose not to register at that time, their email address won't be saved (other than in association with the blog comment). If you think of something to add to this, leave a comment.</p>
| 16,600
|
<p>I have an ASP.NET website and when I press F5 it automatically attaches to the ASP.NET Development Server, how do I attach to IIS worker process instead when I press F5?</p>
|
<p>open project properties, go to the web tab and choose the option for IIS.</p>
<p>That actually starts an instance of the app in IIS and attaches the debugger. If you only wanted to attach to an existing IIS instance, choose attach to process from the debug menu.</p>
|
<p>go to the properties of the web application. Select the "Start Options" section, and change from "USe default web server" to "use custom server". Enter "<a href="http://localhost" rel="nofollow noreferrer">http://localhost</a>" in the base url. </p>
<p>(assumes VS 2008)</p>
| 25,804
|
<p>I have an Arduino sending and receiving instructions with a Python script via a serial port.</p>
<p>The Arduino takes a button state and when it is pushed, it will send a message via the serial port to a Python script and await a response. (via <code>Serial.available()</code>). It works well enough.</p>
<p>However, if the Python script has crashed for whatever reason (ideally it will run in the background, so it can't be easily checked), the Arduino will wait forever and will be unavailable even on a script restart.</p>
<p>Is there a way for my Arduino to check if there is something listening on the serial port? (and alert me with flashing lights, etc. if not) or is this not how serial works? Worst case I guess I could use a timeout, although that is not ideal.</p>
|
<p>You have a limited ability to detect if there is something listening on the other side by using the DSR/DTR pins.</p>
<p>When you open the serial port on the machine your scripts runs on, it should raise its DTR pin (or you should be able to convince it to do so: the documentation of the library you use to drive the COM port should tell you how).</p>
<p>Then, on your Arduino, you can check its DSR pin (assuming null-modem wiring with handshaking, where the PC DTR pin is wired to DSR+CD on the Arduino) at regular intervals, and handle the 'nobody connected' scenario in any way you see fit.</p>
<p>One problem with this approach is that your PC script may not close the serial port when it crashes/stops responding, leaving the DTR pin enabled as if everything is still OK. Also, your script may simply miss the message from the Arduino due to errors on the serial line.</p>
<p>For that reason, you should <i>always</i> implement a timeout in your receive routines: even if there is a party listening at the other end, there is no guarantee it has received your message (or that its response will reach you intact).</p>
<p>Re-sending the message at least once (assuming DSR is raised) if a timeout occurs makes your protocol more reliable. </p>
|
<p>I agree with mdb that timeouts are necessary, but would also add that you might want to implement simple challenge/response system that periodically checks if anyone is listening. (I like ircd's Ping-Pong analogy). </p>
| 23,723
|
<p>I'm trying to implement (what I think is) a pretty simple data model for a counter:</p>
<pre><code>class VisitorDayTypeCounter(models.Model):
visitType = models.CharField(max_length=60)
visitDate = models.DateField('Visit Date')
counter = models.IntegerField()
</code></pre>
<p>When someone comes through, it will look for a row that matches the visitType and visitDate; if this row doesn't exist, it will be created with counter=0.</p>
<p>Then we increment the counter and save.</p>
<p>My concern is that this process is totally a race. Two requests could simultaneously check to see if the entity is there, and both of them could create it. Between reading the counter and saving the result, another request could come through and increment it (resulting in a lost count).</p>
<p>So far I haven't really found a good way around this, either in the Django documentation or in the tutorial (in fact, it looks like the tutorial has a race condition in the Vote part of it).</p>
<p>How do I do this safely?</p>
|
<p>As of Django 1.1 you can use the ORM's F() expressions. </p>
<pre><code>from django.db.models import F
product = Product.objects.get(name='Venezuelan Beaver Cheese')
product.number_sold = F('number_sold') + 1
product.save()
</code></pre>
<p>For more details see the documentation:</p>
<p><a href="https://docs.djangoproject.com/en/1.8/ref/models/instances/#updating-attributes-based-on-existing-fields" rel="noreferrer">https://docs.djangoproject.com/en/1.8/ref/models/instances/#updating-attributes-based-on-existing-fields</a></p>
<p><a href="https://docs.djangoproject.com/en/1.8/ref/models/expressions/#django.db.models.F" rel="noreferrer">https://docs.djangoproject.com/en/1.8/ref/models/expressions/#django.db.models.F</a></p>
|
<p>Your should use database transactions to avoid this kind of race condition. A transaction lets you perform the whole operation of creating, reading, incrementing and saving the counter on an "all or nothing" base. If anything goes wrong it will roll back the whole thing and you can try again.</p>
<p>Check out the Django <a href="http://docs.djangoproject.com/en/dev/topics/db/transactions/?from=olddocs" rel="nofollow noreferrer">docs.</a> There is a transaction middle ware, or you can use decorators around views or methods to create transactions.</p>
| 35,404
|
<p>I need an algorithm to determine if a sentence, paragraph or article is negative or positive in tone... or better yet, how negative or positive.</p>
<p>For instance:</p>
<blockquote>
<blockquote>
<p>Jason is the worst SO user I have ever witnessed (-10)</p>
<p>Jason is an SO user (0)</p>
<p>Jason is the best SO user I have ever seen (+10)</p>
<p>Jason is the best at sucking with SO (-10)</p>
<p>While, okay at SO, Jason is the worst at doing bad (+10)</p>
</blockquote>
</blockquote>
<p>Not easy, huh? :)</p>
<p>I don't expect somebody to explain this algorithm to me, but I assume there is already much work on something like this in academia somewhere. If you can point me to some articles or research, I would love it.</p>
<p>Thanks.</p>
|
<p>There is a sub-field of natural language processing called <a href="http://en.wikipedia.org/wiki/Sentiment_analysis" rel="noreferrer">sentiment analysis</a> that deals specifically with this problem domain. There is a fair amount of commercial work done in the area because consumer products are so heavily reviewed in online user forums (ugc or user-generated-content). There is also a prototype platform for text analytics called <a href="http://gate.ac.uk/" rel="noreferrer">GATE</a> from the university of sheffield, and a python project called <a href="http://sourceforge.net/projects/nltk/" rel="noreferrer">nltk</a>. Both are considered flexible, but not very high performance. One or the other might be good for working out your own ideas.</p>
|
<pre><code> use Algorithm::NaiveBayes;
my $nb = Algorithm::NaiveBayes->new;
$nb->add_instance
(attributes => {foo => 1, bar => 1, baz => 3},
label => 'sports');
$nb->add_instance
(attributes => {foo => 2, blurp => 1},
label => ['sports', 'finance']);
... repeat for several more instances, then:
$nb->train;
# Find results for unseen instances
my $result = $nb->predict
(attributes => {bar => 3, blurp => 2});
</code></pre>
| 37,392
|
<p>I am using PHP with Apache on Linux, with Sendmail. I use the PHP <a href="http://php.net/manual/en/function.mail.php" rel="noreferrer"><code>mail</code></a> function. The email is sent, but the envelope has the <code>Apache_user@localhostname</code> in <code>MAIL FROM</code> (example nobody@conniptin.internal) and some remote mail servers reject this because the domain doesn't exist (obviously). Using <code>mail</code>, can I force it to change the envelope <code>MAIL FROM</code>?</p>
<p>EDIT: If I add a header in the fourth field of the <code>mail</code>() function, that changes the <code>From</code> field in the headers of the body of the message, and DOES NOT change the envelope <code>MAIL FROM</code>.</p>
<p>I can force it by spawning sendmail with <code>sendmail -t -odb -oi -frealname@realhost</code> and piping the email contents to it. Is this a better approach?</p>
<p>Is there a better, simpler, more PHP appropriate way of doing this?</p>
<p>EDIT: The bottom line is I should have RTM. Thanks for the answers folks, the fifth parameter works and all is well.</p>
|
<p>mail() has a 4th and 5th parameter (optional). The 5th argument is what should be passed as options directly to sendmail. I use the following:</p>
<pre><code>mail('to@blah.com','subject!','body!','From: from@blah.com','-f from@blah.com');
</code></pre>
|
<p>What you actually need to do is <strong>change</strong> the <strong>hostname</strong> of the machine Apache is running on, plus the <strong>user</strong> Apache is running as.</p>
<p>In your current case it is:</p>
<ul>
<li>Apache user:<strong>nobody</strong></li>
<li>Server hostname: <strong>conniptin.internal</strong></li>
</ul>
<p>Changing those two values is pretty simple and will solve the root of your problem.</p>
<p>Although if you need to do it from PHP then perhaps use the <code>system/exec</code> functions. I do not think it will work in practice though, as you need to restart Apache and probably also the entire host for the new names to be used.</p>
| 21,587
|
<p>I want to be able to run my Chiron during night-time, but my neighbours tries to sleep at that time of day. I have put a lot of effort into making the printer silent. The controller-fan and power-supply-fan now run slower and only when needed, I have put the printer on those <a href="https://www.thingiverse.com/thing:3225296" rel="nofollow noreferrer">damper feet</a> found on Thingiverse, I have added rods to stabilize the gantry and I have switched to TMC2209 for X, Y and Z. I have made sure the TMCs are tuned for 24V and are using 'stealth chop' below 225 rpm (120 mm/s). The result is impressive compared to how noisy the printer was when I bought it.</p>
<p>One problem was not solved, when Y-axis moves at between 35 and 45 mm/s, the printer starts to loudly vibrate at 220 to 280 Hz. To mitigate that, I first tried to slow down printing, but then print quality was hurt by oozing. Now I have reverted back to my desired print speed, but limited Y-axis feed-rate in Marlin to 32 mm/s using <code>M203 Y 32</code>. It is quiet enough, but many movements are slowed down, affecting quality.</p>
<p>What can I do to stop or mute these vibrations?</p>
<p><strong>ADDED 2021-03-30</strong>
I have no proper accelerometer, so I used a MPU6050 accelerometer and some code in an ESP8266. It samples roughly 400 times per second and gives a vibration-value that can be used to <em>estimate</em> the level of vibrations. It is not frequency-compensated, but gives a hint of what is happening. And it can be used to compare settings.</p>
<p>I also made a program based on an example in TMCStepper so I could run the stepper and see/change all settings. This program also relays the measurements from my accelerometer so I can make graphs.</p>
<p>To do this I removed the stepper from the chassis, as I need to be somewhat quiet when doing these tests. It looks like this:</p>
<p><a href="https://i.stack.imgur.com/MSc3m.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MSc3m.jpg" alt="picture of stepper motor with accelerometer tucked between motor and console" /></a></p>
<p>This graph sums up my findings pretty well:
<a href="https://i.stack.imgur.com/5OYRE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5OYRE.png" alt="graph comparing stealthchop, spreadcycle and the old A4988" /></a>
X-axis shows motor-speed in full steps per second, fsps. fsps corresponds to the frequency of the noises I want to conceal. 200 fsps = 1 revolution per second = 60 rpm. On Chiron Y-axis 60 rpm = 32 mm/s = F1920.</p>
<p>Y-axis is shown with the scale log10(accelerometer values).</p>
<p>Here are the TMC-settings I used during the tests, which are same/or close to what Marlin use for 24V Chiron:
(TPWMTHRS was set to 0 when I tested StealthChop)
<a href="https://i.stack.imgur.com/bclvk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bclvk.png" alt="enter image description here" /></a></p>
<p>What I read from this chart (and my many measurements):
TMC2209 is much quieter below 120 fsps.
StealthChop is fantastic at low speeds.
StealthChop shall ONLY be used at really low speeds in a 3D printer. If at all, since switching mode also is noisy.
SpreadCycle use 256 usteps/fstep. A4988 use 16 usteps/fstep. I think that is the reason for TMC to be more quiet at low speeds.</p>
<p><strong>What I do not understand:</strong>
Why is TMC2209 seems to be more loud at higher speeds. It might make different vibrations that my makeshift accelerometer rates worse, of course. But can I have a defective TMC2209? Or are the BigTreeTech boards bad? Or have I got fake TMC2209 with worse performance?</p>
|
<p>Have you tried a concrete tile for garden with foam below it?</p>
<p>Check <a href="https://www.cnckitchen.com/blog/reduce-your-3d-printing-noise-with-a-concrete-paver" rel="noreferrer">https://www.cnckitchen.com/blog/reduce-your-3d-printing-noise-with-a-concrete-paver</a></p>
<p>The same is on</p>
<p><div class="youtube-embed"><div>
<iframe width="640px" height="395px" src="https://www.youtube.com/embed/y08v6PY_7ak?start=0"></iframe>
</div></div></p>
<p>Frequencies at 200+ Hz should not get to the neighbours, the walls and floor will absorb them. Lower frequencies are transmitted much more (see the video).</p>
<p>Try that, it's super cheap, and if not enough let us know for further help.</p>
|
<p>I noticed that my TMC drivers make a loud KLANK sound when switching from stealthchop to spreadcycle. The solution is to keep the in stealthchop at all time by butting the threshold really high (I set mine to 1000 mm/s). You may also look for resonance in your frame. If you’re using Klipper, you can use input Shaper with an accelerometer to lower ringing, it will improve your print ans make your printer quieter at the same time.</p>
| 1,885
|
<p>I have this input text:</p>
<pre><code><html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"></head><body><table cellspacing="0" cellpadding="0" border="0" align="center" width="603"> <tbody><tr> <td><table cellspacing="0" cellpadding="0" border="0" width="603"> <tbody><tr> <td width="314"><img height="61" width="330" src="/Elearning_Platform/dp_templates/dp-template-images/awards-title.jpg" alt="" /></td> <td width="273"><img height="61" width="273" src="/Elearning_Platform/dp_templates/dp-template-images/awards.jpg" alt="" /></td> </tr> </tbody></table></td> </tr> <tr> <td><table cellspacing="0" cellpadding="0" border="0" align="center" width="603"> <tbody><tr> <td colspan="3"><img height="45" width="603" src="/Elearning_Platform/dp_templates/dp-template-images/top-bar.gif" alt="" /></td> </tr> <tr> <td background="/Elearning_Platform/dp_templates/dp-template-images/left-bar-bg.gif" width="12"><img height="1" width="12" src="/Elearning_Platform/dp_templates/dp-template-images/left-bar-bg.gif" alt="" /></td> <td width="580"><p>&nbsp;what y all heard?</p><p>i'm shark oysters.</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p></td> <td background="/Elearning_Platform/dp_templates/dp-template-images/right-bar-bg.gif" width="11"><img height="1" width="11" src="/Elearning_Platform/dp_templates/dp-template-images/right-bar-bg.gif" alt="" /></td> </tr> <tr> <td colspan="3"><img height="31" width="603" src="/Elearning_Platform/dp_templates/dp-template-images/bottom-bar.gif" alt="" /></td> </tr> </tbody></table></td> </tr> </tbody></table> <p>&nbsp;</p></body></html>
</code></pre>
<p>As you can see, there's no newline in this chunk of HTML text, and I need to look for all image links inside, copy them out to a directory, and change the line inside the text to something like <code>./images/file_name</code>. </p>
<p>Currently, the Perl code that I'm using looks like this:</p>
<pre><code>my ($old_src,$new_src,$folder_name);
foreach my $record (@readfile) {
## so the if else case for the url replacement block below will be correct
$old_src = "";
$new_src = "";
if ($record =~ /\<img(.+)/){
if($1=~/src=\"((\w|_|\\|-|\/|\.|:)+)\"/){
$old_src = $1;
my @tmp = split(/\/Elearning/,$old_src);
$new_src = "/media/www/vprimary/Elearning".$tmp[-1];
push (@images, $new_src);
$folder_name = "images";
}## end if
}
elsif($record =~ /background=\"(.+\.jpg)/){
$old_src = $1;
my @tmp = split(/\/Elearning/,$old_src);
$new_src = "/media/www/vprimary/Elearning".$tmp[-1];
push (@images, $new_src);
$folder_name = "images";
}
elsif($record=~/\<iframe(.+)/){
if($1=~/src=\"((\w|_|\\|\?|=|-|\/|\.|:)+)\"/){
$old_src = $1;
my @tmp = split(/\/Elearning/,$old_src);
$new_src = "/media/www/vprimary/Elearning".$tmp[-1];
## remove the ?rand behind the html file name
if($new_src=~/\?rand/){
my ($fname,$rand) = split(/\?/,$new_src);
$new_src = $fname;
my ($fname,$rand) = split(/\?/,$old_src);
$old_src = $fname."\\?".$rand;
}
print "old_src::$old_src\n"; ##s7test
print "new_src::$new_src\n\n"; ##s7test
push (@iframes, $new_src);
$folder_name = "iframes";
}## end if
}## end if
my $new_record = $record;
if($old_src && $new_src){
$new_record =~ s/$old_src/$new_src/ ;
print "new_record:$new_record\n"; ##s7test
my @tmp = split(/\//,$new_src);
$new_record =~ s/$new_src/\.\\$folder_name\\$tmp[-1]/;
## print "new_record2:$new_record\n\n"; ##s7test
}## end if
print WRITEFILE $new_record;
} # foreach
</code></pre>
<p>This is only sufficient to handle HTML text with newlines in them.
I thought only looping the regex statement,
but then i would have to change the matching line to some other text.</p>
<p>Do you have any idea if there an elegant Perl way to do this?
Or maybe I'm just too dumb to see the obvious way of doing it, plus I know putting global option doesn't work.</p>
<p>thanks.
~steve</p>
|
<p>There are excellent HTML parsers for Perl, learn to use them and stick with that. HTML is complex, allows > in attributes, heavily use nesting, etc. Using regexes to parse it, beyond very simple tasks (or machine generated code), is prone to problems.</p>
|
<p>I think you want my <a href="http://search.cpan.org/dist/HTML-SimpleLinkExtor" rel="nofollow noreferrer">HTML::SimpleLinkExtor</a> module:</p>
<pre>
use HTML::SimpleLinkExtor;
my $extor = HTML::SimpleLinkExtor->new;
$extor->parse_file( $file );
my @imgs = $extor->img;
</pre>
<p>I'm not sure what exactly you're trying to do, but it surely sounds like one of the HTML parsing modules should do the trick if mine doesn't.</p>
| 47,249
|
<p>I would like to do some integration testing of a web service from within NUnit or MBUnit. I haven't delved into this too deeply yet, but I am pretty sure I will need to spin up WebDev.WebServer.exe within the "unit test" to do this. (I know it's not really a unit test).</p>
<p>Yes, I can test the underlying objects the web service uses on their own (which I am), but what I am interested in testing in this cases is that the proxies are all working and handled as expected, etc. </p>
<p>Any advice?</p>
|
<p>I found <a href="http://haacked.com/archive/2006/12/12/using_webserver.webdev_for_unit_tests.aspx" rel="nofollow noreferrer">this post</a> and <a href="http://www.hanselman.com/blog/NUnitUnitTestingOfASPNETPagesBaseClassesControlsAndOtherWidgetryUsingCassiniASPNETWebMatrixVisualStudioWebDeveloper.aspx" rel="nofollow noreferrer">this one</a> which have some solutions on how to start up WebDev.WebServer.exe from within a unit test. Looks like I'll need to do something along these lines.</p>
<p>Until I get that going, I found that what works is to simply run the web service project within VS, let the WebDev server start up that way, and then run the unit tests. Not ideal, but it's OK for now.</p>
|
<p>Not sure what you're asking. If you're looking to do this without some sort of webserver in between your test and the service, you're going to be disappointed.</p>
<p>If that's not what you're asking... maybe some clarification?</p>
| 4,124
|
<p>I'm rewriting an old application and use this as a good opportunity to try out C# and .NET development (I usually do a lot of plug-in stuff in C).</p>
<p>The application is basically a timer collecting data. It has a start view with a button to start the measurement. During the measurement the app has five different views depending on what information the user wants to see.</p>
<p>What is the best practice to switch between the views?
From start to running?
Between the running views?</p>
<p>Ideas:</p>
<ul>
<li>Use one form and hide and show controls</li>
<li>Use one start form and then a form with a TabControl</li>
<li>Use six separate forms</li>
</ul>
|
<p>Creating a bunch of overlaid panels is a design-time nightmare.</p>
<p>I would suggest using a tab control with each "view" on a separate tab, and then picking the correct tab at runtime. You can avoid showing the tab headers by putting something like this in your form's Load event:</p>
<pre><code>tabControl1.Top = tabControl1.Top - tabControl1.ItemSize.Height;
tabControl1.Height = tabControl1.Height + tabControl1.ItemSize.Height;
tabControl1.Region = new Region(new RectangleF(tabPage1.Left, tabPage1.Top, tabPage1.Width, tabPage1.Height + tabControl1.ItemSize.Height));
</code></pre>
|
<p>I would also check out <a href="http://msdn.microsoft.com/en-us/library/cc707819.aspx" rel="nofollow noreferrer">Composite Application Guidance for WPF</a> or <a href="http://msdn.microsoft.com/en-us/library/aa480450.aspx" rel="nofollow noreferrer">Smart Client Software Factory</a> </p>
| 4,478
|
<p>Hello I am compiling a program with make but I get the error of No such file or directory but the file is in a directory of the path.</p>
<p>I have this #include "genetic.h", that file is in a directory called /home/myuser/toolbox/lib/genalg and in the PATH I have ...:/home/myuser/toolbox/lib/genalg, so I do not why make cannot find the library. Any ideas?. Thanks</p>
|
<p>Prior to python 2.2 there were essentially two different types of class: Those defined by C extensions and C coded builtins (types) and those defined by python class statements (classes). This led to problems when you wanted to mix python-types and builtin types. The most common reason for this is subclassing. If you wanted to subclass the list type in python code, you were out of luck, and so various workarounds were used instead, such as subclassing the pure python implementation of lists (in the UserList module) instead.</p>
<p>This was a fairly ugly, so in 2.2 there was a <a href="http://www.python.org/dev/peps/pep-0252/" rel="noreferrer">move</a> to unify python and builtin types, including the ability to <a href="http://www.python.org/dev/peps/pep-0253/" rel="noreferrer">inherit</a> from them. The result is "new style classes". These do have some incompatible differences to old-style classes however, so for backward compatability the bare class syntax creates an old-style class, while the new behaviour is obtained by inheriting from object. The most visible behaviour differences are:</p>
<ul>
<li><p>The method resolution order (MRO). There is a difference in behaviour in diamond-shaped inheritance hierarchies (where A inherits from both B and C, which both inherit from a common base class D. Previously, methods were looked up left-to right, depth first (ie A B D C D) However if C overloads a member of D, it won't be used by A (as it finds D's implementation first) This is bad for various styles of programming (eg. using mixin classes). New style classes will treat this situation as A B C D, (look at the <code>__mro__</code> attribute of a class to see the order it will search)</p></li>
<li><p>The <code>__new__</code> constructor is added, which allows the class to act as a factory method, rather than return a new instance of the class. Useful for returning particular subclasses, or reusing immutable objects rather than creating new ones without having to change the creation interface.</p></li>
<li><p><a href="https://docs.python.org/2/reference/datamodel.html#implementing-descriptors" rel="noreferrer">Descriptors</a>. These are the feature behind such things as properties, classmethods, staticmethods etc. Essentially, they provide a way to control what happens when you access or set a particular attribute on a (new style) class.</p></li>
</ul>
|
<p>Referring to <a href="https://mail.python.org/pipermail/python-dev/2014-August/135701.html" rel="nofollow noreferrer">this</a>
The object in class Foo(object) is meant to make your python 3 code compatible with python 2 and 3.</p>
| 43,040
|
<p>How can i build provisioning profile for deploying an iPhone application?</p>
|
<p>Agree with above, but here is a the gist of it.</p>
<ol>
<li>Register with Apple as an iPhone developer.</li>
<li>Give them 100 bucks to get your entrance into the club that can deploy apps onto phones.</li>
<li>Create your mobile provisioning in the <a href="https://developer.apple.com/ios/manage/overview/index.action" rel="nofollow noreferrer">Portal</a> you gain access to in 2.</li>
<li>Build your apps using this mobile provisioning, in various scenarios. (Development, AdHoc distribution, deployment.)</li>
</ol>
|
<p>Ensure that your iPhone is not jailbroken. The process described is a bit of a pain but it's a one-time thing.</p>
| 48,048
|
<p>Do you expect your WPF developers to know expression blend?</p>
<p>Any good resources for learning more about Blend?</p>
<p>[UPDATE] Does knowing blend make you more productive?</p>
|
<p>I found Blend a great way to ease into XAML. Many of the common things you want to do are easy in Blend, especially databinding. Databinding has no intellisense and I found doing things in Blend a great way of discovering how do write the databinding syntax.</p>
<p>I now find myself mostly editing raw XAML buy hand. </p>
<p>The areas where blend is really handy:</p>
<ul>
<li>Customizing templates. </li>
<li>Animation</li>
<li>Breaking the UI down into user controls</li>
</ul>
|
<p>Developers don't <strong>need</strong> to know Expression at all.</p>
<p>What you <strong>do</strong> need to know is XAML and not hide behind some tool, which would be the worst thing you could do as a WPF developer. Your tool of choice is yours to decide on. I used to use the XML editor in Visual Studio.</p>
<p>The only persons who <strong>need</strong> to know Blend are the ones in charge of the visual aspect of your WPF application. They have to be able to understand how to skin your application with templates, but other than that, they can keep to Blend exclusively.</p>
| 8,658
|
<p>I changed the filament (PLA) in my Wanhao Duplicator I3+. I ended the first try to print when I saw that the 'lines' were too thin. I re-sliced with a higher temperature (195°C instead of 190°C). Now the print started without a problem but after about 25% no more filament came out of the extruder. What can be the reason and how can I resolve it?</p>
<p>The filament is from Vertex, grey. The object that I use to test is a 20 mm hollow cube from Thingiverse that I have used for the previous filament too.</p>
<p>I am not sure that this is a clogging problem since the print starts with no problems. It just stopped after 25%. When I started another print I was able to finish by increasing the temperature. </p>
|
<p>I redid the print in order to reply to some questions posed in the answer of @kdtop. The print started but the output was not consistent and sometimes stopped. The temperature is 195°C and sometimes 'drop' to 194°C. First I pushed the new real so that the extruder did not need to pull so much. When this did not solve the problem I changed the temperature to 200°C. Now the output became consistent and my print finished. It was not as good as the one that I did with my previous filament. The top was not as neatly closed. Only the last 2 layers covered more or less for 100% the surface (perhaps 200°C is too high for this?).</p>
<p>For me the solution is to higher the temperature to 200°C (or perhaps 205°C).</p>
|
<p>My slicer (Cura-lulzbot) has a setting for initial printing temp, and then printing temp after the first few layers. Is it possible that your temp is initially OK, but then drops too low? Does your printer have a readout that shows the current temp? Is the temp still OK when it stops?</p>
<p>It sounds like you are printing a sample cube, so I assume not too large. Could you simulate this by just directly command your printer to extrude 500 mm of filament, or longer? Then see if it clogs. That would tell you if it was a physical problem with your printer instead of some change specified by the G-code for a sliced print. </p>
| 926
|
<p>I'm a relatively new Java programmer coming from C++/STL, and am looking for a class with these characteristics (which the C++ std::deque has, as I understand it):</p>
<ol>
<li>O(1) performance for insertion/removal at the beginning/end</li>
<li>O(1) performance for lookup by index</li>
<li>are growable collections (don't need fixed size bounds)</li>
</ol>
<p>Is there a Java equivalent to this? I found the Java 1.6 [ArrayDeque] class which has the insert/removal and growable characteristics, but don't seem to have lookup-by-index unless you call toArray() which would not be O(1).</p>
|
<p>Primitive Collections for Java has an ArrayDeque with a get(int idx) method.</p>
<p><a href="http://sourceforge.net/projects/pcj" rel="noreferrer">http://sourceforge.net/projects/pcj</a></p>
<p>I can't vouch for the quality of this project though.</p>
<p>An alternative would be to get the JDK ArrayDeque source and add the get(int idx) method yourself. Should be relatively easy.</p>
<p>EDIT: If you intend to use the deque in a highly multi-threaded manner, I would go the "patch the JDK's ArrayDeque" route. This implementation has been tested thoroughly and is used in the new java.util.concurrent ForkJoin framework.</p>
|
<p>My default approach would be to hack together my own class, with ArrayList as an underlying implementation (e.g. map my own class's indices to ArrayList indices)... but I hate reinventing the wheel especially when there's a good chance of screwing up...</p>
| 45,558
|
<p>Why does the following code sometimes causes an Exception with the contents "CLIPBRD_E_CANT_OPEN":</p>
<pre><code>Clipboard.SetText(str);
</code></pre>
<p>This usually occurs the first time the Clipboard is used in the application and not after that.</p>
|
<p>Actually, I think this is the <a href="https://cloudblogs.microsoft.com/enterprisemobility/2006/11/20/why-does-my-shared-clipboard-not-work-part-2/" rel="noreferrer">fault of the Win32 API</a>.</p>
<p>To set data in the clipboard, you have to <a href="http://msdn.microsoft.com/en-us/library/ms649048(VS.85).aspx" rel="noreferrer">open it</a> first. Only one process can have the clipboard open at a time. So, when you check, if another process has the clipboard open <em>for any reason</em>, your attempt to open it will fail.</p>
<p>It just so happens that Terminal Services keeps track of the clipboard, and on older versions of Windows (pre-Vista), you have to open the clipboard to see what's inside... which ends up blocking you. The only solution is to wait until Terminal Services closes the clipboard and try again.</p>
<p>It's important to realize that this is not specific to Terminal Services, though: it can happen with anything. Working with the clipboard in Win32 is a giant race condition. But, since by design you're only supposed to muck around with the clipboard in response to user input, this usually doesn't present a problem.</p>
|
<p>The difference between Cliboard.SetText and Cliboard.SetDataObject in WPF is that the text is not copied to the clipboard, only the pointer. I checked the source code. If we call SetDataObject(data, true) Clipoard.Flush() will also be called. Thanks to this, text or data is available even after closing the application. I think Windows applications only call Flush() when they are shutting down. Thanks to this, it saves memory and at the same time gives access to data without an active application.</p>
<p>Copy to clipboard:</p>
<pre><code>IDataObject CopyStringToClipboard(string s)
{
var dataObject = new DataObject(s);
Clipboard.SetDataObject(dataObject, false);
return dataObject;
}
</code></pre>
<p>Code when app or window is closed:</p>
<pre><code>try
{
if ((clipboardData != null) && Clipboard.IsCurrent(clipboardData))
Clipboard.Flush();
}
catch (COMException ex) {}
</code></pre>
<p>clipboardData is a window class field or static variable.</p>
| 9,423
|
<p>The C++ standard dictates that member variables inside a single access section must be layed out in memory in the same order they were declared in. At the same time, compilers are free to choose the mutual ordering of the access sections themselves. This freedom makes it impossible in theory to link binaries created by different compilers. So what are the remaining reasons for the strict in-section ordering? And does the <s>upcoming C++09</s> new C++11 standard provide a way to fully determine object layouts "by hand"?</p>
|
<blockquote>
<p>This freedom makes it impossible in theory to link binaries created by different compilers.</p>
</blockquote>
<p>It's impossible for a number of reasons, and structure layout is the most minor. vtables, implementations of <code>operator new</code> and <code>delete</code>, data type sizes...</p>
<blockquote>
<p>So what are the remaining reasons for the strict in-section ordering?</p>
</blockquote>
<p>C compatibility, I would have thought, so that a struct defined in C packs the same way it does in C++ <em>for a given compiler set</em>.</p>
<blockquote>
<p>And does the new C++<s>09</s>11 standard provide a way to fully determine object layouts "by hand"?</p>
</blockquote>
<p>No, no more than the current standard does.</p>
<p>For a <code>class</code> or <code>struct</code> with no vtable and entirely private (or public) fields, though, it's already possible if you use the <code>[u]int[8|16|32|64]_t</code> types. What use case do you have for more than this?</p>
|
<p>EDIT: I'm afraid i misunderstood your question</p>
<p>I think it's an optimization for memory access.
For example, if we got this structure:</p>
<pre><code>struct example
{
int16 intData;
byte byteData;
int32 intData;
byte intData;
int32 intData;
}
</code></pre>
<p>Let's suppose the word in this platform are 32 bits. Then you will need 4 complete words to pass all the data in the struct:</p>
<blockquote>
<p>int16 + byte = 24 bits (the netx field doesn't fit here)</p>
<p>int32 = 32 bits (the netx field doesn't fit here)</p>
<p>byte = 8 bits (the netx field doesn't fit here)</p>
<p>int32 = 32 bits</p>
</blockquote>
<p>But if you rearrange the fields to:</p>
<pre><code>struct example
{
int16 intData;
byte byteData;
byte intData;
int32 intData;
int32 intData;
}
</code></pre>
<p>then you can save one memory access.</p>
| 36,879
|
<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 >&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 >&5
/usr/bin/ld: cannot find -lcrypto
collect2: ld returned 1 exit status
configure:27748: $? = 1
</code></pre>
<p>--</p>
|
<ol>
<li>you don't have libcrypto.a and libcrypto.so on your system</li>
<li>you need to install install libcrypto, which is in the libssl-dev package (<code>aptitude install libssl-dev</code>)</li>
<li>Neon is the WebDAV library included in subversion; WebDAV being one of the wire protocols that subversion supports (http:). RSA is an encryption algorithm. Neon doesn't actually need it itself - it's just that configure uses it to determine whether libcrypto is available.</li>
</ol>
|
<p>NB: I'm using a <strong>shared host</strong> so I'm not able to do some things.</p>
<p>Calling </p>
<pre><code>apt-get install libssl-dev
</code></pre>
<p>gives me this error:</p>
<pre><code>E: Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)
E: Unable to lock the administration directory (/var/lib/dpkg/), are you root?
</code></pre>
<p>Calling
aptitude install libssl-dev</p>
<p>gives me this error: </p>
<pre><code>E: Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)
E: Unable to lock the administration directory (/var/lib/dpkg/), are you root
</code></pre>
<p>As you can perhaps see, I'm totally lost so any further hand-holding would be greatly appreciated! :)</p>
| 34,603
|
<p>I have the following dead simple elisp functions; the first removes the fill breaks from the current paragraph, and the second loops through the current document applying the first to each paragraph in turn, in effect removing all single line-breaks from the document. It runs fast on my low-spec Puppy Linux box using emacs 22.3 (10 seconds for 600 pages of Thomas Aquinas), but when I go to a powerful Windows XP machine with emacs 21.3, it takes almost an hour to do the same document. What can I do to make it run as well on the Windows machine with emacs 21.3?</p>
<pre><code>(defun remove-line-breaks ()
"Remove line endings in a paragraph."
(interactive)
(let ((fill-column 90002000))
(fill-paragraph nil)))
</code></pre>
<p>:</p>
<pre><code>(defun remove-all-line-breaks ()
"Remove all single line-breaks in a document"
(interactive)
(while (not (= (point) (buffer-end 1)))
(remove-line-breaks)
(next-line 1)))
</code></pre>
<p>Forgive my poor elisp; I'm having great fun learning Lisp and starting to use the power of emacs, but I'm new to it yet.</p>
|
<p>As the first try, you should download and install Emacs 22.3 for your Windows box and then compare the speed.</p>
<p>Speed difference shouldn't be that big after upgrade.</p>
|
<p>Perhaps it is the big value you assign to fill-column (they suggest less than 80).</p>
| 44,302
|
<p>Can anyone provide and example of downloading a PDF file using Watin? I tried the SaveAsDialogHandler but I couldn't figure it out. Perhaps a MemoryStream could be used?</p>
<p>Thanks,</p>
<p>--jb</p>
|
<p>This code will do the trick. The UsedialogOnce class can be found in the WatiN.UnitTests code and will be part of the WatiN 1.3 release (which will probably be released tonigh 14 october).</p>
<p>FileDownloadHandler fileDownloadHandler = new FileDownloadHandler(file.FullName);
using (new UseDialogOnce(ie.DialogWatcher, fileDownloadHandler))
{
ie.Button("exportPdfButtonId").ClickNoWait();</p>
<pre><code>fileDownloadHandler.WaitUntilFileDownloadDialogIsHandled(30);
fileDownloadHandler.WaitUntilDownloadCompleted(200);
</code></pre>
<p>}</p>
<p>HTH,
Jeroen van Menen
Lead developer WatiN</p>
|
<p>Take a look at this post:</p>
<p><a href="https://stackoverflow.com/questions/1191897/how-to-check-if-pdf-was-successfully-opened-in-the-browser-using-watin/1457215#1457215">How to check if PDF was successfully opened in the browser using WatiN?</a></p>
| 24,148
|
<p>For fun, I'm trying to write one of my son's favorite board games as a piece of software. Eventually I expect to build a WPF UI on top of it, but right now I'm building the machine that models the games and its rules.</p>
<p>As I do this, I keep seeing problems that I think are common to many board games, and perhaps others have already solved them better than I will. </p>
<p>(Note that AI to play the game, and patterns around high performance are not interesting to me.)</p>
<p>So far my patterns are:</p>
<ul>
<li><p>Several immutable types representing entities in the game box, e.g. dice, checkers, cards, a board, spaces on the board, money, etc.</p></li>
<li><p>An object for each player, which contains the players resources (e.g. money, score), their name, etc.</p></li>
<li><p>An object that represents the state of the game: the players, who's turn it is, the layout of the peices on the board, etc.</p></li>
<li><p>A state machine that manages the turn sequence. For example, many games have a small pre-game where each player rolls to see who goes first; that's the start state. When a player's turn starts, first they roll, then they move, then they have to dance in place, then other players guess what breed of chicken they are, then they receive points.</p></li>
</ul>
<p>Is there some prior art I can take advantage of?</p>
<p><strong>EDIT:</strong> One thing I realized recently is that game state can be split in to two categories:</p>
<ul>
<li><p><strong>Game artifact state</strong>. "I have $10" or "my left hand is on blue".</p></li>
<li><p><strong>Game sequence state</strong>. "I have rolled doubles twice; the next one puts me in jail". A state machine may make sense here.</p></li>
</ul>
<p><strong>EDIT:</strong> What I'm really looking for here is the <em>best</em> way to implement multiplayer turn-based games like Chess or Scrabble or Monopoly. I'm sure I could create such a game by just working through it start to finish, but, like other Design Patterns, there are probably some ways to make things go much more smoothly that aren't obvious without careful study. That's what I'm hoping for. </p>
|
<p>it seems this is a 2 month old thread that I've just noticed now, but what the heck. I've designed and developed the gameplay framework for a commercial, networked board game before. We had a very pleasant experience working with it.</p>
<p>Your game can probably be in a (close to) infinite amount of states because of the permutations of things like how much money player A has, how much money player B has, and etc... Therefore, I'm pretty sure you want to stay away from state machines.</p>
<p>The idea behind our framework was to represent the game state as structure with all the data fields that together, provide the complete game state (ie: if you wanted to save the game to disk, you write that structure out).</p>
<p>We used the <a href="http://en.wikipedia.org/wiki/Command_pattern" rel="noreferrer">Command Pattern</a> to represent all of the valid game actions a player could make. Here would be an example action:</p>
<pre><code>class RollDice : public Action
{
public:
RollDice(int player);
virtual void Apply(GameState& gameState) const; // Apply the action to the gamestate, modifying the gamestate
virtual bool IsLegal(const GameState& gameState) const; // Returns true if this is a legal action
};
</code></pre>
<p>So you see that to decide whether a move is valid, you can construct that action and then call its IsLegal function, passing in the current game state. If it is valid, and the player confirms the action, you can call the Apply function to actually modify the game state. By ensuring that your gameplay code can only modify the game state by creating and submitting legal Actions (so in other words, the Action::Apply family of methods are the only thing that directly modifies the game state), then you ensure that your game state will never be invalid. Furthermore, by using the command pattern, you make it possible to serialize your player's desired moves and send them over a network to be executed on other player's game states.</p>
<p>There ended up being one gotcha with this system that turned out to have a fairly elegant solution. Sometimes actions would have two or more phases. For example, the player may land on a property in Monopoly and must now make a new decision. What is the game state between when the player rolled the dice, and before they decide to purchase a property or not? We managed situations like this by featuring an "Action Context" member of our game state. The action context would normally be null, indicating that the game is not currently in any special state. When the player rolls the dice and the dice rolling action is applied to the game state, it will realize that the player has landed on an un-owned property, and can create a new "PlayerDecideToPurchaseProperty" action context that contains the index of the player we are waiting for a decision from. By the time the RollDice action has completed, our game state represents that it is currently waiting for the specified player to decide whether to buy a property is not. It is now easy for all other actions' IsLegal method to return false, except for the "BuyProperty" and "PassPropertyPurchaseOpportunity" actions, which are only legal when the game state has the "PlayerDecideToPurchaseProperty" action context.</p>
<p>Through the use of action contexts, there is never a single point in the life-time of the board game where the game state structure does not completely represent EXACTLY what is happening in the game at that point in time. This is a very desirable property of your board game system. It will it much easier for you to write code when you can find everything you ever want to know about what's happening in the game by examining only one structure.</p>
<p>Furthermore, it extends very nicely to networked environments, where clients can submit their actions over a network to a host machine, which can apply the action to the host's "official" game state, and then echo that action back to all the other clients to have them apply it to their replicated game states.</p>
<p>I hope this was concise and helpful.</p>
|
<p><a href="http://www.threerings.com/code/" rel="nofollow noreferrer">Three Rings</a> offers LGPL'd Java libraries. Nenya and Vilya are the libraries for game related stuff.</p>
<p>Of course, it would help if your question mentioned platform and/or language restrictions you might have.</p>
| 47,113
|
<p>Most of the MVC samples I have seen pass an instance of the view to the controller like this</p>
<pre><code>public class View
{
Controller controller = new Controller(this);
}
</code></pre>
<p>Is there any advantage to passing a class which provides access to just the the properties and events the controller is interested in, like this:</p>
<pre><code>public class UIWrapper
{
private TextBox textBox;
public TextBox TextBox
{
get {return textBox;}
}
public UIWrapper(ref TextBox textBox)
{
this.textBox = textBox;
}
public class View
{
UIWrapper wrapper = new UIWrapper(this);
Controller controller = new Controller(wrapper)
}
</code></pre>
|
<p>My advice is to use the cached framework regardless of your user-base. The fact is, you won't be alone in doing so and it will only be a matter of time before it pays off (even if it is on return visits).</p>
|
<p>This is probably not the solution you want, but just to help you with the log parsing, you can use this to get counts for each from the logs (assuming you're on a linux server) :</p>
<pre><code>grep -c \.swz web_log_dir/*
grep -c \.swf web_log_dir/*
</code></pre>
| 11,405
|
<p>I am fairly new to programming and while doing a lot of reading this concept of a lambda keeps coming up but I'm having a hard time putting my finger on what it actually is and how implementing it will make my programming life so much better. So first, what is a lambda and second how might it be implemented?</p>
<p>Thanks to all who posted. As has been mentioned in the comments, this is a duplicate, but there are so many great answers here I want to preserve them for the community so I'm turning it into a community post. Here is the link to the other question:</p>
<p><a href="https://stackoverflow.com/questions/16501/what-is-a-lambda-function">What is a lambda (function)?</a></p>
|
<p>Lambda are hard to catch, but once you have pictured them, you cannot understand why you didn't get it before.</p>
<h2>Lamdba are anonymous functions</h2>
<p>Lambda are ordinary functions, <strong>the only difference is that you don't give them a name.</strong></p>
<p>To understand that, you must know first that when you create a function, the code is stored in memory at an address only knowned by the computer.</p>
<p>So when you do something like that :</p>
<pre><code>function Foo ()
{
/* your code here */
}
</code></pre>
<p>What you really do is binding the name "Foo" to the adress of the code in memory.</p>
<p>Now, there is an other way to access an address : <strong>references</strong> (and pointers, but let's skip this nasty guys)</p>
<p>Well, a lambda function is a function that have no name, so it can be only access with its reference.</p>
<h2>How do you use them ?</h2>
<p>When you create a lambda function, <em>you usually plan to use it only once.</em> </p>
<p>The step by step process is usually :</p>
<ol>
<li>Create the function</li>
<li>Get the reference</li>
<li>Pass the reference somewhere it will be used</li>
</ol>
<p>Finally, the reference is lost, and so the function is destroyed automatically.</p>
<p>The typical use case is a callback function. You declare, create and pass the function in one row, so it's handy.</p>
<h2>Example from the real word</h2>
<p>In Python, you can use lambda in list comprehensions :</p>
<pre><code>/* create a list of functions */
function_list = [(lambda x : number_to_add + x) for number_to_add in range(0, 10) ]
</code></pre>
<p>In Javascript, you usually pass a function to others functions. Example with JQuery :</p>
<pre><code> $("img").each(
/* here we pass a function without any name to the "each()" method */
function(i){ his.src = "test" i ".jpg"; }
);
</code></pre>
<h2>The things you'd better know</h2>
<ul>
<li><p>Some languages, like Javascript or Lisp, make a massive use of
lambdas. It can be for cultural reason, but the functional programming paradigm tends to lead to lambda-mania.</p></li>
<li><p>Long lambdas make the code hard to read. That's why some languages restrain the possibilities of lambdas, such as Python that does not allow "if" statement in them.</p></li>
<li><p>Lambdas are just normal functions. Where ever you use one, you can use an ordinary function instead. It's just a matter of coding style.</p></li>
</ul>
|
<p>Lambda is <a href="http://en.wikipedia.org/wiki/Lambda_calculus" rel="nofollow noreferrer">lambda calculus</a>, but I think people use it with the term <a href="http://en.wikipedia.org/wiki/Closure_%28computer_science%29" rel="nofollow noreferrer">closure</a> interchangeably. See <a href="https://stackoverflow.com/questions/36636/what-is-a-closure">What is a Closure?</a></p>
<p>Ruby's implementation is easy to understand and very powerful. In the following code <code>times</code> method accepts a block of code between the curly braces and calls it back <code>HEIGHT</code> times. You can define similar method that accepts a block of code and implement looping construct-ish things.</p>
<pre><code>@cells = []
HEIGHT.times { @cells << empty_row }
</code></pre>
<p>I guess it's more interesting if there's a parameter.</p>
<pre><code>5.times { |i| puts i, " " }
</code></pre>
| 48,883
|
<p>Some ways to iterate through the characters of a string in Java are:</p>
<ol>
<li>Using <code>StringTokenizer</code>?</li>
<li>Converting the <code>String</code> to a <code>char[]</code> and iterating over that.</li>
</ol>
<p>What is the easiest/best/most correct way to iterate?</p>
|
<p>I use a for loop to iterate the string and use <code>charAt()</code> to get each character to examine it. Since the String is implemented with an array, the <code>charAt()</code> method is a constant time operation.</p>
<pre><code>String s = "...stuff...";
for (int i = 0; i < s.length(); i++){
char c = s.charAt(i);
//Process char
}
</code></pre>
<p>That's what I would do. It seems the easiest to me.</p>
<p>As far as correctness goes, I don't believe that exists here. It is all based on your personal style.</p>
|
<p>See <a href="http://java.sun.com/docs/books/tutorial/java/data/strings.html" rel="nofollow noreferrer">The Java Tutorials: Strings</a>.</p>
<pre><code>public class StringDemo {
public static void main(String[] args) {
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
char[] tempCharArray = new char[len];
char[] charArray = new char[len];
// put original string in an array of chars
for (int i = 0; i < len; i++) {
tempCharArray[i] = palindrome.charAt(i);
}
// reverse array of chars
for (int j = 0; j < len; j++) {
charArray[j] = tempCharArray[len - 1 - j];
}
String reversePalindrome = new String(charArray);
System.out.println(reversePalindrome);
}
}
</code></pre>
<p>Put the length into <code>int len</code> and use <code>for</code> loop.</p>
| 23,918
|
<p>How does one convert an image from one color profile to another (screen to printer, or scanner to screen). In Visual C++ you would use the function in ICM.h, is there a managed way to do this with GDI+?</p>
<p>I need to use GDI+, not WPF. I'd prefer to have a managed solution, but if it is not available, I guess PInkvoke will have to suffice.</p>
|
<p>There are a number of solutions.</p>
<ol>
<li>For GDI+, <a href="https://web.archive.org/web/20090224151626/http://support.microsoft.com/kb/317825/" rel="nofollow noreferrer">check out this article at MSDN</a> (HOW TO: Use GDI+ and Image Color Management to Adjust Image Colors).</li>
<li>For WPF (.NET 3.0), see the <a href="http://msdn.microsoft.com/en-us/library/system.windows.media.color.colorcontext(VS.85).aspx" rel="nofollow noreferrer">System.Windows.Media</a> namespace. There are a number of different classes, such as the <a href="http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapencoder.aspx" rel="nofollow noreferrer">BitmapEncoder</a>, that have the concept of a <a href="http://msdn.microsoft.com/en-us/library/system.windows.media.colorcontext.aspx" rel="nofollow noreferrer">ColorContext</a>, which "Represents the International Color Consortium (ICC) or Image Color Management (ICM) color profile that is associated with a bitmap image."</li>
</ol>
<p>Both of these seem pretty complex, so there's always the option of buying somebody else's code. Atalasoft's <a href="http://www.atalasoft.com/products/dotimage/photopro/default.aspx" rel="nofollow noreferrer">DotImage Photo Pro</a> has ICC profile setting capabilities built in. The code is expensive; a dev license is almost 2k. But based on their participation in the dotnet community, I'd give them a whirl.</p>
|
<p>You should take a look at <a href="http://www.littlecms.com/" rel="nofollow noreferrer">Lcms</a>. Its a colour management system, fairly complete, but written in C. you can use pinvoke, but I would recommend Managed C++ wrapper. I am actually currently working on a managed wrapper around the engine (just the basics, colour profile conversion, lab readings). I can post a link to the code after i am complete. It may be a week or so though.</p>
| 5,918
|
<p>The <a href="http://doi.org/" rel="noreferrer">DOI</a> system places basically no useful limitations on what constitutes <a href="http://doi.org/handbook_2000/enumeration.html#2.2" rel="noreferrer">a reasonable identifier</a>. However, being able to pull DOIs out of PDFs, web pages, etc. is quite useful for citation information, etc.</p>
<p>Is there a reliable way to identify a DOI in a block of text without assuming the 'doi:' prefix? (any language acceptable, regexes preferred, and avoiding false positives a must)</p>
|
<p>Ok, I'm currently extracting thousands of DOIs from free form text (XML) and I realized that <a href="https://stackoverflow.com/a/10300246/89771">my previous approach</a> had a few problems, namely regarding encoded entities and trailing punctuation, so I went on reading <a href="http://www.doi.org/doi_handbook/2_Numbering.html" rel="nofollow noreferrer">the specification</a> and this is the best I could come with.</p>
<hr />
<blockquote>
<p>The DOI prefix shall be composed of a directory indicator followed by
a registrant code. These two components shall be separated by a full
stop (period).</p>
<p>The directory indicator shall be "10". The directory indicator
distinguishes the entire set of character strings (prefix and suffix)
as digital object identifiers within the resolution system.</p>
</blockquote>
<p>Easy enough, the initial <code>\b</code> prevents us from "matching" a "DOI" that doesn't start with <code>10.</code>:</p>
<pre><code>$pattern = '\b(10[.]';
</code></pre>
<hr />
<blockquote>
<p>The second element of the DOI prefix shall be the registrant code. The
registrant code is a unique string assigned to a registrant.</p>
</blockquote>
<p>Also, all assigned registrant code are numeric, and at least 4 digits long, so:</p>
<pre><code>$pattern = '\b(10[.][0-9]{4,}';
</code></pre>
<hr />
<blockquote>
<p>The registrant code may be further divided into sub-elements for
administrative convenience if desired. Each sub-element of the
registrant code shall be preceded by a full stop.</p>
</blockquote>
<p><code>$pattern = '\b(10[.][0-9]{4,}(?:[.][0-9]+)*';</code></p>
<hr />
<blockquote>
<p>The DOI syntax shall be made up of a DOI prefix and a DOI suffix
separated by a forward slash.</p>
</blockquote>
<p>However, this isn't absolutely necessary, section 2.2.3 states that uncommon suffix systems may use other conventions (such as <code>10.1000.123456</code> instead of <code>10.1000/123456</code>), but lets cut some slack.</p>
<p><code>$pattern = '\b(10[.][0-9]{4,}(?:[.][0-9]+)*/';</code></p>
<hr />
<blockquote>
<p>The DOI name is case-insensitive and can incorporate any printable
characters from the legal graphic characters of Unicode. The DOI
suffix shall consist of a character string of any length chosen by the
registrant. Each suffix shall be unique to the prefix element that
precedes it. The unique suffix can be a sequential number, or it might
incorporate an identifier generated from or based on another system.</p>
</blockquote>
<p>Now this is where it gets trickier, from all the DOIs I have processed, I saw the following characters (besides <code>[0-9a-zA-Z]</code> of course) in their <strong>suffixes</strong>: <code>.-()/:-</code> -- so, while it doesn't exist, the DOI <code>10.1016.12.31/nature.S0735-1097(98)2000/12/31/34:7-7</code> is completely plausible.</p>
<p>The logical choice would be to use <code>\S</code> or the <code>[[:graph:]]</code> PCRE POSIX class, so lets do that:</p>
<p><code>$pattern = '\b(10[.][0-9]{4,}(?:[.][0-9]+)*/\S+'; // or</code></p>
<p><code>$pattern = '\b(10[.][0-9]{4,}(?:[.][0-9]+)*/[[:graph:]]+';</code></p>
<hr />
<p>Now we have a difficult problem, the <code>[[:graph:]]</code> class is a super-set of the <code>[[:punct:]]</code> class, which includes characters easily found in free text or any markup language: <code>"'&<></code> among others.</p>
<p>Lets just filter the markup ones for now using a negative lookahead:</p>
<p><code>$pattern = '\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\'<>])\S)+'; // or</code></p>
<p><code>$pattern = '\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\'<>])[[:graph:]])+';</code></p>
<hr />
<p>The above should cover encoded entities (<code>&</code>), attribute quotes (<code>["']</code>) and open / close tags (<code>[<>]</code>).</p>
<p>Unlike markup languages, free text usually doesn't employ punctuation characters unless they are bounded by at least one space <em><strong>or</strong></em> placed at the end of a sentence, for instance:</p>
<blockquote>
<p>This is a long DOI:
<code>10.1016.12.31/nature.S0735-1097(98)2000/12/31/34:7-7</code><strong>!!!</strong></p>
</blockquote>
<p>The solution here is to close our capture group and assert another word boundary:</p>
<p><code>$pattern = '\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\'<>])\S)+)\b'; // or</code></p>
<p><code>$pattern = '\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\'<>])[[:graph:]])+)\b';</code></p>
<p>And <em>voilá</em>, <a href="http://regexpal.com/?flags=g&regex=%5Cb(10%5B.%5D%5B0-9%5D%7B4%2C%7D(%3F%3A%5B.%5D%5B0-9%5D%2B)*%2F(%3F%3A(%3F!%5B%22%26%5C%27%3C%3E%5D)%5CS)%2B)%5Cb&input=This%20is%20a%20short%20DOI%3A%2010.1000%2F123456.%0AThis%20is%20NOT%20a%20DOI%3A%204210.1000%2F123456.%0AThis%20is%20a%20long%20DOI%3A%2010.1016.12.31%2Fnature.S0735-1097(98)2000%2F12%2F31%2F34%3A7-7!!!%0A%0A10.1007%2F978-3-642-28108-2_19%0A10.1007.10%2F978-3-642-28108-2_19%20(fictitious%20example%2C%20see%20%40Ju9OR%20comment)%0A10.1016%2FS0735-1097(98)00347-7%0A10.1579%2F0044-7447(2006)35%5C%5B89%3ARDUICP%5C%5D2.0.CO%3B2%0A%0AAlso%2C%20correctly%20discards%20some%20falsy%20(X%7CHT)ML%20stuff%20like%3A%0A%0A%3Cgeo%20coords%3D%2210.4515260%2C51.1656910%22%3E%3C%2Fgeo%3E" rel="nofollow noreferrer">here is a demo</a>.</p>
|
<p>The following regex should do the job (Perl regex syntax):</p>
<pre><code>/(10\.\d+\/\d+)/
</code></pre>
<p>You could do some additional sanity checking by opening the urls</p>
<pre><code>http://hdl.handle.net/<doi>
</code></pre>
<p>and</p>
<pre><code>http://dx.doi.org/<doi>
</code></pre>
<p>where is the candidate doi,</p>
<p>and testing that you a) get a 200 OK http status, and b) the returned page is not the "DOI not found" page for the service.</p>
| 4,757
|
<p>I have the following regular expression :
I figured out most of the part which is as follows :</p>
<pre>
ValidationExpression="^[\u0020\u0027\u002C\u002D\u0030-\u0039\u0041-\u005A\u005F\u0061-\u007A\u00C0-\u00FF°./]{1,256}$"
u0020 : SPACE
u0027 : APOSTROPHE
u002C : COMMA
u002D : HYPHEN / MINUS
u0030-\u0039\ : 0-9
u0041-\u005A : A - Z
u005F : UNDERSCORE
u0061-\u007A\ : a - z
u00C0-\u00FF°./ : ??
</pre>
<p>Need help in understanding the final part of the validation expression : </p>
<pre>u00C0-\u00FF°./</pre>
<p>Anyone has any idea what does this mean?</p>
|
<p>weird... according to the character map on Windows I'd say "À to ÿ"</p>
<p>Those are some variations (accents, cedillas) on A, C, E, I, D, N, O, U, Y, the german Sharp s, ...</p>
|
<p>It looks to be the range of characters presented in the last 2 columns in TABLE ASCII-II at the following link to <a href="http://www.cdrummond.qc.ca/cegep/informat/Professeurs/Alain/files/ascii.htm" rel="nofollow noreferrer">The Extended ASCII Chart</a></p>
| 22,779
|
<p>I type </p>
<pre><code>ArrayList memberNames = new ArrayList() { "Jim", "John", "George" };
</code></pre>
<p>and Visual Studio tells me "ArrayList" cannot be found so I have to manually go to the top of the file and type</p>
<pre><code>using System.Collections;
</code></pre>
<p>Is there a way to get Visual Studio to do this automatically?</p>
<p>In FlashDevelop, for instance, you press CTRL-SHIFT-1 and it automatically generates these missing references, a nice feature.</p>
|
<p>SHIFT-ALT-F10 Will activate the Smart Tag on the class, which will give you the options "using System.Collections", and "System.Collections.ArrayList". It's typically two keystrokes to add a using.</p>
<p>Edit: Seems I had a mangled keyboard profile. Updated the key combo to the default. Thanks to Alan for pointing it out.</p>
|
<p><strong>CTRL+.</strong> also activates the Smart Tag, which might be more intuitive.</p>
| 37,282
|
<p>I've been tasked with the the maintenance of a nonprofit website that recently fell victim to a SQL injection attack. Someone exploited a form on the site to add text to every available text-like field in the database (varchar, nvarchar, etc.) which, when rendered as HTML, includes and executes a JavaScript file. </p>
<p>A Google search of the URL indicates that it's from email spammers based out of Romania or China, but that's not what's important right now.</p>
<p>I went through and manually removed the information from the the text fields that render on most visible and popular pages on the site but I'm curious as to what would be the best programmatic way of removing the text from the other text fields on the site. </p>
<p>Obviously there's more that needs to be done (hardening the site against SQL injections, using something like markdown instead of storing HTML, etc.) and I am working on those but for the time being what I really need is a good way to go in and programmatically remove the injected text. I know what the exact text is, it's the same every time, and it's always appended to the end of any text field. I can't afford to strip out all HTML in the database at this time and I don't know when this happened exactly so I can't just roll back to a backup. Also, the site is on shared hosting and I cannot connect to the database directly with SQL Server tools. I can execute queries against it though, so if there's any way of constructing a SQL update statement to the effect of "hey find all the text fields in all of the tables in the entire database and do this to clean them" that would be the best. </p>
|
<p>Restore the data from a recent backup.</p>
|
<p>This will reverse that, also it would be wise to take sysobject permissions away from the username your site runs with, and to sanitize input of course</p>
<pre><code>DECLARE @T VARCHAR(255),@C VARCHAR(4000)
DECLARE Table_Cursor CURSOR FOR
SELECT a.name,b.name FROM sysobjects a,syscolumns b WHERE a.id=b.id and a.xtype='u' and
(b.xtype=99 or b.xtype=35 or b.xtype=231 or b.xtype=167)
OPEN Table_Cursor
FETCH NEXT FROM Table_Cursor INTO @T,@C
WHILE(@@FETCH_STATUS=0)
BEGIN
EXEC('if exists (select 1 from ['+@T+'] where ['+@C+'] like ''%"></title><script src="http://1.verynx.cn/w.js"></script><!--'') begin print ''update ['+@T+'] set ['+@C+']=replace(['+@C+'],''''"></title><script src="http://1.verynx.cn/w.js"></script><!--'''','''''''') where ['+@C+'] like ''''%"></title><script src="http://1.verynx.cn/w.js"></script><!--'''''' end')
FETCH NEXT FROM Table_Cursor INTO @T,@C
END
CLOSE Table_Cursor
DEALLOCATE Table_Cursor
</code></pre>
<p>I wrote about this a while back here: <a href="http://blogs.lessthandot.com/index.php/WebDev/WebDesignGraphicsStyling/microsoft-has-released-tools-to-address-" rel="nofollow noreferrer">Microsoft Has Released Tools To Address SQL Injection Attacks</a></p>
| 5,234
|
<p>I have been working on a legacy C++ application and am definitely outside of my comfort-zone (a good thing). I was wondering if anyone out there would be so kind as to give me a few pointers (pun intended).</p>
<p>I need to cast 2 bytes in an unsigned char array to an unsigned short. The bytes are consecutive. </p>
<p>For an example of what I am trying to do:</p>
<p>I receive a string from a socket and place it in an unsigned char array. I can ignore the first byte and then the next 2 bytes should be converted to an unsigned char. This will be on windows only so there are no Big/Little Endian issues (that I am aware of).</p>
<p>Here is what I have now (not working obviously):</p>
<pre><code>//packetBuffer is an unsigned char array containing the string "123456789" for testing
//I need to convert bytes 2 and 3 into the short, 2 being the most significant byte
//so I would expect to get 515 (2*256 + 3) instead all the code I have tried gives me
//either errors or 2 (only converting one byte
unsigned short myShort;
myShort = static_cast<unsigned_short>(packetBuffer[1])
</code></pre>
|
<p>Well, you are widening the char into a short value. What you want is to interpret two bytes as an short. <code>static_cast</code> cannot cast from <code>unsigned char*</code> to <code>unsigned short*</code>. You have to cast to <code>void*</code>, then to <code>unsigned short*</code>:</p>
<pre><code>unsigned short *p = static_cast<unsigned short*>(static_cast<void*>(&packetBuffer[1]));
</code></pre>
<p>Now, you can dereference p and get the short value. But the problem with this approach is that you cast from unsigned char*, to void* and then to some different type. The Standard doesn't guarantee the address remains the same (and in addition, dereferencing that pointer would be undefined behavior). A better approach is to use bit-shifting, which will always work:</p>
<pre><code>unsigned short p = (packetBuffer[1] << 8) | packetBuffer[2];
</code></pre>
|
<p>Did nobody see the input was a string!</p>
<pre><code>/* If it is a string as explicitly stated in the question.
*/
int byte1 = packetBuffer[1] - '0'; // convert 1st byte from char to number.
int byte2 = packetBuffer[2] - '0';
unsigned short result = (byte1 * 256) + byte2;
/* Alternatively if is an array of bytes.
*/
int byte1 = packetBuffer[1];
int byte2 = packetBuffer[2];
unsigned short result = (byte1 * 256) + byte2;
</code></pre>
<p>This also avoids the problems with alignment that most of the other solutions may have on certain platforms. Note A short is at least two bytes. Most systems will give you a memory error if you try and de-reference a short pointer that is not 2 byte aligned (or whatever the sizeof(short) on your system is)!</p>
| 38,576
|
<p>I want to recreate the stickiness and snapping of windows, like it is implemented in Winamp.</p>
<p>The basic premise is, when you drag a window and it comes close to another one, it will snap to it and will stick. When you move it the two will move together.</p>
<p>I need it for a MDI application.</p>
|
<p>You could read this article and try to adopt it for your program:</p>
<p><a href="http://www.codeproject.com/KB/cs/stickywindows.aspx" rel="nofollow noreferrer">Sticky Windows - How to make your (top-level) forms to stick one to the other or to the screen</a></p>
<p>The class presented in the article inherits from <em>System.Windows.Forms.NativeWindow</em>, thus no inheritance is required in order to make your class "Stick-able".</p>
|
<p>Check out this one:</p>
<p><a href="http://www.codeproject.com/KB/cs/eugsnapformextender.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/cs/eugsnapformextender.aspx</a></p>
| 13,579
|
<p>I want to output the function name each time it is called, I can easily copy and paste the function name, however I wondered if there was a shortcut that would do the job for me?</p>
<p>At the moment I am doing:</p>
<pre><code>SlideInfoHeader* lynxThreeFile::readSlideInfoHeader(QDataStream & in)
{
qDebug("lynxThreeFile::readSlideInfoHeader");
}
</code></pre>
<p>but what I want is something generic:</p>
<pre><code>SlideInfoHeader* lynxThreeFile::readSlideInfoHeader(QDataStream & in)
{
qDebug(this.className() + "::" + this.functionName());
}
</code></pre>
|
<p>"<code>__FUNCTION__</code>" is supported by both MSVC and GCC and should give you the information you need. </p>
|
<p>If you check out boost there is a macro BOOST_CURRENT_FUNCTION that is portable across platforms. In the C99 standard there is a compiler variable <code>__func__</code> that has the desired effect. I believe has been accepted into the C++0x standard. A reasonable number of compilers will already support this.</p>
| 20,946
|
<p>I have a checkstyle suppression filter setup (e.g. ignore magic numbers in unit test code).</p>
<p>The suppression xml file resides in the same folder as the checkstyle xml file. However, where this file actually is varies:
on my windows dev box it is in d:\dev\shared\checkstyle\config
on the Linux CI server it will be in /root/repo/shared/checkstyle/config
on another developers box it could be anywhere (they check out their svn repo to).</p>
<p>The only "consistent" thing is that the suppression file is always in the same folder as the checkstyle xml file.
I cannot work out how to ensure that this file is always consistently picked up. Also I don't know why checkstyle does not support embedded suppression within the checkstyle xml file.</p>
<p>any help?</p>
|
<p>I had this same problem with the Checkstyle suppression configuration when I was going back and forth between Linux and Windows. Here's how I solved it in my Ant-based build system:</p>
<p>Basically, I inject the proper, platform-specific directory value into the main Checkstyle configuration file by configuring a Checkstyle properties file with an Ant build script.</p>
<p>My main Checkstyle configuration file has a <code>SuppressionFilter</code> module declaration as shown below. The value of the <code>checkstyle-suppressions-file</code> property comes from a Checkstyle properties file:</p>
<pre><code><module name="SuppressionFilter">
<property name="file" value="${checkstyle-suppressions-file}"/>
</module>
</code></pre>
<p>The Checkstyle properties file is not static, it is generated by an Ant build script from a properties file template called <code>template-checkstyle.properties</code>. Here's what the template looks like for the suppressions file property:</p>
<pre><code>checkstyle-suppressions-file=@SCM_DIR@/checkstyle_suppressions.xml
</code></pre>
<p>My Ant build script copies this file to a file named <code>checkstyle.properties</code>. The copy has the special token replaced with the proper value of the directory in which the suppressions file is found:</p>
<pre><code><copy file="${scm.dir}/template-checkstyle.properties" tofile="${scm.dir}/checkstyle.properties">
<filterset>
<filter token="SCM_DIR" value="${scm.dir.unix}"/>
</filterset>
</copy>
</code></pre>
<p>Now, where does the value of <code>scm.dir.unix</code> come from? Well, it's <em>derived</em> from a property of my build, read on. You'll need to specify such a value with the directory values that you mentioned.</p>
<p>Note that there is one slightly non-obvious issue concerning the way in which you specify this directory. I say that the <code>scm.dir.unix</code> value is derived from a build property because I observed that the main Checkstyle configuration file cannot contain backslashes, i.e. Windows path separator characters, in the value of the <code>file</code> property of the <code>SuppressionFilter</code> module. For example, specifying something like <code>C:\foo\bar\baz</code> leads to a Checkstyle error message saying that <code>C:foobarbaz</code> cannot be found. I work around this by "converting" the <code>scm.dir</code> directory build property to a "unix" format with Ant's <code>pathconvert</code> task:</p>
<pre><code><pathconvert targetos="unix" property="scm.dir.unix">
<path location="${scm.dir}"/>
</pathconvert>
</code></pre>
<p>Then I call the <code>checkstyle</code> Ant task like this:</p>
<pre><code><checkstyle config="${scm.dir}/checkstyle_checks.xml"
properties="${scm.dir}/checkstyle.properties">
<!-- details elided -->
</checkstyle>
</code></pre>
<p>The call to the <code>checkstyle</code> task injects the key/value pairs contained in the <code>checkstyle.properties</code> file into the main Checkstyle configuration.</p>
<p>If you like, you can see the full scripts <a href="http://virtualteamtls.svn.sourceforge.net/viewvc/virtualteamtls/trunk/scm/" rel="noreferrer">here</a></p>
<p>Hope this helps</p>
|
<p>Since CheckStyle 4.26.0 you can use predefined constants in your config files.</p>
<p>(<a href="https://github.com/jshiell/checkstyle-idea/issues/217" rel="nofollow noreferrer">https://github.com/jshiell/checkstyle-idea/issues/217</a>) : </p>
<blockquote>
<ul>
<li>${basedir} & ${project_loc} - gets mapped to the current project directory</li>
<li>${workspace_loc} - gets mapped to the current Eclipse workspace directory</li>
<li>${config_loc} & ${samedir} - get mapped to the directory the configuration file lies in</li>
</ul>
</blockquote>
<p>If you want to share the config with maven you will need to "alias" the "eclipse constants" in your POM configuration (in the reporting section) using the "propertyExpansion" configuration element : </p>
<pre><code><plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<configLocation>${project.basedir}/quality/checkstyle/dap_checkstyle_checks.xml</configLocation>
<propertyExpansion>basedir=${project.basedir}</propertyExpansion>
</configuration>
<reportSets>
<reportSet>
<reports>
<report>checkstyle</report>
</reports>
</reportSet>
</reportSets>
</plugin>
</code></pre>
<p>The "propertyExpansion" is inspired from : <a href="https://github.com/checkstyle/checkstyle/blob/master/pom.xml#L582" rel="nofollow noreferrer">https://github.com/checkstyle/checkstyle/blob/master/pom.xml#L582</a>.</p>
| 24,144
|
<p>Recently when I looked into iPhone memory management, I tried to compare the convenience method and init method on the same object. For example, I have UIImageView where it displays a downloaded NSData:</p>
<p>Convenience method:</p>
<pre><code>imageView.image = [UIImage imageWithData:[downloads dataAtIndex:0]];
</code></pre>
<p>init method:</p>
<pre><code>UIImage *aImage = [[UIImage alloc] initWithData:[downloads dataAtIndex:0]];
imageView.image = aImage;
[aImage release];
</code></pre>
<p>When I try to go back and forth on the views to increase the memory usage and hit "Simulate Memory Warning", the memory usage for the app went from 20MB to 18MB with convenience method, and init method went from 20MB to 13MB immediately.</p>
<p>I also waited and interacted with the app to give time on releasing on the convenience method's autorelease. But it didn't drop much.</p>
<p>Other than the autorelease vs release, what else contributed the difference?</p>
|
<p>Your autoreleased objects created by the convenience methods will not be released until the containing autorelease pool is drained. It is advisable to wrap memory intensive operations inside of an <code>NSAutoreleasePool</code> block if you will be making heavy use of them.</p>
|
<p>The only difference that could be causing this is that imageWithData: doesn't use the system image cache, while initWithData: does. So maybe the image that's made with the initializer can release it's image data when it receives a memory warning since it can go back to the system cache, while the one that's created by the convenience method can't.</p>
| 36,883
|
<p>Recently developers highlighted that it is bit hard for them to keep track of which document has been updated. And they thus suggested that using SVN to keep track of document changes will be better as they will be able to know if document if being updated when doing checking out of the project. </p>
<p>But i also highlighted the several cons that may occur</p>
<ul>
<li>Binary file using up alot of diskspace everytime word, excel document is commited</li>
<li>Checkout a project will take much more time although we can separate the documents into another project in the repository</li>
<li>It will take time to teach personnel on how to use SVN.</li>
</ul>
<p>Another feature is that for these kind of functional documents, it should be locked while editing.</p>
<p>Anyone have any idea on how to go about it? Or what are the pros and cons to it. Please feel free to share with me.</p>
|
<p>We use Subversion for document management at work. It works great.</p>
<ul>
<li>Don't worry about the disk space. Revisions are stored compressed anyway.</li>
<li>Checking out a project with documentation doesn't take much more time than one without. Unless your documents are absolutely huge, this shouldn't be a problem.</li>
<li>Training time is a consideration. Fortunately, TortoiseSVN makes this easy.</li>
</ul>
<p>To manage Word documents so they can only be edited by one person at a time, use the <a href="http://svnbook.red-bean.com/en/1.2/svn.advanced.locking.html" rel="nofollow noreferrer"><code>svn:needs-lock</code></a> property. This will make the files appear as read-only on a normal checkout, and read-write when a developer has locked them for editing. After commit, the file will be unlocked and read-only again.</p>
<p>An additional benefit of TortoiseSVN is that it can do diffs of Word documents and present the differences in Word itself. This alone is a killer feature for me.</p>
|
<p>Subversion <strong>only</strong> stores the difference between revisions, which makes it very efficient. I'm not aware if this is true for binary files (such as Word or Excel files), however I believe it may be. If not, it may be to your advantage to use CSV files if possible instead of .XLS files and RTF files if possible instead of .DOC files.</p>
| 30,060
|
<p>I realise that the view/controller stuff will be different between Mac and IPhone apps but the model code may well be similar/the same. So whats the best way to organise a project(s) so that the model code is/can be shared?</p>
<ol>
<li>Copy/paste - just duplicate it and manually keep it in sync </li>
<li>Have 2 xcode projects point at the same workarea - one for Mac and one for IPhone and share the code.</li>
<li>Common library - presumably you can't do this (or can you)</li>
</ol>
<p>Thanks for any tips.</p>
|
<p>There are a few ways to do this. The first thing you can do is is create a project that builds as a framework on Mac OS X. Since you cannot use frameworks on iPhone, you can make static library target that contains the same code files. That basically works, but the header paths will be different. If you want the header paths to be the the same (i.e. <Myframework/MyFramework.h>) you will need to modify the the install path of the static library headers so that they are copied into "$SDK_ROOT/usr/local/include/MyFramework", and make sure /usr/local/include is an included header search path. You will then need to install the library and headers into each SDK_ROOT.</p>
<p>I started out doing the above, but I found it to be a royal pain. So I ended up doing something that is a variant of #2. Basically, I get the header paths to be equivalent by making a directory named "Externals" in my iPhone project root, then a directory named with the appropriate name ("MyFramework") in the externals folder. That is the folder I copy I drag the framework files into.Findally I add the Externals folder as a system header path (which is admittedly sort of a gross hack). You need to manually add new files to the iPhone project, but I have found that to be less of a pain the installing static libs into my build root.</p>
|
<p>You could develop your application in JavaScript, CSS, and HTML. You would use the WebView and UIWebView objects on the Mac and the iPhone respectively. You can do pretty much anything you want in the WebView objects, even make calls down to Objective-C.</p>
<p>The QuickConnectiPhone installer, found here <a href="https://sourceforge.net/projects/quickconnect/" rel="nofollow noreferrer">https://sourceforge.net/projects/quickconnect/</a>, installs QuickConnectMac and QuickConnectiPhone templates into Xcode.</p>
<p>This way you can quickly create an application in one environment and then migrate the view to the other. In fact the QuickConnect framework is highly modular.</p>
<p>If you don't want to develop in JavaScript the same modular framework is found on the Objective-C side of the templates installed.</p>
<p>It should make it much easier for you to do what you are attempting.</p>
| 28,323
|
<p>I'm trying to find a good way to print leading <code>0</code>, such as <code>01001</code> for a <a href="https://en.wikipedia.org/wiki/ZIP_Code" rel="noreferrer">ZIP Code</a>. While the number would be stored as <code>1001</code>, what is a good way to do it?</p>
<p>I thought of using either <code>case</code> statements or <code>if</code> to figure out how many digits the number is and then convert it to an <code>char</code> array with extra <code>0</code>'s for printing, but I can't help but think there may be a way to do this with the <code>printf</code> format syntax that is eluding me.</p>
|
<pre><code>printf("%05d", zipCode);
</code></pre>
<p>The <code>0</code> indicates what you are padding with and the <code>5</code> shows the width of the integer number.</p>
<p>Example 1: If you use <code>"%02d"</code> (useful for dates) this would only pad zeros for numbers in the ones column. E.g., <code>06</code> instead of <code>6</code>.</p>
<p>Example 2: <code>"%03d"</code> would pad 2 zeros for one number in the ones column and pad 1 zero for a number in the tens column. E.g., number 7 padded to <code>007</code> and number 17 padded to <code>017</code>.</p>
|
<p>More flexible..
Here's an example printing rows of right-justified numbers with fixed widths, and space-padding.</p>
<pre><code>//---- Header
std::string getFmt ( int wid, long val )
{
char buf[64];
sprintf ( buf, "% *ld", wid, val );
return buf;
}
#define FMT (getFmt(8,x).c_str())
//---- Put to use
printf ( " COUNT USED FREE\n" );
printf ( "A: %s %s %s\n", FMT(C[0]), FMT(U[0]), FMT(F[0]) );
printf ( "B: %s %s %s\n", FMT(C[1]), FMT(U[1]), FMT(F[1]) );
printf ( "C: %s %s %s\n", FMT(C[2]), FMT(U[2]), FMT(F[2]) );
//-------- Output
COUNT USED FREE
A: 354 148523 3283
B: 54138259 12392759 200391
C: 91239 3281 61423
</code></pre>
<p>The function and macro are designed so the printfs are more readable.</p>
| 18,589
|
<p>I have a VS 2005 C# project that uses a special Plugin folder to load extra DLLs (for use as nodes in an asset conversion process).</p>
<p>I have a mixture of C# and C++ DLLs in this folder.</p>
<p>The issue I have is that when Shadow Copying is enabled, the C++ DLLs refuse to load using Assembly.LoadFrom. I have attempted to create a custom app domain, and used Load, but this also failed.</p>
<p>Finally, I tried reading the DLL in as byte[] data and using Load on that - again, only the C# DLLs would work this way, with an error "Additional information: Unverifiable code failed policy check. (Exception from HRESULT: 0x80131402)".</p>
<p>An article on the net prompted me to attempt to use /clr:safe when building that particular DLL, but then it simply failed to build due to thousands of errors in Microsoft code... (apparently)</p>
<p>With Shadow Copying disabled, LoadFrom works fine for all DLLs. The app is itself a plugin for Maya, and this used to work with Maya 8.5 but fails with 2008 / 2009 (if Shadow Copying is enabled).</p>
<p>We really would prefer to use Shadow Copying, because it prevents DLL file locks when the app is running (the Plugins folder is stored in a location that Perforce can update while the app is running).</p>
<p>Any ideas as to how I can persuade Shadow Copying to work with a custom folder AND a mix of C# / C++ DLLs without these problems?</p>
|
<p>Sounds like a trust issue. Try getting a Fusion log (see <a href="http://blogs.msdn.com/suzcook/archive/2003/05/29/57120.aspx" rel="nofollow noreferrer">this blog post</a>). Your C++ DLLs are unverifiable since they weren't compiled with <code>/clr:safe</code>, so they can only be loaded as full trust. Presumably when shadow copying, the download cache location doesn't have full trust.</p>
<p>Running <code>caspol -s</code> may get you up and running if this is a development-only issue.</p>
|
<p>Assembly.Load(byte[] ...) explicitly disallows unverifiable (mixed mode) assemblies. you can check the issue on <a href="https://connect.microsoft.com/VisualStudio/feedback/details/97801/loading-mixed-assembly-with-assembly-load-byte-throw-exception-changed-behaviour" rel="nofollow noreferrer">Microsoft Connect</a>.</p>
| 34,236
|
<p>I have a function which searches an STL container then returns the iterator when it finds the position, however I am getting some funny error messages, can tell me what I am doing wrong?</p>
<p>Function:</p>
<pre><code>std::vector< CClass >::iterator CClass::SearchFunction( const std::string& strField )
{
...
return it;
...
}
</code></pre>
<p>Error:</p>
<pre><code>error C2664: 'std::_Vector_iterator<_Ty,_Alloc>::_Vector_iterator(const std::_Vector_iterator<_Ty,_Alloc> &)' : cannot convert parameter 1 from 'std::_Vector_const_iterator<_Ty,_Alloc> *__w64 ' to 'const std::_Vector_iterator<_Ty,_Alloc> &'
</code></pre>
|
<p>Your search function is returning a const_iterator. You should either return the same type, i.e. <code>std::vector< CClass >::const_iterator</code>, or cast it to a <code>std::vector< CClass >::iterator</code> if you intend the caller to be able to modify the found item through the iterator.</p>
<p>EDIT: after seeing your update, it seems the problem is your iterator (it) has a different type than your function return. They should be the same.</p>
<pre><code>std::vector< CClass >::iterator it;
</code></pre>
|
<p>Sounds like you have your const_iterators mixed up. Please post more code, specifically how you are declaring your iterator.</p>
| 40,498
|
<p>Using VS2008, C#, .Net 2 and Winforms how can I make a regular Button look "pressed"?
Imagine this button is an on/off switch.
<code>ToolStripButton</code> has the Checked property, but the regular Button does not.</p>
|
<p>One method you can used to obtain this option is by placing a "CheckBox" object and changing its "Appearance" from "Normal" to "Button" this will give you the same functionality that I believe you are looking for.</p>
|
<p>I think you may need a <code>ToggleButton</code>. You can take a look at third party vendors of WinForms components such as Telerik, DevExpress, ComponentFactory, ViBlend which provide such control. They all provide toggle buttons.</p>
| 2,690
|
<p>The rich presentational capabilities of WPF and Silverlight mean developers like me will be working closely with graphic designers more often these days, as is the case in my next project. </p>
<p>Does anyone out there have any tips and experience (from both points of view) on making this go more smoothly? </p>
<p>For example, when I mentioned source control to a designer recently, I was quickly told you can't source control graphics, images etc, so it is a waste of time. So I responded: ok but, what about XAML files in WPF/Silverlight? </p>
<p>Scott Hanselman spoke about this topic in a <a href="http://www.hanselminutes.com/default.aspx?showID=138" rel="noreferrer">podcast</a>, but he focused more on the tools, while I'm more interested in the communication issues/aspects.</p>
|
<p>I have spent 4 months on a project working extremely closely with a designer and he has still not picked up the basic idea of CVS (which is not my choice of source control system). I'm talking template files, JavaScript and CSS here. He's not stupid, it's just one of these things that makes his job harder so he resists fully commiting himself to it.</p>
<p>In my case I had to really hammer home the point that almost all of my JavaScript depended on the mark-up and when he changed his pure CSS, DIV-based layout into a table-based one without telling me then all my JS is going to break.</p>
<p>Often during the course of the project myself and the designer, who I get on with quite well and play soccer with outside of work, had very heated exchanges about our respective responsibilities. If I didn't know him well enough to just get past these exchanges then I think it would have created an unbearable working environment. So I think it's important you establish between you both and with some sort of manager or project supervisor exactly what is expected of both parties during the project. </p>
<p>In my case there have been very few problems lately, because the situation with CVS has been sorted out as well as the idea that he can't just go and change the mark-up whenever he feels like it. Rather than try and create template files and work on them directly, the designer only works on static files and its my responsibility to plug them into my template files.</p>
<p>It's all about communication and a little bit of compromise on both sides.</p>
|
<p>Quite frankly you should tell the designer that images can, should and "will be put in source control mister!" :) </p>
<p>It may be slightly non-conventional and you wont be able to do a merge or anything of that nature, but there will be revisions and a history, etc .. Images can also be embedded in a resource file which goes into source control as well. </p>
<p>XAML can (and should) be put in source control and as its a markup file it will benefit from all of the features. </p>
<p>As far as tips from working with a designer, the one you are working with scares the heck outta me just by that comment alone, so it may all boil down to WHO you are working with. I would explain basic best practices in a nice manner and proceed from there.</p>
| 7,478
|
<p>I've make an application in PHP that uses DOMDocument() in PHP 5.</p>
<p>The problem is that my server uses PHP 4 and DOM object is not recognized. What can I do?</p>
<p>Can I download any kind of software and put it in my server and use include?
Which one? </p>
<p>Thanks a lot.</p>
|
<p>You can use the DOM XML extension in PHP4: <a href="http://de.php.net/manual/en/book.domxml.php" rel="nofollow noreferrer">http://de.php.net/manual/en/book.domxml.php</a>.</p>
<p>Please note that the API is not compatible with the <a href="http://de.php.net/manual/en/book.dom.php" rel="nofollow noreferrer">PHP5 DOM extension</a>.</p>
|
<p>PHP 5</p>
<p>Have your server admin upgrade your server.</p>
| 26,962
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.