qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
243,494
|
<p>I have some legacy code that uses VBA to parse a word document and build some XML output; </p>
<p>Needless to say it runs like a dog but I was interested in profiling it to see where it's breaking down and maybe if there are some options to make it faster.</p>
<p>I don't want to try anything until I can start measuring my results so profiling is a must - I've done a little searching around but can't find anything that would do this job easily. There was one tool by brentwood? that requires modifying your code but it didn't work and I ran outa time.</p>
<p>Anyone know anything simple that works?</p>
<p>Update: The code base is about 20 or so files, each with at least 100 methods - manually adding in start/end calls for each method just isn't appropriate - especially removing them all afterwards - I was actually thinking about doing some form of REGEX to solve this issue and another to remove them all after but its just a little too intrusive but may be the only solution. I've found some nice timing code on here earlier so the timing part of it isn't an issue.</p>
|
[
{
"answer_id": 243545,
"author": "Svante Svenson",
"author_id": 19707,
"author_profile": "https://Stackoverflow.com/users/19707",
"pm_score": 0,
"selected": false,
"text": "Debug.Print \"before/after foo\", Now\n"
},
{
"answer_id": 244103,
"author": "Aardvark",
"author_id": 3655,
"author_profile": "https://Stackoverflow.com/users/3655",
"pm_score": 2,
"selected": true,
"text": "#If PROFILE = 1 Then\n\nPrivate m_locationName As String\nPrivate Sub Class_Initialize()\n m_locationName = \"unknown\"\nEnd Sub\n\nPublic Sub Start(locationName As String)\n m_locationName = locationName\n MsgBox m_locationName\nEnd Sub\n\nPrivate Sub Class_Terminate()\n MsgBox m_locationName & \" end\"\nEnd Sub\n\n#Else\n\nPublic Sub Start(locationName As String)\n 'no op\nEnd Sub\n\n#End If\n ' helper \"factory\" since VBA classes don't have ctor params (or do they?)\nPrivate Function start_profile(location As String) As Profiler\n Set start_profile = New Profiler\n start_profile.Start location\nEnd Function\n\nPrivate Sub test()\n Set p = start_profile(\"test\")\n MsgBox \"do work\"\n subroutine\nEnd Sub\n\nPrivate Sub subroutine()\n Set p = start_profile(\"subroutine\")\nEnd Sub\n PROFILE = 1\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24525/"
] |
243,504
|
<p>How would one go about capturing users keystrokes in the SMS composer on the Symbian OS, specifically for a Nokia N73 (or any of the symbian supported devices <a href="http://en.wikipedia.org/wiki/Symbian_OS#Devices_that_have_used_the_Symbian_OS" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Symbian_OS#Devices_that_have_used_the_Symbian_OS</a>)? I'm new to symbian development and I'm trying to write an application to analyse writing styles of those who send SMSs. Any information (or push in the right direction) would be great.</p>
<p>Many Thanks,</p>
<p>A</p>
|
[
{
"answer_id": 286611,
"author": "KevinD",
"author_id": 26497,
"author_profile": "https://Stackoverflow.com/users/26497",
"pm_score": 3,
"selected": true,
"text": "RWindowGroup::CaptureKey() RWindowGroup::CaptureLongKey() RWsSession::SendEventToWindowGroup() TApaTask::SendKey()"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/368855/"
] |
243,510
|
<p>Does anyone know what is wrong with this query?</p>
<pre><code> SELECT DISTINCT c.CN as ClaimNumber,
a.ItemDate as BillReceivedDate, c.DTN as
DocTrackNumber
FROM ItemData a,
ItemDataPage b,
KeyGroupData c
WHERE a.ItemTypeNum in (112, 113, 116, 172, 189)
AND a.ItemNum = b.ItemNum
AND b.ItemNum = c.ItemNum
ORDER BY a.DateStored DESC;
</code></pre>
<p>I have done T-Sql most of my career and this looks correct to me, however this query is for an Oracle database and Toad just places the cursor on the a.DateStored in the Order By section. I'm sure this is elementary for anyone doing PL/SQL.</p>
<p>Thanks!</p>
<p>[EDIT] For future reference, the error given by SQL*Plus was: "ORA-01791: not a SELECTed expression" </p>
|
[
{
"answer_id": 243520,
"author": "Chris Conway",
"author_id": 2849,
"author_profile": "https://Stackoverflow.com/users/2849",
"pm_score": 2,
"selected": false,
"text": " SELECT DISTINCT c.CN as ClaimNumber, \na.ItemDate as BillReceivedDate, \nc.DTN as DocTrackNumber, \na.DateStored \nFROM ItemData a, \nItemDataPage b, \nKeyGroupData c \nWHERE a.ItemTypeNum in (112, 113, 116, 172, 189) \nAND a.ItemNum = b.ItemNum \nAND b.ItemNum = c.ItemNum \nORDER BY a.DateStored DESC;\n"
},
{
"answer_id": 243523,
"author": "Brian Schmitt",
"author_id": 30492,
"author_profile": "https://Stackoverflow.com/users/30492",
"pm_score": 5,
"selected": true,
"text": "SELECT DISTINCT c.CN as ClaimNumber, \n a.ItemDate as BillReceivedDate, c.DTN as\n DocTrackNumber, a.DateStored\n FROM ItemData a,\n ItemDataPage b,\n KeyGroupData c\n WHERE a.ItemTypeNum in (112, 113, 116, 172, 189)\n AND a.ItemNum = b.ItemNum\n AND b.ItemNum = c.ItemNum\n ORDER BY a.DateStored DESC;\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2849/"
] |
243,528
|
<p>We're looking at using Oracle Hierarchical queries to model potentially very large tree structures (potentially infinitely wide, and depth of 30+). My understanding is that hierarchal queries provide a method to write recursively joining SQL but they it does not provide any real performance enhancements over if you were to manually write an equivalent query... is this the case? What sort of experiences have people had, performance wise, with using oracle hierarchical queries?</p>
|
[
{
"answer_id": 245156,
"author": "dacracot",
"author_id": 13930,
"author_profile": "https://Stackoverflow.com/users/13930",
"pm_score": 1,
"selected": false,
"text": "CREATE TABLE\n loopy\n (key NUMBER, key_hier number, info VARCHAR2, part NUMBER)\nPARTITION BY\n RANGE (part)\n (\n PARTITION low VALUES LESS THAN (1000),\n PARTITION mid VALUES LESS THAN (10000),\n PARTITION high VALUES LESS THAN (MAXVALUE)\n ); \n\nSELECT\n info\nFROM\n loopy PARTITION(mid)\nCONNECT BY\n key = key_hier\nSTART WITH\n key = <some value>;\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9155/"
] |
243,553
|
<p>How can I find out which row in a JTable the user just clicked?</p>
|
[
{
"answer_id": 243560,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 6,
"selected": true,
"text": "aJTable.rowAtPoint(evt.getPoint());"
},
{
"answer_id": 245005,
"author": "oxbow_lakes",
"author_id": 16853,
"author_profile": "https://Stackoverflow.com/users/16853",
"pm_score": 4,
"selected": false,
"text": "jTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {\n public void valueChanged(ListSelectionEvent e) {\n int sel = jTable.getSelectedRow();\n }\n});\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24028/"
] |
243,554
|
<p>I'm currently creating a window system for XNA games from scratch. I'm developing primarily for Windows, but who knows what platforms I might support in the future. Feel free to answer if you know this for native Direct3D, since the performance semantics should be similar. If possible, consider what would change if the target platform was X-Box 360.</p>
<p>I'm making good progress, but now I am unsure on how to exactly render the windows. I came up with four approaches:</p>
<ul>
<li><p>Just render all controls directly onto the screen. This is what I do now. Controls can be animated by blending between states as long as they are not semi-transparent. I did not find a good way to animate between an arbitrary number of states (suppose a button that is currently animating from button-up to button-down and from mouse-out to mouse-over, and then it is being disabled. It should smoothly blend from its last state to the new state. With this approach, this only works if one animation is played after the last one finished, or you'll have jumps in animation.</p></li>
<li><p>Render each top-level window and all controls into a render target, and then use that to render the top-level windows with semi-transparency onto the screen. This makes semi-transparency at top-level work and is easy to manage, but doesn't change the thing with the animations.</p></li>
<li><p>Render each control into a render target, which is only updated when the control becomes dirty (i.e. must animate or the text has been changed). This way, per-control semi-transparency would work.</p></li>
<li><p>Like the previous, but in addition to solve the animation problem have a second render target for each control. Whenever an animation starts, swap render targets, so we have the state when the animation starts, and blend it with the destination state into the other render target. This should not add overhead over the previous approach, we just had twice as many render targets, of which in any given frame only one would be rendered to (at maximum). But here comes the problem: For this to work, I would need to have the "old" render target preserve its contents. This should work with good performance on Windows, but appears to have a serious performance impact on X-Box 360. On the other hand, the "preserve" bit is only necessary while an animation is active.</p></li>
</ul>
<p>And here come the actual questions. Anything that clarifies is welcome. With the performance questions, remember that this would just be the window system of a game - the game behind might use many render targets and suck up performance as well, and likely much more than the window system. Assume that we might have five top-level windows with 20-40 controls each on the screen in absolute worst-case.</p>
<ul>
<li>Which of these approaches, if any, would you recommend and why? Feel free, of course, to add another approach.</li>
<li>Is there a performance impact when just having let's say 200 or 400 render targets available, provided that only maybe 20 of them are being rendered to each frame?</li>
<li>Is the performance impact of PreserveContents really that bad on X-Box 360? How bad is it on Windows?</li>
<li>The RenderTarget2D.RenderTargetUsage property can be written to. Is switching this at runtime a good idea, to enable PreserveContents only as needed?</li>
<li>Would you (as a player) mind if control animations would jump in certain situations, like hovering over a button, moving the mouse out and then in again, so the "normal->hover" animation is played twice from the beginning because it is slower than you?</li>
</ul>
|
[
{
"answer_id": 1133845,
"author": "Jodi",
"author_id": 127081,
"author_profile": "https://Stackoverflow.com/users/127081",
"pm_score": 2,
"selected": false,
"text": "size (bits) = width x height x color data size (bits)\n 3,515625MB = 29491200 bits = 1280 x 760 x 32 bits\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20363/"
] |
243,567
|
<p>The database type is PostGres 8.3.</p>
<p>If I wrote: </p>
<pre><code>SELECT field1, field2, field3, count(*)
FROM table1
GROUP BY field1, field2, field3 having count(*) > 1;
</code></pre>
<p>I have some rows that have a count over 1. How can I take out the duplicate (I do still want 1 row for each of them instead of +1 row... I do not want to delete them all.)</p>
<p>Example:</p>
<pre><code>1-2-3
1-2-3
1-2-3
2-3-4
4-5-6
</code></pre>
<p>Should become :</p>
<pre><code>1-2-3
2-3-4
4-5-6
</code></pre>
<p><em>The only answer I found is <a href="http://www.siafoo.net/article/64" rel="noreferrer">there</a> but I am wondering if I could do it without hash column.</em></p>
<p><strong>Warning</strong>
I do not have a PK with an unique number so I can't use the technique of min(...). The PK is the 3 fields.</p>
|
[
{
"answer_id": 243627,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 0,
"selected": false,
"text": "CREATE <temporary table> (<correct structure for table being cleaned>);\nBEGIN WORK; -- if needed\nINSERT INTO <temporary table> SELECT DISTINCT * FROM <source table>;\nDELETE FROM <source table>\nINSERT INTO <source table> SELECT * FROM <temporary table>;\nCOMMIT WORK; -- needed\nDROP <temporary table>;\n"
},
{
"answer_id": 243629,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 4,
"selected": true,
"text": "SELECT field1, field2, field3, count(*) \nINTO temp_table1\nFROM table1\nGROUP BY field1, field2, field3 having count(*) > 1\n\nDELETE T1\nFROM table1 T1\nINNER JOIN (SELECT field1, field2, field3\n FROM table1\n GROUP BY field1, field2, field3 having count(*) > 1) SQ ON\n SQ.field1 = T1.field1 AND\n SQ.field2 = T1.field2 AND\n SQ.field3 = T1.field3\n\nINSERT INTO table1 (field1, field2, field3)\nSELECT field1, field2, field3\nFROM temp_table1\n\nDROP TABLE temp_table1\n"
},
{
"answer_id": 243638,
"author": "Brian Schmitt",
"author_id": 30492,
"author_profile": "https://Stackoverflow.com/users/30492",
"pm_score": 0,
"selected": false,
"text": "DELETE FROM table1\nWHERE OID NOT IN (SELECT MIN (OID)\n FROM table1\n GROUP BY field1, field2, field3)\n"
},
{
"answer_id": 243652,
"author": "Ta01",
"author_id": 7280,
"author_profile": "https://Stackoverflow.com/users/7280",
"pm_score": 0,
"selected": false,
"text": "-- **Disclaimer** using TSQL\n-- You could select your records into a temp table with a pk\nCreate Table #dupes\n([id] int not null identity(1,1), f1 int, f2 int, f3 int)\n\nInsert Into #dupes (f1,f2,f3) values (1,2,3)\nInsert Into #dupes (f1,f2,f3) values (1,2,3)\nInsert Into #dupes (f1,f2,f3) values (1,2,3)\nInsert Into #dupes (f1,f2,f3) values (2,3,4)\nInsert Into #dupes (f1,f2,f3) values (4,5,6)\nInsert Into #dupes (f1,f2,f3) values (4,5,6)\nInsert Into #dupes (f1,f2,f3) values (4,5,6)\nInsert Into #dupes (f1,f2,f3) values (7,8,9)\n\nSelect f1,f2,f3 From #dupes\n\nDeclare @rowCount int\nDeclare @counter int\nSet @counter = 1\nSet @rowCount = (Select Count([id]) from #dupes)\n\nwhile (@counter < @rowCount + 1)\n Begin\n Delete From #dupes\n Where [Id] <> \n (Select [id] From #dupes where [id]=@counter)\n and\n (\n [f1] = (Select [f1] from #dupes where [id]=@counter)\n and\n [f2] = (Select [f2] from #dupes where [id]=@counter)\n and\n [f3] = (Select [f3] from #dupes where [id]=@counter)\n )\n Set @counter = @counter + 1\n End\n\nSelect f1,f2,f3 From #dupes -- You could take these results and pump them back into --your original table\n\nDrop Table #dupes\n"
},
{
"answer_id": 243666,
"author": "Aaron Palmer",
"author_id": 24908,
"author_profile": "https://Stackoverflow.com/users/24908",
"pm_score": 0,
"selected": false,
"text": "CREATE TABLE tmp AS SELECT distinct * FROM table1\ntruncate table table1\ninsert into table1 select * from tmp\ndrop table tmp\n select distinct * into #tmp from table1\ntruncate table table1\ninsert into table1 select * from #tmp\ndrop table #tmp\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13913/"
] |
243,568
|
<p>I found in a bug in an old C++ MFC program we have that calculates an offset (in days) for a given date from a fixed base date. We were seeing results that were off by one for some reason, and I tracked it down to where the original programmer had used the CTimeSpan.GetDays() method. According to the <a href="http://msdn.microsoft.com/en-us/library/14zezc9x.aspx" rel="nofollow noreferrer">documentation</a>:</p>
<blockquote>
<p>Note that Daylight Savings Time can cause GetDays to return a potentially surprising result. For example, when DST is in effect, GetDays reports the number of days between April 1 and May 1 as 29, not 30, because one day in April is shortened by an hour and therefore does not count as a complete day.</p>
</blockquote>
<p>My proposed fix is to use <code>(obj.GetTotalHours()+1)/24</code> instead. I think that would cover all the issues since this is a batch job that runs at about the same time every day, but I thought I'd ask the smart people here before implementing it if there might be a better way. </p>
<p>This is just a side issue, but I'm also curious how this would be handled if the program could be run at any time.</p>
|
[
{
"answer_id": 243841,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 3,
"selected": true,
"text": "CTime startDay(start.GetYear(), start.GetMonth(), start.GetDay(), 0, 0, 0);\nCTime finishDay(finish.GetYear(), finish.GetMonth(), finish.GetDay(), 0, 0, 0);\nint days = ((finishDay - startDay).GetTotalHours() + 1) / 24;\n"
},
{
"answer_id": 16320654,
"author": "mjk99",
"author_id": 1630774,
"author_profile": "https://Stackoverflow.com/users/1630774",
"pm_score": 0,
"selected": false,
"text": "CTime // Discard hours, minutes, seconds, and daylight savings time\nCTime startDay(start.GetYear(), start.GetMonth(), start.GetDay(), 0, 0, 0, 0);\nCTime endDay(end.GetYear(), end.GetMonth(), end.GetDay(), 0, 0, 0, 0);\n\n// Get number of days apart\nCTimeSpan span = endDay - startDay;\nint nDays = span.GetDays();\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043/"
] |
243,569
|
<p>consider this code block</p>
<pre><code>public void ManageInstalledComponentsUpdate()
{
IUpdateView view = new UpdaterForm();
BackgroundWorker worker = new BackgroundWorker();
Update update = new Update();
worker.WorkerReportsProgress = true;
worker.WorkerSupportsCancellation = true;
worker.DoWork += new DoWorkEventHandler(update.DoUpdate);
worker.ProgressChanged += new ProgressChangedEventHandler(view.ProgressCallback);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(view.CompletionCallback);
worker.RunWorkerAsync();
Application.Run(view as UpdaterForm);
}
</code></pre>
<p>It all works great but I want to understand why the objects (worker,view and update) don't get garbage collected</p>
|
[
{
"answer_id": 243600,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": true,
"text": "using System;\nusing System.ComponentModel;\nusing System.Threading;\nusing System.Windows.Forms;\nclass Demo : Form\n{\n class ChattyWorker : BackgroundWorker\n {\n ~ChattyWorker()\n {\n Console.WriteLine(\"Worker finalized\");\n }\n }\n class SomeTarget\n {\n ~SomeTarget()\n {\n Console.WriteLine(\"Target finalized\");\n }\n public SomeTarget()\n {\n Console.WriteLine(\"Target created\");\n }\n public void Foo(object sender, EventArgs args)\n {\n Console.WriteLine(\"Foo\");\n }\n }\n static void Collect(object sender, EventArgs args)\n {\n Console.WriteLine(\"Collecting...\");\n GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);\n }\n protected override void OnLoad(EventArgs e)\n {\n base.OnLoad(e);\n\n System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();\n timer.Interval = 100;\n timer.Tick += Collect;\n timer.Start();\n\n ChattyWorker worker = new ChattyWorker();\n worker.RunWorkerCompleted += new SomeTarget().Foo;\n worker.DoWork += delegate\n {\n Console.WriteLine(\"Worker starting\");\n for (int i = 0; i < 10; i++)\n {\n Thread.Sleep(250);\n Console.WriteLine(i);\n }\n Console.WriteLine(\"Worker exiting\");\n };\n worker.RunWorkerAsync();\n }\n [STAThread]\n static void Main()\n { // using a form to force a sync context\n Application.Run(new Demo());\n }\n}\n"
},
{
"answer_id": 245230,
"author": "jyoung",
"author_id": 14841,
"author_profile": "https://Stackoverflow.com/users/14841",
"pm_score": -1,
"selected": false,
"text": "public void ManageInstalledComponentsUpdate() {\n UpdaterForm form = new UpdaterForm();\n FireAndForgetWorker( form );\n Application.Run( form ); //does not return until form exits\n}\n\nvoid FireAndForgetWorker( IUpdateView view ) {\n BackgroundWorker worker = new BackgroundWorker();\n Update update = new Update();\n worker.WorkerReportsProgress = true;\n worker.WorkerSupportsCancellation = true;\n worker.DoWork += new DoWorkEventHandler(update.DoUpdate);\n worker.ProgressChanged += new ProgressChangedEventHandler(view.ProgressCallback);\n worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(view.CompletionCallback);\n worker.RunWorkerAsync();\n}\n class FailsOnGarbageCollection \n{ ~FailsOnGarbageCollection() { throw new NotSupportedException(); } }\n\nclass Program{\n static void WaitForever() { while (true) { var o = new object(); } }\n\n static void Main(string[] args)\n {\n var x = new FailsOnGarbageCollection();\n //x = null; //use this line to release x and cause the above exception\n WaitForever();\n }\n}\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30324/"
] |
243,572
|
<p>I am configure log4net to use a composite RollingFileAppender so that the current file is always named <strong>logfile.log</strong> and all subsequent files are named <strong>logfile-YYYY.MM.dd.seq.log</strong> where <strong>seq</strong> is the sequence number if a log exceeds a certain size within a single day. Unfortunately, I have had very little success in configuring such a setup. </p>
<p><strong>Edit:</strong></p>
<p>My current configuration is pasted below. It has been updated based on several answers which gets me close enough for my needs. This generates files of the format: <strong>logfile_YYYY.MM.dd.log.seq</strong></p>
<pre><code><log4net>
<root>
<level value="DEBUG" />
<appender-ref ref="RollingFileAppender" />
</root>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="logs\\logfile"/>
<staticLogFileName value="false"/>
<appendToFile value="true"/>
<rollingStyle value="Composite"/>
<datePattern value="_yyyy.MM.dd&quot;.log&quot;"/>
<maxSizeRollBackups value="10"/>
<maximumFileSize value="75KB"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"/>
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="DEBUG" />
<param name="LevelMax" value="FATAL" />
</filter>
</appender>
</log4net>
</code></pre>
<p>One interesting note, setting</p>
<pre><code><staticLogFileName value="false"/>
</code></pre>
<p>to true causes the logger to not write any files.</p>
|
[
{
"answer_id": 243607,
"author": "Leandro López",
"author_id": 22695,
"author_profile": "https://Stackoverflow.com/users/22695",
"pm_score": 2,
"selected": false,
"text": "protected string GetNextOutputFileName(string fileName)\n{\n if (!m_staticLogFileName) \n {\n fileName = fileName.Trim();\n\n if (m_rollDate)\n {\n fileName = fileName + m_now.ToString(m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo);\n }\n\n if (m_countDirection >= 0) \n {\n fileName = fileName + '.' + m_curSizeRollBackups;\n }\n }\n\n return fileName;\n}\n logfileYYYY-MM-dd.n.log"
},
{
"answer_id": 243608,
"author": "paul",
"author_id": 11249,
"author_profile": "https://Stackoverflow.com/users/11249",
"pm_score": 5,
"selected": true,
"text": "<appender name=\"roller\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n <param name=\"File\" value=\"Applog.log\"/>\n <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\"/>\n <layout class=\"org.apache.log4j.PatternLayout\">\n <param name=\"ConversionPattern\" value=\"[slf5s.start]%d{DATE}[slf5s.DATE]%n%p[slf5s.PRIORITY]%n%x[slf5s.NDC]%n%t[slf5s.THREAD]%n%c[slf5s.CATEGORY]%n%l[slf5s.LOCATION]%n%m[slf5s.MESSAGE]%n%n\"/>\n </layout>\n</appender>\n"
},
{
"answer_id": 243840,
"author": "Charley Rathkopf",
"author_id": 10119,
"author_profile": "https://Stackoverflow.com/users/10119",
"pm_score": 1,
"selected": false,
"text": " <maxSizeRollBackups value=\"10\"/>\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19977/"
] |
243,617
|
<p>I have a Java based web-application and a new requirement to allow Users to place variables into text fields that are replaced when a document or other output is produced. How have others gone about this?</p>
<p>I was thinking of having a pre-defined set of variables such as :<br>
<code>@BOOKING_NUMBER@</code><br>
<code>@INVOICE_NUMBER@</code> </p>
<p>Then when a user enters some text they can specify a variable inline (select it from a modal or similar). For example:</p>
<p><em>"This is some text for Booking <code>@BOOKING_NUMBER@</code> that is needed by me"</em> </p>
<p>When producing some output (eg. PDF) that uses this text, I would do a regex and find all variables and replace them with the correct value: </p>
<p><em>"This is some text for Booking 10001 that is needed by me"</em> </p>
<p>My initial thought was something like Freemarker but I think that is too complex for my Users and would require them to know my DataModel (eww).</p>
<p>Thanks for reading!</p>
<p>D.</p>
|
[
{
"answer_id": 243781,
"author": "belugabob",
"author_id": 13397,
"author_profile": "https://Stackoverflow.com/users/13397",
"pm_score": 2,
"selected": false,
"text": "MessageFormat.format(\"This is some text for booking {0} that is needed by me, for use with invoice {1}\", bookingNumber, invoiceNumber);\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2955/"
] |
243,644
|
<p>I have currently more than 100 connections in Sleep state.</p>
<p>Some connection must stay in Sleep state (and don't close) because it's permanent connection but some others (with a different user name) are from some php script and I want them to timeout very fast.</p>
<p>Is it possible to setup a wait_timeout per user? and if yes, How?</p>
|
[
{
"answer_id": 244291,
"author": "Gary Richardson",
"author_id": 2506,
"author_profile": "https://Stackoverflow.com/users/2506",
"pm_score": 0,
"selected": false,
"text": "mysql.user +-----------------------+-----------------------------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+-----------------------+-----------------------------------+------+-----+---------+-------+\n| Host | char(60) | NO | PRI | | |\n| User | char(16) | NO | PRI | | |\n| Password | char(41) | NO | | | |\n| Select_priv | enum('N','Y') | NO | | N | |\n| Insert_priv | enum('N','Y') | NO | | N | |\n| Update_priv | enum('N','Y') | NO | | N | |\n| Delete_priv | enum('N','Y') | NO | | N | |\n| Create_priv | enum('N','Y') | NO | | N | |\n| Drop_priv | enum('N','Y') | NO | | N | |\n| Reload_priv | enum('N','Y') | NO | | N | |\n| Shutdown_priv | enum('N','Y') | NO | | N | |\n| Process_priv | enum('N','Y') | NO | | N | |\n| File_priv | enum('N','Y') | NO | | N | |\n| Grant_priv | enum('N','Y') | NO | | N | |\n| References_priv | enum('N','Y') | NO | | N | |\n| Index_priv | enum('N','Y') | NO | | N | |\n| Alter_priv | enum('N','Y') | NO | | N | |\n| Show_db_priv | enum('N','Y') | NO | | N | |\n| Super_priv | enum('N','Y') | NO | | N | |\n| Create_tmp_table_priv | enum('N','Y') | NO | | N | |\n| Lock_tables_priv | enum('N','Y') | NO | | N | |\n| Execute_priv | enum('N','Y') | NO | | N | |\n| Repl_slave_priv | enum('N','Y') | NO | | N | |\n| Repl_client_priv | enum('N','Y') | NO | | N | |\n| Create_view_priv | enum('N','Y') | NO | | N | |\n| Show_view_priv | enum('N','Y') | NO | | N | |\n| Create_routine_priv | enum('N','Y') | NO | | N | |\n| Alter_routine_priv | enum('N','Y') | NO | | N | |\n| Create_user_priv | enum('N','Y') | NO | | N | |\n| ssl_type | enum('','ANY','X509','SPECIFIED') | NO | | | |\n| ssl_cipher | blob | NO | | | |\n| x509_issuer | blob | NO | | | |\n| x509_subject | blob | NO | | | |\n| max_questions | int(11) unsigned | NO | | 0 | |\n| max_updates | int(11) unsigned | NO | | 0 | |\n| max_connections | int(11) unsigned | NO | | 0 | |\n| max_user_connections | int(11) unsigned | NO | | 0 | |\n+-----------------------+-----------------------------------+------+-----+---------+-------+\n37 rows in set (0.00 sec)\n MaxServers MaxSpareServers MinSpareServers StartServers"
},
{
"answer_id": 244744,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 6,
"selected": true,
"text": "wait_timeout mysql> SHOW VARIABLES LIKE 'wait_timeout';\n wait_timout mysql> SET SESSION wait_timeout = 60;\nmysql> SHOW VARIABLES LIKE 'wait_timeout';\n wait_timeout wait_timeout"
},
{
"answer_id": 244804,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 2,
"selected": false,
"text": "wait_timeout interactive_timeout CLIENT_INTERACTIVE mysql_real_connect() client_flag wait_timeout interactive_timeout"
},
{
"answer_id": 13345116,
"author": "Sych",
"author_id": 1818256,
"author_profile": "https://Stackoverflow.com/users/1818256",
"pm_score": 3,
"selected": false,
"text": "my.conf [mysqld]\ninteractive_timeout=180\nwait_timeout=180\n wait_timeout interactive_timeout"
},
{
"answer_id": 17174741,
"author": "Toddius Zho",
"author_id": 451621,
"author_profile": "https://Stackoverflow.com/users/451621",
"pm_score": 2,
"selected": false,
"text": "jdbc:mysql://hostname:3306/schema?sessionVariables=wait_timeout=600"
},
{
"answer_id": 41847505,
"author": "Karthik Appigatla",
"author_id": 1837866,
"author_profile": "https://Stackoverflow.com/users/1837866",
"pm_score": 2,
"selected": false,
"text": "mysql> SET GLOBAL init_connect=\"SET @@wait_timeout = CASE WHEN CURRENT_USER() LIKE 'app1@%' THEN '30' ELSE @@wait_timeout END\";"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6605/"
] |
243,646
|
<p>I've got an <code>RSA</code> private key in <code>PEM</code> format, is there a straight forward way to read that from .NET and instantiate an <code>RSACryptoServiceProvider</code> to decrypt data encrypted with the corresponding public key?</p>
|
[
{
"answer_id": 243685,
"author": "wprl",
"author_id": 17847,
"author_profile": "https://Stackoverflow.com/users/17847",
"pm_score": 5,
"selected": false,
"text": "//------- Parses binary ans.1 RSA private key; returns RSACryptoServiceProvider ---\npublic static RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey)\n{\n byte[] MODULUS, E, D, P, Q, DP, DQ, IQ ;\n\n // --------- Set up stream to decode the asn.1 encoded RSA private key ------\n MemoryStream mem = new MemoryStream(privkey) ;\n BinaryReader binr = new BinaryReader(mem) ; //wrap Memory Stream with BinaryReader for easy reading\n byte bt = 0;\n ushort twobytes = 0;\n int elems = 0;\n try {\n twobytes = binr.ReadUInt16();\n if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)\n binr.ReadByte(); //advance 1 byte\n else if (twobytes == 0x8230)\n binr.ReadInt16(); //advance 2 bytes\n else\n return null;\n\n twobytes = binr.ReadUInt16();\n if (twobytes != 0x0102) //version number\n return null;\n bt = binr.ReadByte();\n if (bt !=0x00)\n return null;\n\n\n //------ all private key components are Integer sequences ----\n elems = GetIntegerSize(binr);\n MODULUS = binr.ReadBytes(elems);\n\n elems = GetIntegerSize(binr);\n E = binr.ReadBytes(elems) ;\n\n elems = GetIntegerSize(binr);\n D = binr.ReadBytes(elems) ;\n\n elems = GetIntegerSize(binr);\n P = binr.ReadBytes(elems) ;\n\n elems = GetIntegerSize(binr);\n Q = binr.ReadBytes(elems) ;\n\n elems = GetIntegerSize(binr);\n DP = binr.ReadBytes(elems) ;\n\n elems = GetIntegerSize(binr);\n DQ = binr.ReadBytes(elems) ;\n\n elems = GetIntegerSize(binr);\n IQ = binr.ReadBytes(elems) ;\n\n Console.WriteLine(\"showing components ..\");\n if (verbose) {\n showBytes(\"\\nModulus\", MODULUS) ;\n showBytes(\"\\nExponent\", E);\n showBytes(\"\\nD\", D);\n showBytes(\"\\nP\", P);\n showBytes(\"\\nQ\", Q);\n showBytes(\"\\nDP\", DP);\n showBytes(\"\\nDQ\", DQ);\n showBytes(\"\\nIQ\", IQ);\n }\n\n // ------- create RSACryptoServiceProvider instance and initialize with public key -----\n RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();\n RSAParameters RSAparams = new RSAParameters();\n RSAparams.Modulus =MODULUS;\n RSAparams.Exponent = E;\n RSAparams.D = D;\n RSAparams.P = P;\n RSAparams.Q = Q;\n RSAparams.DP = DP;\n RSAparams.DQ = DQ;\n RSAparams.InverseQ = IQ;\n RSA.ImportParameters(RSAparams);\n return RSA;\n }\n catch (Exception) {\n return null;\n }\n finally {\n binr.Close();\n }\n}\n"
},
{
"answer_id": 243787,
"author": "João Augusto",
"author_id": 6909,
"author_profile": "https://Stackoverflow.com/users/6909",
"pm_score": 1,
"selected": false,
"text": "using System.Security.Cryptography;\n\n\npublic static string DecryptEncryptedData(stringBase64EncryptedData, stringPathToPrivateKeyFile) { \n X509Certificate2 myCertificate; \n try{ \n myCertificate = new X509Certificate2(PathToPrivateKeyFile); \n } catch{ \n throw new CryptographicException(\"Unable to open key file.\"); \n } \n\n RSACryptoServiceProvider rsaObj; \n if(myCertificate.HasPrivateKey) { \n rsaObj = (RSACryptoServiceProvider)myCertificate.PrivateKey; \n } else \n throw new CryptographicException(\"Private key not contained within certificate.\"); \n\n if(rsaObj == null) \n return String.Empty; \n\n byte[] decryptedBytes; \n try{ \n decryptedBytes = rsaObj.Decrypt(Convert.FromBase64String(Base64EncryptedData), false); \n } catch { \n throw new CryptographicException(\"Unable to decrypt data.\"); \n } \n\n // Check to make sure we decrpyted the string \n if(decryptedBytes.Length == 0) \n return String.Empty; \n else \n return System.Text.Encoding.UTF8.GetString(decryptedBytes); \n} \n"
},
{
"answer_id": 248662,
"author": "Rasmus Faber",
"author_id": 5542,
"author_profile": "https://Stackoverflow.com/users/5542",
"pm_score": 2,
"selected": false,
"text": "-----BEGIN RSA PRIVATE KEY---- \n -----END RSA PRIVATE KEY----- \n"
},
{
"answer_id": 251757,
"author": "Simone",
"author_id": 32093,
"author_profile": "https://Stackoverflow.com/users/32093",
"pm_score": 7,
"selected": true,
"text": "var privateKey = @\"-----BEGIN RSA PRIVATE KEY-----\n{ the full PEM private key } \n-----END RSA PRIVATE KEY-----\";\n\nvar rsa = RSA.Create();\nrsa.ImportFromPem(privateKey.ToCharArray());\n\nvar decryptedBytes = rsa.Decrypt(\n Convert.FromBase64String(\"{ base64-encoded encrypted string }\"), \n RSAEncryptionPadding.Pkcs1\n);\n\n// this will print the original unencrypted string\nConsole.WriteLine(Encoding.UTF8.GetString(decryptedBytes));\n var bytesToDecrypt = Convert.FromBase64String(\"la0Cz.....D43g==\"); // string to decrypt, base64 encoded\n \nAsymmetricCipherKeyPair keyPair; \n \nusing (var reader = File.OpenText(@\"c:\\myprivatekey.pem\")) // file containing RSA PKCS1 private key\n keyPair = (AsymmetricCipherKeyPair) new PemReader(reader).ReadObject(); \n \nvar decryptEngine = new Pkcs1Encoding(new RsaEngine());\ndecryptEngine.Init(false, keyPair.Private); \n \nvar decrypted = Encoding.UTF8.GetString(decryptEngine.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length)); \n"
},
{
"answer_id": 5394967,
"author": "SeventhPath",
"author_id": 669498,
"author_profile": "https://Stackoverflow.com/users/669498",
"pm_score": 5,
"selected": false,
"text": "openssl pkcs12 -in a.crt -inkey a.key -export -out a.pfx\n using System.Security.Cryptography.X509Certificates;\n\nX509Certificate2 combinedCertificate = new X509Certificate2(@\"C:\\path\\to\\file.pfx\");\n X509KeyStorageFlags flags = X509KeyStorageFlags.Exportable;\nX509Certificate2 cert = new X509Certificate2(\"my.pfx\", \"somepass\", flags);\n\nRSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert.PrivateKey;\nRSAParameters rsaParam = rsa.ExportParameters(true); \n"
},
{
"answer_id": 19579157,
"author": "The Lazy Coder",
"author_id": 661229,
"author_profile": "https://Stackoverflow.com/users/661229",
"pm_score": 2,
"selected": false,
"text": "#/bin/sh\n\nssh-keygen -f host.key\nopenssl req -new -key host.key -out request.csr\nopenssl x509 -req -days 99999 -in request.csr -signkey host.key -out server.crt\nopenssl pkcs12 -export -inkey host.key -in server.crt -out private_public.p12 -name \"SslCert\"\nopenssl base64 -in private_public.p12 -out Base64.key\n chmod +x genkey.sh\n ./genkey.sh\n Enter pass phrase for host.key:\nEnter Export Password: {Important to enter a password here}\nVerifying - Enter Export Password: { Same password here }\n private string sslKey = \"MIIJiAIBA....................................\" +\n \"......................ETC....................\" +\n \"......................ETC....................\" +\n \"......................ETC....................\" +\n \".............ugICCAA=\";\n X509Certificate2 _serverCertificate = null;\nX509Certificate2 serverCertificate{\n get\n {\n if (_serverCertificate == null){\n string pass = \"Your Export Password Here\";\n _serverCertificate = new X509Certificate(Convert.FromBase64String(sslKey), pass, X509KeyStorageFlags.Exportable);\n }\n return _serverCertificate;\n }\n}\n SslStream sslStream = new SslStream(serverCertificate, false, SslProtocols.Tls, true);\n"
},
{
"answer_id": 43711671,
"author": "Jack Bond",
"author_id": 5875717,
"author_profile": "https://Stackoverflow.com/users/5875717",
"pm_score": 2,
"selected": false,
"text": " RSAparams.D = ConvertRSAParametersField(D, MODULUS.Length);\n RSAparams.DP = ConvertRSAParametersField(DP, P.Length);\n RSAparams.DQ = ConvertRSAParametersField(DQ, Q.Length);\n RSAparams.InverseQ = ConvertRSAParametersField(IQ, Q.Length);\n\n private static byte[] ConvertRSAParametersField(byte[] bs, int size)\n {\n if (bs.Length == size)\n return bs;\n\n if (bs.Length > size)\n throw new ArgumentException(\"Specified size too small\", \"size\");\n\n byte[] padded = new byte[size];\n Array.Copy(bs, 0, padded, size - bs.Length, bs.Length);\n return padded;\n }\n\n-----BEGIN RSA PRIVATE KEY-----\nMIIEoQIBAAKCAQEAxCgWAYJtfKBVa6Px1Blrj+3Wq7LVXDzx+MiQFrLCHnou2Fvb\nfxuDeRmd6ERhDWnsY6dxxm981vTlXukvYKpIZQYpiSzL5pyUutoi3yh0+/dVlsHZ\nUHheVGZjSMgUagUCLX1p/augXltAjgblUsj8GFBoKJBr3TMKuR5TwF7lBNYZlaiR\nk9MDZTROk6MBGiHEgD5RaPKA/ot02j3CnSGbGNNubN2tyXXAgk8/wBmZ4avT0U4y\n5oiO9iwCF/Hj9gK/S/8Q2lRsSppgUSsCioSg1CpdleYzIlCB0li1T0flB51zRIpg\nJhWRfmK1uTLklU33xfzR8zO2kkfaXoPTHSdOGQIDAQABAoIBAAkhfzoSwttKRgT8\nsgUYKdRJU0oqyO5s59aXf3LkX0+L4HexzvCGbK2hGPihi42poJdYSV4zUlxZ31N2\nXKjjRFDE41S/Vmklthv8i3hX1G+Q09XGBZekAsAVrrQfRtP957FhD83/GeKf3MwV\nBhe/GKezwSV3k43NvRy2N1p9EFa+i7eq1e5i7MyDxgKmja5YgADHb8izGLx8Smdd\n+v8EhWkFOcaPnQRj/LhSi30v/CjYh9MkxHMdi0pHMMCXleiUK0Du6tnsB8ewoHR3\noBzL4F5WKyNHPvesYplgTlpMiT0uUuN8+9Pq6qsdUiXs0wdFYbs693mUMekLQ4a+\n1FOWvQECgYEA7R+uI1r4oP82sTCOCPqPi+fXMTIOGkN0x/1vyMXUVvTH5zbwPp9E\n0lG6XmJ95alMRhjvFGMiCONQiSNOQ9Pec5TZfVn3M/w7QTMZ6QcWd6mjghc+dGGE\nURmCx8xaJb847vACir7M08AhPEt+s2C7ZokafPCoGe0qw/OD1fLt3NMCgYEA08WK\nS+G7dbCvFMrBP8SlmrnK4f5CRE3pV4VGneWp/EqJgNnWwaBCvUTIegDlqS955yVp\nq7nVpolAJCmlUVmwDt4gHJsWXSQLMXy3pwQ25vdnoPe97y3xXsi0KQqEuRjD1vmw\nK7SXoQqQeSf4z74pFal4CP38U3pivvoE4MQmJeMCfyJFceWqQEUEneL+IYkqrZSK\n7Y8urNse5MIC3yUlcose1cWVKyPh4RCEv2rk0U1gKqX29Jb9vO2L7RflAmrLNFuA\nJ+72EcRxsB68RAJqA9VHr1oeAejQL0+JYF2AK4dJG/FsvvFOokv4eNU+FBHY6Tzo\nk+t63NDidkvb5jIF6lsCgYEAlnQ08f5Y8Z9qdCosq8JpKYkwM+kxaVe1HUIJzqpZ\nX24RTOL3aa8TW2afy9YRVGbvg6IX9jJcMSo30Llpw2cl5xo21Dv24ot2DF2gGN+s\npeFF1Z3Naj1Iy99p5/KaIusOUBAq8pImW/qmc/1LD0T56XLyXekcuK4ts6Lrjkit\nFaMCgYAusOLTsRgKdgdDNI8nMQB9iSliwHAG1TqzB56S11pl+fdv9Mkbo8vrx6g0\nNM4DluCGNEqLZb3IkasXXdok9e8kmX1en1lb5GjyPbc/zFda6eZrwIqMX9Y68eNR\nIWDUM3ckwpw3rcuFXjFfa+w44JZVIsgdoGHiXAdrhtlG/i98Rw==\n-----END RSA PRIVATE KEY-----\n"
},
{
"answer_id": 51397431,
"author": "huysentruitw",
"author_id": 1300910,
"author_profile": "https://Stackoverflow.com/users/1300910",
"pm_score": 2,
"selected": false,
"text": "PM> Install-Package PemUtils\n PM> Install-Package DerConverter\n using (var stream = File.OpenRead(path))\nusing (var reader = new PemReader(stream))\n{\n var rsaParameters = reader.ReadRsaKey();\n // ...\n}\n"
},
{
"answer_id": 60423034,
"author": "starteleport",
"author_id": 1845402,
"author_profile": "https://Stackoverflow.com/users/1845402",
"pm_score": 2,
"selected": false,
"text": "PemException malformed sequence in RSA private key Org.BouncyCastle.OpenSsl.PemReader Org.BouncyCastle.Utilities.IO.Pem.PemReader private static RSAParameters GetRsaParameters(string rsaPrivateKey)\n{\n var byteArray = Encoding.ASCII.GetBytes(rsaPrivateKey);\n using (var ms = new MemoryStream(byteArray))\n {\n using (var sr = new StreamReader(ms))\n {\n var pemReader = new Org.BouncyCastle.Utilities.IO.Pem.PemReader(sr);\n var pem = pemReader.ReadPemObject();\n var privateKey = PrivateKeyFactory.CreateKey(pem.Content);\n\n return DotNetUtilities.ToRSAParameters(privateKey as RsaPrivateCrtKeyParameters);\n }\n }\n}\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32093/"
] |
243,683
|
<p>How do I extract the value of a property in a PropertyCollection?</p>
<p>If I drill down on the 'Properties' in the line below is visual studion I can see the value but how do I read it?</p>
<pre><code>foreach (string propertyName in result.Properties.PropertyNames)
{
MessageBox.Show(ProperyNames[0].Value.ToString()); <--Wrong!
}
</code></pre>
|
[
{
"answer_id": 243703,
"author": "steve",
"author_id": 32103,
"author_profile": "https://Stackoverflow.com/users/32103",
"pm_score": -1,
"selected": false,
"text": "foreach (string propertyName in result.Properties.PropertyNames)\n{ MessageBox.Show(properyName.ToString()); <--Wrong!\n}\n"
},
{
"answer_id": 243705,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "foreach (string propertyName in result.Properties.PropertyNames)\n{\n MessageBox.Show(result.Properties[propertyName].ToString());\n}\n foreach (object prop in result.Properties)\n{\n MessageBox.Show(prop.ToString());\n}\n"
},
{
"answer_id": 243715,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "foreach (string propertyName in result.Properties.PropertyNames)\n{\n MessageBox.Show(PropertyName.ToString());\n}\n"
},
{
"answer_id": 243725,
"author": "Stu Mackellar",
"author_id": 28591,
"author_profile": "https://Stackoverflow.com/users/28591",
"pm_score": 0,
"selected": false,
"text": "foreach (object value in result.Properties.Values)\n{ \n MessageBox.Show(property.ToString());\n}\n"
},
{
"answer_id": 243741,
"author": "thismat",
"author_id": 14045,
"author_profile": "https://Stackoverflow.com/users/14045",
"pm_score": 0,
"selected": false,
"text": "For Each prop As String In result.Properties.PropertyNames\n MessageBox.Show(result.Properties(prop).Item(0), result.Item(i).Properties(prt).Item(0))\nNext\n foreach (string property in result.Properties.PropertyNames)\n{\n MessageBox.Show(result.Properties[property].Item[0]);\n}\n"
},
{
"answer_id": 243785,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": " ResultPropertyValueCollection values = result.Properties[propertyName];\n if (propertyName == \"abctest\")\n { \n MessageBox.Show(values[0].ToString());\n }\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
243,691
|
<p>[Error] WARNING. Duplicate resource(s):
[Error] Type 2 (BITMAP), ID TWWDBRICHEDITMSWORD:
[Error] File C:\Borland\Delphi7\ip4000vcl7\LIB\wwrichsp.RES resource kept;
file C:\Borland\Delphi7\ip4000vcl7\LIB\wwrichsp.RES resource discarded.
I have searched the code for same named objects, like objects.
Can anyone give me a clue what else I can look for. </p>
|
[
{
"answer_id": 243890,
"author": "Lars Truijens",
"author_id": 1242,
"author_profile": "https://Stackoverflow.com/users/1242",
"pm_score": 2,
"selected": false,
"text": "{$R wwrichsp.RES}\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
243,696
|
<p>MathWorks currently doesn't allow you to use <code>cout</code> from a mex file when the MATLAB desktop is open because they have redirected stdout. Their current workaround is providing a function, <a href="http://www.mathworks.com/support/tech-notes/1600/1605.html" rel="nofollow noreferrer">mexPrintf, that they request you use instead</a>. After googling around a bit, I think that it's possible to extend the <code>std::stringbuf</code> class to do what I need. Here's what I have so far. Is this robust enough, or are there other methods I need to overload or a better way to do this? (Looking for portability in a general UNIX environment and the ability to use <code>std::cout</code> as normal if this code is not linked against a mex executable)</p>
<pre><code>class mstream : public stringbuf {
public:
virtual streamsize xsputn(const char *s, std::streamsize n)
{
mexPrintf("*s",s,n);
return basic_streambuf<char, std::char_traits<char>>::xsputn(s,n);
}
};
mstream mout;
outbuf = cout.rdbuf(mout.rdbuf());
</code></pre>
|
[
{
"answer_id": 244286,
"author": "Max Lybbert",
"author_id": 10593,
"author_profile": "https://Stackoverflow.com/users/10593",
"pm_score": 0,
"selected": false,
"text": "cout cout fstream ofstream cout rdbuf"
},
{
"answer_id": 244584,
"author": "Shane Powell",
"author_id": 23235,
"author_profile": "https://Stackoverflow.com/users/23235",
"pm_score": 4,
"selected": true,
"text": "std::stringbuf std::streambuf std::basic_streambuf cout ostream ostream cout ofstream cout mycout #include <streambuf>\n#include <ostream>\n\nclass mystream : public std::streambuf\n{\npublic:\n mystream() {}\n\nprotected:\n virtual int_type overflow(int_type c)\n {\n if(c != EOF)\n {\n char z = c;\n mexPrintf(\"%c\",c);\n return EOF;\n }\n return c;\n }\n\n virtual std::streamsize xsputn(const char* s, std::streamsize num)\n {\n mexPrintf(\"*s\",s,n);\n return num;\n }\n};\n\nclass myostream : public std::ostream\n{\nprotected:\n mystream buf;\n\npublic:\n myostream() : std::ostream(&buf) {}\n};\n\nmyostream mycout;\n typedef std::cout mycout;\n"
},
{
"answer_id": 249008,
"author": "user27315",
"author_id": 27315,
"author_profile": "https://Stackoverflow.com/users/27315",
"pm_score": 3,
"selected": false,
"text": "class mstream : public std::streambuf {\npublic:\nprotected:\n virtual std::streamsize xsputn(const char *s, std::streamsize n); \n virtual int overflow(int c = EOF);\n}; \n std::streamsize \nmstream::xsputn(const char *s, std::streamsize n) \n{\n mexPrintf(\"%.*s\",n,s);\n return n;\n}\n\nint \nmstream::overflow(int c) \n{\n if (c != EOF) {\n mexPrintf(\"%.1s\",&c);\n }\n return 1;\n}\n // Replace the std stream with the 'matlab' stream\n// Put this in the beginning of the mex function\nmstream mout;\nstd::streambuf *outbuf = std::cout.rdbuf(&mout); \n // Restore the std stream buffer \nstd::cout.rdbuf(outbuf); \n"
},
{
"answer_id": 41276477,
"author": "Cris Luengo",
"author_id": 7328782,
"author_profile": "https://Stackoverflow.com/users/7328782",
"pm_score": 2,
"selected": false,
"text": "std::cout class mxstreambuf : public std::streambuf {\n public:\n mxstreambuf() {\n stdoutbuf = std::cout.rdbuf( this );\n }\n ~mxstreambuf() {\n std::cout.rdbuf( stdoutbuf );\n }\n protected:\n virtual std::streamsize xsputn( const char* s, std::streamsize n ) override {\n mexPrintf( \"%.*s\", n, s );\n return n;\n }\n virtual int overflow( int c = EOF ) override {\n if( c != EOF ) {\n mexPrintf( \"%.1s\", & c );\n }\n return 1;\n }\n private:\n std::streambuf *stdoutbuf;\n};\n mxstreambuf mout;\nstd::cout << \"Hello World!\\n\";\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27315/"
] |
243,701
|
<p>I'd like to check a few queries generated by ActiveRecord, but I don't need to actually run them. Is there a way to get at the query before it returns its result?</p>
|
[
{
"answer_id": 243934,
"author": "Gene T",
"author_id": 413049,
"author_profile": "https://Stackoverflow.com/users/413049",
"pm_score": 2,
"selected": false,
"text": "construct_finder_sql,\n"
},
{
"answer_id": 1634280,
"author": "gtd",
"author_id": 8376,
"author_profile": "https://Stackoverflow.com/users/8376",
"pm_score": 0,
"selected": false,
"text": "ActiveRecord::Base.connection.instance_variable_set :@logger, Logger.new(STDOUT)\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1190/"
] |
243,712
|
<p>Hey! I was looking at this code at <a href="http://www.gnu.org/software/m68hc11/examples/primes_8c-source.html" rel="noreferrer">http://www.gnu.org/software/m68hc11/examples/primes_8c-source.html</a></p>
<p>I noticed that in some situations they used hex numbers, like in line 134:</p>
<pre><code>for (j = 1; val && j <= 0x80; j <<= 1, q++)
</code></pre>
<p>Now why would they use the 0x80? I am not that good with hex but I found an online hex to decimal and it gave me 128 for 0x80.</p>
<p>Also before line 134, on line 114 they have this:</p>
<pre><code>small_n = (n & 0xffff0000) == 0;
</code></pre>
<p>The hex to decimal gave me 4294901760 for that hex number.
So here in this line they are making a bit AND and comparing the result to 0??</p>
<p>Why not just use the number?
Can anyone please explain and please do give examples of other situations.</p>
<p>Also I have seen large lines of code where it's just hex numbers and never really understood why :(</p>
|
[
{
"answer_id": 243727,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 8,
"selected": true,
"text": "j 0000:0001 0000:0010 0000:0100 0000:1000 0001:0000 0010:0000 0100:0000 1000:0000 0x01 0x02 0x04 0x08 0x10 0x20 0x40 0x80 0x4996:02d2 0x4996:0000"
},
{
"answer_id": 243729,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 4,
"selected": false,
"text": "0xffff0000 0xffff0000 0x80"
},
{
"answer_id": 243783,
"author": "Lucas Gabriel Sánchez",
"author_id": 20601,
"author_profile": "https://Stackoverflow.com/users/20601",
"pm_score": 3,
"selected": false,
"text": "OxFF = 1111 1111 ( F = 1111 )\n 255 = 1111 1111 \n 255 / 2 = 127 (rest 1)\n127 / 2 = 63 (rest 1)\n63 / 2 = 31 (rest 1)\n... etc\n"
},
{
"answer_id": 244020,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "int mask = 0b00001111;\n #define b0 (0x00)\n#define b1 (0x01)\n#define b00 (0x00)\n#define b01 (0x01)\n#define b10 (0x02)\n#define b11 (0x03)\n#define b000 (0x00)\n#define b001 (0x01)\n...\n#define b11111110 (0xFE)\n#define b11111111 (0xFF)\n"
},
{
"answer_id": 244074,
"author": "mkClark",
"author_id": 30970,
"author_profile": "https://Stackoverflow.com/users/30970",
"pm_score": 3,
"selected": false,
"text": "#define bit_0 1\n#define bit_1 2\n#define bit_2 4\n#define bit_3 8\n#define bit_4 16\netc...\n #define bit_0 0x01\n#define bit_1 0x02\n#define bit_2 0x04\n#define bit_3 0x08\n#define bit_4 0x10\netc...\n #define bit_0 (1<<0)\n#define bit_1 (1<<1)\n#define bit_2 (1<<2)\n#define bit_3 (1<<3)\n#define bit_4 (1<<4)\netc...\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8715/"
] |
243,728
|
<p>I got dtd in file and I cant remove it. When i try to parse it in Java I get "Caused by: java.net.SocketException: Network is unreachable: connect", because its remote dtd. can I disable somehow dtd checking?</p>
|
[
{
"answer_id": 243747,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 5,
"selected": true,
"text": "<?xml version=\"1.0\"?>\n<!DOCTYPE foo PUBLIC \"//FOO//\" \"foo.dtd\">\n<foo>\n <bar>Value</bar>\n</foo>\n import java.io.File;\nimport java.io.IOException;\nimport java.io.StringReader;\n\nimport javax.xml.parsers.DocumentBuilder;\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.xpath.XPath;\nimport javax.xml.xpath.XPathFactory;\n\nimport org.w3c.dom.Document;\nimport org.xml.sax.EntityResolver;\nimport org.xml.sax.InputSource;\nimport org.xml.sax.SAXException;\n\npublic class Main {\n\n public static void main(String[] args) throws Exception {\n DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\n DocumentBuilder builder = factory.newDocumentBuilder();\n\n builder.setEntityResolver(new EntityResolver() {\n\n @Override\n public InputSource resolveEntity(String publicId, String systemId)\n throws SAXException, IOException {\n System.out.println(\"Ignoring \" + publicId + \", \" + systemId);\n return new InputSource(new StringReader(\"\"));\n }\n });\n Document document = builder.parse(new File(\"src/foo.xml\"));\n XPathFactory xpathFactory = XPathFactory.newInstance();\n XPath xpath = xpathFactory.newXPath();\n String content = xpath.evaluate(\"/foo/bar/text()\", document\n .getDocumentElement());\n System.out.println(content);\n }\n}\n"
},
{
"answer_id": 243757,
"author": "Owen",
"author_id": 2109,
"author_profile": "https://Stackoverflow.com/users/2109",
"pm_score": 2,
"selected": false,
"text": "<!DOCTYPE root-element SYSTEM \"filename\">\n"
},
{
"answer_id": 2357979,
"author": "David",
"author_id": 98109,
"author_profile": "https://Stackoverflow.com/users/98109",
"pm_score": 4,
"selected": false,
"text": " SAXParserFactory saxfac = SAXParserFactory.newInstance();\n saxfac.setValidating(false);\n try {\n saxfac.setFeature(\"http://xml.org/sax/features/validation\", false);\n saxfac.setFeature(\"http://apache.org/xml/features/nonvalidating/load-dtd-grammar\", false);\n saxfac.setFeature(\"http://apache.org/xml/features/nonvalidating/load-external-dtd\", false);\n saxfac.setFeature(\"http://xml.org/sax/features/external-general-entities\", false);\n saxfac.setFeature(\"http://xml.org/sax/features/external-parameter-entities\", false);\n }\n catch (Exception e1) {\n e1.printStackTrace();\n }\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30453/"
] |
243,734
|
<p>I am trying to compile a labview CIN using visual studio 2003.</p>
<p>I have followed the tutorial located <a href="http://zone.ni.com/devzone/cda/tut/p/id/3172" rel="nofollow noreferrer">here</a> to the letter, but am getting the following error:</p>
<blockquote>
<p>Project : error PRJ0019: A tool returned an error code from "Performing Custom Build Step"</p>
</blockquote>
<p>Does anyone know what is causing this? I tried this <a href="http://detritus.blogs.com/lycangeek/2006/03/building_cins_w.html" rel="nofollow noreferrer">link</a> found at an expert's exchange <a href="http://www.experts-exchange.com/Microsoft/Development/.NET/Visual_CPP/Q_23144843.html" rel="nofollow noreferrer">question</a> but it does not seem relevant.</p>
<p>Is there an easier way to build a CIN using visual studio?</p>
|
[
{
"answer_id": 243762,
"author": "Tim",
"author_id": 10755,
"author_profile": "https://Stackoverflow.com/users/10755",
"pm_score": 0,
"selected": false,
"text": "\"$(CINTOOLS_DIR)\\lvsbutil\" \"$(TargetName)\" -d \"$(ProjectDir)$(OutDir)\"\n $(OutDir)$(TargetName).lsb"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1555/"
] |
243,750
|
<p>I've searched around a bit for similar questions, but other than running one command or perhaps a few command with items such as:</p>
<pre><code>ssh user@host -t sudo su -
</code></pre>
<p>However, what if I essentially need to run a script on (let's say) 15 servers at once. Is this doable in bash? In a perfect world I need to avoid installing applications if at all possible to pull this off. For argument's sake, let's just say that I need to do the following across 10 hosts:</p>
<ol>
<li>Deploy a new Tomcat container</li>
<li>Deploy an application in the container, and configure it</li>
<li>Configure an Apache vhost</li>
<li>Reload Apache</li>
</ol>
<p>I have a script that does all of that, but it relies on me logging into all the servers, pulling a script down from a repo, and then running it. If this isn't doable in bash, what alternatives do you suggest? Do I need a bigger hammer, such as Perl (Python might be preferred since I can guarantee Python is on all boxes in a RHEL environment thanks to yum/up2date)? If anyone can point to me to any useful information it'd be greatly appreciated, especially if it's doable in bash. I'll settle for Perl or Python, but I just don't know those as well (working on that). Thanks!</p>
|
[
{
"answer_id": 243803,
"author": "antik",
"author_id": 1625,
"author_profile": "https://Stackoverflow.com/users/1625",
"pm_score": 3,
"selected": false,
"text": "man expect"
},
{
"answer_id": 243818,
"author": "Yang Zhao",
"author_id": 31095,
"author_profile": "https://Stackoverflow.com/users/31095",
"pm_score": 3,
"selected": false,
"text": "ssh -t user@host 'sh' < path_to_script\n"
},
{
"answer_id": 243917,
"author": "Bash",
"author_id": 16051,
"author_profile": "https://Stackoverflow.com/users/16051",
"pm_score": 4,
"selected": false,
"text": "ssh root@server /bin/sh <<\\EOF \nwget http://server/warfile # Could use NFS here \ncp app.war /location \ncommand 1 \ncommand 2 \n/etc/init.d/httpd restart \nEOF \n"
},
{
"answer_id": 244136,
"author": "dlamblin",
"author_id": 459,
"author_profile": "https://Stackoverflow.com/users/459",
"pm_score": 1,
"selected": false,
"text": "rsh sh perl ssh tomcatuser@server perl -e 'do-everything-on-one-line;' scp the_package.tbz tomcatuser@server:the_place/. ssh tomcatuser@server /bin/sh <<\\EOF TOMCAT_WEBAPPS=/usr/local/share/tomcat/webapps tar xj the_package.tbz rsync rsync://repository/the_package_place mv $TOMCAT_WEBAPPS/old_war $TOMCAT_WEBAPPS/old_war.old mv $THE_PLACE/new_war $TOMCAT_WEBAPPS/new_war touch $TOMCAT_WEBAPPS/new_war mv $THE_PLACE/vhost_file $APACHE_VHOST_DIR/vhost_file $APACHECTL restart EOF"
},
{
"answer_id": 245114,
"author": "Philip Durbin",
"author_id": 19464,
"author_profile": "https://Stackoverflow.com/users/19464",
"pm_score": 3,
"selected": false,
"text": "gsh for box in box1_name box2_name box3_name [pdurbin@beamish ~]$ gsh web \"cat /etc/redhat-release; uname -r\"\nwww-2.foo.com: Red Hat Enterprise Linux AS release 4 (Nahant Update 7)\nwww-2.foo.com: 2.6.9-78.0.1.ELsmp\nwww-3.foo.com: Red Hat Enterprise Linux AS release 4 (Nahant Update 7)\nwww-3.foo.com: 2.6.9-78.0.1.ELsmp\nwww-4.foo.com: Red Hat Enterprise Linux Server release 5.2 (Tikanga)\nwww-4.foo.com: 2.6.18-92.1.13.el5\nwww-5.foo.com: Red Hat Enterprise Linux Server release 5.2 (Tikanga)\nwww-5.foo.com: 2.6.18-92.1.13.el5\n[pdurbin@beamish ~]$\n"
},
{
"answer_id": 247048,
"author": "Steve Baker",
"author_id": 13566,
"author_profile": "https://Stackoverflow.com/users/13566",
"pm_score": 1,
"selected": false,
"text": "dsh -a /path/to/some/command/or/script\n"
},
{
"answer_id": 247589,
"author": "Jeremy Cantrell",
"author_id": 18866,
"author_profile": "https://Stackoverflow.com/users/18866",
"pm_score": 0,
"selected": false,
"text": "$ cat your_script.sh | ssh your_host bash\n"
},
{
"answer_id": 10389204,
"author": "Brad Montgomery",
"author_id": 182778,
"author_profile": "https://Stackoverflow.com/users/182778",
"pm_score": 2,
"selected": false,
"text": "fabfile.py from fabric.api import env, run\n\nenv.hosts = ['host1@example.com', 'host2@example.com']\n\ndef reload():\n \"\"\" Reload Apache \"\"\"\n run(\"sudo /etc/init.d/apache2 reload\")\n fab reload sudo /etc/init.d/apache2 reload env.hosts"
},
{
"answer_id": 10914809,
"author": "Quierati",
"author_id": 1439819,
"author_profile": "https://Stackoverflow.com/users/1439819",
"pm_score": 1,
"selected": false,
"text": "#Use in .bashrc\n#Use \"HashKnownHosts no\" in ~/.ssh/config or /etc/ssh/ssh_config \n# If known_hosts is encrypted and delete known_hosts\n\n[ ! -d ~/bin ] && mkdir ~/bin\nfor host in `cut -d, -f1 ~/.ssh/known_hosts|cut -f1 -d \" \"`;\n do\n [ ! -s ~/bin/$host ] && echo ssh $host '$*' > ~/bin/$host\ndone\n[ -d ~/bin ] && chmod -R 700 ~/bin\nexport PATH=$PATH:~/bin \n $for i in hostname{1..10}; do $i who;done\n"
},
{
"answer_id": 25556957,
"author": "user3438301",
"author_id": 3438301,
"author_profile": "https://Stackoverflow.com/users/3438301",
"pm_score": 0,
"selected": false,
"text": "#----------------------------------------------------------------------\n# Create a temp script to echo the SSH password, used by SSH_ASKPASS\n#----------------------------------------------------------------------\nSSH_ASKPASS_SCRIPT=/tmp/ssh-askpass-script\ncat > ${SSH_ASKPASS_SCRIPT} <<EOL\n#!/bin/bash\necho \"${PASS}\"\nEOL\nchmod u+x ${SSH_ASKPASS_SCRIPT}\n\n# Tell SSH to read in the output of the provided script as the password.\n# We still have to use setsid to eliminate access to a terminal and thus avoid\n# it ignoring this and asking for a password.\nexport SSH_ASKPASS=${SSH_ASKPASS_SCRIPT}\n......\n......\n# Log in to the remote server and run the above command.\n# The use of setsid is a part of the machinations to stop ssh \n# prompting for a password.\nsetsid ssh ${SSH_OPTIONS} ${USER}@${SERVER} \"ls -rlt\"\n"
},
{
"answer_id": 61327005,
"author": "Patoshi パトシ",
"author_id": 1642231,
"author_profile": "https://Stackoverflow.com/users/1642231",
"pm_score": 0,
"selected": false,
"text": "tmux\n ctrl-b + %\n ctrl+b <arrow-keys>\n ctrl+b :setw synchronize-panes on\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14838/"
] |
243,752
|
<p>Is there a way to do this without iterating through the List and adding the items to the ObservableCollection?</p>
|
[
{
"answer_id": 243766,
"author": "Nescio",
"author_id": 14484,
"author_profile": "https://Stackoverflow.com/users/14484",
"pm_score": 6,
"selected": true,
"text": "Dim list as new List(of string)\n...some stuff to fill the list...\nDim observable as new ObservableCollection(of string)(list)\n"
},
{
"answer_id": 1328283,
"author": "Junior Mayhé",
"author_id": 66708,
"author_profile": "https://Stackoverflow.com/users/66708",
"pm_score": 4,
"selected": false,
"text": "public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> coll)\n{\n var c = new ObservableCollection<T>();\n foreach (var e in coll) c.Add(e);\n return c;\n}\n List<Product> myProds = ......\nObservableCollection<Product> oc = new ObservableCollection<Product>(myProds);\n"
},
{
"answer_id": 5193871,
"author": "Jordan",
"author_id": 589774,
"author_profile": "https://Stackoverflow.com/users/589774",
"pm_score": 2,
"selected": false,
"text": "//Applications is an Observable Collection of Application in this example\nList<Application> filteredApplications = \n (Applications.Where( i => i.someBooleanDetail )).ToList();\nApplications = new ObservableCollection<Application>( filteredApplications );\n"
},
{
"answer_id": 7889816,
"author": "Joby Mavelikara",
"author_id": 1012779,
"author_profile": "https://Stackoverflow.com/users/1012779",
"pm_score": 2,
"selected": false,
"text": "//Create an observable collection TObservable.\n\nObservableCollection (TObservable) =new ObservableCollection (TObservable)();\n\n//Convert List items(OldListItems) to collection\n\nOldListItems.ForEach(x => TObservable.Add(x));\n"
},
{
"answer_id": 14027789,
"author": "Zin Min",
"author_id": 1927641,
"author_profile": "https://Stackoverflow.com/users/1927641",
"pm_score": 0,
"selected": false,
"text": "ObservableCollection<yourobjectname> result = new ObservableCollection<yourobjectname>(yourobjectlist);\n"
},
{
"answer_id": 21455199,
"author": "trix",
"author_id": 3252456,
"author_profile": "https://Stackoverflow.com/users/3252456",
"pm_score": 1,
"selected": false,
"text": "public static ObservableCollection<TDest> ToObservableCollection<TDest, TSource>(this IEnumerable<TSource> coll, Func<TSource, TDest> converter)\n {\n var c = new ObservableCollection<TDest>();\n foreach (var e in coll)\n {\n c.Add(converter(e));\n }\n return c;\n }\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/132931/"
] |
243,777
|
<p>do you know any not strict xpath for java? (I want it to not check dtd and schema) and it would be cool if it dont care about correct xml.</p>
|
[
{
"answer_id": 243866,
"author": "David M. Karr",
"author_id": 10508,
"author_profile": "https://Stackoverflow.com/users/10508",
"pm_score": 0,
"selected": false,
"text": "/*[local-name()='foo']/*[local-name()='bar']\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30453/"
] |
243,782
|
<p>I'm trying to select a column from a single table (no joins) and I need the count of the number of rows, ideally before I begin retrieving the rows. I have come to two approaches that provide the information I need.</p>
<p><strong>Approach 1:</strong></p>
<pre><code>SELECT COUNT( my_table.my_col ) AS row_count
FROM my_table
WHERE my_table.foo = 'bar'
</code></pre>
<p>Then</p>
<pre><code>SELECT my_table.my_col
FROM my_table
WHERE my_table.foo = 'bar'
</code></pre>
<p>Or <strong>Approach 2</strong></p>
<pre><code>SELECT my_table.my_col, ( SELECT COUNT ( my_table.my_col )
FROM my_table
WHERE my_table.foo = 'bar' ) AS row_count
FROM my_table
WHERE my_table.foo = 'bar'
</code></pre>
<p>I am doing this because my SQL driver (SQL Native Client 9.0) does not allow me to use SQLRowCount on a SELECT statement but I need to know the number of rows in my result in order to allocate an array before assigning information to it. The use of a dynamically allocated container is, unfortunately, not an option in this area of my program.</p>
<p>I am concerned that the following scenario might occur:</p>
<ul>
<li>SELECT for count occurs</li>
<li>Another instruction occurs, adding or removing a row</li>
<li>SELECT for data occurs and suddenly the array is the wrong size.<br>
-In the worse case, this will attempt to write data beyond the arrays limits and crash my program.</li>
</ul>
<p>Does Approach 2 prohibit this issue?</p>
<p>Also, Will one of the two approaches be faster? If so, which?</p>
<p>Finally, is there a better approach that I should consider (perhaps a way to instruct the driver to return the number of rows in a SELECT result using SQLRowCount?)</p>
<p>For those that asked, I am using Native C++ with the aforementioned SQL driver (provided by Microsoft.)</p>
|
[
{
"answer_id": 243963,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 2,
"selected": false,
"text": "SELECT \n mt.my_row,\n (SELECT COUNT(mt2.my_row) FROM my_table mt2 WHERE mt2.foo = mt.foo) as cnt\nFROM my_table mt\nWHERE mt.foo = 'bar';\n"
},
{
"answer_id": 244043,
"author": "Joe Pineda",
"author_id": 21258,
"author_profile": "https://Stackoverflow.com/users/21258",
"pm_score": 2,
"selected": false,
"text": "BEGIN TRAN bogus\n\nSELECT COUNT( my_table.my_col ) AS row_count\nFROM my_table\nWHERE my_table.foo = 'bar'\n\nSELECT my_table.my_col\nFROM my_table\nWHERE my_table.foo = 'bar'\nROLLBACK TRAN bogus\n DECLARE @dummy INT\n\nSELECT my_table.my_col\nINTO #temp_table\nFROM my_table\nWHERE my_table.foo = 'bar'\n\nSET @dummy=@@ROWCOUNT\nSELECT @dummy, * FROM #temp_table\n"
},
{
"answer_id": 244128,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 5,
"selected": true,
"text": "COUNT(*) COUNT(*) SNAPSHOT SERIALIZABLE SET TRANSACTION ISOLATION"
},
{
"answer_id": 244132,
"author": "Adam Porad",
"author_id": 21353,
"author_profile": "https://Stackoverflow.com/users/21353",
"pm_score": 5,
"selected": false,
"text": "SELECT my_table.my_col\n FROM my_table\n WHERE my_table.foo = 'bar'\n\nSELECT @@Rowcount\n SELECT my_table.my_col,\n count(*) OVER(PARTITION BY my_table.foo) AS 'Count'\n FROM my_table\n WHERE my_table.foo = 'bar'\n SELECT my_table.my_col, count(*) OVER() AS 'Count'\n FROM my_table\n WHERE my_table.foo = 'bar'\n"
},
{
"answer_id": 3388687,
"author": "Deepfreezed",
"author_id": 318089,
"author_profile": "https://Stackoverflow.com/users/318089",
"pm_score": 0,
"selected": false,
"text": "IF (@@ROWCOUNT > 0)\nBEGIN\nSELECT my_table.my_col\n FROM my_table\n WHERE my_table.foo = 'bar'\nEND\n"
},
{
"answer_id": 30139525,
"author": "Tschallacka",
"author_id": 1356107,
"author_profile": "https://Stackoverflow.com/users/1356107",
"pm_score": 0,
"selected": false,
"text": "WITH temptable AS\n (SELECT one,two\n FROM\n (SELECT one, two\n FROM table3\n WHERE dimension=0\n UNION ALL SELECT one, two\n FROM table2\n WHERE dimension=0\n UNION ALL SELECT one, two\n FROM table1\n WHERE dimension=0)\n ORDER BY date DESC)\nSELECT *\nFROM temptable\nLEFT JOIN\n (SELECT count(*)/7 AS cnt,\n 0 AS bonus\n FROM temptable) counter\nWHERE 0 = counter.bonus\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1625/"
] |
243,790
|
<p>I have this table in an Oracle DB which has a primary key defined on 3 of the data columns. I want to drop the primary key constraint to allow rows with duplicate data for those columns, and create a new column, 'id', to contain an auto-incrementing integer ID for these rows. I know how to create a sequence and trigger to add an auto-incrementing ID for new rows added to the table, but is it possible to write a PL/SQL statement to add unique IDs to all the rows that are already in the table?</p>
|
[
{
"answer_id": 243838,
"author": "Steve",
"author_id": 15470,
"author_profile": "https://Stackoverflow.com/users/15470",
"pm_score": 2,
"selected": false,
"text": "update\ntable\nset id = rownum\n"
},
{
"answer_id": 244080,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 4,
"selected": true,
"text": "update mytable\nset id = mysequence.nextval;\n"
},
{
"answer_id": 245100,
"author": "DCookie",
"author_id": 8670,
"author_profile": "https://Stackoverflow.com/users/8670",
"pm_score": 2,
"selected": false,
"text": "UPDATE your_table\n SET id = your_seq.nextval;\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3101/"
] |
243,794
|
<p>I'm using the latest version of the <a href="https://jqueryui.com/tabs/" rel="nofollow noreferrer">jQuery UI tabs</a>. I have tabs positioned toward the bottom of the page. </p>
<p>Every time I click a tab, the screen jumps toward the top.</p>
<p>How can I prevent this from happening?</p>
<p>Please see this example:</p>
<p><a href="http://5bosses.com/examples/tabs/sample_tabs.html" rel="nofollow noreferrer">http://5bosses.com/examples/tabs/sample_tabs.html</a></p>
|
[
{
"answer_id": 243832,
"author": "changelog",
"author_id": 5646,
"author_profile": "https://Stackoverflow.com/users/5646",
"pm_score": 4,
"selected": false,
"text": "<a href=\"#\" onclick=\"activateTab('tab1');\">Tab 1</a> return false; <a href=\"#\" onclick=\"activateTab('tab1'); return false;\">Tab 1</a>"
},
{
"answer_id": 244622,
"author": "Edward",
"author_id": 31869,
"author_profile": "https://Stackoverflow.com/users/31869",
"pm_score": 2,
"selected": false,
"text": "<li class=\"\"><a href=\"#fragment-2\"><span>Two</span></a></li>\n <li class=\"\"><a href=\"#fragment-2\" onclick=\"return false;\"><span>Two</span></a></li>\n"
},
{
"answer_id": 245099,
"author": "Brian Ramsay",
"author_id": 3078,
"author_profile": "https://Stackoverflow.com/users/3078",
"pm_score": 3,
"selected": false,
"text": " // Show a tab, animation prevents browser scrolling to fragment,\n $('.tab_container > ul').tabs(); \n$('.tab_container > ul').tabs({ fx: { height: 'toggle', opacity: 'toggle', duration: 'fast' } });\n $('.tab_container > ul').tabs(); \n//$('.tab_container > ul').tabs({ fx: { height: 'toggle', opacity: 'toggle', duration: 'fast' } });\n var scroll_to_x = 0;\nvar scroll_to_y = 0;\n$('.ui-tabs-nav').bind('tabsselect', function(event, ui) {\n scroll_to_x = window.pageXOffset;\n scroll_to_y = window.pageYOffset;\n});\n$('.ui-tabs-nav').bind('tabsshow', function(event, ui) {\n window.scroll(scroll_to_x, scroll_to_y);\n});\n"
},
{
"answer_id": 245424,
"author": "edt",
"author_id": 32242,
"author_profile": "https://Stackoverflow.com/users/32242",
"pm_score": 1,
"selected": false,
"text": "> var scroll_to_x = 0; var scroll_to_y =\n> 0;\n> $('.ui-tabs-nav').bind('tabsselect',\n> function(event, ui) {\n> scroll_to_x = window.pageXOffset;\n> scroll_to_y = window.pageYOffset; }); $('.ui-tabs-nav').bind('tabsshow',\n> function(event, ui) {\n> window.scroll(scroll_to_x, scroll_to_y); });\n"
},
{
"answer_id": 1635723,
"author": "Mike Petrovich",
"author_id": 197895,
"author_profile": "https://Stackoverflow.com/users/197895",
"pm_score": 6,
"selected": false,
"text": ".tabs({ fx: { opacity: 'toggle' } }); jQuery('#tabs').tabs({\n fx: { opacity: 'toggle' },\n select: function(event, ui) {\n jQuery(this).css('height', jQuery(this).height());\n jQuery(this).css('overflow', 'hidden');\n },\n show: function(event, ui) {\n jQuery(this).css('height', 'auto');\n jQuery(this).css('overflow', 'visible');\n }\n});\n"
},
{
"answer_id": 3855437,
"author": "FDisk",
"author_id": 175404,
"author_profile": "https://Stackoverflow.com/users/175404",
"pm_score": -1,
"selected": false,
"text": "fx: {opacity:'toggle', duration:100}\n"
},
{
"answer_id": 9856531,
"author": "Tomas",
"author_id": 684229,
"author_profile": "https://Stackoverflow.com/users/684229",
"pm_score": 2,
"selected": false,
"text": "$(...).tabs({\n beforeActivate: function(event, ui) {\n $(this).data('scrollTop', $(window).scrollTop()); // save scrolltop\n },\n activate: function(event, ui) {\n if (!$(this).data('scrollTop')) { // there was no scrolltop before\n jQuery('html').css('height', 'auto'); // reset back to auto...\n // this may not work on page where originally\n // the html tag was of a fixed height...\n return;\n }\n //console.log('activate: scrolltop pred = ' + $(this).data('scrollTop') + ', nyni = ' + $(window).scrollTop());\n if ($(window).scrollTop() == $(this).data('scrollTop')) // the scrolltop was not moved\n return; // nothing to be done\n // scrolltop moved - we need to fix it\n var min_height = $(this).data('scrollTop') + $(window).height();\n // minimum height the document must have to have that scrollTop\n if ($('html').outerHeight() < min_height) { // just a test to be sure\n // but this test should be always true\n /* be sure to use $('html').height() instead of $(document).height()\n because the document height is always >= window height!\n Not what you want. And to handle potential html padding, be sure\n to use outerHeight instead!\n Now enlarge the html tag (unfortunatelly cannot set\n $(document).height()) - we want to set min_height\n as html's outerHeight:\n */\n $('html').height(min_height -\n ($('html').outerHeight() - $('html').height()));\n }\n $(window).scrollTop($(this).data('scrollTop')); // finally, set it back\n }\n});\n fx"
},
{
"answer_id": 17619122,
"author": "Zach Johnson",
"author_id": 1154738,
"author_profile": "https://Stackoverflow.com/users/1154738",
"pm_score": 2,
"selected": false,
"text": " $(\"ul.ui-menu li a\").click(function(e) {\n e.preventDefault();\n });\n"
},
{
"answer_id": 23339446,
"author": "Alexander Georgiev",
"author_id": 2604345,
"author_profile": "https://Stackoverflow.com/users/2604345",
"pm_score": 2,
"selected": false,
"text": "event.preventDefault(); $(function() {\n var $tabs = $('#measureTabs').tabs();\n $(\".btn-contiue\").click(function (event) {\n event.preventDefault();\n $( \"#measureTabs\" ).tabs( \"option\", \"active\", $(\"#measureTabs\").tabs ('option', 'active')+1 );\n });\n });\n"
},
{
"answer_id": 28317149,
"author": "Zeihlis",
"author_id": 2866076,
"author_profile": "https://Stackoverflow.com/users/2866076",
"pm_score": 1,
"selected": false,
"text": "$(\"#tabs\").tabs({\n hide: {\n effect: \"fade\",\n duration: \"500\"\n },\n show: {\n effect: \"fade\",\n duration: \"500\"\n }\n});\n show $(\"#tabs\").tabs({\n hide: {\n effect: \"fade\",\n duration: \"500\"\n }\n });\n"
},
{
"answer_id": 37106368,
"author": "Bill Searle",
"author_id": 2484389,
"author_profile": "https://Stackoverflow.com/users/2484389",
"pm_score": 0,
"selected": false,
"text": "href=#example1 id $('.nav-tabs li a').click( function(e) {\n e.preventDefault();\n});"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31869/"
] |
243,800
|
<p><strong>The Situation</strong></p>
<p>I have an area of the screen that can be shown and hidden via JavaScript (something like "show/hide advanced search options"). Inside this area there are form elements (select, checkbox, etc). For users using assistive technology like a screen-reader (in this case JAWS), we need to link these form elements with a label or use the "title" attribute to describe the purpose of each element. I'm using the title attribute because there isn't enough space for a label, and the tooltip you get is nice for non-screen-reader users.</p>
<p>The code looks something like this:</p>
<pre><code><div id="placeholder" style="display:none;">
<select title="Month">
<option>January</option>
<option>February</option>
...
</select>
</div>
</code></pre>
<p><strong>The Problem</strong></p>
<p>Normally, JAWS will not read hidden elements... because well, they're hidden and it knows that. However, it seems as though if the element has a title set, JAWS reads it no matter what. If I remove the title, JAWS reads nothing, but obviously this is in-accessible markup.</p>
<p><strong>Possible Solutions</strong></p>
<p>My first thought was to use a hidden label instead of the title, like this:</p>
<pre><code><div id="placeholder" style="display:none;">
<label for="month" style="display:none">Month</label>
<select id="month">...</select>
</div>
</code></pre>
<p>This results in the exact same behavior, and now we lose the tool-tips for non-screen-reader users. Also we end up generating twice as much Html.</p>
<p>The second option is to still use a label, put position it off the screen. That way it will be read by the screen-reader, but won't be seen by the visual user:</p>
<pre><code><div id="placeholder" style="display:none;">
<label for="month" style="position:absolute;left:-5000px:width:1px;">Month</label>
<select id="month">...</select>
</div>
</code></pre>
<p>This actually works, but again we lose the tool-tip and still generate additional Html.</p>
<p>My third possible solution is to recursively travel through the DOM in JavaScript, removing the title when the area is hidden and adding it back when the area is shown. This also works... but is pretty ugly for obvious reasons and doesn't really scale well to a more general case.</p>
<p>Any other ideas anyone? Why is JAWS behaving this way?</p>
|
[
{
"answer_id": 29660365,
"author": "Noah Herron",
"author_id": 2612003,
"author_profile": "https://Stackoverflow.com/users/2612003",
"pm_score": 0,
"selected": false,
"text": "<div id=\"placeholder\" style=\"display:none;\">\n <select title=\"Month\" style=\"speak:none;\">\n <option>January</option>\n <option>February</option>\n ...\n </select>\n</div>\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9960/"
] |
243,811
|
<p>Looking through some code I came across the following code</p>
<pre><code>trTuDocPackTypdBd.update(TrTuDocPackTypeDto.class.cast(packDto));
</code></pre>
<p>and I'd like to know if casting this way has any advantages over </p>
<pre><code>trTuDocPackTypdBd.update((TrTuDocPackTypeDto)packDto);
</code></pre>
<p>I've asked the developer responsible and he said he used it because it was new (which doesn't seem like a particularly good reason to me), but I'm intrigued when I would want to use the method.</p>
|
[
{
"answer_id": 243835,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "T Class<? extends T> T"
},
{
"answer_id": 243862,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 5,
"selected": true,
"text": "invokevirtual checkcast (TrTuDocPackTypeDto) packDto cast public <T> Set<T> find(Class<T> clz, Filter criteria) {\n List<?> raw = session.find(clz, criteria); /* A legacy, un-generic API. */\n Set<T> safe = new HashSet<T>();\n for (Object o : raw) \n safe.add(clz.cast(o));\n return safe;\n}\n /* DO NOT DO THIS! */\nList raw = new ArrayList();\n...\nreturn (List<Widget>) raw;\n Unchecked cast from List to List<Widget> Gadget ClassCastException Widget"
},
{
"answer_id": 643667,
"author": "phtrivier",
"author_id": 77804,
"author_profile": "https://Stackoverflow.com/users/77804",
"pm_score": 0,
"selected": false,
"text": "/**\n * Casts an object to the class or interface represented\n * by this <tt>Class</tt> object.\n *\n * @param obj the object to be cast\n * @return the object after casting, or null if obj is null\n *\n * @throws ClassCastException if the object is not\n * null and is not assignable to the type T.\n *\n * @since 1.5\n */\npublic T cast(Object obj) {\nif (obj != null && !isInstance(obj))\n throw new ClassCastException();\nreturn (T) obj;\n}\n"
},
{
"answer_id": 643722,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 0,
"selected": false,
"text": "trTuDocPackTypdBd.update(TrTuDocPackTypeDto.class.cast(packDto));\n public void dynamicCast( Class clazz, Object o ) { \n this.x = clazz.cast( o );\n}\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4389/"
] |
243,814
|
<p>I am attempting to deploy .NET 2.0 web services on IIS that has both 1.0 and 2.0 installed. This web server primarily serves a large .NET 1.0 application. </p>
<p>I have copied by .NET 2.0 web service project to the server and have created a virtual directory to point to the necessary folder. </p>
<p>When I set the ASP.NET version to 2.0 in IIS, The application prompts me for a username and password (when I attempt to open the site in the browser), If I set it back to 1.0, then I am not prompted for a password, but obviously get a full application error. </p>
<p>I have anonymous access enabled (with a username / password) and have authenticated access checked as "Integrated Windows Authentication)</p>
<p>How can I configure IIS so that I am not prompted for a password while having ASP.NET version set to 2.0?</p>
<p>Thanks...</p>
<p><strong>EDIT</strong> I had major connection problems and apparently created some duplicate posts...I'll delete the ones with no answers. </p>
|
[
{
"answer_id": 243835,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "T Class<? extends T> T"
},
{
"answer_id": 243862,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 5,
"selected": true,
"text": "invokevirtual checkcast (TrTuDocPackTypeDto) packDto cast public <T> Set<T> find(Class<T> clz, Filter criteria) {\n List<?> raw = session.find(clz, criteria); /* A legacy, un-generic API. */\n Set<T> safe = new HashSet<T>();\n for (Object o : raw) \n safe.add(clz.cast(o));\n return safe;\n}\n /* DO NOT DO THIS! */\nList raw = new ArrayList();\n...\nreturn (List<Widget>) raw;\n Unchecked cast from List to List<Widget> Gadget ClassCastException Widget"
},
{
"answer_id": 643667,
"author": "phtrivier",
"author_id": 77804,
"author_profile": "https://Stackoverflow.com/users/77804",
"pm_score": 0,
"selected": false,
"text": "/**\n * Casts an object to the class or interface represented\n * by this <tt>Class</tt> object.\n *\n * @param obj the object to be cast\n * @return the object after casting, or null if obj is null\n *\n * @throws ClassCastException if the object is not\n * null and is not assignable to the type T.\n *\n * @since 1.5\n */\npublic T cast(Object obj) {\nif (obj != null && !isInstance(obj))\n throw new ClassCastException();\nreturn (T) obj;\n}\n"
},
{
"answer_id": 643722,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 0,
"selected": false,
"text": "trTuDocPackTypdBd.update(TrTuDocPackTypeDto.class.cast(packDto));\n public void dynamicCast( Class clazz, Object o ) { \n this.x = clazz.cast( o );\n}\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] |
243,816
|
<p>How to validate iscontrolkeys in textbox keydown event in .net?</p>
|
[
{
"answer_id": 243879,
"author": "Russ Cam",
"author_id": 1831,
"author_profile": "https://Stackoverflow.com/users/1831",
"pm_score": 0,
"selected": false,
"text": " private void textBox1_KeyDown(object sender, KeyEventArgs e)\n {\n if (e.KeyCode == Keys.ControlKey)\n {\n //Do some work\n }\n }\n Private Sub textBox1_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs)\n If e.KeyCode = Keys.ControlKey Then\n 'Do some work'\n End If\n End Sub\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
243,831
|
<p>Is there a way to get the Unicode Block of a character in python? The <a href="http://www.python.org/doc/2.5.2/lib/module-unicodedata.html" rel="noreferrer">unicodedata</a> module doesn't seem to have what I need, and I couldn't find an external library for it.</p>
<p>Basically, I need the same functionality as <a href="http://java.sun.com/javase/6/docs/api/java/lang/Character.UnicodeBlock.html#of(char)" rel="noreferrer"><code>Character.UnicodeBlock.of()</code></a> in java.</p>
|
[
{
"answer_id": 245072,
"author": "zaphod",
"author_id": 13871,
"author_profile": "https://Stackoverflow.com/users/13871",
"pm_score": 5,
"selected": true,
"text": "unicodedata bisect struct def block(ch):\n '''\n Return the Unicode block name for ch, or None if ch has no block.\n\n >>> block(u'a')\n 'Basic Latin'\n >>> block(unichr(0x0b80))\n 'Tamil'\n >>> block(unichr(0xe0080))\n\n '''\n\n assert isinstance(ch, unicode) and len(ch) == 1, repr(ch)\n cp = ord(ch)\n for start, end, name in _blocks:\n if start <= cp <= end:\n return name\n\ndef _initBlocks(text):\n global _blocks\n _blocks = []\n import re\n pattern = re.compile(r'([0-9A-F]+)\\.\\.([0-9A-F]+);\\ (\\S.*\\S)')\n for line in text.splitlines():\n m = pattern.match(line)\n if m:\n start, end, name = m.groups()\n _blocks.append((int(start, 16), int(end, 16), name))\n\n# retrieved from http://unicode.org/Public/UNIDATA/Blocks.txt\n_initBlocks('''\n# Blocks-12.0.0.txt\n# Date: 2018-07-30, 19:40:00 GMT [KW]\n# © 2018 Unicode®, Inc.\n# For terms of use, see http://www.unicode.org/terms_of_use.html\n#\n# Unicode Character Database\n# For documentation, see http://www.unicode.org/reports/tr44/\n#\n# Format:\n# Start Code..End Code; Block Name\n\n# ================================================\n\n# Note: When comparing block names, casing, whitespace, hyphens,\n# and underbars are ignored.\n# For example, \"Latin Extended-A\" and \"latin extended a\" are equivalent.\n# For more information on the comparison of property values,\n# see UAX #44: http://www.unicode.org/reports/tr44/\n#\n# All block ranges start with a value where (cp MOD 16) = 0,\n# and end with a value where (cp MOD 16) = 15. In other words,\n# the last hexadecimal digit of the start of range is ...0\n# and the last hexadecimal digit of the end of range is ...F.\n# This constraint on block ranges guarantees that allocations\n# are done in terms of whole columns, and that code chart display\n# never involves splitting columns in the charts.\n#\n# All code points not explicitly listed for Block\n# have the value No_Block.\n\n# Property: Block\n#\n# @missing: 0000..10FFFF; No_Block\n\n0000..007F; Basic Latin\n0080..00FF; Latin-1 Supplement\n0100..017F; Latin Extended-A\n0180..024F; Latin Extended-B\n0250..02AF; IPA Extensions\n02B0..02FF; Spacing Modifier Letters\n0300..036F; Combining Diacritical Marks\n0370..03FF; Greek and Coptic\n0400..04FF; Cyrillic\n0500..052F; Cyrillic Supplement\n0530..058F; Armenian\n0590..05FF; Hebrew\n0600..06FF; Arabic\n0700..074F; Syriac\n0750..077F; Arabic Supplement\n0780..07BF; Thaana\n07C0..07FF; NKo\n0800..083F; Samaritan\n0840..085F; Mandaic\n0860..086F; Syriac Supplement\n08A0..08FF; Arabic Extended-A\n0900..097F; Devanagari\n0980..09FF; Bengali\n0A00..0A7F; Gurmukhi\n0A80..0AFF; Gujarati\n0B00..0B7F; Oriya\n0B80..0BFF; Tamil\n0C00..0C7F; Telugu\n0C80..0CFF; Kannada\n0D00..0D7F; Malayalam\n0D80..0DFF; Sinhala\n0E00..0E7F; Thai\n0E80..0EFF; Lao\n0F00..0FFF; Tibetan\n1000..109F; Myanmar\n10A0..10FF; Georgian\n1100..11FF; Hangul Jamo\n1200..137F; Ethiopic\n1380..139F; Ethiopic Supplement\n13A0..13FF; Cherokee\n1400..167F; Unified Canadian Aboriginal Syllabics\n1680..169F; Ogham\n16A0..16FF; Runic\n1700..171F; Tagalog\n1720..173F; Hanunoo\n1740..175F; Buhid\n1760..177F; Tagbanwa\n1780..17FF; Khmer\n1800..18AF; Mongolian\n18B0..18FF; Unified Canadian Aboriginal Syllabics Extended\n1900..194F; Limbu\n1950..197F; Tai Le\n1980..19DF; New Tai Lue\n19E0..19FF; Khmer Symbols\n1A00..1A1F; Buginese\n1A20..1AAF; Tai Tham\n1AB0..1AFF; Combining Diacritical Marks Extended\n1B00..1B7F; Balinese\n1B80..1BBF; Sundanese\n1BC0..1BFF; Batak\n1C00..1C4F; Lepcha\n1C50..1C7F; Ol Chiki\n1C80..1C8F; Cyrillic Extended-C\n1C90..1CBF; Georgian Extended\n1CC0..1CCF; Sundanese Supplement\n1CD0..1CFF; Vedic Extensions\n1D00..1D7F; Phonetic Extensions\n1D80..1DBF; Phonetic Extensions Supplement\n1DC0..1DFF; Combining Diacritical Marks Supplement\n1E00..1EFF; Latin Extended Additional\n1F00..1FFF; Greek Extended\n2000..206F; General Punctuation\n2070..209F; Superscripts and Subscripts\n20A0..20CF; Currency Symbols\n20D0..20FF; Combining Diacritical Marks for Symbols\n2100..214F; Letterlike Symbols\n2150..218F; Number Forms\n2190..21FF; Arrows\n2200..22FF; Mathematical Operators\n2300..23FF; Miscellaneous Technical\n2400..243F; Control Pictures\n2440..245F; Optical Character Recognition\n2460..24FF; Enclosed Alphanumerics\n2500..257F; Box Drawing\n2580..259F; Block Elements\n25A0..25FF; Geometric Shapes\n2600..26FF; Miscellaneous Symbols\n2700..27BF; Dingbats\n27C0..27EF; Miscellaneous Mathematical Symbols-A\n27F0..27FF; Supplemental Arrows-A\n2800..28FF; Braille Patterns\n2900..297F; Supplemental Arrows-B\n2980..29FF; Miscellaneous Mathematical Symbols-B\n2A00..2AFF; Supplemental Mathematical Operators\n2B00..2BFF; Miscellaneous Symbols and Arrows\n2C00..2C5F; Glagolitic\n2C60..2C7F; Latin Extended-C\n2C80..2CFF; Coptic\n2D00..2D2F; Georgian Supplement\n2D30..2D7F; Tifinagh\n2D80..2DDF; Ethiopic Extended\n2DE0..2DFF; Cyrillic Extended-A\n2E00..2E7F; Supplemental Punctuation\n2E80..2EFF; CJK Radicals Supplement\n2F00..2FDF; Kangxi Radicals\n2FF0..2FFF; Ideographic Description Characters\n3000..303F; CJK Symbols and Punctuation\n3040..309F; Hiragana\n30A0..30FF; Katakana\n3100..312F; Bopomofo\n3130..318F; Hangul Compatibility Jamo\n3190..319F; Kanbun\n31A0..31BF; Bopomofo Extended\n31C0..31EF; CJK Strokes\n31F0..31FF; Katakana Phonetic Extensions\n3200..32FF; Enclosed CJK Letters and Months\n3300..33FF; CJK Compatibility\n3400..4DBF; CJK Unified Ideographs Extension A\n4DC0..4DFF; Yijing Hexagram Symbols\n4E00..9FFF; CJK Unified Ideographs\nA000..A48F; Yi Syllables\nA490..A4CF; Yi Radicals\nA4D0..A4FF; Lisu\nA500..A63F; Vai\nA640..A69F; Cyrillic Extended-B\nA6A0..A6FF; Bamum\nA700..A71F; Modifier Tone Letters\nA720..A7FF; Latin Extended-D\nA800..A82F; Syloti Nagri\nA830..A83F; Common Indic Number Forms\nA840..A87F; Phags-pa\nA880..A8DF; Saurashtra\nA8E0..A8FF; Devanagari Extended\nA900..A92F; Kayah Li\nA930..A95F; Rejang\nA960..A97F; Hangul Jamo Extended-A\nA980..A9DF; Javanese\nA9E0..A9FF; Myanmar Extended-B\nAA00..AA5F; Cham\nAA60..AA7F; Myanmar Extended-A\nAA80..AADF; Tai Viet\nAAE0..AAFF; Meetei Mayek Extensions\nAB00..AB2F; Ethiopic Extended-A\nAB30..AB6F; Latin Extended-E\nAB70..ABBF; Cherokee Supplement\nABC0..ABFF; Meetei Mayek\nAC00..D7AF; Hangul Syllables\nD7B0..D7FF; Hangul Jamo Extended-B\nD800..DB7F; High Surrogates\nDB80..DBFF; High Private Use Surrogates\nDC00..DFFF; Low Surrogates\nE000..F8FF; Private Use Area\nF900..FAFF; CJK Compatibility Ideographs\nFB00..FB4F; Alphabetic Presentation Forms\nFB50..FDFF; Arabic Presentation Forms-A\nFE00..FE0F; Variation Selectors\nFE10..FE1F; Vertical Forms\nFE20..FE2F; Combining Half Marks\nFE30..FE4F; CJK Compatibility Forms\nFE50..FE6F; Small Form Variants\nFE70..FEFF; Arabic Presentation Forms-B\nFF00..FFEF; Halfwidth and Fullwidth Forms\nFFF0..FFFF; Specials\n10000..1007F; Linear B Syllabary\n10080..100FF; Linear B Ideograms\n10100..1013F; Aegean Numbers\n10140..1018F; Ancient Greek Numbers\n10190..101CF; Ancient Symbols\n101D0..101FF; Phaistos Disc\n10280..1029F; Lycian\n102A0..102DF; Carian\n102E0..102FF; Coptic Epact Numbers\n10300..1032F; Old Italic\n10330..1034F; Gothic\n10350..1037F; Old Permic\n10380..1039F; Ugaritic\n103A0..103DF; Old Persian\n10400..1044F; Deseret\n10450..1047F; Shavian\n10480..104AF; Osmanya\n104B0..104FF; Osage\n10500..1052F; Elbasan\n10530..1056F; Caucasian Albanian\n10600..1077F; Linear A\n10800..1083F; Cypriot Syllabary\n10840..1085F; Imperial Aramaic\n10860..1087F; Palmyrene\n10880..108AF; Nabataean\n108E0..108FF; Hatran\n10900..1091F; Phoenician\n10920..1093F; Lydian\n10980..1099F; Meroitic Hieroglyphs\n109A0..109FF; Meroitic Cursive\n10A00..10A5F; Kharoshthi\n10A60..10A7F; Old South Arabian\n10A80..10A9F; Old North Arabian\n10AC0..10AFF; Manichaean\n10B00..10B3F; Avestan\n10B40..10B5F; Inscriptional Parthian\n10B60..10B7F; Inscriptional Pahlavi\n10B80..10BAF; Psalter Pahlavi\n10C00..10C4F; Old Turkic\n10C80..10CFF; Old Hungarian\n10D00..10D3F; Hanifi Rohingya\n10E60..10E7F; Rumi Numeral Symbols\n10F00..10F2F; Old Sogdian\n10F30..10F6F; Sogdian\n10FE0..10FFF; Elymaic\n11000..1107F; Brahmi\n11080..110CF; Kaithi\n110D0..110FF; Sora Sompeng\n11100..1114F; Chakma\n11150..1117F; Mahajani\n11180..111DF; Sharada\n111E0..111FF; Sinhala Archaic Numbers\n11200..1124F; Khojki\n11280..112AF; Multani\n112B0..112FF; Khudawadi\n11300..1137F; Grantha\n11400..1147F; Newa\n11480..114DF; Tirhuta\n11580..115FF; Siddham\n11600..1165F; Modi\n11660..1167F; Mongolian Supplement\n11680..116CF; Takri\n11700..1173F; Ahom\n11800..1184F; Dogra\n118A0..118FF; Warang Citi\n119A0..119FF; Nandinagari\n11A00..11A4F; Zanabazar Square\n11A50..11AAF; Soyombo\n11AC0..11AFF; Pau Cin Hau\n11C00..11C6F; Bhaiksuki\n11C70..11CBF; Marchen\n11D00..11D5F; Masaram Gondi\n11D60..11DAF; Gunjala Gondi\n11EE0..11EFF; Makasar\n11FC0..11FFF; Tamil Supplement\n12000..123FF; Cuneiform\n12400..1247F; Cuneiform Numbers and Punctuation\n12480..1254F; Early Dynastic Cuneiform\n13000..1342F; Egyptian Hieroglyphs\n13430..1343F; Egyptian Hieroglyph Format Controls\n14400..1467F; Anatolian Hieroglyphs\n16800..16A3F; Bamum Supplement\n16A40..16A6F; Mro\n16AD0..16AFF; Bassa Vah\n16B00..16B8F; Pahawh Hmong\n16E40..16E9F; Medefaidrin\n16F00..16F9F; Miao\n16FE0..16FFF; Ideographic Symbols and Punctuation\n17000..187FF; Tangut\n18800..18AFF; Tangut Components\n1B000..1B0FF; Kana Supplement\n1B100..1B12F; Kana Extended-A\n1B130..1B16F; Small Kana Extension\n1B170..1B2FF; Nushu\n1BC00..1BC9F; Duployan\n1BCA0..1BCAF; Shorthand Format Controls\n1D000..1D0FF; Byzantine Musical Symbols\n1D100..1D1FF; Musical Symbols\n1D200..1D24F; Ancient Greek Musical Notation\n1D2E0..1D2FF; Mayan Numerals\n1D300..1D35F; Tai Xuan Jing Symbols\n1D360..1D37F; Counting Rod Numerals\n1D400..1D7FF; Mathematical Alphanumeric Symbols\n1D800..1DAAF; Sutton SignWriting\n1E000..1E02F; Glagolitic Supplement\n1E100..1E14F; Nyiakeng Puachue Hmong\n1E2C0..1E2FF; Wancho\n1E800..1E8DF; Mende Kikakui\n1E900..1E95F; Adlam\n1EC70..1ECBF; Indic Siyaq Numbers\n1ED00..1ED4F; Ottoman Siyaq Numbers\n1EE00..1EEFF; Arabic Mathematical Alphabetic Symbols\n1F000..1F02F; Mahjong Tiles\n1F030..1F09F; Domino Tiles\n1F0A0..1F0FF; Playing Cards\n1F100..1F1FF; Enclosed Alphanumeric Supplement\n1F200..1F2FF; Enclosed Ideographic Supplement\n1F300..1F5FF; Miscellaneous Symbols and Pictographs\n1F600..1F64F; Emoticons\n1F650..1F67F; Ornamental Dingbats\n1F680..1F6FF; Transport and Map Symbols\n1F700..1F77F; Alchemical Symbols\n1F780..1F7FF; Geometric Shapes Extended\n1F800..1F8FF; Supplemental Arrows-C\n1F900..1F9FF; Supplemental Symbols and Pictographs\n1FA00..1FA6F; Chess Symbols\n1FA70..1FAFF; Symbols and Pictographs Extended-A\n20000..2A6DF; CJK Unified Ideographs Extension B\n2A700..2B73F; CJK Unified Ideographs Extension C\n2B740..2B81F; CJK Unified Ideographs Extension D\n2B820..2CEAF; CJK Unified Ideographs Extension E\n2CEB0..2EBEF; CJK Unified Ideographs Extension F\n2F800..2FA1F; CJK Compatibility Ideographs Supplement\nE0000..E007F; Tags\nE0100..E01EF; Variation Selectors Supplement\nF0000..FFFFF; Supplementary Private Use Area-A\n100000..10FFFF; Supplementary Private Use Area-B\n\n# EOF\n''')\n"
},
{
"answer_id": 63930824,
"author": "Koterpillar",
"author_id": 288201,
"author_profile": "https://Stackoverflow.com/users/288201",
"pm_score": 2,
"selected": false,
"text": "pip install unicodeblock\n >>> import unicodeblock.blocks\n>>> print(unicodeblock.blocks.of('0'))\nDIGIT\n>>> print(unicodeblock.blocks.of('汉'))\nCJK_UNIFIED_IDEOGRAPHS\n>>> print(unicodeblock.blocks.of('あ'))\nHIRAGANA\n"
},
{
"answer_id": 72469378,
"author": "Super Mario",
"author_id": 7484554,
"author_profile": "https://Stackoverflow.com/users/7484554",
"pm_score": 0,
"selected": false,
"text": "import re\n\nclass RangeDict(dict):\n def __getitem__(self, item):\n if not isinstance(item, range): # or xrange in Python 2\n for key in self:\n if item in key:\n return self[key]\n raise KeyError(item)\n else:\n return super().__getitem__(item)\n\nunicode_doc = '''\n# Blocks-14.0.0.txt\n# Date: 2021-01-22, 23:29:00 GMT [KW]\n# © 2021 Unicode®, Inc.\n# For terms of use, see http://www.unicode.org/terms_of_use.html\n#\n# Unicode Character Database\n# For documentation, see http://www.unicode.org/reports/tr44/\n#\n# Format:\n# Start Code..End Code; Block Name\n\n# ================================================\n\n# Note: When comparing block names, casing, whitespace, hyphens,\n# and underbars are ignored.\n# For example, \"Latin Extended-A\" and \"latin extended a\" are equivalent.\n# For more information on the comparison of property values,\n# see UAX #44: http://www.unicode.org/reports/tr44/\n#\n# All block ranges start with a value where (cp MOD 16) = 0,\n# and end with a value where (cp MOD 16) = 15. In other words,\n# the last hexadecimal digit of the start of range is ...0\n# and the last hexadecimal digit of the end of range is ...F.\n# This constraint on block ranges guarantees that allocations\n# are done in terms of whole columns, and that code chart display\n# never involves splitting columns in the charts.\n#\n# All code points not explicitly listed for Block\n# have the value No_Block.\n\n# Property: Block\n#\n# @missing: 0000..10FFFF; No_Block\n\n0000..007F; Basic Latin\n0080..00FF; Latin-1 Supplement\n0100..017F; Latin Extended-A\n0180..024F; Latin Extended-B\n0250..02AF; IPA Extensions\n02B0..02FF; Spacing Modifier Letters\n0300..036F; Combining Diacritical Marks\n0370..03FF; Greek and Coptic\n0400..04FF; Cyrillic\n0500..052F; Cyrillic Supplement\n0530..058F; Armenian\n0590..05FF; Hebrew\n0600..06FF; Arabic\n0700..074F; Syriac\n0750..077F; Arabic Supplement\n0780..07BF; Thaana\n07C0..07FF; NKo\n0800..083F; Samaritan\n0840..085F; Mandaic\n0860..086F; Syriac Supplement\n0870..089F; Arabic Extended-B\n08A0..08FF; Arabic Extended-A\n0900..097F; Devanagari\n0980..09FF; Bengali\n0A00..0A7F; Gurmukhi\n0A80..0AFF; Gujarati\n0B00..0B7F; Oriya\n0B80..0BFF; Tamil\n0C00..0C7F; Telugu\n0C80..0CFF; Kannada\n0D00..0D7F; Malayalam\n0D80..0DFF; Sinhala\n0E00..0E7F; Thai\n0E80..0EFF; Lao\n0F00..0FFF; Tibetan\n1000..109F; Myanmar\n10A0..10FF; Georgian\n1100..11FF; Hangul Jamo\n1200..137F; Ethiopic\n1380..139F; Ethiopic Supplement\n13A0..13FF; Cherokee\n1400..167F; Unified Canadian Aboriginal Syllabics\n1680..169F; Ogham\n16A0..16FF; Runic\n1700..171F; Tagalog\n1720..173F; Hanunoo\n1740..175F; Buhid\n1760..177F; Tagbanwa\n1780..17FF; Khmer\n1800..18AF; Mongolian\n18B0..18FF; Unified Canadian Aboriginal Syllabics Extended\n1900..194F; Limbu\n1950..197F; Tai Le\n1980..19DF; New Tai Lue\n19E0..19FF; Khmer Symbols\n1A00..1A1F; Buginese\n1A20..1AAF; Tai Tham\n1AB0..1AFF; Combining Diacritical Marks Extended\n1B00..1B7F; Balinese\n1B80..1BBF; Sundanese\n1BC0..1BFF; Batak\n1C00..1C4F; Lepcha\n1C50..1C7F; Ol Chiki\n1C80..1C8F; Cyrillic Extended-C\n1C90..1CBF; Georgian Extended\n1CC0..1CCF; Sundanese Supplement\n1CD0..1CFF; Vedic Extensions\n1D00..1D7F; Phonetic Extensions\n1D80..1DBF; Phonetic Extensions Supplement\n1DC0..1DFF; Combining Diacritical Marks Supplement\n1E00..1EFF; Latin Extended Additional\n1F00..1FFF; Greek Extended\n2000..206F; General Punctuation\n2070..209F; Superscripts and Subscripts\n20A0..20CF; Currency Symbols\n20D0..20FF; Combining Diacritical Marks for Symbols\n2100..214F; Letterlike Symbols\n2150..218F; Number Forms\n2190..21FF; Arrows\n2200..22FF; Mathematical Operators\n2300..23FF; Miscellaneous Technical\n2400..243F; Control Pictures\n2440..245F; Optical Character Recognition\n2460..24FF; Enclosed Alphanumerics\n2500..257F; Box Drawing\n2580..259F; Block Elements\n25A0..25FF; Geometric Shapes\n2600..26FF; Miscellaneous Symbols\n2700..27BF; Dingbats\n27C0..27EF; Miscellaneous Mathematical Symbols-A\n27F0..27FF; Supplemental Arrows-A\n2800..28FF; Braille Patterns\n2900..297F; Supplemental Arrows-B\n2980..29FF; Miscellaneous Mathematical Symbols-B\n2A00..2AFF; Supplemental Mathematical Operators\n2B00..2BFF; Miscellaneous Symbols and Arrows\n2C00..2C5F; Glagolitic\n2C60..2C7F; Latin Extended-C\n2C80..2CFF; Coptic\n2D00..2D2F; Georgian Supplement\n2D30..2D7F; Tifinagh\n2D80..2DDF; Ethiopic Extended\n2DE0..2DFF; Cyrillic Extended-A\n2E00..2E7F; Supplemental Punctuation\n2E80..2EFF; CJK Radicals Supplement\n2F00..2FDF; Kangxi Radicals\n2FF0..2FFF; Ideographic Description Characters\n3000..303F; CJK Symbols and Punctuation\n3040..309F; Hiragana\n30A0..30FF; Katakana\n3100..312F; Bopomofo\n3130..318F; Hangul Compatibility Jamo\n3190..319F; Kanbun\n31A0..31BF; Bopomofo Extended\n31C0..31EF; CJK Strokes\n31F0..31FF; Katakana Phonetic Extensions\n3200..32FF; Enclosed CJK Letters and Months\n3300..33FF; CJK Compatibility\n3400..4DBF; CJK Unified Ideographs Extension A\n4DC0..4DFF; Yijing Hexagram Symbols\n4E00..9FFF; CJK Unified Ideographs\nA000..A48F; Yi Syllables\nA490..A4CF; Yi Radicals\nA4D0..A4FF; Lisu\nA500..A63F; Vai\nA640..A69F; Cyrillic Extended-B\nA6A0..A6FF; Bamum\nA700..A71F; Modifier Tone Letters\nA720..A7FF; Latin Extended-D\nA800..A82F; Syloti Nagri\nA830..A83F; Common Indic Number Forms\nA840..A87F; Phags-pa\nA880..A8DF; Saurashtra\nA8E0..A8FF; Devanagari Extended\nA900..A92F; Kayah Li\nA930..A95F; Rejang\nA960..A97F; Hangul Jamo Extended-A\nA980..A9DF; Javanese\nA9E0..A9FF; Myanmar Extended-B\nAA00..AA5F; Cham\nAA60..AA7F; Myanmar Extended-A\nAA80..AADF; Tai Viet\nAAE0..AAFF; Meetei Mayek Extensions\nAB00..AB2F; Ethiopic Extended-A\nAB30..AB6F; Latin Extended-E\nAB70..ABBF; Cherokee Supplement\nABC0..ABFF; Meetei Mayek\nAC00..D7AF; Hangul Syllables\nD7B0..D7FF; Hangul Jamo Extended-B\nD800..DB7F; High Surrogates\nDB80..DBFF; High Private Use Surrogates\nDC00..DFFF; Low Surrogates\nE000..F8FF; Private Use Area\nF900..FAFF; CJK Compatibility Ideographs\nFB00..FB4F; Alphabetic Presentation Forms\nFB50..FDFF; Arabic Presentation Forms-A\nFE00..FE0F; Variation Selectors\nFE10..FE1F; Vertical Forms\nFE20..FE2F; Combining Half Marks\nFE30..FE4F; CJK Compatibility Forms\nFE50..FE6F; Small Form Variants\nFE70..FEFF; Arabic Presentation Forms-B\nFF00..FFEF; Halfwidth and Fullwidth Forms\nFFF0..FFFF; Specials\n10000..1007F; Linear B Syllabary\n10080..100FF; Linear B Ideograms\n10100..1013F; Aegean Numbers\n10140..1018F; Ancient Greek Numbers\n10190..101CF; Ancient Symbols\n101D0..101FF; Phaistos Disc\n10280..1029F; Lycian\n102A0..102DF; Carian\n102E0..102FF; Coptic Epact Numbers\n10300..1032F; Old Italic\n10330..1034F; Gothic\n10350..1037F; Old Permic\n10380..1039F; Ugaritic\n103A0..103DF; Old Persian\n10400..1044F; Deseret\n10450..1047F; Shavian\n10480..104AF; Osmanya\n104B0..104FF; Osage\n10500..1052F; Elbasan\n10530..1056F; Caucasian Albanian\n10570..105BF; Vithkuqi\n10600..1077F; Linear A\n10780..107BF; Latin Extended-F\n10800..1083F; Cypriot Syllabary\n10840..1085F; Imperial Aramaic\n10860..1087F; Palmyrene\n10880..108AF; Nabataean\n108E0..108FF; Hatran\n10900..1091F; Phoenician\n10920..1093F; Lydian\n10980..1099F; Meroitic Hieroglyphs\n109A0..109FF; Meroitic Cursive\n10A00..10A5F; Kharoshthi\n10A60..10A7F; Old South Arabian\n10A80..10A9F; Old North Arabian\n10AC0..10AFF; Manichaean\n10B00..10B3F; Avestan\n10B40..10B5F; Inscriptional Parthian\n10B60..10B7F; Inscriptional Pahlavi\n10B80..10BAF; Psalter Pahlavi\n10C00..10C4F; Old Turkic\n10C80..10CFF; Old Hungarian\n10D00..10D3F; Hanifi Rohingya\n10E60..10E7F; Rumi Numeral Symbols\n10E80..10EBF; Yezidi\n10F00..10F2F; Old Sogdian\n10F30..10F6F; Sogdian\n10F70..10FAF; Old Uyghur\n10FB0..10FDF; Chorasmian\n10FE0..10FFF; Elymaic\n11000..1107F; Brahmi\n11080..110CF; Kaithi\n110D0..110FF; Sora Sompeng\n11100..1114F; Chakma\n11150..1117F; Mahajani\n11180..111DF; Sharada\n111E0..111FF; Sinhala Archaic Numbers\n11200..1124F; Khojki\n11280..112AF; Multani\n112B0..112FF; Khudawadi\n11300..1137F; Grantha\n11400..1147F; Newa\n11480..114DF; Tirhuta\n11580..115FF; Siddham\n11600..1165F; Modi\n11660..1167F; Mongolian Supplement\n11680..116CF; Takri\n11700..1174F; Ahom\n11800..1184F; Dogra\n118A0..118FF; Warang Citi\n11900..1195F; Dives Akuru\n119A0..119FF; Nandinagari\n11A00..11A4F; Zanabazar Square\n11A50..11AAF; Soyombo\n11AB0..11ABF; Unified Canadian Aboriginal Syllabics Extended-A\n11AC0..11AFF; Pau Cin Hau\n11C00..11C6F; Bhaiksuki\n11C70..11CBF; Marchen\n11D00..11D5F; Masaram Gondi\n11D60..11DAF; Gunjala Gondi\n11EE0..11EFF; Makasar\n11FB0..11FBF; Lisu Supplement\n11FC0..11FFF; Tamil Supplement\n12000..123FF; Cuneiform\n12400..1247F; Cuneiform Numbers and Punctuation\n12480..1254F; Early Dynastic Cuneiform\n12F90..12FFF; Cypro-Minoan\n13000..1342F; Egyptian Hieroglyphs\n13430..1343F; Egyptian Hieroglyph Format Controls\n14400..1467F; Anatolian Hieroglyphs\n16800..16A3F; Bamum Supplement\n16A40..16A6F; Mro\n16A70..16ACF; Tangsa\n16AD0..16AFF; Bassa Vah\n16B00..16B8F; Pahawh Hmong\n16E40..16E9F; Medefaidrin\n16F00..16F9F; Miao\n16FE0..16FFF; Ideographic Symbols and Punctuation\n17000..187FF; Tangut\n18800..18AFF; Tangut Components\n18B00..18CFF; Khitan Small Script\n18D00..18D7F; Tangut Supplement\n1AFF0..1AFFF; Kana Extended-B\n1B000..1B0FF; Kana Supplement\n1B100..1B12F; Kana Extended-A\n1B130..1B16F; Small Kana Extension\n1B170..1B2FF; Nushu\n1BC00..1BC9F; Duployan\n1BCA0..1BCAF; Shorthand Format Controls\n1CF00..1CFCF; Znamenny Musical Notation\n1D000..1D0FF; Byzantine Musical Symbols\n1D100..1D1FF; Musical Symbols\n1D200..1D24F; Ancient Greek Musical Notation\n1D2E0..1D2FF; Mayan Numerals\n1D300..1D35F; Tai Xuan Jing Symbols\n1D360..1D37F; Counting Rod Numerals\n1D400..1D7FF; Mathematical Alphanumeric Symbols\n1D800..1DAAF; Sutton SignWriting\n1DF00..1DFFF; Latin Extended-G\n1E000..1E02F; Glagolitic Supplement\n1E100..1E14F; Nyiakeng Puachue Hmong\n1E290..1E2BF; Toto\n1E2C0..1E2FF; Wancho\n1E7E0..1E7FF; Ethiopic Extended-B\n1E800..1E8DF; Mende Kikakui\n1E900..1E95F; Adlam\n1EC70..1ECBF; Indic Siyaq Numbers\n1ED00..1ED4F; Ottoman Siyaq Numbers\n1EE00..1EEFF; Arabic Mathematical Alphabetic Symbols\n1F000..1F02F; Mahjong Tiles\n1F030..1F09F; Domino Tiles\n1F0A0..1F0FF; Playing Cards\n1F100..1F1FF; Enclosed Alphanumeric Supplement\n1F200..1F2FF; Enclosed Ideographic Supplement\n1F300..1F5FF; Miscellaneous Symbols and Pictographs\n1F600..1F64F; Emoticons\n1F650..1F67F; Ornamental Dingbats\n1F680..1F6FF; Transport and Map Symbols\n1F700..1F77F; Alchemical Symbols\n1F780..1F7FF; Geometric Shapes Extended\n1F800..1F8FF; Supplemental Arrows-C\n1F900..1F9FF; Supplemental Symbols and Pictographs\n1FA00..1FA6F; Chess Symbols\n1FA70..1FAFF; Symbols and Pictographs Extended-A\n1FB00..1FBFF; Symbols for Legacy Computing\n20000..2A6DF; CJK Unified Ideographs Extension B\n2A700..2B73F; CJK Unified Ideographs Extension C\n2B740..2B81F; CJK Unified Ideographs Extension D\n2B820..2CEAF; CJK Unified Ideographs Extension E\n2CEB0..2EBEF; CJK Unified Ideographs Extension F\n2F800..2FA1F; CJK Compatibility Ideographs Supplement\n30000..3134F; CJK Unified Ideographs Extension G\nE0000..E007F; Tags\nE0100..E01EF; Variation Selectors Supplement\nF0000..FFFFF; Supplementary Private Use Area-A\n100000..10FFFF; Supplementary Private Use Area-B\n\n# EOF\n'''\n\ndef parse_unicode_blocks(txt):\n pattern = re.compile(r'([0-9A-F]+)\\.\\.([0-9A-F]+);\\ (\\S.*\\S)')\n blocks = RangeDict()\n for line in txt.splitlines():\n m = pattern.match(line)\n if m:\n start, end, block_name = m.groups()\n blocks[range(int(start, 16),int(end, 16))] = block_name\n return blocks\n\nblocks = parse_unicode_blocks(unicode_doc)\n\n\ndef block(ch, unicode_blocks=blocks):\n if isinstance(ch, str) and len(ch) == 1:\n cp = ord(ch)\n return blocks[cp]\n else:\n return ''\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7581/"
] |
243,836
|
<p>Is there a library method to copy all the properties between two (already present) instances of the same class, in Python?</p>
<p>I mean, something like Apache Commons' <code>PropertyUtilsBean.copyProperties()</code></p>
|
[
{
"answer_id": 244116,
"author": "Peter Hoffmann",
"author_id": 720,
"author_profile": "https://Stackoverflow.com/users/720",
"pm_score": 7,
"selected": true,
"text": "__getitem__ __setitem__ __dict__ nobj.__dict__ = oobj.__dict__.copy() # just a shallow copy\n inspect.getmembers()"
},
{
"answer_id": 244654,
"author": "Peter Hosey",
"author_id": 30461,
"author_profile": "https://Stackoverflow.com/users/30461",
"pm_score": 6,
"selected": false,
"text": "destination.__dict__.update(source.__dict__)"
},
{
"answer_id": 248608,
"author": "Ali Afshar",
"author_id": 28380,
"author_profile": "https://Stackoverflow.com/users/28380",
"pm_score": 0,
"selected": false,
"text": "firstobject.an_attribute = secondobject.an_attribute\nfirstobject.another_attribute = secondobject.another_attribute\n"
},
{
"answer_id": 252393,
"author": "Ali Afshar",
"author_id": 28380,
"author_profile": "https://Stackoverflow.com/users/28380",
"pm_score": 2,
"selected": false,
"text": "Class Copyable(object):\n copyable_attributes = ('an_attribute', 'another_attribute')\n setattr(new, attr, getattr(old, attr))"
},
{
"answer_id": 48970465,
"author": "user",
"author_id": 4934640,
"author_profile": "https://Stackoverflow.com/users/4934640",
"pm_score": 1,
"selected": false,
"text": "import sys\n\n_target_object = sys.stderr\n_target_object_class_type = type( _target_object )\n\nclass TargetCopiedObject(_target_object_class_type):\n \"\"\"\n Which special methods bypasses __getattribute__ in Python?\n https://stackoverflow.com/questions/12872695/which-special-methods-bypasses\n \"\"\"\n\n if hasattr( _target_object, \"__abstractmethods__\" ):\n __abstractmethods__ = _target_object.__abstractmethods__\n\n if hasattr( _target_object, \"__base__\" ):\n __base__ = _target_object.__base__\n\n if hasattr( _target_object, \"__bases__\" ):\n __bases__ = _target_object.__bases__\n\n if hasattr( _target_object, \"__basicsize__\" ):\n __basicsize__ = _target_object.__basicsize__\n\n if hasattr( _target_object, \"__call__\" ):\n __call__ = _target_object.__call__\n\n if hasattr( _target_object, \"__class__\" ):\n __class__ = _target_object.__class__\n\n if hasattr( _target_object, \"__delattr__\" ):\n __delattr__ = _target_object.__delattr__\n\n if hasattr( _target_object, \"__dict__\" ):\n __dict__ = _target_object.__dict__\n\n if hasattr( _target_object, \"__dictoffset__\" ):\n __dictoffset__ = _target_object.__dictoffset__\n\n if hasattr( _target_object, \"__dir__\" ):\n __dir__ = _target_object.__dir__\n\n if hasattr( _target_object, \"__doc__\" ):\n __doc__ = _target_object.__doc__\n\n if hasattr( _target_object, \"__eq__\" ):\n __eq__ = _target_object.__eq__\n\n if hasattr( _target_object, \"__flags__\" ):\n __flags__ = _target_object.__flags__\n\n if hasattr( _target_object, \"__format__\" ):\n __format__ = _target_object.__format__\n\n if hasattr( _target_object, \"__ge__\" ):\n __ge__ = _target_object.__ge__\n\n if hasattr( _target_object, \"__getattribute__\" ):\n __getattribute__ = _target_object.__getattribute__\n\n if hasattr( _target_object, \"__gt__\" ):\n __gt__ = _target_object.__gt__\n\n if hasattr( _target_object, \"__hash__\" ):\n __hash__ = _target_object.__hash__\n\n if hasattr( _target_object, \"__init__\" ):\n __init__ = _target_object.__init__\n\n if hasattr( _target_object, \"__init_subclass__\" ):\n __init_subclass__ = _target_object.__init_subclass__\n\n if hasattr( _target_object, \"__instancecheck__\" ):\n __instancecheck__ = _target_object.__instancecheck__\n\n if hasattr( _target_object, \"__itemsize__\" ):\n __itemsize__ = _target_object.__itemsize__\n\n if hasattr( _target_object, \"__le__\" ):\n __le__ = _target_object.__le__\n\n if hasattr( _target_object, \"__lt__\" ):\n __lt__ = _target_object.__lt__\n\n if hasattr( _target_object, \"__module__\" ):\n __module__ = _target_object.__module__\n\n if hasattr( _target_object, \"__mro__\" ):\n __mro__ = _target_object.__mro__\n\n if hasattr( _target_object, \"__name__\" ):\n __name__ = _target_object.__name__\n\n if hasattr( _target_object, \"__ne__\" ):\n __ne__ = _target_object.__ne__\n\n if hasattr( _target_object, \"__new__\" ):\n __new__ = _target_object.__new__\n\n if hasattr( _target_object, \"__prepare__\" ):\n __prepare__ = _target_object.__prepare__\n\n if hasattr( _target_object, \"__qualname__\" ):\n __qualname__ = _target_object.__qualname__\n\n if hasattr( _target_object, \"__reduce__\" ):\n __reduce__ = _target_object.__reduce__\n\n if hasattr( _target_object, \"__reduce_ex__\" ):\n __reduce_ex__ = _target_object.__reduce_ex__\n\n if hasattr( _target_object, \"__repr__\" ):\n __repr__ = _target_object.__repr__\n\n if hasattr( _target_object, \"__setattr__\" ):\n __setattr__ = _target_object.__setattr__\n\n if hasattr( _target_object, \"__sizeof__\" ):\n __sizeof__ = _target_object.__sizeof__\n\n if hasattr( _target_object, \"__str__\" ):\n __str__ = _target_object.__str__\n\n if hasattr( _target_object, \"__subclasscheck__\" ):\n __subclasscheck__ = _target_object.__subclasscheck__\n\n if hasattr( _target_object, \"__subclasses__\" ):\n __subclasses__ = _target_object.__subclasses__\n\n if hasattr( _target_object, \"__subclasshook__\" ):\n __subclasshook__ = _target_object.__subclasshook__\n\n if hasattr( _target_object, \"__text_signature__\" ):\n __text_signature__ = _target_object.__text_signature__\n\n if hasattr( _target_object, \"__weakrefoffset__\" ):\n __weakrefoffset__ = _target_object.__weakrefoffset__\n\n if hasattr( _target_object, \"mro\" ):\n mro = _target_object.mro\n\n def __init__(self):\n \"\"\"\n Override any super class `type( _target_object )` constructor,\n so we can instantiate any kind of replacement object.\n\n Assures all properties were statically replaced just above. This\n should happen in case some new attribute is added to the python\n language.\n\n This also ignores the only two methods which are not equal,\n `__init__()` and `__getattribute__()`.\n\n How do you programmatically set an attribute?\n https://stackoverflow.com/questions/285061/how-do-you-programmatically\n \"\"\"\n different_methods = set([\"__init__\", \"__getattribute__\"])\n attributes_to_check = set( dir( object ) + dir( type ) )\n attributes_to_copy = dir( _target_object )\n\n # Check for missing magic built-ins methods on the class static initialization\n for attribute in attributes_to_check:\n\n if attribute not in different_methods \\\n and hasattr( _target_object, attribute ):\n\n base_class_attribute = self.__getattribute__( attribute )\n target_class_attribute = _target_object.__getattribute__( attribute )\n\n if base_class_attribute != target_class_attribute:\n sys.stdout.write(\n \" The base class attribute `%s` is different from the \"\n \"target class:\\n%s\\n%s\\n\\n\" % ( attribute,\n base_class_attribute, \n target_class_attribute ) )\n # Finally copy everything it can\n different_methods.update( attributes_to_check )\n\n for attribute in attributes_to_copy:\n\n if attribute not in different_methods:\n print( \"Setting:\", attribute )\n\n try:\n target_class_attribute = _target_object.__getattribute__(attribute)\n setattr( self, attribute, target_class_attribute )\n\n except AttributeError as error:\n print( \"Error coping the attribute `%s`: %s\" % (attribute, error) )\n\n\no = TargetCopiedObject()\nprint( \"TargetCopiedObject:\", o )\n python test.py\nSetting: _CHUNK_SIZE\nSetting: __del__\nSetting: __enter__\nSetting: __exit__\nSetting: __getstate__\nSetting: __iter__\nSetting: __next__\nSetting: _checkClosed\nSetting: _checkReadable\nSetting: _checkSeekable\nSetting: _checkWritable\nSetting: _finalizing\nSetting: buffer\nError coping the attribute `buffer`: readonly attribute\nSetting: close\nSetting: closed\nError coping the attribute `closed`: attribute 'closed' of '_io.TextIOWrapper' objects is not writable\nSetting: detach\nSetting: encoding\nError coping the attribute `encoding`: readonly attribute\nSetting: errors\nError coping the attribute `errors`: attribute 'errors' of '_io.TextIOWrapper' objects is not writable\nSetting: fileno\nSetting: flush\nSetting: isatty\nSetting: line_buffering\nError coping the attribute `line_buffering`: readonly attribute\nSetting: mode\nSetting: name\nError coping the attribute `name`: attribute 'name' of '_io.TextIOWrapper' objects is not writable\nSetting: newlines\nError coping the attribute `newlines`: attribute 'newlines' of '_io.TextIOWrapper' objects is not writable\nSetting: read\nSetting: readable\nSetting: readline\nSetting: readlines\nSetting: seek\nSetting: seekable\nSetting: tell\nSetting: truncate\nSetting: writable\nSetting: write\nSetting: writelines\nTargetCopiedObject: <_io.TextIOWrapper name='<stderr>' mode='w' encoding='utf-8'>\n __str__ import sys\n\n_target_object = sys.stderr\n_target_object_class_type = type( _target_object )\n\nclass TargetCopiedObject(_target_object_class_type):\n \"\"\"\n Which special methods bypasses __getattribute__ in Python?\n https://stackoverflow.com/questions/12872695/which-special-methods-bypasses\n \"\"\"\n\n if hasattr( _target_object, \"__abstractmethods__\" ):\n __abstractmethods__ = _target_object.__abstractmethods__\n\n if hasattr( _target_object, \"__base__\" ):\n __base__ = _target_object.__base__\n\n if hasattr( _target_object, \"__bases__\" ):\n __bases__ = _target_object.__bases__\n\n if hasattr( _target_object, \"__basicsize__\" ):\n __basicsize__ = _target_object.__basicsize__\n\n if hasattr( _target_object, \"__call__\" ):\n __call__ = _target_object.__call__\n\n if hasattr( _target_object, \"__class__\" ):\n __class__ = _target_object.__class__\n\n if hasattr( _target_object, \"__delattr__\" ):\n __delattr__ = _target_object.__delattr__\n\n if hasattr( _target_object, \"__dict__\" ):\n __dict__ = _target_object.__dict__\n\n if hasattr( _target_object, \"__dictoffset__\" ):\n __dictoffset__ = _target_object.__dictoffset__\n\n if hasattr( _target_object, \"__dir__\" ):\n __dir__ = _target_object.__dir__\n\n if hasattr( _target_object, \"__doc__\" ):\n __doc__ = _target_object.__doc__\n\n if hasattr( _target_object, \"__eq__\" ):\n __eq__ = _target_object.__eq__\n\n if hasattr( _target_object, \"__flags__\" ):\n __flags__ = _target_object.__flags__\n\n if hasattr( _target_object, \"__format__\" ):\n __format__ = _target_object.__format__\n\n if hasattr( _target_object, \"__ge__\" ):\n __ge__ = _target_object.__ge__\n\n if hasattr( _target_object, \"__getattribute__\" ):\n __getattribute__ = _target_object.__getattribute__\n\n if hasattr( _target_object, \"__gt__\" ):\n __gt__ = _target_object.__gt__\n\n if hasattr( _target_object, \"__hash__\" ):\n __hash__ = _target_object.__hash__\n\n if hasattr( _target_object, \"__init__\" ):\n __init__ = _target_object.__init__\n\n if hasattr( _target_object, \"__init_subclass__\" ):\n __init_subclass__ = _target_object.__init_subclass__\n\n if hasattr( _target_object, \"__instancecheck__\" ):\n __instancecheck__ = _target_object.__instancecheck__\n\n if hasattr( _target_object, \"__itemsize__\" ):\n __itemsize__ = _target_object.__itemsize__\n\n if hasattr( _target_object, \"__le__\" ):\n __le__ = _target_object.__le__\n\n if hasattr( _target_object, \"__lt__\" ):\n __lt__ = _target_object.__lt__\n\n if hasattr( _target_object, \"__module__\" ):\n __module__ = _target_object.__module__\n\n if hasattr( _target_object, \"__mro__\" ):\n __mro__ = _target_object.__mro__\n\n if hasattr( _target_object, \"__name__\" ):\n __name__ = _target_object.__name__\n\n if hasattr( _target_object, \"__ne__\" ):\n __ne__ = _target_object.__ne__\n\n if hasattr( _target_object, \"__new__\" ):\n __new__ = _target_object.__new__\n\n if hasattr( _target_object, \"__prepare__\" ):\n __prepare__ = _target_object.__prepare__\n\n if hasattr( _target_object, \"__qualname__\" ):\n __qualname__ = _target_object.__qualname__\n\n if hasattr( _target_object, \"__reduce__\" ):\n __reduce__ = _target_object.__reduce__\n\n if hasattr( _target_object, \"__reduce_ex__\" ):\n __reduce_ex__ = _target_object.__reduce_ex__\n\n if hasattr( _target_object, \"__repr__\" ):\n __repr__ = _target_object.__repr__\n\n if hasattr( _target_object, \"__setattr__\" ):\n __setattr__ = _target_object.__setattr__\n\n if hasattr( _target_object, \"__sizeof__\" ):\n __sizeof__ = _target_object.__sizeof__\n\n if hasattr( _target_object, \"__str__\" ):\n __str__ = _target_object.__str__\n\n if hasattr( _target_object, \"__subclasscheck__\" ):\n __subclasscheck__ = _target_object.__subclasscheck__\n\n if hasattr( _target_object, \"__subclasses__\" ):\n __subclasses__ = _target_object.__subclasses__\n\n if hasattr( _target_object, \"__subclasshook__\" ):\n __subclasshook__ = _target_object.__subclasshook__\n\n if hasattr( _target_object, \"__text_signature__\" ):\n __text_signature__ = _target_object.__text_signature__\n\n if hasattr( _target_object, \"__weakrefoffset__\" ):\n __weakrefoffset__ = _target_object.__weakrefoffset__\n\n if hasattr( _target_object, \"mro\" ):\n mro = _target_object.mro\n\n # Copy all the other read only attributes\n if hasattr( _target_object, \"buffer\" ):\n buffer = _target_object.buffer\n\n if hasattr( _target_object, \"closed\" ):\n closed = _target_object.closed\n\n if hasattr( _target_object, \"encoding\" ):\n encoding = _target_object.encoding\n\n if hasattr( _target_object, \"errors\" ):\n errors = _target_object.errors\n\n if hasattr( _target_object, \"line_buffering\" ):\n line_buffering = _target_object.line_buffering\n\n if hasattr( _target_object, \"name\" ):\n name = _target_object.name\n\n if hasattr( _target_object, \"newlines\" ):\n newlines = _target_object.newlines\n\n def __init__(self):\n \"\"\"\n Override any super class `type( _target_object )` constructor,\n so we can instantiate any kind of replacement object.\n\n Assures all properties were statically replaced just above. This\n should happen in case some new attribute is added to the python\n language.\n\n This also ignores the only two methods which are not equal,\n `__init__()` and `__getattribute__()`.\n\n How do you programmatically set an attribute?\n https://stackoverflow.com/questions/285061/how-do-you-programmatically\n \"\"\"\n\n # Add the copied read only atribute to the ignored list, so they\n # do not throw new errors while trying copy they dynamically\n different_methods = set\\\n ([\n \"__init__\",\n \"__getattribute__\",\n \"buffer\",\n \"closed\",\n \"encoding\",\n \"errors\",\n \"line_buffering\",\n \"name\",\n \"newlines\",\n ])\n\n attributes_to_check = set( dir( object ) + dir( type ) )\n attributes_to_copy = dir( _target_object )\n\n # Check for missing magic built-ins methods on the class static initialization\n for attribute in attributes_to_check:\n\n if attribute not in different_methods \\\n and hasattr( _target_object, attribute ):\n\n base_class_attribute = self.__getattribute__( attribute )\n target_class_attribute = _target_object.__getattribute__( attribute )\n\n if base_class_attribute != target_class_attribute:\n sys.stdout.write(\n \" The base class attribute `%s` is different from the \"\n \"target class:\\n%s\\n%s\\n\\n\" % ( attribute,\n base_class_attribute,\n target_class_attribute ) )\n # Finally copy everything it can\n different_methods.update( attributes_to_check )\n\n for attribute in attributes_to_copy:\n\n if attribute not in different_methods:\n print( \"Setting:\", attribute )\n\n try:\n target_class_attribute = _target_object.__getattribute__(attribute)\n setattr( self, attribute, target_class_attribute )\n\n except AttributeError as error:\n print( \"Error coping the attribute `%s`: %s\" % (attribute, error) )\n\n\no = TargetCopiedObject()\nprint( \"TargetCopiedObject:\", o )\n python test.py\nSetting: _CHUNK_SIZE\nSetting: __del__\nSetting: __enter__\nSetting: __exit__\nSetting: __getstate__\nSetting: __iter__\nSetting: __next__\nSetting: _checkClosed\nSetting: _checkReadable\nSetting: _checkSeekable\nSetting: _checkWritable\nSetting: _finalizing\nSetting: close\nSetting: detach\nSetting: fileno\nSetting: flush\nSetting: isatty\nSetting: mode\nSetting: read\nSetting: readable\nSetting: readline\nSetting: readlines\nSetting: seek\nSetting: seekable\nSetting: tell\nSetting: truncate\nSetting: writable\nSetting: write\nSetting: writelines\nTargetCopiedObject: <_io.TextIOWrapper name='<stderr>' mode='w' encoding='utf-8'>\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3497/"
] |
243,851
|
<p>I'm trying to unit test a piece of code that needs a currently logged in user in the test. Using the .Net 2.0 Membership Provider, how can I programmatically log in as a user for this test?</p>
|
[
{
"answer_id": 250787,
"author": "user31934",
"author_id": 31934,
"author_profile": "https://Stackoverflow.com/users/31934",
"pm_score": 2,
"selected": false,
"text": " public class TemporaryPrincipal : IDisposable {\n private readonly IPrincipal _cache;\n\n public TemporaryPrincipal(IPrincipal tempPrincipal) {\n _cache = Thread.CurrentPrincipal;\n Thread.CurrentPrincipal = tempPrincipal;\n }\n\n public void Dispose() {\n Thread.CurrentPrincipal = _cache;\n }\n }\n using (new TemporaryPrincipal(new AnonymousUserPrincipal())) {\n ClassUnderTest.MethodUnderTest();\n}\n"
},
{
"answer_id": 1111545,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "if(Membership.ValidateUser(\"user1\",P@ssw0rd))\n {\n FormsAuthentication.SetAuthCookie(\"user1\",true); \n}\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16027/"
] |
243,852
|
<p>I am attempting to deploy an ASP.NET 2.0 Web service application on an IIS server that currently serves a large .NET 1.0 web application. </p>
<p>I have set up an appropriate virtual directory and have set the ASP.NET version for the virtual directory to 2.0, when I attempt to browse the site in a web-browser, I am prompted for a password. If I set the ASP.NET version down to 1.0, I am not prompted for a password, but obviously receive a full application error.</p>
<p>How can I configure IIS so that I can have the .NET 2.0 version selected without requiring the password prompt?</p>
<p>I have anonymous access enabled and have the "Authenticated Access" set to integrated windows authentication"</p>
<p>Any help or suggestions is appreciated...</p>
<p>Thanks.</p>
|
[
{
"answer_id": 566516,
"author": "Tom Anderson",
"author_id": 13502,
"author_profile": "https://Stackoverflow.com/users/13502",
"pm_score": 0,
"selected": false,
"text": "c:\\windows\\microsoft.net\\framework\\v2.0.50727\\aspnet_regiis.exe -i\n C:\\windows\\microsoft.net\\framework\\v2.0.50727\\Temporary ASP.NET Files\\\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] |
243,864
|
<p>I want to create a list of integers from 1 to <code>n</code>. I can do this in Python using <code>range(1, n+1)</code>, and in Haskell using: <code>take n (iterate (1+) 1)</code>.</p>
<p>What is the right OCaml idiom for this?</p>
|
[
{
"answer_id": 244078,
"author": "Thedric Walker",
"author_id": 26166,
"author_profile": "https://Stackoverflow.com/users/26166",
"pm_score": 4,
"selected": false,
"text": "let rec range i j = \n if i > j then [] \n else i :: range (i+1) j\n"
},
{
"answer_id": 244104,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 6,
"selected": true,
"text": "# let (--) i j = \n let rec aux n acc =\n if n < i then acc else aux (n-1) (n :: acc)\n in aux j [] ;;\nval ( -- ) : int -> int -> int list = <fun>\n# 1--2;;\n- : int list = [1; 2]\n# 1--5;;\n- : int list = [1; 2; 3; 4; 5]\n# 5--10;;\n- : int list = [5; 6; 7; 8; 9; 10]\n [i .. j]"
},
{
"answer_id": 2926149,
"author": "Michael Ekstrand",
"author_id": 1385039,
"author_profile": "https://Stackoverflow.com/users/1385039",
"pm_score": 4,
"selected": false,
"text": "let nums = List.of_enum (1--10);;\n -- --^ 1--^10"
},
{
"answer_id": 27674212,
"author": "user69818",
"author_id": 2579955,
"author_profile": "https://Stackoverflow.com/users/2579955",
"pm_score": 2,
"selected": false,
"text": "open Batteries range(1,n+1) List.range 1 `To n To List.init n f"
},
{
"answer_id": 33000776,
"author": "Matthias Braun",
"author_id": 775954,
"author_profile": "https://Stackoverflow.com/users/775954",
"pm_score": 2,
"selected": false,
"text": "let () =\n let my_char = 'a' in\n let is_lower_case = match my_char with\n | 'a'..'z' -> true (* Two dots define a range pattern *)\n | _ -> false\n in\n printf \"result: %b\" is_lower_case\n Core List.range 0 1000\n"
},
{
"answer_id": 36098304,
"author": "JustGage",
"author_id": 1402585,
"author_profile": "https://Stackoverflow.com/users/1402585",
"pm_score": 2,
"selected": false,
"text": "let rec range ?(start=0) len =\n if start >= len\n then []\n else start :: (range len ~start:(start+1))\n range 10 \n (* equals: [0; 1; 2; 3; 4; 5; 6; 7; 8; 9] *)\n\nrange ~start:(-3) 3 \n (* equals: [-3; -2; -1; 0; 1; 2] *)\n"
},
{
"answer_id": 49781512,
"author": "Alex Coventry",
"author_id": 1941213,
"author_profile": "https://Stackoverflow.com/users/1941213",
"pm_score": 4,
"selected": false,
"text": "\n# List.init 5 (fun x -> x + 1);;\n- : int list = [1; 2; 3; 4; 5]\n"
},
{
"answer_id": 50050695,
"author": "rdavison",
"author_id": 1631912,
"author_profile": "https://Stackoverflow.com/users/1631912",
"pm_score": 0,
"selected": false,
"text": "let range start stop = \n List.init (abs @@ stop - start) (fun i -> i + start)\n"
},
{
"answer_id": 55790735,
"author": "Travis S",
"author_id": 7644777,
"author_profile": "https://Stackoverflow.com/users/7644777",
"pm_score": 3,
"selected": false,
"text": "let range n = List.init n succ;; \n> val range : int -> int list = <fun> \nrange 3;; \n> - : int list = [1; 2; 3] \n"
},
{
"answer_id": 56913825,
"author": "Nondv",
"author_id": 3891844,
"author_profile": "https://Stackoverflow.com/users/3891844",
"pm_score": 2,
"selected": false,
"text": "let range a b =\n List.init (b - a) ((+) a)\n"
},
{
"answer_id": 59956239,
"author": "Gark Garcia",
"author_id": 9615454,
"author_profile": "https://Stackoverflow.com/users/9615454",
"pm_score": 3,
"selected": false,
"text": "range Stream let range (start: int) (step: int) (stop: int): int stream =\n Stream.from (fun i -> let j = i * step + start in if j < stop then Some j else None)\n"
},
{
"answer_id": 59981035,
"author": "Aldrik",
"author_id": 8830034,
"author_profile": "https://Stackoverflow.com/users/8830034",
"pm_score": 0,
"selected": false,
"text": "(* print sum of all values between 1 and 50, adding 4 to all elements and excluding 53 *)\nRange.(\n from 1 50 \n |> map ((+) 4) \n |> filter ((!=) 53) \n |> fold (+) 0 \n |> print_int\n);;\n"
},
{
"answer_id": 70613105,
"author": "Anentropic",
"author_id": 202168,
"author_profile": "https://Stackoverflow.com/users/202168",
"pm_score": 2,
"selected": false,
"text": "range let range ?(from=0) until ?(step=1) =\n let cmp = match step with\n | i when i < 0 -> (>)\n | i when i > 0 -> (<)\n | _ -> raise (Invalid_argument \"step must not be zero\")\n in\n Seq.unfold (function\n i when cmp i until -> Some (i, i + step) | _ -> None\n ) from\n n # let n = 10;;\nval n : int = 10\n# List.of_seq @@ range ~from:1 (n + 1);;\n- : int list = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]\n # List.of_seq @@ range 5;;\n- : int list = [0; 1; 2; 3; 4]\n # List.of_seq @@ range ~from:20 2 ~step:(-3);;\n- : int list = [20; 17; 14; 11; 8; 5]\n\n(* you have to use a negative step *)\n# List.of_seq @@ range ~from:20 2;;\n- : int list = []\n\n# List.of_seq @@ range 10 ~step:0;;\nException: Invalid_argument \"step must not be zero\".\n"
},
{
"answer_id": 72602784,
"author": "Mateo",
"author_id": 3210331,
"author_profile": "https://Stackoverflow.com/users/3210331",
"pm_score": 0,
"selected": false,
"text": "open Base\n\nlet pylike_range ?(from=0) ?(step=1) (until: int) : int Sequence.t = \n Sequence.range ~stride:step ~start:`inclusive ~stop:`exclusive from until\n\nlet range_list ?(from=0) ?(step=1) (until: int) : int list = \n pylike_range ~from:from ~step:step until \n |> Sequence.to_list \n # range_list 10;;\n- : int list = [0; 1; 2; 3; 4; 5; 6; 7; 8; 9]\n\n# range_list 10 ~from:3;;\n- : int list = [3; 4; 5; 6; 7; 8; 9]\n\n# range_list 10 ~from:3 ~step:2;;\n- : int list = [3; 5; 7; 9]\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1386292/"
] |
243,865
|
<p>I have two iterators, a <code>list</code> and an <code>itertools.count</code> object (i.e. an infinite value generator). I would like to merge these two into a resulting iterator that will alternate yield values between the two:</p>
<pre><code>>>> import itertools
>>> c = itertools.count(1)
>>> items = ['foo', 'bar']
>>> merged = imerge(items, c) # the mythical "imerge"
>>> merged.next()
'foo'
>>> merged.next()
1
>>> merged.next()
'bar'
>>> merged.next()
2
>>> merged.next()
Traceback (most recent call last):
...
StopIteration
</code></pre>
<p>What is the simplest, most concise way to do this?</p>
|
[
{
"answer_id": 243892,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 4,
"selected": false,
"text": "a b def imerge(a, b):\n i1 = iter(a)\n i2 = iter(b)\n while True:\n try:\n yield i1.next()\n yield i2.next()\n except StopIteration:\n return\n"
},
{
"answer_id": 243902,
"author": "Pramod",
"author_id": 1386292,
"author_profile": "https://Stackoverflow.com/users/1386292",
"pm_score": 7,
"selected": true,
"text": "def imerge(a, b):\n for i, j in itertools.izip(a,b):\n yield i\n yield j\n"
},
{
"answer_id": 243909,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 4,
"selected": false,
"text": "zip itertools.chain merge=itertools.chain(*[iter(i) for i in zip(['foo', 'bar'], itertools.count(1))])\n"
},
{
"answer_id": 244049,
"author": "David Locke",
"author_id": 1447,
"author_profile": "https://Stackoverflow.com/users/1447",
"pm_score": 4,
"selected": false,
"text": "def izipmerge(a, b):\n for i, j in itertools.izip(a,b):\n yield i\n yield j\n"
},
{
"answer_id": 244957,
"author": "Andrea Ambu",
"author_id": 21384,
"author_profile": "https://Stackoverflow.com/users/21384",
"pm_score": 0,
"selected": false,
"text": "def imerge(a,b):\n for i,j in zip(a,b):\n yield i\n yield j\n"
},
{
"answer_id": 245042,
"author": "John Fouhy",
"author_id": 15154,
"author_profile": "https://Stackoverflow.com/users/15154",
"pm_score": 2,
"selected": false,
"text": ">>> items = ['foo', 'bar', 'baz']\n>>> for i, item in enumerate(items):\n... print item\n... print i\n... \nfoo\n0\nbar\n1\nbaz\n2\n"
},
{
"answer_id": 345415,
"author": "Tom Swirly",
"author_id": 43839,
"author_profile": "https://Stackoverflow.com/users/43839",
"pm_score": 4,
"selected": false,
"text": " def tmerge(*iterators):\n for values in zip(*iterators):\n for value in values:\n yield value\n def tmerge(*iterators):\n empty = {}\n for values in itertools.zip_longest(*iterators, fillvalue=empty):\n for value in values:\n if value is not empty:\n yield value\n"
},
{
"answer_id": 345433,
"author": "user26294",
"author_id": 26294,
"author_profile": "https://Stackoverflow.com/users/26294",
"pm_score": 0,
"selected": false,
"text": "itertools.izip() zip()"
},
{
"answer_id": 345576,
"author": "A. Coady",
"author_id": 36433,
"author_profile": "https://Stackoverflow.com/users/36433",
"pm_score": 1,
"selected": false,
"text": ">>> list(itertools.chain.from_iterable(itertools.izip(items, c))) # 2.6 only\n['foo', 1, 'bar', 2]\n\n>>> list(itertools.chain(*itertools.izip(items, c)))\n['foo', 1, 'bar', 2]\n"
},
{
"answer_id": 394427,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "generator = (it.next() for it in itertools.cycle([i1, i2]))\n"
},
{
"answer_id": 5399982,
"author": "vampolo",
"author_id": 672268,
"author_profile": "https://Stackoverflow.com/users/672268",
"pm_score": 3,
"selected": false,
"text": "iter = reduce(lambda x,y: itertools.chain(x,y), iters)\n"
},
{
"answer_id": 5487453,
"author": "Petr Viktorin",
"author_id": 99057,
"author_profile": "https://Stackoverflow.com/users/99057",
"pm_score": 2,
"selected": false,
"text": "def imerge(*iterators):\n return (value for row in itertools.izip(*iterators) for value in row)\n"
},
{
"answer_id": 40498526,
"author": "user76284",
"author_id": 1667423,
"author_profile": "https://Stackoverflow.com/users/1667423",
"pm_score": 2,
"selected": false,
"text": "def alternate(*iterators):\n while len(iterators) > 0:\n try:\n yield next(iterators[0])\n # Move this iterator to the back of the queue\n iterators = iterators[1:] + iterators[:1]\n except StopIteration:\n # Remove this iterator from the queue completely\n iterators = iterators[1:]\n from collections import deque\n\ndef alternate(*iterators):\n queue = deque(iterators)\n while len(queue) > 0:\n iterator = queue.popleft()\n try:\n yield next(iterator)\n queue.append(iterator)\n except StopIteration:\n pass\n from itertools import count\n\nfor n in alternate(count(), iter(range(3)), count(100)):\n input(n)\n 0\n0\n100\n1\n1\n101\n2\n2\n102\n3\n103\n4\n104\n5\n105\n6\n106\n def alternate(*iterables):\n queue = deque(map(iter, iterables))\n ...\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18950/"
] |
243,894
|
<p>Does the placement of a function have an effect on the performance of closures within scope? If so, where is the optimal place to put these functions? If not, is the implied association by closure enough reason to place a function in another place logically?</p>
<p>For instance, if <strong>foo</strong> does not rely on the value of <strong>localState</strong>, does the fact that <strong>localState</strong> is accessible from <strong>foo</strong> have implications as to <strong>foo</strong>'s execution time, memory use, etc.?</p>
<pre><code>(function(){
var localState;
function foo(){
// code
}
function bar(){
// code
return localState;
}
})();
</code></pre>
<p>In other words, would this be a better choice, and if so why?</p>
<pre><code>(function(){
function foo(){
// code
}
var localState;
function bar(){
// code
return localState;
}
})();
</code></pre>
<p><a href="https://stackoverflow.com/users/27024/darius-bacon">Darius Bacon</a> has suggested <a href="https://stackoverflow.com/questions/243894/javascript-closures-and-function-placement#243942">below</a> that the two samples above are identical since <strong>localState</strong> can be accessed anywhere from within the block. However, the example below where <strong>foo</strong> is defined outside the block may be a different case. What do you think?</p>
<pre><code>function foo(){
// code
}
(function(){
var localState;
function bar(){
// code
foo();
return localState;
}
})();
</code></pre>
|
[
{
"answer_id": 243949,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 3,
"selected": false,
"text": "localState foo foo foo foo foo"
},
{
"answer_id": 246945,
"author": "WPWoodJr",
"author_id": 32122,
"author_profile": "https://Stackoverflow.com/users/32122",
"pm_score": 3,
"selected": true,
"text": "var x = 3;\nfunction y() eval(\"x\");\ny();\n3\n"
},
{
"answer_id": 1278280,
"author": "coderjoe",
"author_id": 127792,
"author_profile": "https://Stackoverflow.com/users/127792",
"pm_score": 0,
"selected": false,
"text": "CheckOne();\nfunction CheckOne() {\n alert('check...check one.');\n}\n\nCheckTwo();\nvar CheckTwo = function() {\n alert('check...check two.');\n};\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/208/"
] |
243,897
|
<p>I have a variable that is built in loop. Something like:</p>
<pre><code>$str = "";
for($i = 0; $i < 10; $i++) $str .= "something";
</code></pre>
<p>If $str = "" is ommitted, I get undefined variable notice, but I thought php auto-declare a variable the first time it sees undeclared one?</p>
<p>How do I do this right?</p>
|
[
{
"answer_id": 243913,
"author": "vIceBerg",
"author_id": 17766,
"author_profile": "https://Stackoverflow.com/users/17766",
"pm_score": 5,
"selected": true,
"text": "$str = $str . \"something\"; $str = [undefined value] . \"something\"; [undefined value] \"something\" \"\""
},
{
"answer_id": 243925,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 3,
"selected": false,
"text": "for($i = 0, $str = ''; $i < 10; $i++) $str .= \"something\";\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15345/"
] |
243,900
|
<p>I've seen some code where a <em>Class</em> is imported, instead of a namespace, making all the static members/methods of that class available. Is this a feature of VB? Or do other languages do this as well?</p>
<p>TestClass.vb</p>
<pre><code>public class TestClass
public shared function Somefunc() as Boolean
return true
end function
end class
</code></pre>
<p>MainClass.vb</p>
<pre><code>imports TestClass
public class MainClass
public sub Main()
Somefunc()
end sub
end class
</code></pre>
<p>These files are in the App_Code directory. Just curious, because I've never thought of doing this before, nor have I read about it anywhere. </p>
|
[
{
"answer_id": 246615,
"author": "RS Conley",
"author_id": 7890,
"author_profile": "https://Stackoverflow.com/users/7890",
"pm_score": 3,
"selected": true,
"text": "GlobalMultiUse GlobalMultiUse Instancing"
},
{
"answer_id": 5697882,
"author": "gumuruh",
"author_id": 687088,
"author_profile": "https://Stackoverflow.com/users/687088",
"pm_score": -1,
"selected": false,
"text": "Protected Overrides Sub Finalize()\n MyBase.Finalize()\nEnd Sub\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40/"
] |
243,929
|
<p>I have several arrays of arrays or arrays of dicts that I would like to store in my iPhone app. This lists are static and won't be modified by the app or users. Occasionally they may be displayed but more likely they'll be iterated over and compared to some input value. Would the best way to store these arrays be a CoreData/SQLite data store, in a header file, or something I'm not thinking of? I could see making a class that only has these arrays stored in them for access, but I'm not sure if that's the best route to take.</p>
|
[
{
"answer_id": 244978,
"author": "Colin Barrett",
"author_id": 23106,
"author_profile": "https://Stackoverflow.com/users/23106",
"pm_score": 3,
"selected": true,
"text": "@implementation DataSource\n+ (NSArray *)someData\n{\n static NSArray *data = nil;\n if (!data) {\n data = [[NSArray arrayWithObjects:..., nil] retain];\n }\n return data;\n}\n@end\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29263/"
] |
243,945
|
<p>From wikipedia: </p>
<blockquote>
<p>the cross product is a binary operation on two vectors in a <strong>three-dimensional</strong> Euclidean space that results in another vector which is perpendicular to the plane containing the two input vectors.</p>
</blockquote>
<p>Given that the definition is only defined in three (<a href="https://en.wikipedia.org/wiki/Seven-dimensional_cross_product#Consequences_of_the_defining_properties" rel="noreferrer">or seven, one and zero</a>) dimensions, how does one calculate the cross product of two 2d vectors?</p>
<p>I have seen two implementations. One returns a new vector (but only accepts a single vector), the other returns a scalar (but is a calculation between two vectors).</p>
<p>Implementation 1 (returns a scalar):</p>
<pre><code>float CrossProduct(const Vector2D & v1, const Vector2D & v2) const
{
return (v1.X*v2.Y) - (v1.Y*v2.X);
}
</code></pre>
<p>Implementation 2 (returns a vector):</p>
<pre><code>Vector2D CrossProduct(const Vector2D & v) const
{
return Vector2D(v.Y, -v.X);
}
</code></pre>
<p>Why the varying implementations? What would I use the scalar implementation for? What would I use the vector implementation for?</p>
<p>The reason I ask is because I'm writing a Vector2D class myself and don't know which method to use.</p>
|
[
{
"answer_id": 244046,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 4,
"selected": false,
"text": "a b"
},
{
"answer_id": 29060469,
"author": "Bill Burdick",
"author_id": 1026782,
"author_profile": "https://Stackoverflow.com/users/1026782",
"pm_score": 3,
"selected": false,
"text": "sin cos"
},
{
"answer_id": 50703927,
"author": "Bram",
"author_id": 301166,
"author_profile": "https://Stackoverflow.com/users/301166",
"pm_score": 3,
"selected": false,
"text": "/// 2D vector cross product analog.\n/// The cross product of 2D vectors results in a 3D vector with only a z component.\n/// This function returns the magnitude of the z value.\nstatic inline cpFloat cpvcross(const cpVect v1, const cpVect v2)\n{\n return v1.x*v2.y - v1.y*v2.x;\n}\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18265/"
] |
243,956
|
<p>I currently have a silverlight application which rotates through several graphs of live data. Each page has two user controls though: one for an info box at the top and another for the graph to display. I have tried to add a background image to the master page that they are displayed on so that the image is behind everything but as soon as they load, they overwrite the image with their blank canvas.</p>
<p>So far attempts to make the background of the user controls transparent have had no effect.</p>
<p>Any help would be greatly appreciated.</p>
|
[
{
"answer_id": 245384,
"author": "Bryant",
"author_id": 10893,
"author_profile": "https://Stackoverflow.com/users/10893",
"pm_score": 2,
"selected": false,
"text": "<object data=\"data:application/x-silverlight-2,\" type=\"application/x-silverlight-2\" width=\"100%\" height=\"100%\">\n <param name=\"source\" value=\"[your xap file]\"/>\n <param name=\"background\" value=\"transparent\" />\n ....\n</object>\n"
},
{
"answer_id": 246252,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<param name=\"windowless\" value=\"true\" /> \n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
243,962
|
<p>Which Eclipse package should I choose for Python development with <a href="http://www.pydev.org/" rel="nofollow noreferrer">PyDev</a>?</p>
<p>Nothing on the Eclipse homepage tells me what to choose, and the PyDev documentation assumes I already have Eclipse installed. Does it matter which Eclipse package I choose?</p>
|
[
{
"answer_id": 1215589,
"author": "J. Peterson",
"author_id": 105767,
"author_profile": "https://Stackoverflow.com/users/105767",
"pm_score": 2,
"selected": false,
"text": "Help > Software Updates >"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23423/"
] |
243,966
|
<p>I need to send an email to someone and want them to be able to simply reply to the email without having to specify the email address.</p>
<p>Using sp_send_dbmail sets the reply-to address as the name of the profile that it was sent from.</p>
<p>Can this be changed to specify the reply-to so it looks like it came from me.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 26142821,
"author": "Doug_Ivison",
"author_id": 1259871,
"author_profile": "https://Stackoverflow.com/users/1259871",
"pm_score": 2,
"selected": false,
"text": "sp_send_dbmail sp_send_dbmail"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11989/"
] |
243,967
|
<p>Sometimes you need to skip execution of part of a method under certain non-critical error conditions. You can use <em>exceptions</em> for that, but exceptions generally are not recommended in normal application logic, only for abnormal situations.</p>
<p>So I do a trick like this:</p>
<pre><code>do
{
bool isGood = true;
.... some code
if(!isGood)
break;
.... some more code
if(!isGood)
break;
.... some more code
} while(false);
..... some other code, which has to be executed.
</code></pre>
<p>I use a "fake" loop which will run once, and I can abort it by <em>break</em> or <em>continue</em>.</p>
<p>Some of my colleagues did not like that, and they called it "bad practice". I personally find that approach pretty slick. But what do you think?</p>
|
[
{
"answer_id": 243978,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 5,
"selected": false,
"text": "bool isGood = true;\n\n .... some code\n\n if(isGood)\n {\n .... some more code\n }\n\n if(isGood)\n {\n .... some more code\n }\n"
},
{
"answer_id": 243982,
"author": "g .",
"author_id": 6944,
"author_profile": "https://Stackoverflow.com/users/6944",
"pm_score": 5,
"selected": false,
"text": "someMethod()\n{\n .... some code\n\n if(!isGood)\n return;\n\n .... some more code\n\n if(!isGood)\n return;\n\n .... some more code\n\n }\n"
},
{
"answer_id": 243991,
"author": "jonnii",
"author_id": 4590,
"author_profile": "https://Stackoverflow.com/users/4590",
"pm_score": 3,
"selected": false,
"text": "public bool Method1(){ ... }\npublic bool Method2(){ ... }\n\npublic void DoStuff(){\n bool everythingWorked = Method1() && Method2();\n ... stuff you want executed always ...\n}\n"
},
{
"answer_id": 243996,
"author": "Fry",
"author_id": 23553,
"author_profile": "https://Stackoverflow.com/users/23553",
"pm_score": -1,
"selected": false,
"text": "if(isGood)\n{\n...Execute more code\n}\n"
},
{
"answer_id": 244011,
"author": "Aaron",
"author_id": 14153,
"author_profile": "https://Stackoverflow.com/users/14153",
"pm_score": 3,
"selected": false,
"text": "goto if(succeeded(..)) if(failed(..)) break; do{\n bool isGood = true;\n .... some code\n if(!isGood)\n break;\n .... some more code\n for(....){\n if(!isGood)\n break; // <-- OOPS, this will exit the 'for' loop, which \n // probably isn't what the author intended\n .... some more code\n }\n} while(false);\n..... some other code, which has to be executed.\n goto cleanup if(succeeded(..))"
},
{
"answer_id": 244013,
"author": "Dave Hillier",
"author_id": 1575281,
"author_profile": "https://Stackoverflow.com/users/1575281",
"pm_score": 1,
"selected": false,
"text": "bool success = someSensibleFunctionName();\n\nif(success)\n{\n ...\n}\n\nsomeCommonCodeInAnotherFunction();\n"
},
{
"answer_id": 244016,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 3,
"selected": false,
"text": "// Code\n\nif (bad_thing_happened) goto catch;\n\n// More code\n\nif (bad_thing_happened) goto catch;\n\n// Even more code\n\nfinally:\n\n// This code is executed in any case\n// whether we have an exception or not,\n// just like finally statement in other\n// languages\n\nreturn whatever;\n\ncatch:\n\n// Code to handle bad error condition\n\n// Make sure code tagged for finally\n// is executed in any case\ngoto finally;\n"
},
{
"answer_id": 244081,
"author": "bruceatk",
"author_id": 791,
"author_profile": "https://Stackoverflow.com/users/791",
"pm_score": 1,
"selected": false,
"text": " If (isError)\n{\n //Do whatever you need to do for the error and\n return;\n}\n If (!isGood)\n{\n //Do something\n}\n"
},
{
"answer_id": 244121,
"author": "Wedge",
"author_id": 332,
"author_profile": "https://Stackoverflow.com/users/332",
"pm_score": 4,
"selected": false,
"text": "private void DoSomething()\n{\n // some code\n if (some condition)\n {\n return;\n }\n // some more code\n if (some other condition)\n {\n return;\n }\n // yet more code\n}\n"
},
{
"answer_id": 244137,
"author": "philsquared",
"author_id": 32136,
"author_profile": "https://Stackoverflow.com/users/32136",
"pm_score": 1,
"selected": false,
"text": "\n void method1()\n {\n ... some code\n if( condition )\n method2();\n }\n\n void method2()\n {\n ... some more code\n if( condition )\n method3();\n }\n\n void method3()\n {\n ... yet more code\n if( condition )\n method4();\n }\n"
},
{
"answer_id": 244139,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 7,
"selected": true,
"text": "do\n{\n bool isError = false ;\n\n /* some code, perhaps setting isError to true */\n if(isError) break ;\n /* some code, perhaps setting isError to true */\n if(isError) break ;\n /* some code, perhaps setting isError to true */\n}\nwhile(false) ;\n \n// some other code \n {\n // etc.\n if(/*some failure condition*/) goto MY_EXIT ;\n // etc.\n\n while(/* etc.*/)\n {\n // etc.\n for(/* etc.*/)\n {\n // etc.\n if(/*some failure condition*/) goto MY_EXIT ;\n // etc.\n }\n // etc.\n if(/*some failure condition*/) goto MY_EXIT ;\n // etc.\n }\n\n // etc.\n}\n\nMY_EXIT:\n \n// some other code \n try\n{\n // All your code\n // You can throw the moment something fails\n // Note that you can call functions, use reccursion,\n // have multiple loops, etc. it won't change\n // anything: If you want to exit the process,\n // then throw a MyExitProcessException exception.\n\n if(/* etc. */)\n {\n // etc.\n while(/* etc.*/)\n {\n // etc.\n for(/* etc.*/)\n {\n // etc.\n if(/*some failure condition*/) throw MyExitProcessException() ;\n // etc.\n }\n // etc.\n\n callSomeFunction() ;\n // the function will throw if the condition is met\n // so no need to test a return code\n\n // etc.\n }\n // etc.\n }\n\n // etc.\n}\ncatch(const MyExitProcessException & e)\n{\n // To avoid catching other exceptions, you should\n // define a \"MyExitProcessException\" exception\n}\n\n// some other code\n"
},
{
"answer_id": 244167,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 2,
"selected": false,
"text": " /* This is a one-cycle loop that simplifies error handling */\n do\n {\n ...modestly complex code, including a nested loop...\n } while (0);\n"
},
{
"answer_id": 244523,
"author": "Dean Michael",
"author_id": 11274,
"author_profile": "https://Stackoverflow.com/users/11274",
"pm_score": 1,
"selected": false,
"text": "if (condition1(...) && condition2(...) && condition3(...) && ... && conditionN(...)) {\n // code that ought to run after all conditions\n};\n// code that ought to run whether all conditions are met or not\n bool conditionN(...) {\n if (!real_condition) return false;\n // code that ought to run\n return true;\n};\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20390/"
] |
243,971
|
<p>What do you think of using a metric of function point to lines of code as a metric?</p>
<p>It makes me think of the old game show "Name That Tune". "I can name that tune in three notes!" I can write that functionality in 0.1 klocs! Is this useful?</p>
<p>It would certainly seem to promote library usage, but is that what you want?</p>
|
[
{
"answer_id": 244298,
"author": "T.E.D.",
"author_id": 29639,
"author_profile": "https://Stackoverflow.com/users/29639",
"pm_score": 0,
"selected": false,
"text": "grep -c \";\" *.h *.cpp | awk -F: '/:/ {x += $2} END {print x}'\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13930/"
] |
243,992
|
<p>When I create a zip Archive via <code>java.util.zip.*</code>, is there a way to split the resulting archive in multiple volumes? </p>
<p>Let's say my overall archive has a <code>filesize</code> of <code>24 MB</code> and I want to split it into 3 files on a limit of 10 MB per file.<br>
Is there a zip API which has this feature? Or any other nice ways to achieve this?</p>
<p>Thanks
Thollsten</p>
|
[
{
"answer_id": 244025,
"author": "sakana",
"author_id": 28921,
"author_profile": "https://Stackoverflow.com/users/28921",
"pm_score": 4,
"selected": true,
"text": "import java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.util.zip.ZipEntry;\nimport java.util.zip.ZipOutputStream;\n\npublic class ChunkedZippedOutputStream {\n\n private ZipOutputStream zipOutputStream;\n\n private final String path;\n private final String name;\n\n private long currentSize;\n private int currentChunkIndex;\n private final long MAX_FILE_SIZE = 16000000; // Whatever size you want\n private final String PART_POSTFIX = \".part.\";\n private final String FILE_EXTENSION = \".zip\";\n\n public ChunkedZippedOutputStream(String path, String name) throws FileNotFoundException {\n this.path = path;\n this.name = name;\n constructNewStream();\n }\n\n public void addEntry(ZipEntry entry) throws IOException {\n long entrySize = entry.getCompressedSize();\n if ((currentSize + entrySize) > MAX_FILE_SIZE) {\n closeStream();\n constructNewStream();\n } else {\n currentSize += entrySize;\n zipOutputStream.putNextEntry(entry);\n }\n }\n\n private void closeStream() throws IOException {\n zipOutputStream.close();\n }\n\n private void constructNewStream() throws FileNotFoundException {\n zipOutputStream = new ZipOutputStream(new FileOutputStream(new File(path, constructCurrentPartName())));\n currentChunkIndex++;\n currentSize = 0;\n }\n\n private String constructCurrentPartName() {\n // This will give names is the form of <file_name>.part.0.zip, <file_name>.part.1.zip, etc.\n return name + PART_POSTFIX + currentChunkIndex + FILE_EXTENSION;\n }\n}\n"
},
{
"answer_id": 51214186,
"author": "tpky",
"author_id": 4396142,
"author_profile": "https://Stackoverflow.com/users/4396142",
"pm_score": 0,
"selected": false,
"text": "import java.io.*;\nimport java.util.Enumeration;\nimport java.util.zip.ZipEntry;\nimport java.util.zip.ZipFile;\nimport java.util.zip.ZipInputStream;\nimport java.util.zip.ZipOutputStream;\n\nclass ChunkedZip {\n private final static long MAX_FILE_SIZE = 1000 * 1000 * 1024; // around 1GB \n private final static String zipCopyDest = \"C:\\\\zip2split\\\\copy\";\n\n public static void splitZip(String zipFileName, String zippedPath, String coreId) throws IOException {\n\n System.out.println(\"process whole zip file..\");\n FileInputStream fis = new FileInputStream(zippedPath);\n ZipInputStream zipInputStream = new ZipInputStream(fis);\n ZipEntry entry = null;\n int currentChunkIndex = 0;\n //using just to get the uncompressed size of the zipentries\n long entrySize = 0;\n ZipFile zipFile = new ZipFile(zippedPath);\n Enumeration enumeration = zipFile.entries();\n\n String copDest = zipCopyDest + \"\\\\\" + coreId + \"_\" + currentChunkIndex + \".zip\";\n\n FileOutputStream fos = new FileOutputStream(new File(copDest));\n BufferedOutputStream bos = new BufferedOutputStream(fos);\n ZipOutputStream zos = new ZipOutputStream(bos);\n long currentSize = 0;\n\n try {\n while ((entry = zipInputStream.getNextEntry()) != null && enumeration.hasMoreElements()) {\n\n ZipEntry zipEntry = (ZipEntry) enumeration.nextElement();\n System.out.println(zipEntry.getName());\n System.out.println(zipEntry.getSize());\n entrySize = zipEntry.getSize();\n\n ByteArrayOutputStream outputStream = new ByteArrayOutputStream();\n //long entrySize = entry.getCompressedSize();\n //entrySize = entry.getSize(); //gives -1\n\n if ((currentSize + entrySize) > MAX_FILE_SIZE) {\n zos.close();\n //construct a new stream\n //zos = new ZipOutputStream(new FileOutputStream(new File(zippedPath, constructCurrentPartName(coreId))));\n currentChunkIndex++;\n zos = getOutputStream(currentChunkIndex, coreId);\n currentSize = 0;\n\n } else {\n currentSize += entrySize;\n zos.putNextEntry(new ZipEntry(entry.getName()));\n byte[] buffer = new byte[8192];\n int length = 0;\n while ((length = zipInputStream.read(buffer)) > 0) {\n outputStream.write(buffer, 0, length);\n }\n\n byte[] unzippedFile = outputStream.toByteArray();\n zos.write(unzippedFile);\n unzippedFile = null;\n outputStream.close();\n zos.closeEntry();\n }\n //zos.close();\n }\n } finally {\n zos.close();\n }\n }\n\n public static ZipOutputStream getOutputStream(int i, String coreId) throws IOException {\n System.out.println(\"inside of getOutputStream()..\");\n ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipCopyDest + \"\\\\\" + coreId + \"_\" + i + \".zip\"));\n // out.setLevel(Deflater.DEFAULT_COMPRESSION);\n return out;\n }\n\n public static void main(String args[]) throws IOException {\n String zipFileName = \"Large_files_for_testing.zip\";\n String zippedPath = \"C:\\\\zip2split\\\\Large_files_for_testing.zip\";\n String coreId = \"Large_files_for_testing\";\n splitZip(zipFileName, zippedPath, coreId);\n }\n}\n"
},
{
"answer_id": 55911479,
"author": "Drakes",
"author_id": 1938889,
"author_profile": "https://Stackoverflow.com/users/1938889",
"pm_score": 1,
"selected": false,
"text": "/**\n * Utility class to split a zip archive into parts (not volumes)\n * by attempting to fit as many entries into a single part before\n * creating a new part. If a part would otherwise be empty because\n * the next entry won't fit, it will be added anyway to avoid empty parts.\n *\n * @author Eric Draken, 2019\n */\npublic class Zip\n{\n private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;\n\n private static final String ZIP_PART_FORMAT = \"%s.part%dof%d.zip\";\n\n private static final String EXT = \"zip\";\n\n private static final Logger logger = LoggerFactory.getLogger( MethodHandles.lookup().lookupClass() );\n\n /**\n * Split a large archive into smaller parts\n *\n * @param zipFile Source zip file to split (must end with .zip)\n * @param outZipFile Destination zip file base path. The \"part\" number will be added automatically\n * @param approxPartSizeBytes Approximate part size\n * @throws IOException Exceptions on file access\n */\n public static void splitZipArchive(\n @NotNull final File zipFile,\n @NotNull final File outZipFile,\n final long approxPartSizeBytes ) throws IOException\n {\n String basename = FilenameUtils.getBaseName( outZipFile.getName() );\n Path basePath = outZipFile.getParentFile() != null ? // Check if this file has a parent folder\n outZipFile.getParentFile().toPath() :\n Paths.get( \"\" );\n String extension = FilenameUtils.getExtension( zipFile.getName() );\n if ( !extension.equals( EXT ) )\n {\n throw new IllegalArgumentException( \"The archive to split must end with .\" + EXT );\n }\n\n // Get a list of entries in the archive\n try ( ZipFile zf = new ZipFile( zipFile ) )\n {\n // Silliness check\n long minRequiredSize = zipFile.length() / 100;\n if ( minRequiredSize > approxPartSizeBytes )\n {\n throw new IllegalArgumentException(\n \"Please select a minimum part size over \" + minRequiredSize + \" bytes, \" +\n \"otherwise there will be over 100 parts.\"\n );\n }\n\n // Loop over all the entries in the large archive\n // to calculate the number of parts required\n Enumeration<? extends ZipEntry> enumeration = zf.entries();\n long partSize = 0;\n long totalParts = 1;\n while ( enumeration.hasMoreElements() )\n {\n long nextSize = enumeration.nextElement().getCompressedSize();\n if ( partSize + nextSize > approxPartSizeBytes )\n {\n partSize = 0;\n totalParts++;\n }\n partSize += nextSize;\n }\n\n // Silliness check: if there are more parts than there\n // are entries, then one entry will occupy one part by contract\n totalParts = Math.min( totalParts, zf.size() );\n\n logger.debug( \"Split requires {} parts\", totalParts );\n if ( totalParts == 1 )\n {\n // No splitting required. Copy file\n Path outFile = basePath.resolve(\n String.format( ZIP_PART_FORMAT, basename, 1, 1 )\n );\n Files.copy( zipFile.toPath(), outFile );\n logger.debug( \"Copied {} to {} (pass-though)\", zipFile.toString(), outFile.toString() );\n return;\n }\n\n // Reset\n enumeration = zf.entries();\n\n // Split into parts\n int currPart = 1;\n ZipEntry overflowZipEntry = null;\n while ( overflowZipEntry != null || enumeration.hasMoreElements() )\n {\n Path outFilePart = basePath.resolve(\n String.format( ZIP_PART_FORMAT, basename, currPart++, totalParts )\n );\n overflowZipEntry = writeEntriesToPart( overflowZipEntry, zf, outFilePart, enumeration, approxPartSizeBytes );\n logger.debug( \"Wrote {}\", outFilePart );\n }\n }\n }\n\n /**\n * Write an entry to the to the outFilePart\n *\n * @param overflowZipEntry ZipEntry that didn't fit in the last part, or null\n * @param inZipFile The large archive to split\n * @param outFilePart The part of the archive currently being worked on\n * @param enumeration Enumeration of ZipEntries\n * @param approxPartSizeBytes Approximate part size\n * @return Overflow ZipEntry, or null\n * @throws IOException File access exceptions\n */\n private static ZipEntry writeEntriesToPart(\n @Nullable ZipEntry overflowZipEntry,\n @NotNull final ZipFile inZipFile,\n @NotNull final Path outFilePart,\n @NotNull final Enumeration<? extends ZipEntry> enumeration,\n final long approxPartSizeBytes\n ) throws IOException\n {\n try (\n ZipOutputStream zos =\n new ZipOutputStream( new FileOutputStream( outFilePart.toFile(), false ) )\n )\n {\n long partSize = 0;\n byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];\n while ( overflowZipEntry != null || enumeration.hasMoreElements() )\n {\n ZipEntry entry = overflowZipEntry != null ? overflowZipEntry : enumeration.nextElement();\n overflowZipEntry = null;\n\n long entrySize = entry.getCompressedSize();\n if ( partSize + entrySize > approxPartSizeBytes )\n {\n if ( partSize != 0 )\n {\n return entry; // Finished this part, but return the dangling ZipEntry\n }\n // Add the entry anyway if the part would otherwise be empty\n }\n partSize += entrySize;\n zos.putNextEntry( entry );\n\n // Get the input stream for this entry and copy the entry\n try ( InputStream is = inZipFile.getInputStream( entry ) )\n {\n int bytesRead;\n while ( (bytesRead = is.read( buffer )) != -1 )\n {\n zos.write( buffer, 0, bytesRead );\n }\n }\n }\n return null; // Finished splitting\n }\n }\n"
},
{
"answer_id": 65830012,
"author": "codigoalvo",
"author_id": 2547418,
"author_profile": "https://Stackoverflow.com/users/2547418",
"pm_score": 0,
"selected": false,
"text": "public abstract class ZipHelper {\n\n public static NumberFormat formater = NumberFormat.getNumberInstance(new Locale(\"pt\", \"BR\"));\n\n public static List<Path> zip(Collection<File> inputFiles, long maxSize) throws IOException {\n\n byte[] buffer = new byte[1024];\n int count = 0;\n long currentZipSize = maxSize;\n List<Path> response = new ArrayList<>();\n ZipOutputStream zip = null;\n for (File currentFile : inputFiles) {\n long nextFileSize = currentFile.length();\n long predictedZipSize = currentZipSize + nextFileSize;\n boolean needNewFile = predictedZipSize >= maxSize;\n System.out.println(\"[=] ZIP current (\" + formater.format(currentZipSize) + \") + next file (\" + formater.format(nextFileSize) + \") = predicted (\" + formater.format(predictedZipSize) + \") > max (\" + formater.format(maxSize) + \") ? \" + needNewFile);\n if (needNewFile) {\n safeClose(zip);\n Path tmpFile = Files.createTempFile(\"teste-\", (\".part.\" + count++ + \".zip\"));\n System.out.println(\"[#] Starting new file: \" + tmpFile);\n zip = new ZipOutputStream(Files.newOutputStream(tmpFile));\n zip.setLevel(Deflater.BEST_COMPRESSION);\n response.add(tmpFile);\n currentZipSize = 0;\n }\n ZipEntry zipEntry = new ZipEntry(currentFile.getName());\n System.out.println(\"[<] Adding to ZIP: \" + currentFile.getName());\n zip.putNextEntry(zipEntry);\n FileInputStream in = new FileInputStream(currentFile);\n zip.write(in.readAllBytes());\n zip.closeEntry();\n safeClose(in);\n long compressed = zipEntry.getCompressedSize();\n System.out.println(\"[=] Compressed current file: \" + formater.format(compressed));\n currentZipSize += zipEntry.getCompressedSize();\n }\n safeClose(zip);\n return response;\n }\n\n public static void safeClose(Closeable... closeables) {\n if (closeables != null) {\n for (Closeable closeable : closeables) {\n if (closeable != null) {\n try {\n System.out.println(\"[X] Closing: (\" + closeable.getClass() + \") - \" + closeable);\n closeable.close();\n } catch (Throwable ex) {\n System.err.println(\"[!] Error on close: \" + closeable);\n ex.printStackTrace();\n }\n }\n }\n }\n }\n}\n [?] Files to process: [\\data\\teste\\TestFile(1).pdf, \\data\\teste\\TestFile(2).pdf, \\data\\teste\\TestFile(3).pdf, \\data\\teste\\TestFile(4).pdf, \\data\\teste\\TestFile(5).pdf, \\data\\teste\\TestFile(6).pdf, \\data\\teste\\TestFile(7).pdf]\n[=] ZIP current (3.145.728) + next file (1.014.332) = predicted (4.160.060) > max (3.145.728) ? true\n[#] Starting new file: C:\\Users\\Cassio\\AppData\\Local\\Temp\\teste-3319961516431535912.part.0.zip\n[<] Adding to ZIP: TestFile(1).pdf\n[X] Closing: (class java.io.FileInputStream) - java.io.FileInputStream@3d99d22e\n[=] Compressed current file: 940.422\n[=] ZIP current (940.422) + next file (1.511.862) = predicted (2.452.284) > max (3.145.728) ? false\n[<] Adding to ZIP: TestFile(2).pdf\n[X] Closing: (class java.io.FileInputStream) - java.io.FileInputStream@49fc609f\n[=] Compressed current file: 1.475.178\n[=] ZIP current (2.415.600) + next file (2.439.287) = predicted (4.854.887) > max (3.145.728) ? true\n[X] Closing: (class java.util.zip.ZipOutputStream) - java.util.zip.ZipOutputStream@cd2dae5\n[#] Starting new file: C:\\Users\\Cassio\\AppData\\Local\\Temp\\teste-8849887746791381380.part.1.zip\n[<] Adding to ZIP: TestFile(3).pdf\n[X] Closing: (class java.io.FileInputStream) - java.io.FileInputStream@4973813a\n[=] Compressed current file: 2.374.718\n[=] ZIP current (2.374.718) + next file (2.385.447) = predicted (4.760.165) > max (3.145.728) ? true\n[X] Closing: (class java.util.zip.ZipOutputStream) - java.util.zip.ZipOutputStream@6321e813\n[#] Starting new file: C:\\Users\\Cassio\\AppData\\Local\\Temp\\teste-6305809161676875106.part.2.zip\n[<] Adding to ZIP: TestFile(4).pdf\n[X] Closing: (class java.io.FileInputStream) - java.io.FileInputStream@79be0360\n[=] Compressed current file: 2.202.203\n[=] ZIP current (2.202.203) + next file (292.918) = predicted (2.495.121) > max (3.145.728) ? false\n[<] Adding to ZIP: TestFile(5).pdf\n[X] Closing: (class java.io.FileInputStream) - java.io.FileInputStream@22a67b4\n[=] Compressed current file: 230.491\n[=] ZIP current (2.432.694) + next file (4.197.512) = predicted (6.630.206) > max (3.145.728) ? true\n[X] Closing: (class java.util.zip.ZipOutputStream) - java.util.zip.ZipOutputStream@57855c9a\n[#] Starting new file: C:\\Users\\Cassio\\AppData\\Local\\Temp\\teste-17160527941340008316.part.3.zip\n[<] Adding to ZIP: TestFile(6).pdf\n[X] Closing: (class java.io.FileInputStream) - java.io.FileInputStream@3b084709\n[=] Compressed current file: 3.020.115\n[=] ZIP current (3.020.115) + next file (1.556.237) = predicted (4.576.352) > max (3.145.728) ? true\n[X] Closing: (class java.util.zip.ZipOutputStream) - java.util.zip.ZipOutputStream@3224f60b\n[#] Starting new file: C:\\Users\\Cassio\\AppData\\Local\\Temp\\teste-14050058835776413808.part.4.zip\n[<] Adding to ZIP: TestFile(7).pdf\n[X] Closing: (class java.io.FileInputStream) - java.io.FileInputStream@63e2203c\n[=] Compressed current file: 1.460.566\n[X] Closing: (class java.util.zip.ZipOutputStream) - java.util.zip.ZipOutputStream@1efed156\n[>] Generated ZIP files(s): [C:\\Users\\Cassio\\AppData\\Local\\Temp\\teste-3319961516431535912.part.0.zip, C:\\Users\\Cassio\\AppData\\Local\\Temp\\teste-8849887746791381380.part.1.zip, C:\\Users\\Cassio\\AppData\\Local\\Temp\\teste-6305809161676875106.part.2.zip, C:\\Users\\Cassio\\AppData\\Local\\Temp\\teste-17160527941340008316.part.3.zip, C:\\Users\\Cassio\\AppData\\Local\\Temp\\teste-14050058835776413808.part.4.zip]\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9688/"
] |
243,995
|
<p>I am trying to set the permissions of a folder and all of it's children on a vista computer. The code I have so far is this.</p>
<pre><code> public static void SetPermissions(string dir)
{
DirectoryInfo info = new DirectoryInfo(dir);
DirectorySecurity ds = info.GetAccessControl();
ds.AddAccessRule(new FileSystemAccessRule(@"BUILTIN\Users",
FileSystemRights.FullControl,
InheritanceFlags.ContainerInherit,
PropagationFlags.None,
AccessControlType.Allow));
info.SetAccessControl(ds);
}
</code></pre>
<p>However it's not working as I would expect it to.<br>
Even if I run the code as administrator it will not set the permissions.</p>
<p>The folder I am working with is located in C:\ProgramData\<my folder> and I can manually change the rights on it just fine.</p>
<p>Any one want to point me in the right direction.</p>
|
[
{
"answer_id": 244798,
"author": "Erin",
"author_id": 22835,
"author_profile": "https://Stackoverflow.com/users/22835",
"pm_score": 4,
"selected": true,
"text": "public static void SetPermissions(string dir)\n {\n DirectoryInfo info = new DirectoryInfo(dir);\n DirectorySecurity ds = info.GetAccessControl(); \n ds.AddAccessRule(new FileSystemAccessRule(@\"BUILTIN\\Users\", \n FileSystemRights.FullControl,\n InheritanceFlags.ObjectInherit |\n InheritanceFlags.ContainerInherit,\n PropagationFlags.None,\n AccessControlType.Allow));\n info.SetAccessControl(ds); \n }\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/243995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22835/"
] |
244,001
|
<p>I know that cursors are frowned upon and I try to avoid their use as much as possible, but there may be some legitimate reasons to use them. I have one and I am trying to use a pair of cursors: one for the primary table and one for the secondary table. The primary table cursor iterates through the primary table in an outer loop. the secondary table cursor iterates through the secondary table in the inner loop.
The problem is, that the primary table cursor though apparently proceeding and saving the primary key column value [Fname] into a local variable @Fname, but it does not get the row for the corresponding foreign key column in the secondary table. For the secondary table it always returns the rows whose foreign key column value matches the primary key column value of the <strong>first row</strong> of the primary table. </p>
<p>Following is a very simplified example for what I want to do in the real stored procedure.
Names is the primary table</p>
<pre><code>SET NOCOUNT ON
DECLARE
@Fname varchar(50) -- to hold the fname column value from outer cursor loop
,@FK_Fname varchar(50) -- to hold the fname column value from inner cursor loop
,@score int
;
--prepare primary table to be iterated in the outer loop
DECLARE @Names AS Table (Fname varchar(50))
INSERT @Names
SELECT 'Jim' UNION
SELECT 'Bob' UNION
SELECT 'Sam' UNION
SELECT 'Jo'
--prepare secondary/detail table to be iterated in the inner loop
DECLARE @Scores AS Table (Fname varchar(50), Score int)
INSERT @Scores
SELECT 'Jo',1 UNION
SELECT 'Jo',5 UNION
SELECT 'Jim',4 UNION
SELECT 'Bob',10 UNION
SELECT 'Bob',15
--cursor to iterate on the primary table in the outer loop
DECLARE curNames CURSOR
FOR SELECT Fname FROM @Names
OPEN curNames
FETCH NEXT FROM curNames INTO @Fname
--cursor to iterate on the secondary table in the inner loop
DECLARE curScores CURSOR
FOR
SELECT FName,Score
FROM @Scores
WHERE Fname = @Fname
--*** NOTE: Using the primary table's column value @Fname from the outer loop
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'Outer loop @Fname = ' + @Fname
OPEN curScores
FETCH NEXT FROM curScores INTO @FK_Fname, @Score
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT ' FK_Fname=' + @FK_Fname + '. Score=' + STR(@Score)
FETCH NEXT FROM curScores INTO @FK_Fname, @Score
END
CLOSE curScores
FETCH NEXT FROM curNames INTO @Fname
END
DEALLOCATE curScores
CLOSE curNames
DEALLOCATE curNames
</code></pre>
<p>Here is what I get for the result. Please note that for the outer loop it DOES show the up-to-date Fname, but when that Fname is used as @Fname to fetch the relevant row from the secondary table for the succeeding iterations, it still get the rows that match the first row (Bob) of the primary table.</p>
<pre><code>Outer loop @Fname = Bob
FK_Fname=Bob. Score=10
FK_Fname=Bob. Score=15
Outer loop @Fname = Jim
FK_Fname=Bob. Score=10
FK_Fname=Bob. Score=15
Outer loop @Fname = Jo
FK_Fname=Bob. Score=10
FK_Fname=Bob. Score=15
Outer loop @Fname = Sam
FK_Fname=Bob. Score=10
FK_Fname=Bob. Score=15
</code></pre>
<p>Please let me know what am I do wrong.
Thanks in advance!</p>
|
[
{
"answer_id": 244024,
"author": "Eduardo Campañó",
"author_id": 12091,
"author_profile": "https://Stackoverflow.com/users/12091",
"pm_score": 0,
"selected": false,
"text": "DECLARE curScores CURSOR\nFOR \n SELECT FName,Score \n FROM @Scores \n WHERE Fname = @Fname \n"
},
{
"answer_id": 244582,
"author": "Aamir",
"author_id": 262613,
"author_profile": "https://Stackoverflow.com/users/262613",
"pm_score": 1,
"selected": false,
"text": "SET NOCOUNT ON\nDECLARE \n @Fname varchar(50) -- to hold the fname column value from outer cursor loop\n ,@FK_Fname varchar(50) -- to hold the fname column value from inner cursor loop\n ,@score int\n;\n\n--prepare primary table to be iterated in the outer loop\nDECLARE @Names AS Table (Fname varchar(50))\nINSERT @Names\n SELECT 'Jim' UNION\n SELECT 'Bob' UNION\n SELECT 'Sam' UNION\n SELECT 'Jo' \n\n\n--prepare secondary/detail table to be iterated in the inner loop\nDECLARE @Scores AS Table (Fname varchar(50), Score int)\nINSERT @Scores\n SELECT 'Jo',1 UNION\n SELECT 'Jo',5 UNION\n SELECT 'Jim',4 UNION\n SELECT 'Bob',10 UNION\n SELECT 'Bob',15 \n\n--cursor to iterate on the primary table in the outer loop\nDECLARE curNames CURSOR\nFOR SELECT Fname FROM @Names\n\n\nOPEN curNames\nFETCH NEXT FROM curNames INTO @Fname\n\n--cursor to iterate on the secondary table in the inner loop\nDECLARE curScores CURSOR\nFOR \n SELECT FName,Score \n FROM @Scores \n WHERE Fname = @Fname \n --*** NOTE: Using the primary table's column value @Fname from the outer loop\n\nWHILE @@FETCH_STATUS = 0\nBEGIN\n PRINT 'Outer loop @Fname = ' + @Fname\n\n OPEN curScores\n FETCH NEXT FROM curScores INTO @FK_Fname, @Score\n\n WHILE @@FETCH_STATUS = 0\n BEGIN\n PRINT ' FK_Fname=' + @FK_Fname + '. Score=' + STR(@Score)\n FETCH NEXT FROM curScores INTO @FK_Fname, @Score\n END\n CLOSE curScores\n FETCH NEXT FROM curNames INTO @Fname\nEND\n\nDEALLOCATE curScores\n\nCLOSE curNames\nDEALLOCATE curNames\n Outer loop @Fname = Bob\n FK_Fname=Bob. Score= 10\n FK_Fname=Bob. Score= 15\nOuter loop @Fname = Jim\n FK_Fname=Jim. Score= 4\nOuter loop @Fname = Jo\n FK_Fname=Jo. Score= 1\n FK_Fname=Jo. Score= 5\nOuter loop @Fname = Sam\n"
},
{
"answer_id": 244606,
"author": "jcollum",
"author_id": 30946,
"author_profile": "https://Stackoverflow.com/users/30946",
"pm_score": 1,
"selected": false,
"text": "create table #temp1\n(\n row int identity(1,1)\n , ... \n)\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/262613/"
] |
244,009
|
<p>In my Rails controller, I'm creating multiple instances of the same model class. I want to add some RSpec expectations so I can test that it is creating the correct number with the correct parameters. So, here's what I have in my spec:</p>
<pre>
Bandmate.should_receive(:create).with(:band_id => @band.id, :user_id => @user.id, :position_id => 1, :is_leader => true)
Bandmate.should_receive(:create).with(:band_id => @band.id, :user_id => "2222", :position_id => 2)
Bandmate.should_receive(:create).with(:band_id => @band.id, :user_id => "3333", :position_id => 3)
Bandmate.should_receive(:create).with(:band_id => @band.id, :user_id => "4444", :position_id => 4)
</pre>
<p>This is causing problems because it seems that the Bandmate class can only have 1 "should_receive" expectation set on it. So, when I run the example, I get the following error:</p>
<pre>
Spec::Mocks::MockExpectationError in 'BandsController should create all the bandmates when created'
Mock 'Class' expected :create with ({:band_id=>1014, :user_id=>999, :position_id=>1, :is_leader=>true}) but received it with ({:band_id=>1014, :user_id=>"2222", :position_id=>"2"})
</pre>
<p>Those are the correct parameters for the second call to create, but RSpec is testing against the wrong parameters.</p>
<p>Does anyone know how I can set up my should_receive expectations to allow multiple different calls?</p>
|
[
{
"answer_id": 248742,
"author": "James Baker",
"author_id": 9365,
"author_profile": "https://Stackoverflow.com/users/9365",
"pm_score": 6,
"selected": true,
"text": ".ordered"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19964/"
] |
244,018
|
<p>I'm using Flex 3 in the UI of a Windows app (Flash player as an embedded ActiveX control), and passing data between them with ExternalInterface (primarily into the Flex app, as opposed to out). I'm finding, though, that the performance is pretty awful, particularly with larger (i.e., custom) objects; the more EI calls we make, and the larger the custom objects as pass in, the harder things seem to drop off performance-wise.</p>
<p>I'm assuming there's a good deal of overhead in serializing these objects, so I'm wondering, are there any best practices out there for using ExternalInterface in this particular way? There doesn't seem to be much out there in terms of documentation on this subject yet.</p>
<p>Is it better, say, to pass a large block of XML into the player control as a string, and parse it with Flex, than to pass it as a custom object, as a rule? How should Flex apps requiring a relatively tight integration with their host apps best use ExternalInterface without sacrificing performance? Is EI performance an issue Adobe is addressing? Any implementation differences between players 9 and 10? What kinds of things should we avoid to get the most out of this feature?</p>
<p>Thanks in advance!</p>
<p>Chris </p>
|
[
{
"answer_id": 248742,
"author": "James Baker",
"author_id": 9365,
"author_profile": "https://Stackoverflow.com/users/9365",
"pm_score": 6,
"selected": true,
"text": ".ordered"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32129/"
] |
244,019
|
<p>I've used HttpWebRequests to post data to HTTPS websites before, and I've never had todo anything different than a regular HTTP Post.</p>
<p>Does anyone know if there are any tricks involved that I missed to ensure that this is done properly?</p>
|
[
{
"answer_id": 244089,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 2,
"selected": false,
"text": "System.Net.ServicePointManager.ServerCertificateValidationCallback +=\n delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate,\n System.Security.Cryptography.X509Certificates.X509Chain chain,\n System.Net.Security.SslPolicyErrors sslPolicyErrors)\n {\n return true; // **** Always accept\n };\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] |
244,029
|
<p>I am trying to insert a time only value, but get the following error</p>
<blockquote>
<ul>
<li>ex {"SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM."} System.Exception</li>
</ul>
</blockquote>
<p>From the front end, the time is selected using the "TimeEdit" control, with the up and down arrows. The table in SQL Server has the fields set as smalldatetime. I only need to store the time. I use the following to return data to the app</p>
<p>select id,CONVERT(CHAR(5),timeFrom,8)as timeFrom,CONVERT(CHAR(5),timeTo,8)as timeTo
FROM dbo.Availability
where id = @id
and dayName = @weekday</p>
<p>How do I pass time only to the table?</p>
<p>Edit ~ Solution
As per Euardo and Chris, my solution was to pass a datetime string instead of a time only string. I formatted my result as per <a href="http://msdn.microsoft.com/en-us/library/az4se3k1(VS.71).aspx" rel="nofollow noreferrer">Time Format</a> using "g".</p>
<p>Thanks</p>
|
[
{
"answer_id": 244041,
"author": "StingyJack",
"author_id": 16391,
"author_profile": "https://Stackoverflow.com/users/16391",
"pm_score": -1,
"selected": false,
"text": "SELECT (GETDATE() - (CAST(FLOOR(CAST(GETDATE() as FLOAT)) AS DateTime)))\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23667/"
] |
244,034
|
<p>Wanna write a RegEx to validate a driving license. </p>
<p>if it doesn't start with (US, CA, CN) then it has to be followed with XX and after that with any number of Alpha numeric letters. </p>
<p>So for example if the driving license starts with GB then it has to be followed with XX
GBXX12345363
However if it starts with US then we don't care what comes after it.
USLA039247230</p>
|
[
{
"answer_id": 244045,
"author": "Tanktalus",
"author_id": 23512,
"author_profile": "https://Stackoverflow.com/users/23512",
"pm_score": 0,
"selected": false,
"text": "/^(?:(?:US|CA|CN)\\w+|[[:alpha:]]{2}XX\\w+)$/\n"
},
{
"answer_id": 244094,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 0,
"selected": false,
"text": "/^((US|CA|CN)[a-zA-Z\\d]*|[a-zA-Z]{2}XX[a-zA-Z\\d]*)$/\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
244,063
|
<p>I have a <code><button></code> with an accesskey assgined to it. The accesskey works fine as long as the button is visible, but when I set <code>display: none</code> or <code>visibility: hidden</code>, the accesskey no longer works.</p>
<p>Also tried without success:</p>
<ul>
<li>Use a different element type: a, input (various types, even typeless).</li>
<li>Assign the accesskey to a label that wraps the invisible control.</li>
</ul>
<p>Note, I'm not sure if this is the standard behavior, but prior to Firefox 3 the accesskey seemed to worked regardless of visibility.</p>
|
[
{
"answer_id": 244176,
"author": "Sal",
"author_id": 32144,
"author_profile": "https://Stackoverflow.com/users/32144",
"pm_score": 2,
"selected": false,
"text": "display:none visibility:hidden"
},
{
"answer_id": 245831,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<button accesskey=\"a\" style=\"position: absolute; top: -9999px\">button</button>\n"
},
{
"answer_id": 6095905,
"author": "Catalin Z. Alexandru",
"author_id": 765824,
"author_profile": "https://Stackoverflow.com/users/765824",
"pm_score": 1,
"selected": false,
"text": "height: 0px; margin: 0px; padding: 0px;"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14749/"
] |
244,085
|
<p>Delphi 2009 complains with an E2283 error: [DCC Error] outputcode.pas(466): E2283 Too many local constants. Use shorter procedures</p>
<p>Delphi 2007 compiles just fine. I can't find an abundance of local constants, it's a short (500 line) unit. Do you see any abundance of constants or literals I can address?</p>
<pre><code>procedure TOutputCodeForm.FormCreate(Sender: TObject);
var
poParser : TStringStream;
begin
if ( IsWindowsVista() ) then
begin
SetVistaFonts( self );
end;
poParser := TStringStream.Create( gstrSQLParser );
SQLParser := TSyntaxMemoParser.Create( self );
SQLParser.RegistryKey := '\Software\Advantage Data Architect\SQLSyntaxMemo';
SQLParser.UseRegistry := True;
SQLParser.CompileFromStream( poParser );
FreeAndNil( poParser );
poParser := TStringStream.Create( gstrCPPParser );
cppParser := TSyntaxMemoParser.Create( self );
cppParser.RegistryKey := '\Software\Advantage Data Architect\SQLSyntaxMemo';
cppParser.UseRegistry := True;
cppParser.CompileFromStream( poParser );
FreeAndNil( poParser );
poParser := TStringStream.Create( gstrPasParser );
pasParser := TSyntaxMemoParser.Create( self );
pasParser.RegistryKey := '\Software\Advantage Data Architect\SQLSyntaxMemo';
pasParser.Script := ExtractFilePath( Application.ExeName ) + 'pasScript.txt';
pasParser.CompileFromStream( poParser );
{* Free the stream since we are finished with it. *}
FreeAndNil( poParser );
poCodeOutput := TSyntaxMemo.Create( self );
poCodeOutput.Parent := Panel1;
poCodeOutput.Left := 8;
poCodeOutput.Top := 8;
poCodeOutput.Width := Panel1.Width - 16;
poCodeOutput.Height := Panel1.Height - 16;
poCodeOutput.ClipCopyFormats := [smTEXT, smRTF];
poCodeOutput.Font.Charset := ANSI_CHARSET;
poCodeOutput.Font.Color := clWindowText;
poCodeOutput.Font.Height := -11;
poCodeOutput.Font.Name := 'Courier New';
poCodeOutput.Font.Style := [];
poCodeOutput.GutterFont.Charset := DEFAULT_CHARSET;
poCodeOutput.GutterFont.Color := clWindowText;
poCodeOutput.GutterFont.Height := -11;
poCodeOutput.GutterFont.Name := 'MS Sans Serif';
poCodeOutput.GutterFont.Style := [];
poCodeOutput.HyperCursor := crDefault;
poCodeOutput.IndentStep := 1;
poCodeOutput.Margin := 2;
poCodeOutput.Modified := False;
poCodeOutput.MonoPrint := True;
poCodeOutput.Options := [smoSyntaxHighlight, smoPrintWrap, smoPrintLineNos, smoPrintFilename, smoPrintDate, smoPrintPageNos, smoAutoIndent, smoTabToColumn, smoWordSelect, smoShowRMargin, smoShowGutter, smoShowWrapColumn, smoTitleAsFilename, smoProcessDroppedFiles, smoBlockOverwriteCursor, smoShowWrapGlyph, smoColumnTrack, smoUseTAB, smoSmartFill, smoOLEDragSource];
poCodeOutput.ReadOnly := False;
poCodeOutput.RightMargin := 80;
poCodeOutput.SaveFormat := sfTEXT;
poCodeOutput.ScrollBars := ssBoth;
poCodeOutput.SelLineStyle := lsCRLF;
poCodeOutput.SelStart := 3;
poCodeOutput.SelLength := 0;
poCodeOutput.SelTextColor := clWhite;
poCodeOutput.SelTextBack := clBlack;
poCodeOutput.TabDefault := 4;
poCodeOutput.TabOrder := 0;
poCodeOutput.VisiblePropEdPages := [ppOPTIONS, ppHIGHLIGHTING, ppKEYS, ppAUTOCORRECT, ppTEMPLATES];
poCodeOutput.WrapAtColumn := 0;
poCodeOutput.OnKeyDown := FormKeyDown;
poCodeOutput.ActiveParser := 3;
poCodeOutput.Anchors := [akLeft, akTop, akRight, akBottom];
poCodeOutput.Parser1 := pasParser;
poCodeOutput.Parser2 := cppParser;
poCodeOutput.Parser3 := SQLParser;
SQLParser.AttachEditor( poCodeOutput );
cppParser.AttachEditor( poCodeOutput );
pasParser.AttachEditor( poCodeOutput );
poCodeOutput.Lines.AddStrings( poCode );
if ( CodeType = ctCPP ) then
poCodeOutput.ActiveParser := 2
else if ( CodeType = ctPascal ) then
poCodeOutput.ActiveParser := 1
else
poCodeOutput.ActiveParser := 3;
MainForm.AdjustFormSize( self, 0.95, 0.75 );
end;
</code></pre>
|
[
{
"answer_id": 244488,
"author": "Jeremy Mullin",
"author_id": 7893,
"author_profile": "https://Stackoverflow.com/users/7893",
"pm_score": 0,
"selected": false,
"text": "procedure TOutputCodeForm.FormCreate(Sender: TObject);\nbegin\n\n if ( IsWindowsVista() ) then\n begin\n SetVistaFonts( self );\n end;\n\n SetupParser( SQLParser, gstrSQLParser, '' );\n // unresolved jmu - have to comment this out for now or delphi will complain\n // that there are too many literals in this file. Seems like a delphi bug\n // since this builds in older versions, and I've already refactored it.\n //SetupParser( cppParser, gstrCPPParser, '' );\n SetupParser( pasParser, gstrPasParser, ExtractFilePath( Application.ExeName ) + 'pasScript.txt' );\n SetupCodeOutput( poCodeOutput );\n\n SQLParser.AttachEditor( poCodeOutput );\n cppParser.AttachEditor( poCodeOutput );\n pasParser.AttachEditor( poCodeOutput );\n\n poCodeOutput.Lines.AddStrings( poCode );\n\n if ( CodeType = ctCPP ) then\n poCodeOutput.ActiveParser := 2\n else if ( CodeType = ctPascal ) then\n poCodeOutput.ActiveParser := 1\n else\n poCodeOutput.ActiveParser := 3;\n\n MainForm.AdjustFormSize( self, 0.95, 0.75 );\nend;\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7893/"
] |
244,087
|
<p>What are some things I can do to improve query performance of an oracle query without creating indexes?</p>
<p>Here is the query I'm trying to run faster:</p>
<pre><code>SELECT c.ClaimNumber, a.ItemDate, c.DTN, b.FilePath
FROM items a,
itempages b,
keygroupdata c
WHERE a.ItemType IN (112,115,189,241)
AND a.ItemNum = b.ItemNum
AND b.ItemNum = c.ItemNum
ORDER BY a.DateStored DESC
</code></pre>
<p>None of these columns are indexed and each of the tables contains millions of records. Needless to say, it takes over 3 and half minutes for the query to execute. This is a third party database in a production environment and I'm not allowed to create any indexes so any performance improvements would have to be made to the query itself.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 244131,
"author": "Rob Booth",
"author_id": 16445,
"author_profile": "https://Stackoverflow.com/users/16445",
"pm_score": 4,
"selected": true,
"text": "SELECT c.ClaimNumber, a.ItemDate, c.DTN, b.FilePath\nFROM items a\nINNER JOIN itempages b ON b.ItemNum = a.ItemNum\nINNER JOIN keygroupdata c ON c.ItemNum = b.ItemNum\nWHERE a.ItemType IN (112,115,189,241)\nORDER BY a.DateStored DESC\n"
},
{
"answer_id": 244241,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 1,
"selected": false,
"text": "itemType IN (...)"
},
{
"answer_id": 244313,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 2,
"selected": false,
"text": "select \n c.claimnumber,\n a.itemdate, \n c.dtn,\n b.filepath\nfrom \n (\n select itemdate\n from items it\n where it.itemtype in(112,115,189,241)\n ) a\n itempages b,\n keygroupdata c\nwhere a.itemnum = b.itemnum\n and b.itemnum = c.itemnum\n SELECT /*+RULE*/\n c.ClaimNumber, a.ItemDate, c.DTN, b.FilePath\nFROM\n items a,\n itempages b,\n keygroupdata c\nWHERE a.ItemType IN (112,115,189,241)\n AND a.ItemNum = b.ItemNum\n AND b.ItemNum = c.ItemNum\nORDER BY a.DateStored DESC\n"
},
{
"answer_id": 246720,
"author": "Brian Schmitt",
"author_id": 30492,
"author_profile": "https://Stackoverflow.com/users/30492",
"pm_score": 0,
"selected": false,
"text": "SELECT c.ClaimNumber, a.ItemDate, c.DTN, b.FilePath\nFROM items a,\nitempages b,\nkeygroupdata c\nWHERE ((a.ItemType IN ('112','115','189','241'))\nAND (a.ItemNum = b.ItemNum)\nAND (b.ItemNum = c.ItemNum))\nORDER BY a.DateStored DESC\n"
},
{
"answer_id": 8071856,
"author": "armin walland",
"author_id": 1038572,
"author_profile": "https://Stackoverflow.com/users/1038572",
"pm_score": 1,
"selected": false,
"text": "with a as (\n select \n * \n from \n items \n where \n ItemType IN (112,115,189,241)\n)\nSELECT \n c.ClaimNumber\n , a.ItemDate\n , c.DTN, b.FilePath\nFROM \n a,\n itempages b,\n keygroupdata c\nWHERE \n a.ItemNum = b.ItemNum\n AND b.ItemNum = c.ItemNum\nORDER BY \n a.DateStored DESC\n /*+ MATERIALIZE */ WITH"
},
{
"answer_id": 47328788,
"author": "Max Lambertini",
"author_id": 1035663,
"author_profile": "https://Stackoverflow.com/users/1035663",
"pm_score": 0,
"selected": false,
"text": "\nwith a as (select /*+ MATERIALIZE */ ItemType, ItemNum, DateStored, ItemDate from items where ItemType in (112,115,189,241))\nSELECT c.ClaimNumber, a.ItemDate, c.DTN, b.FilePath\nFROM a,\nitempages b,\nkeygroupdata c\nWHERE a.ItemNum = b.ItemNum\nAND b.ItemNum = c.ItemNum\nORDER BY a.DateStored DESC\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2849/"
] |
244,110
|
<p>Here's the code. Not much to it.</p>
<pre><code><?php
include("Spreadsheet/Excel/Writer.php");
$xls = new Spreadsheet_Excel_Writer();
$sheet = $xls->addWorksheet('At a Glance');
$colNames = array('Foo', 'Bar');
$sheet->writeRow(0, 0, $colNames, $colHeadingFormat);
for($i=1; $i<=10; $i++)
{
$row = array( "foo $i", "bar $i");
$sheet->writeRow($rowNumber++, 0, $row);
}
header ("Expires: " . gmdate("D,d M Y H:i:s") . " GMT");
header ("Last-Modified: " . gmdate("D,d M Y H:i:s") . " GMT");
header ("Cache-Control: no-cache, must-revalidate");
header ("Pragma: no-cache");
$xls->send("test.xls");
$xls->close();
?>
</code></pre>
<p>The issue is that I get the following error when I actually open the file with Excel:</p>
<pre><code>File error: data may have been lost.
</code></pre>
<p>Even stranger is the fact that, despite the error, the file seems fine. Any data I happen to be writing is there.</p>
<p>Any ideas on how to get rid of this error?</p>
<hr />
<h3>Edit</h3>
<p>I've modified the code sample to better illustrate the problem. I don't think the first sample was a legit test.</p>
|
[
{
"answer_id": 244404,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 4,
"selected": true,
"text": "$sheet->writeRow(0, 0, $colNames, $colHeadingFormat);\n for($i=1; $i<=10; $i++)\n{\n $row = array( \"foo $i\", \"bar $i\");\n\n $sheet->writeRow($rowNumber++, 0, $row);\n}\n <?php\ninclude(\"Spreadsheet/Excel/Writer.php\");\n\n$xls = new Spreadsheet_Excel_Writer();\n\n$rowNumber = 0;\n$sheet = $xls->addWorksheet('At a Glance');\n\n$colNames = array('Foo', 'Bar');\n$sheet->writeRow($rowNumber, 0, $colNames, $colHeadingFormat);\n\nfor($i=1; $i<=10; $i++)\n{\n $rowNumber++;\n $row = array( \"foo $i\", \"bar $i\");\n\n $sheet->writeRow($rowNumber, 0, $row);\n}\n\nheader (\"Expires: \" . gmdate(\"D,d M Y H:i:s\") . \" GMT\");\nheader (\"Last-Modified: \" . gmdate(\"D,d M Y H:i:s\") . \" GMT\");\nheader (\"Cache-Control: no-cache, must-revalidate\");\nheader (\"Pragma: no-cache\");\n$xls->send(\"test.xls\");\n$xls->close();\n?>\n"
},
{
"answer_id": 258324,
"author": "jmcnamara",
"author_id": 10238,
"author_profile": "https://Stackoverflow.com/users/10238",
"pm_score": 2,
"selected": false,
"text": "$rowNumber"
},
{
"answer_id": 1660780,
"author": "Joernsn",
"author_id": 168502,
"author_profile": "https://Stackoverflow.com/users/168502",
"pm_score": 0,
"selected": false,
"text": "$this->m_excel->getActiveSheet()->SetCellValue($chr[$col].$row, $data));\n $row"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
] |
244,113
|
<p>I'm working on a stored procedure in SQL Server 2000 with a temp table defined like this:</p>
<pre>CREATE TABLE #MapTable (Category varchar(40), Code char(5))</pre>
<p>After creating the table I want to insert some standard records (which will then be supplemented dynamically in the procedure). Each category (about 10) will have several codes (typically 3-5), and I'd like to express the insert operation for each category in one statement. </p>
<p>Any idea how to do that? </p>
<p>The best idea I've had so far is to keep a real table in the db as a template, but I'd really like to avoid that if possible. The database where this will live is a snapshot of a mainframe system, such that the entire database is blown away every night and re-created in a batch process- stored procedures are re-loaded from source control at the end of the process.</p>
<p>The issue I'm trying to solve isn't so much keeping it to one statement as it is trying to avoid re-typing the category name over and over.</p>
|
[
{
"answer_id": 244158,
"author": "DJ.",
"author_id": 10492,
"author_profile": "https://Stackoverflow.com/users/10492",
"pm_score": 0,
"selected": false,
"text": "CREATE TABLE #MapTable (Category varchar(40), Code char(5))\n\nINSERT INTO #MapTable \nSELECT X.Category, X.Code FROM\n(SELECT 'Foo' as Category, 'AAAAA' as Code\nUNION\nSELECT 'Foo' as Category, 'BBBBB' as Code\nUNION\nSELECT 'Foo' as Category, 'CCCCC' as Code) AS X\n\nSELECT * FROM #MapTable\n"
},
{
"answer_id": 244194,
"author": "Bob Probst",
"author_id": 12424,
"author_profile": "https://Stackoverflow.com/users/12424",
"pm_score": 3,
"selected": false,
"text": "insert into #MapTable (category,code) values ('Foo','AAAAA')\ninsert into #MapTable (category,code) values ('Foo','BBBBB')\ninsert into #MapTable (category,code) values ('Foo','CCCCC')\ninsert into #MapTable (category,code) values ('Bar','AAAAA')\n CREATE TABLE #MapTable (Category varchar(40), Code char(5))\n\nINSERT INTO #MapTable (Category, Code)\nSELECT 'Foo', 'AAAAA'\nUNION\nSELECT 'Foo', 'BBBBB'\nUNION\nSELECT 'Foo', 'CCCCC' \n\nSELECT * FROM #MapTable\n =\"insert into #MapTable (category,code) values ('\"&A1&\"','\"&B1&\"')\"\n"
},
{
"answer_id": 244638,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "SELECT 'foo1', b.code\nFROM ( select 'bar11' as code\n union select 'bar12'\n union select 'bar13' ) b\n\nUNION SELECT 'foo2', b.code\nFROM ( select 'bar21' as code\n union select 'bar22' \n union select 'bar32' ) b\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043/"
] |
244,114
|
<p>I'm developing a poker game in C#. At the moment I'm trying to get the players hand score using <code>RegEx</code>. I search the string (composed of the cards suit and number) and look for suits or numbers to match the <code>RegEx</code>. If i get 2 matches then the player has a pair, 3 matches he has 3 of a kind. </p>
<p>I have 3 classes at the moment, a Card class (with number and suit), a Deck class (that contains 52 Cards) and a Hand class that gets five cards from the shuffled deck.</p>
<p>Deck class has a <code>shuffleDeck()</code>;
Hand class has the functions to calculate the score (is in these functions that I am using RegEx).</p>
<p>I generate the string on which I use <code>RegEx</code> by adding the 5 suits and numbers that the hand has.</p>
<p>Is this a good idea or should I do it another way, if so, how?</p>
<p>Thank you for your help</p>
<p>PS. I am one of the unexperienced programmers that want to use a newly learned tool for everything</p>
|
[
{
"answer_id": 4459394,
"author": "Dalou",
"author_id": 538032,
"author_profile": "https://Stackoverflow.com/users/538032",
"pm_score": 2,
"selected": false,
"text": "// D H S C \ncolors = [7,5,3,2]\n\n// A Q K J T 9 8 7 6 5 4 3 2 \nranks = [61,59,53,43,41,37,31,29,23,19,17,13,11,61]\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23146/"
] |
244,115
|
<p>Just for my own purposes, I'm trying to build a tokenizer in Java where I can define a regular grammar and have it tokenize input based on that. The StringTokenizer class is deprecated, and I've found a couple functions in Scanner that hint towards what I want to do, but no luck yet. Anyone know a good way of going about this?</p>
|
[
{
"answer_id": 244236,
"author": "Balint Pato",
"author_id": 19621,
"author_profile": "https://Stackoverflow.com/users/19621",
"pm_score": 2,
"selected": false,
"text": " import java.util.Scanner;\n\n\n public class Main { \n\n public static void main(String[] args) {\n\n String textToTokenize = \"This is a text that will be tokenized. I will use 1-2 methods.\";\n Scanner scanner = new Scanner(textToTokenize);\n scanner.useDelimiter(\"i.\");\n while (scanner.hasNext()){\n System.out.println(scanner.next());\n }\n\n System.out.println(\" **************** \");\n String[] sSplit = textToTokenize.split(\"i.\");\n\n for (String token: sSplit){\n System.out.println(token);\n }\n }\n\n}\n"
},
{
"answer_id": 247495,
"author": "Alan Moore",
"author_id": 20938,
"author_profile": "https://Stackoverflow.com/users/20938",
"pm_score": 5,
"selected": true,
"text": "scanf() split() split() usePattern() import java.util.*;\nimport java.util.regex.*;\n\npublic class RETokenizer\n{\n static List<Token> tokenize(String source, List<Rule> rules)\n {\n List<Token> tokens = new ArrayList<Token>();\n int pos = 0;\n final int end = source.length();\n Matcher m = Pattern.compile(\"dummy\").matcher(source);\n m.useTransparentBounds(true).useAnchoringBounds(false);\n while (pos < end)\n {\n m.region(pos, end);\n for (Rule r : rules)\n {\n if (m.usePattern(r.pattern).lookingAt())\n {\n tokens.add(new Token(r.name, m.start(), m.end()));\n pos = m.end();\n break;\n }\n }\n pos++; // bump-along, in case no rule matched\n }\n return tokens;\n }\n\n static class Rule\n {\n final String name;\n final Pattern pattern;\n\n Rule(String name, String regex)\n {\n this.name = name;\n pattern = Pattern.compile(regex);\n }\n }\n\n static class Token\n {\n final String name;\n final int startPos;\n final int endPos;\n\n Token(String name, int startPos, int endPos)\n {\n this.name = name;\n this.startPos = startPos;\n this.endPos = endPos;\n }\n\n @Override\n public String toString()\n {\n return String.format(\"Token [%2d, %2d, %s]\", startPos, endPos, name);\n }\n }\n\n public static void main(String[] args) throws Exception\n {\n List<Rule> rules = new ArrayList<Rule>();\n rules.add(new Rule(\"WORD\", \"[A-Za-z]+\"));\n rules.add(new Rule(\"QUOTED\", \"\\\"[^\\\"]*+\\\"\"));\n rules.add(new Rule(\"COMMENT\", \"//.*\"));\n rules.add(new Rule(\"WHITESPACE\", \"\\\\s+\"));\n\n String str = \"foo //in \\\"comment\\\"\\nbar \\\"no //comment\\\" end\";\n List<Token> result = RETokenizer.tokenize(str, rules);\n for (Token t : result)\n {\n System.out.println(t);\n }\n }\n}\n lookingAt()"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1370/"
] |
244,119
|
<p>Can anoyne recommend a good library that will let me easily read/write private member fields of a class? I was looking through apache commons, but couldnt see it. I must be getting blind ?</p>
<p>Edit: Asking questions on the border of legalities always give these questions of "why"? I am writing several javarebel plugins for hotswapping classes. Accessing private variables is only step 1, I might even have to replace implementations of some methods.</p>
|
[
{
"answer_id": 244146,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 1,
"selected": false,
"text": "java.lang.reflect"
},
{
"answer_id": 244156,
"author": "sakana",
"author_id": 28921,
"author_profile": "https://Stackoverflow.com/users/28921",
"pm_score": 4,
"selected": true,
"text": "public class Foo {\n\n /**\n * Gets the name Field.\n * \n * @return the name\n */\n public final String getName() {\n return name;\n }\n\n /**\n * Sets the name Field with the name input value.\n * \n * @param name the name to set\n */\n public final void setName(String name) {\n this.name = name;\n }\n\n private String name;\n\n}\n import java.lang.reflect.Field;\n....\n\nFoo foo = new Foo();\nfoo.setName(\"old Name\");\nString fieldName = \"name\";\nClass class1 = Foo.class;\n\ntry {\n\n System.out.println(foo.getName());\n\n Field field = class1.getDeclaredField(fieldName);\n\n field.setAccessible(true);\n\n field.set(foo, \"My New Name\");\n\n System.out.println(foo.getName());\n\n} catch (NoSuchFieldException e) {\n System.out.println(\"FieldNotFound: \" + e);\n} catch (IllegalAccessException e) {\n System.out.println(\"Ilegal Access: \" + e);\n}\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23691/"
] |
244,152
|
<p>I have a site that requires Windows Authentication the application obtains the credential from the Security.Prinicipal once the user is autenticated the problem is that my credentials on my local environment are different that the ones stored in the DB and the user preferences cannot be obtain. i am doing the following workaround in order to deal with this issue.</p>
<pre><code> #if DEBUG
var myUser = userBL.GetSingle(@"desiredDomain\otherUserName");
#else
var myUser = userBL.GetSingle(HttpApplication.User.Identity.Name);
#endif
Session.Add("User",myUser);
</code></pre>
<p>is there any other way rather than impersonating or the above mentioned workaorund to change the the value of HttpApplication.User.Identity.Name this is beacuse I have to change my code everytime I need to commit into repository or deploy the App</p>
|
[
{
"answer_id": 244874,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 3,
"selected": true,
"text": "UPDATE Users \nSET \n UserName = REPLACE(UserName, '\\\\ProductionDomain\\', '\\\\DevDomain\\')\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14440/"
] |
244,157
|
<p>I am trying to read an XML-file from another server. However the the company that's hosting me seems to have turned of the file_get_contents function from retrieving files for files from other servers (and their support is not very bright and it takes forever for them to answer). So I need a work around in some way.</p>
<p>This is my current code</p>
<pre><code> $url = urldecode( $object_list_url );
$xmlstr = file_get_contents ( $url );
$obj = new SimpleXMLElement ( $xmlstr, LIBXML_NOCDATA );
</code></pre>
|
[
{
"answer_id": 244163,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 0,
"selected": false,
"text": "allow_url_fopen var_dump(ini_get('allow_url_fopen'));\n copy"
},
{
"answer_id": 244166,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 4,
"selected": true,
"text": "$c = curl_init($url);\ncurl_setopt($c, CURLOPT_RETURNTRANSFER, true);\n$xmlstr = curl_exec($c);\n"
},
{
"answer_id": 244169,
"author": "Jake McGraw",
"author_id": 302,
"author_profile": "https://Stackoverflow.com/users/302",
"pm_score": 0,
"selected": false,
"text": "<?php\nphpinfo();\n?>\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27943/"
] |
244,164
|
<p>I need to resize PNG, JPEG and GIF files. How can I do this using Java?</p>
|
[
{
"answer_id": 244177,
"author": "Burkhard",
"author_id": 12860,
"author_profile": "https://Stackoverflow.com/users/12860",
"pm_score": 8,
"selected": true,
"text": "BufferedImage createResizedCopy(Image originalImage, \n int scaledWidth, int scaledHeight, \n boolean preserveAlpha)\n {\n System.out.println(\"resizing...\");\n int imageType = preserveAlpha ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;\n BufferedImage scaledBI = new BufferedImage(scaledWidth, scaledHeight, imageType);\n Graphics2D g = scaledBI.createGraphics();\n if (preserveAlpha) {\n g.setComposite(AlphaComposite.Src);\n }\n g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null); \n g.dispose();\n return scaledBI;\n }\n"
},
{
"answer_id": 4528136,
"author": "Riyad Kalla",
"author_id": 553524,
"author_profile": "https://Stackoverflow.com/users/553524",
"pm_score": 8,
"selected": false,
"text": "BufferedImage scaledImage = Scalr.resize(myImage, 200);\n"
},
{
"answer_id": 5051429,
"author": "coobird",
"author_id": 17172,
"author_profile": "https://Stackoverflow.com/users/17172",
"pm_score": 6,
"selected": false,
"text": "Thumbnails.of(\"path/to/image\")\n .size(100, 100)\n .toFile(\"path/to/thumbnail\");\n 0.85 thumbnail. Thumbnails.of(new File(\"path/to/directory\").listFiles())\n .size(100, 100)\n .outputFormat(\"JPEG\")\n .outputQuality(0.85)\n .toFiles(Rename.PREFIX_DOT_THUMBNAIL);\n"
},
{
"answer_id": 16076530,
"author": "Ruju",
"author_id": 1425564,
"author_profile": "https://Stackoverflow.com/users/1425564",
"pm_score": 2,
"selected": false,
"text": "<dependency>\n <groupId>com.mortennobel</groupId>\n <artifactId>java-image-scaling</artifactId>\n <version>0.8.6</version>\n</dependency>\n ResampleOp resamOp = new ResampleOp(50, 40);\nBufferedImage modifiedImage = resamOp.filter(originalBufferedImage, null);\n"
},
{
"answer_id": 37228567,
"author": "shareef",
"author_id": 944593,
"author_profile": "https://Stackoverflow.com/users/944593",
"pm_score": 0,
"selected": false,
"text": " /**\n * utility method to get an icon from the resources of this class\n * @param name the name of the icon\n * @return the icon, or null if the icon wasn't found.\n */\n public Icon getIcon(String name) {\n Icon icon = null;\n URL url = null;\n ImageIcon imgicon = null;\n BufferedImage scaledImage = null;\n try {\n url = getClass().getResource(name);\n\n icon = new ImageIcon(url);\n if (icon == null) {\n System.out.println(\"Couldn't find \" + url);\n }\n\n BufferedImage bi = new BufferedImage(\n icon.getIconWidth(),\n icon.getIconHeight(),\n BufferedImage.TYPE_INT_RGB);\n Graphics g = bi.createGraphics();\n // paint the Icon to the BufferedImage.\n icon.paintIcon(null, g, 0,0);\n g.dispose();\n\n bi = resizeImage(bi,30,30);\n scaledImage = bi;// or replace with this line Scalr.resize(bi, 30,30);\n imgicon = new ImageIcon(scaledImage);\n\n } catch (Exception e) {\n System.out.println(\"Couldn't find \" + getClass().getName() + \"/\" + name);\n e.printStackTrace();\n }\n return imgicon;\n }\n\n public static BufferedImage resizeImage (BufferedImage image, int areaWidth, int areaHeight) {\n float scaleX = (float) areaWidth / image.getWidth();\n float scaleY = (float) areaHeight / image.getHeight();\n float scale = Math.min(scaleX, scaleY);\n int w = Math.round(image.getWidth() * scale);\n int h = Math.round(image.getHeight() * scale);\n\n int type = image.getTransparency() == Transparency.OPAQUE ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;\n\n boolean scaleDown = scale < 1;\n\n if (scaleDown) {\n // multi-pass bilinear div 2\n int currentW = image.getWidth();\n int currentH = image.getHeight();\n BufferedImage resized = image;\n while (currentW > w || currentH > h) {\n currentW = Math.max(w, currentW / 2);\n currentH = Math.max(h, currentH / 2);\n\n BufferedImage temp = new BufferedImage(currentW, currentH, type);\n Graphics2D g2 = temp.createGraphics();\n g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);\n g2.drawImage(resized, 0, 0, currentW, currentH, null);\n g2.dispose();\n resized = temp;\n }\n return resized;\n } else {\n Object hint = scale > 2 ? RenderingHints.VALUE_INTERPOLATION_BICUBIC : RenderingHints.VALUE_INTERPOLATION_BILINEAR;\n\n BufferedImage resized = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);\n Graphics2D g2 = resized.createGraphics();\n g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);\n g2.drawImage(image, 0, 0, w, h, null);\n g2.dispose();\n return resized;\n }\n }\n"
},
{
"answer_id": 38775238,
"author": "The One True Colter",
"author_id": 6669464,
"author_profile": "https://Stackoverflow.com/users/6669464",
"pm_score": 1,
"selected": false,
"text": " g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);\n"
},
{
"answer_id": 59348618,
"author": "Fridjato Part Fridjat",
"author_id": 12087120,
"author_profile": "https://Stackoverflow.com/users/12087120",
"pm_score": 0,
"selected": false,
"text": "ImageIcon icon = new ImageIcon(\"image.png\");\nImage img = icon.getImage();\nImage newImg = img.getScaledInstance(350, 350, java.evt.Image.SCALE_SMOOTH);\nicon = new ImageIcon(img);\nJOptionPane.showMessageDialog(null, \"image on The frame\", \"Display Image\", JOptionPane.INFORMATION_MESSAGE, icon);\n"
},
{
"answer_id": 71508153,
"author": "Aqib Butt",
"author_id": 2369244,
"author_profile": "https://Stackoverflow.com/users/2369244",
"pm_score": 0,
"selected": false,
"text": "Process p = Runtime.getRuntime().exec(\"convert \" + origPath + \" -resize 75% -quality 70 \" + largePath + \"\");\n p.waitFor();\n"
},
{
"answer_id": 73666348,
"author": "Ruwan Pathirana",
"author_id": 19273724,
"author_profile": "https://Stackoverflow.com/users/19273724",
"pm_score": 0,
"selected": false,
"text": "JLabel label1 = new JLabel(\"\");\nlabel1.setHorizontalAlignment(SwingConstants.CENTER);\nlabel1.setBounds(628, 28, 169, 125);\nframe1.getContentPane().add(label1); //frame1 = \"Jframe name\"\n ImageIcon imageIcon1 = new ImageIcon(new ImageIcon(\"add location url\").getImage().getScaledInstance(100, 100, Image.SCALE_DEFAULT)); //100, 100 add your own size\nlabel1.setIcon(imageIcon1);\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2011/"
] |
244,183
|
<p>I'm working on a site which contains a whole bunch of mp3s and images, and I'd like to display a loading gif while all the content loads. </p>
<p>I have no idea how to achieve this, but I do have the animated gif I want to use. </p>
<p>Any suggestions?</p>
|
[
{
"answer_id": 244190,
"author": "mmattax",
"author_id": 1638,
"author_profile": "https://Stackoverflow.com/users/1638",
"pm_score": 6,
"selected": true,
"text": "readystatechanged function load(url) {\n // display loading image here...\n document.getElementById('loadingImg').visible = true;\n // request your data...\n var req = new XMLHttpRequest();\n req.open(\"POST\", url, true);\n\n req.onreadystatechange = function () {\n if (req.readyState == 4 && req.status == 200) {\n // content is loaded...hide the gif and display the content...\n if (req.responseText) {\n document.getElementById('content').innerHTML = req.responseText;\n document.getElementById('loadingImg').visible = false;\n }\n }\n };\n request.send(vars);\n}\n"
},
{
"answer_id": 4100608,
"author": "Mike E.",
"author_id": 332044,
"author_profile": "https://Stackoverflow.com/users/332044",
"pm_score": 4,
"selected": false,
"text": "<body> <html>\n <head>\n <style media=\"screen\" type=\"text/css\">\n .layer1_class { position: absolute; z-index: 1; top: 100px; left: 0px; visibility: visible; }\n .layer2_class { position: absolute; z-index: 2; top: 10px; left: 10px; visibility: hidden }\n </style>\n <script>\n function downLoad(){\n if (document.all){\n document.all[\"layer1\"].style.visibility=\"hidden\";\n document.all[\"layer2\"].style.visibility=\"visible\";\n } else if (document.getElementById){\n node = document.getElementById(\"layer1\").style.visibility='hidden';\n node = document.getElementById(\"layer2\").style.visibility='visible';\n }\n }\n </script>\n </head>\n <body onload=\"downLoad()\">\n <div id=\"layer1\" class=\"layer1_class\">\n <table width=\"100%\">\n <tr>\n <td align=\"center\"><strong><em>Please wait while this page is loading...</em></strong></p></td>\n </tr>\n </table>\n </div>\n <div id=\"layer2\" class=\"layer2_class\">\n <script type=\"text/javascript\">\n alert('Just holding things up here. While you are reading this, the body of the page is not loading and the onload event is being delayed');\n </script>\n Final content. \n </div>\n </body>\n</html>\n <DIV>"
},
{
"answer_id": 11255697,
"author": "Johnz",
"author_id": 1490205,
"author_profile": "https://Stackoverflow.com/users/1490205",
"pm_score": 1,
"selected": false,
"text": "<script type=\"test/javascript\">\n\n function showcontent(x){\n\n if(window.XMLHttpRequest) {\n xmlhttp = new XMLHttpRequest();\n } else {\n xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');\n }\n\n xmlhttp.onreadystatechange = function() {\n if(xmlhttp.readyState == 1) {\n document.getElementById('content').innerHTML = \"<img src='loading.gif' />\";\n }\n if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {\n document.getElementById('content').innerHTML = xmlhttp.responseText;\n } \n }\n\n xmlhttp.open('POST', x+'.html', true);\n xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');\n xmlhttp.send(null);\n\n }\n <body onload=\"showcontent(main)\"> <!-- onload optional -->\n<div id=\"content\"><img src=\"loading.gif\"></div> <!-- leave img out if not onload -->\n</body>\n"
},
{
"answer_id": 21005907,
"author": "Raj Nandan Sharma",
"author_id": 3090583,
"author_profile": "https://Stackoverflow.com/users/3090583",
"pm_score": 0,
"selected": false,
"text": "<progress> <progress id=\"progressbar\" value=\"20\" max=\"100\"></progress>\n <script>\n $(document).ready(function() {\n if(!Modernizr.meter){\n alert('Sorry your brower does not support HTML5 progress bar');\n } else {\n var progressbar = $('#progressbar'),\n max = progressbar.attr('max'),\n time = (1000/max)*10, \n value = progressbar.val();\n var loading = function() {\n value += 1;\n addValue = progressbar.val(value);\n $('.progress-value').html(value + '%');\n if (value == max) {\n clearInterval(animate);\n //Do Something\n }\nif (value == 16) {\n//Do something \n}\nif (value == 38) {\n//Do something\n}\nif (value == 55) {\n//Do something \n}\nif (value == 72) {\n//Do something \n}\nif (value == 1) {\n//Do something \n}\nif (value == 86) {\n//Do something \n }\n\n};\nvar animate = setInterval(function() {\nloading();\n}, time);\n};\n});\n</script>\n <div class=\"demo-wrapper html5-progress-bar\">\n<div class=\"progress-bar-wrapper\">\n <progress id=\"progressbar\" value=\"0\" max=\"100\"></progress>\n <span class=\"progress-value\">0%</span>\n</div>\n </div>\n"
},
{
"answer_id": 27340661,
"author": "joe_young",
"author_id": 4206206,
"author_profile": "https://Stackoverflow.com/users/4206206",
"pm_score": 3,
"selected": false,
"text": "$(window).load(function() { //Do the code in the {}s when the window has loaded \n $(\"#loader\").fadeOut(\"fast\"); //Fade out the #loader div\n});\n <div id=\"loader\"></div>\n #loader {\n width: 100%;\n height: 100%;\n background-color: white;\n margin: 0;\n}\n div"
},
{
"answer_id": 34551921,
"author": "Peach",
"author_id": 5734986,
"author_profile": "https://Stackoverflow.com/users/5734986",
"pm_score": 2,
"selected": false,
"text": "<body>"
},
{
"answer_id": 36768317,
"author": "MindCraftMagic",
"author_id": 5993161,
"author_profile": "https://Stackoverflow.com/users/5993161",
"pm_score": 2,
"selected": false,
"text": "<style> .loader {\n position: fixed;\n background-color: #FFF;\n opacity: 1;\n height: 100%;\n width: 100%;\n top: 0;\n left: 0;\n z-index: 10;\n}\n</style> <div class=\"loader\">\n Your Content For Load Screen\n</div> <style>\n.loader {\n -webkit-animation: load-out 1s;\n animation: load-out 1s;\n -webkit-animation-fill-mode: forwards;\n animation-fill-mode: forwards;\n}\n\n@-webkit-keyframes load-out {\n from {\n top: 0;\n opacity: 1;\n }\n\n to {\n top: 100%;\n opacity: 0;\n }\n}\n\n@keyframes load-out {\n from {\n top: 0;\n opacity: 1;\n }\n\n to {\n top: 100%;\n opacity: 0;\n }\n}\n</style>"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27171/"
] |
244,184
|
<p>We have are relatively simple Reporting Services report that our users commonly export to Excel. I've noticed that the files produced by the Excel export seem unusually large. If I open one of these files and just click save, without making any changes, the file size reduces to about half of it's previous size. Has anyone else run into this and is there a known workaround?</p>
|
[
{
"answer_id": 923724,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "DataElementOutput Data tab convert text to column use the delimiter"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/162/"
] |
244,191
|
<p>For example:</p>
<pre><code>public void doSomething() {
final double MIN_INTEREST = 0.0;
// ...
}
</code></pre>
<p>Personally, I would rather see these substitution constants declared statically at the class level.
I suppose I'm looking for an "industry viewpoint" on the matter.</p>
|
[
{
"answer_id": 244215,
"author": "sakana",
"author_id": 28921,
"author_profile": "https://Stackoverflow.com/users/28921",
"pm_score": -1,
"selected": false,
"text": "public class Test {\n\n final double MIN_INTEREST = 0.0;\n\n /**\n * @param args\n */\n public static void main(String[] args) {\n\n\n Test test = new Test();\n\n test.doSomethingLocal();\n test.doSomethingGlobal();\n\n }\n\n public void doSomethingGlobal() {\n\n System.out.println(\"Global-> \" + MIN_INTEREST);\n\n }\n\n public void doSomethingLocal() {\n\n final double MIN_INTEREST = 0.1;\n\n System.out.println(\"Local-> \" + MIN_INTEREST);\n\n }\n}\n Local-> 0.1\nGlobal-> 0.0\n"
},
{
"answer_id": 244315,
"author": "Chris Cudmore",
"author_id": 18907,
"author_profile": "https://Stackoverflow.com/users/18907",
"pm_score": 5,
"selected": true,
"text": "MIN_INTEREST"
},
{
"answer_id": 42460729,
"author": "Gautam",
"author_id": 5971511,
"author_profile": "https://Stackoverflow.com/users/5971511",
"pm_score": 1,
"selected": false,
"text": "public void doSomething() {\n\n final double MIN_INTEREST = 0.0;\n\n // ... \n}\n 500 lines 50 methods 1 2 3 1 2 pi pi/2"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32142/"
] |
244,192
|
<p>I have a pattern to match with the string:
string pattern = @"asc"
I am checking the SQL SELECT query for right syntax, semantics, ...
I need to say that in the end of the query string I can have "asc" or "desc".
How can it be written in C#?</p>
|
[
{
"answer_id": 244201,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 1,
"selected": false,
"text": "asc|desc\n"
},
{
"answer_id": 244203,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 3,
"selected": true,
"text": "new Regex(\"asc$|desc$\").IsMatch(yourQuery)\n (?:asc|desc)$ $"
},
{
"answer_id": 244216,
"author": "Eoin Campbell",
"author_id": 30155,
"author_profile": "https://Stackoverflow.com/users/30155",
"pm_score": 1,
"selected": false,
"text": "string tempString = \"SELECT * FROM MyTable ORDER BY column DESC\";\n\nRegex r = new Regex(\"asc$|desc$\", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);\n\nbool answer = r.IsMatch(tempString);\n"
},
{
"answer_id": 244229,
"author": "penderi",
"author_id": 32027,
"author_profile": "https://Stackoverflow.com/users/32027",
"pm_score": 0,
"selected": false,
"text": "asc|desc\\z\n asc|desc$\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28298/"
] |
244,208
|
<p>I'm using MySQL 5.0.45 on CentOS 5.1.</p>
<p><code>SELECT DISTINCT(email) FROM newsletter</code></p>
<p>Returns 217259 rows</p>
<p><code>SELECT COUNT(DISTINCT(email)) FROM newsletter</code></p>
<p>Returns 180698 for the count.</p>
<p><code>SELECT COUNT(*) FROM (SELECT DISTINCT(email) FROM newsletter) AS foo</code></p>
<p>Returns 180698 for the count.</p>
<p>Shouldn't all 3 queries return the same value?</p>
<p>Here is the schema of the newsletter table</p>
<pre>
CREATE TABLE `newsletter` (
`newsID` int(11) NOT NULL auto_increment,
`email` varchar(128) NOT NULL default '',
`newsletter` varchar(8) NOT NULL default '',
PRIMARY KEY (`newsID`)
) ENGINE=MyISAM;
</pre>
<p><strong>Update:</strong> I've found that if I add a <codE>WHERE</code> clause to the first query then I get the correct results. The <codE>WHERE</code> clause is such that it will not effect the results.</p>
<p><code>SELECT DISTINCT(email) FROM newsletter WHERE newsID > 0</code></p>
|
[
{
"answer_id": 244262,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 0,
"selected": false,
"text": "select distinct(email) from newsletter order by email;"
},
{
"answer_id": 244435,
"author": "Maglob",
"author_id": 27520,
"author_profile": "https://Stackoverflow.com/users/27520",
"pm_score": 2,
"selected": false,
"text": "select count(*) from newsletter where email is null;\n"
},
{
"answer_id": 244454,
"author": "Leandro López",
"author_id": 22695,
"author_profile": "https://Stackoverflow.com/users/22695",
"pm_score": 0,
"selected": false,
"text": "SELECT COUNT(COALESCE(email, 0)) FROM newsletter\n"
},
{
"answer_id": 244472,
"author": "Dave Costa",
"author_id": 6568,
"author_profile": "https://Stackoverflow.com/users/6568",
"pm_score": 0,
"selected": false,
"text": "SELECT email FROM newsletter GROUP BY email;\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/796/"
] |
244,219
|
<p>In c# (3.0 or 3.5, so we can use lambdas), is there an elegant way of sorting a list of dates in descending order? I know I can do a straight sort and then reverse the whole thing, </p>
<pre><code>docs.Sort((x, y) => x.StoredDate.CompareTo(y.StoredDate));
docs.Reverse();
</code></pre>
<p>but is there a lambda expression to do it one step?</p>
<p>In the above example, StoredDate is a property typed as a DateTime.</p>
|
[
{
"answer_id": 244221,
"author": "jonnii",
"author_id": 4590,
"author_profile": "https://Stackoverflow.com/users/4590",
"pm_score": 4,
"selected": false,
"text": "docs.Sort((x, y) => y.StoredDate.CompareTo(x.StoredDate));\n"
},
{
"answer_id": 244227,
"author": "Tamas Czinege",
"author_id": 8954,
"author_profile": "https://Stackoverflow.com/users/8954",
"pm_score": 3,
"selected": false,
"text": "docs.Sort((x, y) => -x.StoredDate.CompareTo(y.StoredDate));\n"
},
{
"answer_id": 244228,
"author": "Austin Salonen",
"author_id": 4068,
"author_profile": "https://Stackoverflow.com/users/4068",
"pm_score": 7,
"selected": true,
"text": "docs.Sort((x, y) => y.StoredDate.CompareTo(x.StoredDate));\n"
},
{
"answer_id": 8002567,
"author": "Scott Baker",
"author_id": 127888,
"author_profile": "https://Stackoverflow.com/users/127888",
"pm_score": 6,
"selected": false,
"text": "docs.OrderByDescending(d => d.StoredDate);\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2849/"
] |
244,222
|
<p>I have compression enabled within IIS7 and it works as expected on all responses except for those constructed by ASP.NET AJAX. I have a web service that provides data to the client. When the web service is called directly, it is properly compressed. However, when it is called via ASP.NET AJAX, the JSON response is not compressed.</p>
<p>How can I get ASP.NET AJAX to send its JSON response with GZip compression?</p>
|
[
{
"answer_id": 266753,
"author": "stevemegson",
"author_id": 25028,
"author_profile": "https://Stackoverflow.com/users/25028",
"pm_score": 3,
"selected": false,
"text": "<dynamicTypes>\n <add mimeType=\"text/*\" enabled=\"true\" />\n <add mimeType=\"message/*\" enabled=\"true\" />\n <add mimeType=\"application/x-javascript\" enabled=\"true\" />\n <add mimeType=\"*/*\" enabled=\"false\" />\n</dynamicTypes>\n text/xml application/json <add mimeType=\"application/json\" enabled=\"true\" />\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
244,243
|
<p>I ran into the problem that my primary key sequence is not in sync with my table rows. </p>
<p>That is, when I insert a new row I get a duplicate key error because the sequence implied in the serial datatype returns a number that already exists.</p>
<p>It seems to be caused by import/restores not maintaining the sequence properly.</p>
|
[
{
"answer_id": 244265,
"author": "meleyal",
"author_id": 4196,
"author_profile": "https://Stackoverflow.com/users/4196",
"pm_score": 11,
"selected": true,
"text": "-- Login to psql and run the following\n\n-- What is the result?\nSELECT MAX(id) FROM your_table;\n\n-- Then run...\n-- This should be higher than the last result.\nSELECT nextval('your_table_id_seq');\n\n-- If it's not higher... run this set the sequence last to your highest id. \n-- (wise to run a quick pg_dump first...)\n\nBEGIN;\n-- protect against concurrent inserts while you update the counter\nLOCK TABLE your_table IN EXCLUSIVE MODE;\n-- Update the sequence\nSELECT setval('your_table_id_seq', COALESCE((SELECT MAX(id)+1 FROM your_table), 1), false);\nCOMMIT;\n"
},
{
"answer_id": 355416,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "SELECT setval(pg_get_serial_sequence('table_name', 'id'), MAX(id)) FROM table_name;\n"
},
{
"answer_id": 3698777,
"author": "tardate",
"author_id": 6329,
"author_profile": "https://Stackoverflow.com/users/6329",
"pm_score": 8,
"selected": false,
"text": "pg_get_serial_sequence SELECT pg_catalog.setval(pg_get_serial_sequence('table_name', 'id'), (SELECT MAX(id) FROM table_name)+1);\n SELECT pg_catalog.setval(pg_get_serial_sequence('table_name', 'id'), MAX(id)) FROM table_name;\n ALTER SEQUENCE ALTER SEQUENCE table_name_id_seq RESTART WITH 1;\nALTER SEQUENCE table_name_id_seq RESTART; -- 8.4 or higher\n ALTER SEQUENCE setval SELECT setval(pg_get_serial_sequence('t1', 'id'), coalesce(max(id),0) + 1, false) FROM t1;\n pg_get_serial_sequence serial ALTER SEQUENCE .. OWNED BY serial CREATE TABLE t1 (\n id serial,\n name varchar(20)\n);\n\nSELECT pg_get_serial_sequence('t1', 'id'); -- returns 't1_id_seq'\n\n-- reset the sequence, regardless whether table has rows or not:\nSELECT setval(pg_get_serial_sequence('t1', 'id'), coalesce(max(id),0) + 1, false) FROM t1;\n CREATE TABLE t2 (\n id integer NOT NULL,\n name varchar(20)\n);\n\nCREATE SEQUENCE t2_custom_id_seq\n START WITH 1\n INCREMENT BY 1\n NO MINVALUE\n NO MAXVALUE\n CACHE 1;\n\nALTER TABLE t2 ALTER COLUMN id SET DEFAULT nextval('t2_custom_id_seq'::regclass);\n\nALTER SEQUENCE t2_custom_id_seq OWNED BY t2.id; -- required for pg_get_serial_sequence\n\nSELECT pg_get_serial_sequence('t2', 'id'); -- returns 't2_custom_id_seq'\n\n-- reset the sequence, regardless whether table has rows or not:\nSELECT setval(pg_get_serial_sequence('t2', 'id'), coalesce(max(id),0) + 1, false) FROM t1;\n"
},
{
"answer_id": 3786682,
"author": "user457226",
"author_id": 457226,
"author_profile": "https://Stackoverflow.com/users/457226",
"pm_score": 3,
"selected": false,
"text": "CREATE OR REPLACE FUNCTION \"reset_sequence\" (tablename text) RETURNS \"pg_catalog\".\"void\" AS \n$body$ \n DECLARE \n BEGIN \n EXECUTE 'SELECT setval( ''' \n || tablename \n || '_id_seq'', ' \n || '(SELECT id + 1 FROM \"' \n || tablename \n || '\" ORDER BY id DESC LIMIT 1), false)'; \n END; \n$body$ LANGUAGE 'plpgsql';\n\nselect sequence_name, reset_sequence(split_part(sequence_name, '_id_seq',1)) from information_schema.sequences\n where sequence_schema='public';\n"
},
{
"answer_id": 4101362,
"author": "David Snowsill",
"author_id": 6218,
"author_profile": "https://Stackoverflow.com/users/6218",
"pm_score": 6,
"selected": false,
"text": "CREATE OR REPLACE FUNCTION \"reset_sequence\" (tablename text, columnname text, sequence_name text) \n RETURNS \"pg_catalog\".\"void\" AS \n \n $body$ \n DECLARE \n BEGIN \n \n EXECUTE 'SELECT setval( ''' || sequence_name || ''', ' || '(SELECT MAX(' || columnname || \n ') FROM ' || tablename || ')' || '+1)';\n \n END; \n \n $body$ LANGUAGE 'plpgsql';\n \n \nSELECT table_name || '_' || column_name || '_seq', \n reset_sequence(table_name, column_name, table_name || '_' || column_name || '_seq') \nFROM information_schema.columns where column_default like 'nextval%';\n"
},
{
"answer_id": 5252155,
"author": "mauro",
"author_id": 652407,
"author_profile": "https://Stackoverflow.com/users/652407",
"pm_score": 2,
"selected": false,
"text": "select sequence_name, --PG_CLASS.relname, PG_ATTRIBUTE.attname\n reset_sequence(split_part(sequence_name, '_id_seq',1))\nfrom PG_CLASS\njoin PG_ATTRIBUTE on PG_ATTRIBUTE.attrelid = PG_CLASS.oid\njoin information_schema.sequences\n on information_schema.sequences.sequence_name = PG_CLASS.relname || '_' || PG_ATTRIBUTE.attname\nwhere sequence_schema='public';\n"
},
{
"answer_id": 5252617,
"author": "mauro",
"author_id": 652407,
"author_profile": "https://Stackoverflow.com/users/652407",
"pm_score": 2,
"selected": false,
"text": "drop function IF EXISTS rebuilt_sequences() RESTRICT;\nCREATE OR REPLACE FUNCTION rebuilt_sequences() RETURNS integer as\n$body$\n DECLARE sequencedefs RECORD; c integer ;\n BEGIN\n FOR sequencedefs IN Select\n constraint_column_usage.table_name as tablename,\n constraint_column_usage.table_name as tablename, \n constraint_column_usage.column_name as columnname,\n replace(replace(columns.column_default,'''::regclass)',''),'nextval(''','') as sequencename\n from information_schema.constraint_column_usage, information_schema.columns\n where constraint_column_usage.table_schema ='public' AND \n columns.table_schema = 'public' AND columns.table_name=constraint_column_usage.table_name\n AND constraint_column_usage.column_name = columns.column_name\n AND columns.column_default is not null\n LOOP \n EXECUTE 'select max('||sequencedefs.columnname||') from ' || sequencedefs.tablename INTO c;\n IF c is null THEN c = 0; END IF;\n IF c is not null THEN c = c+ 1; END IF;\n EXECUTE 'alter sequence ' || sequencedefs.sequencename ||' restart with ' || c;\n END LOOP;\n\n RETURN 1; END;\n$body$ LANGUAGE plpgsql;\n\nselect rebuilt_sequences();\n --drop function IF EXISTS reset_sequence (text,text) RESTRICT;\nCREATE OR REPLACE FUNCTION \"reset_sequence\" (tablename text,columnname text) RETURNS bigint --\"pg_catalog\".\"void\"\nAS\n$body$\n DECLARE seqname character varying;\n c integer;\n BEGIN\n select tablename || '_' || columnname || '_seq' into seqname;\n EXECUTE 'SELECT max(\"' || columnname || '\") FROM \"' || tablename || '\"' into c;\n if c is null then c = 0; end if;\n c = c+1; --because of substitution of setval with \"alter sequence\"\n --EXECUTE 'SELECT setval( \"' || seqname || '\", ' || cast(c as character varying) || ', false)'; DOES NOT WORK!!!\n EXECUTE 'alter sequence ' || seqname ||' restart with ' || cast(c as character varying);\n RETURN nextval(seqname)-1;\n END;\n$body$ LANGUAGE 'plpgsql';\n\nselect sequence_name, PG_CLASS.relname, PG_ATTRIBUTE.attname,\n reset_sequence(PG_CLASS.relname,PG_ATTRIBUTE.attname)\nfrom PG_CLASS\njoin PG_ATTRIBUTE on PG_ATTRIBUTE.attrelid = PG_CLASS.oid\njoin information_schema.sequences\n on information_schema.sequences.sequence_name = PG_CLASS.relname || '_' || PG_ATTRIBUTE.attname || '_seq'\nwhere sequence_schema='public';\n"
},
{
"answer_id": 5943183,
"author": "alvherre",
"author_id": 242383,
"author_profile": "https://Stackoverflow.com/users/242383",
"pm_score": 4,
"selected": false,
"text": "CREATE OR REPLACE FUNCTION sequence_max_value(oid) RETURNS bigint\nVOLATILE STRICT LANGUAGE plpgsql AS $$\nDECLARE\n tabrelid oid;\n colname name;\n r record;\n newmax bigint;\nBEGIN\n FOR tabrelid, colname IN SELECT attrelid, attname\n FROM pg_attribute\n WHERE (attrelid, attnum) IN (\n SELECT adrelid::regclass,adnum\n FROM pg_attrdef\n WHERE oid IN (SELECT objid\n FROM pg_depend\n WHERE refobjid = $1\n AND classid = 'pg_attrdef'::regclass\n )\n ) LOOP\n FOR r IN EXECUTE 'SELECT max(' || quote_ident(colname) || ') FROM ' || tabrelid::regclass LOOP\n IF newmax IS NULL OR r.max > newmax THEN\n newmax := r.max;\n END IF;\n END LOOP;\n END LOOP;\n RETURN newmax;\nEND; $$ ;\n select relname, setval(oid, sequence_max_value(oid))\n from pg_class\n where relkind = 'S';\n select relname, setval(pg_class.oid, sequence_max_value(pg_class.oid))\n from pg_class, pg_namespace\n where pg_class.relnamespace = pg_namespace.oid and\n nspname = 'public' and\n relkind = 'S';\n alvherre=# \\d baz\n Tabla «public.baz»\n Columna | Tipo | Modificadores \n---------+---------+------------------------------------------------\n a | integer | default nextval(('foo_a_seq'::text)::regclass)\n alvherre=# alter table baz alter a set default nextval('foo_a_seq');\nALTER TABLE\n alvherre=# \\d baz\n Tabla «public.baz»\n Columna | Tipo | Modificadores \n---------+---------+----------------------------------------\n a | integer | default nextval('foo_a_seq'::regclass)\n"
},
{
"answer_id": 7406591,
"author": "Daniel Cristian Cruz",
"author_id": 943169,
"author_profile": "https://Stackoverflow.com/users/943169",
"pm_score": 3,
"selected": false,
"text": "BEGIN;\nCREATE OR REPLACE FUNCTION reset_sequence(_table_schema text, _tablename text, _columnname text, _sequence_name text)\nRETURNS pg_catalog.void AS\n$BODY$\nDECLARE\nBEGIN\n PERFORM 1\n FROM information_schema.sequences\n WHERE\n sequence_schema = _table_schema AND\n sequence_name = _sequence_name;\n IF FOUND THEN\n EXECUTE 'SELECT setval( ''' || _table_schema || '.' || _sequence_name || ''', ' || '(SELECT MAX(' || _columnname || ') FROM ' || _table_schema || '.' || _tablename || ')' || '+1)';\n ELSE\n RAISE WARNING 'SEQUENCE NOT UPDATED ON %.%', _tablename, _columnname;\n END IF;\nEND; \n$BODY$\n LANGUAGE 'plpgsql';\n\nSELECT reset_sequence(table_schema, table_name, column_name, table_name || '_' || column_name || '_seq')\nFROM information_schema.columns\nWHERE column_default LIKE 'nextval%';\n\nDROP FUNCTION reset_sequence(_table_schema text, _tablename text, _columnname text, _sequence_name text) ;\nCOMMIT;\n"
},
{
"answer_id": 13308052,
"author": "Antony Hatchkins",
"author_id": 237105,
"author_profile": "https://Stackoverflow.com/users/237105",
"pm_score": 3,
"selected": false,
"text": "CREATE OR REPLACE FUNCTION \"reset_sequence\" (tablename text) \nRETURNS \"pg_catalog\".\"void\" AS\n$body$\nDECLARE\nBEGIN\n EXECUTE 'SELECT setval( pg_get_serial_sequence(''' || tablename || ''', ''id''),\n (SELECT COALESCE(MAX(id)+1,1) FROM ' || tablename || '), false)';\nEND;\n$body$ LANGUAGE 'plpgsql';\n id'"
},
{
"answer_id": 14633145,
"author": "EB.",
"author_id": 84041,
"author_profile": "https://Stackoverflow.com/users/84041",
"pm_score": 4,
"selected": false,
"text": "CREATE OR REPLACE FUNCTION \"reset_sequence\" (tablename text, columnname text)\nRETURNS \"pg_catalog\".\"void\" AS\n$body$\nDECLARE\nBEGIN\n EXECUTE 'SELECT setval( pg_get_serial_sequence(''' || tablename || ''', ''' || columnname || '''),\n (SELECT COALESCE(MAX(id)+1,1) FROM ' || tablename || '), false)';\nEND;\n$body$ LANGUAGE 'plpgsql';\n\nselect table_name || '_' || column_name || '_seq', reset_sequence(table_name, column_name) from information_schema.columns where column_default like 'nextval%';\n"
},
{
"answer_id": 16781395,
"author": "Wolph",
"author_id": 54017,
"author_profile": "https://Stackoverflow.com/users/54017",
"pm_score": 1,
"selected": false,
"text": "pg_dump -s <DATABASE> | grep 'CREATE TABLE' | awk '{print \"SELECT setval(#\" $3 \"_id_seq#, (SELECT MAX(id) FROM \" $3 \"));\"}' | sed \"s/#/'/g\" | psql <DATABASE> -f -\n"
},
{
"answer_id": 23390399,
"author": "Erwin Brandstetter",
"author_id": 939860,
"author_profile": "https://Stackoverflow.com/users/939860",
"pm_score": 8,
"selected": false,
"text": "SELECT setval('tbl_tbl_id_seq', max(tbl_id)) FROM tbl;\n tbl_id serial IDENTITY tbl tbl_tbl_id_seq pg_get_serial_sequence() IDENTITY SELECT setval(pg_get_serial_sequence('tbl', 'tbl_id'), max(tbl_id)) FROM tbl;\n last_value is_called nextval SELECT setval(pg_get_serial_sequence('tbl', 'tbl_id')\n , COALESCE(max(tbl_id) + 1, 1)\n , false)\nFROM tbl;\n 0 SHARE BEGIN;\n\nLOCK TABLE tbl IN SHARE MODE;\n\nSELECT setval('tbl_tbl_id_seq', max(tbl_id))\nFROM tbl\nHAVING max(tbl_id) > (SELECT last_value FROM tbl_tbl_id_seq); -- prevent lower number\n\nCOMMIT;\n SHARE ROW EXCLUSIVE UPDATE DELETE INSERT"
},
{
"answer_id": 23831064,
"author": "user",
"author_id": 781695,
"author_profile": "https://Stackoverflow.com/users/781695",
"pm_score": 2,
"selected": false,
"text": "INSERT INTO book (id, name, price) VALUES (1 , 'Alchemist' , 10),\n id INSERT INTO book (name, price) VALUES ('Alchemist' , 10),\n"
},
{
"answer_id": 25603776,
"author": "Haider Ali Wajihi",
"author_id": 870561,
"author_profile": "https://Stackoverflow.com/users/870561",
"pm_score": 5,
"selected": false,
"text": "ALTER SEQUENCE \"your_sequence_name\" RESTART WITH 0;\n \"TableName_FieldName_seq\" \"MyTable\" \"MyID\" \"MyTable_MyID_seq\" (select max()...) alter"
},
{
"answer_id": 26801367,
"author": "Ian Bytchek",
"author_id": 458356,
"author_profile": "https://Stackoverflow.com/users/458356",
"pm_score": 3,
"selected": false,
"text": "SELECT setval('serial', max(id)) FROM distributors;\n SELECT setval('\"Serial\"', max(id)) FROM distributors;\n"
},
{
"answer_id": 30380044,
"author": "mcandre",
"author_id": 350106,
"author_profile": "https://Stackoverflow.com/users/350106",
"pm_score": -1,
"selected": false,
"text": "SELECT setval... -- work around JDBC 'A result was returned when none was expected.'\n-- fix broken nextval due to poorly written 20140320100000_CreateAdminUserRoleTables.sql\nDO 'BEGIN PERFORM setval(pg_get_serial_sequence(''admin_user_role_groups'', ''id''), 1 + COALESCE(MAX(id), 0), FALSE) FROM admin_user_role_groups; END;';\n"
},
{
"answer_id": 30593263,
"author": "anydasa",
"author_id": 2987511,
"author_profile": "https://Stackoverflow.com/users/2987511",
"pm_score": 3,
"selected": false,
"text": "CREATE OR REPLACE FUNCTION public.recheck_sequence (\n)\nRETURNS void AS\n$body$\nDECLARE\n _table_name VARCHAR;\n _column_name VARCHAR; \n _sequence_name VARCHAR;\nBEGIN\n FOR _table_name IN SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = 'public' LOOP\n FOR _column_name IN SELECT column_name FROM information_schema.columns WHERE table_name = _table_name LOOP\n SELECT pg_get_serial_sequence(_table_name, _column_name) INTO _sequence_name;\n IF _sequence_name IS NOT NULL THEN \n EXECUTE 'SELECT setval('''||_sequence_name||''', COALESCE((SELECT MAX('||quote_ident(_column_name)||')+1 FROM '||quote_ident(_table_name)||'), 1), FALSE);';\n END IF;\n END LOOP; \n END LOOP;\nEND;\n$body$\nLANGUAGE 'plpgsql'\nVOLATILE\nCALLED ON NULL INPUT\nSECURITY INVOKER\nCOST 100;\n"
},
{
"answer_id": 37867461,
"author": "Baldiry",
"author_id": 2797271,
"author_profile": "https://Stackoverflow.com/users/2797271",
"pm_score": 2,
"selected": false,
"text": "drop function IF EXISTS rebuilt_sequences() RESTRICT;\nCREATE OR REPLACE FUNCTION rebuilt_sequences() RETURNS integer as\n$body$\n DECLARE sequencedefs RECORD; c integer ;\n BEGIN\n FOR sequencedefs IN Select\n DISTINCT(constraint_column_usage.table_name) as tablename,\n constraint_column_usage.column_name as columnname,\n replace(replace(columns.column_default,'''::regclass)',''),'nextval(''','') as sequencename\n from information_schema.constraint_column_usage, information_schema.columns\n where constraint_column_usage.table_schema ='public' AND \n columns.table_schema = 'public' AND columns.table_name=constraint_column_usage.table_name\n AND constraint_column_usage.column_name = columns.column_name\n AND columns.column_default is not null \n ORDER BY sequencename\n LOOP \n EXECUTE 'select max('||sequencedefs.columnname||') from ' || sequencedefs.tablename INTO c;\n IF c is null THEN c = 0; END IF;\n IF c is not null THEN c = c+ 1; END IF;\n EXECUTE 'alter sequence ' || sequencedefs.sequencename ||' minvalue '||c ||' start ' || c ||' restart with ' || c;\n END LOOP;\n\n RETURN 1; END;\n$body$ LANGUAGE plpgsql;\n\nselect rebuilt_sequences();\n"
},
{
"answer_id": 38575949,
"author": "Pietro",
"author_id": 488413,
"author_profile": "https://Stackoverflow.com/users/488413",
"pm_score": 4,
"selected": false,
"text": "SELECT 'SELECT SETVAL(' ||\n quote_literal(quote_ident(PGT.schemaname) || '.' || quote_ident(S.relname)) ||\n ', COALESCE(MAX(' ||quote_ident(C.attname)|| '), 1) ) FROM ' ||\n quote_ident(PGT.schemaname)|| '.'||quote_ident(T.relname)|| ';'\nFROM pg_class AS S,\n pg_depend AS D,\n pg_class AS T,\n pg_attribute AS C,\n pg_tables AS PGT\nWHERE S.relkind = 'S'\n AND S.oid = D.objid\n AND D.refobjid = T.oid\n AND D.refobjid = C.attrelid\n AND D.refobjsubid = C.attnum\n AND T.relname = PGT.tablename\nORDER BY S.relname;\n psql -Atq -f reset.sql -o temp\npsql -f temp\nrm temp\n"
},
{
"answer_id": 39274810,
"author": "Stanislav Yanev",
"author_id": 6783854,
"author_profile": "https://Stackoverflow.com/users/6783854",
"pm_score": 2,
"selected": false,
"text": "-- Create Function\nCREATE OR REPLACE FUNCTION \"sy_restart_seq_to_1\" (\n relname TEXT\n)\nRETURNS \"pg_catalog\".\"void\" AS\n$BODY$\n\nDECLARE\n\nBEGIN\n EXECUTE 'ALTER SEQUENCE '||relname||' RESTART WITH 1;';\nEND;\n$BODY$\n\nLANGUAGE 'plpgsql';\n\n-- Use Function\nSELECT \n relname\n ,sy_restart_seq_to_1(relname)\nFROM pg_class\nWHERE relkind = 'S';\n"
},
{
"answer_id": 43519125,
"author": "Vao Tsun",
"author_id": 5315974,
"author_profile": "https://Stackoverflow.com/users/5315974",
"pm_score": 3,
"selected": false,
"text": "max(att) > then lastval do --check seq not in sync\n$$\ndeclare\n _r record;\n _i bigint;\n _m bigint;\nbegin\n for _r in (\n SELECT relname,nspname,d.refobjid::regclass, a.attname, refobjid\n FROM pg_depend d\n JOIN pg_attribute a ON a.attrelid = d.refobjid AND a.attnum = d.refobjsubid\n JOIN pg_class r on r.oid = objid\n JOIN pg_namespace n on n.oid = relnamespace\n WHERE d.refobjsubid > 0 and relkind = 'S'\n ) loop\n execute format('select last_value from %I.%I',_r.nspname,_r.relname) into _i;\n execute format('select max(%I) from %s',_r.attname,_r.refobjid) into _m;\n if coalesce(_m,0) > _i then\n raise info '%',concat('changed: ',_r.nspname,'.',_r.relname,' from:',_i,' to:',_m);\n execute format('alter sequence %I.%I restart with %s',_r.nspname,_r.relname,_m+1);\n end if;\n end loop;\n\nend;\n$$\n;\n --execute format('alter sequence"
},
{
"answer_id": 44932074,
"author": "Nintynuts",
"author_id": 6220064,
"author_profile": "https://Stackoverflow.com/users/6220064",
"pm_score": 2,
"selected": false,
"text": "CREATE OR REPLACE FUNCTION \"reset_sequence\" (tablename text, columnname text)\nRETURNS \"pg_catalog\".\"void\" AS\n$body$\nDECLARE\nBEGIN\nEXECUTE format('SELECT setval(pg_get_serial_sequence(''%1$I'', %2$L),\n (SELECT COALESCE(MAX(%2$I)+1,1) FROM %1$I), false)',tablename,columnname);\nEND;\n$body$ LANGUAGE 'plpgsql';\n\nSELECT format('%s_%s_seq',table_name,column_name), reset_sequence(table_name,column_name) \nFROM information_schema.columns WHERE column_default like 'nextval%';\n pg_get_serial_sequence \"TableName\" --it thinks it's a table or column\n'TableName' --it thinks it's a string, but makes it lower case\n'\"TableName\"' --it works!\n ''%1$I'' '' 1$ I"
},
{
"answer_id": 49719450,
"author": "Yehia Amer",
"author_id": 1835701,
"author_profile": "https://Stackoverflow.com/users/1835701",
"pm_score": 3,
"selected": false,
"text": "DO\n$do$\nDECLARE tablename text;\nBEGIN\n -- change the where statments to include or exclude whatever tables you need\n FOR tablename IN SELECT table_name FROM information_schema.tables WHERE table_schema='public' AND table_type='BASE TABLE' AND table_name != '__EFMigrationsHistory'\n LOOP\n EXECUTE format('SELECT setval(pg_get_serial_sequence(''\"%s\"'', ''Id''), (SELECT MAX(\"Id\") + 1 from \"%s\"))', tablename, tablename);\n END LOOP;\nEND\n$do$\n"
},
{
"answer_id": 55090083,
"author": "Михаил Шатилов",
"author_id": 7856242,
"author_profile": "https://Stackoverflow.com/users/7856242",
"pm_score": 2,
"selected": false,
"text": "select 'SELECT SETVAL(' || seq [ 1] || ', COALESCE(MAX('||column_name||')+1, 1) ) FROM '||table_name||';'\nfrom (\n SELECT table_name, column_name, column_default, regexp_match(column_default, '''.*''') as seq\n from information_schema.columns\n where column_default ilike 'nextval%'\n ) as sequense_query\n"
},
{
"answer_id": 56155955,
"author": "Nick Van Berckelaer",
"author_id": 5795188,
"author_profile": "https://Stackoverflow.com/users/5795188",
"pm_score": 1,
"selected": false,
"text": "DO $$ DECLARE\n r RECORD;\nBEGIN\nFOR r IN (SELECT tablename, pg_get_serial_sequence(tablename, 'id') as sequencename\n FROM pg_catalog.pg_tables\n WHERE schemaname='YOUR_SCHEMA'\n AND tablename IN (SELECT table_name \n FROM information_schema.columns \n WHERE table_name=tablename and column_name='id')\n order by tablename)\nLOOP\nEXECUTE\n 'SELECT setval(''' || r.sequencename || ''', COALESCE(MAX(id), 1), MAX(id) IS NOT null)\n FROM ' || r.tablename || ';';\nEND LOOP;\nEND $$;\n"
},
{
"answer_id": 58185391,
"author": "Asad Rao",
"author_id": 852406,
"author_profile": "https://Stackoverflow.com/users/852406",
"pm_score": 2,
"selected": false,
"text": "SELECT setval('my_table_seq', (SELECT max(id) FROM my_table));\n"
},
{
"answer_id": 61831530,
"author": "brianwaganer",
"author_id": 10298071,
"author_profile": "https://Stackoverflow.com/users/10298071",
"pm_score": 0,
"selected": false,
"text": "drop function IF EXISTS reset_sequences(text[], text) RESTRICT;\nCREATE OR REPLACE FUNCTION reset_sequences(\n in_schema_name_list text[] = '{\"django\", \"dbaas\", \"metrics\", \"monitor\", \"runner\", \"db_counts\"}',\n in_table_name text = '%') RETURNS text[] as\n$body$\n DECLARE changed_seqs text[];\n DECLARE sequence_defs RECORD; c integer ;\n BEGIN\n FOR sequence_defs IN\n select\n DISTINCT(ccu.table_name) as table_name,\n ccu.column_name as column_name,\n replace(replace(c.column_default,'''::regclass)',''),'nextval(''','') as sequence_name\n from information_schema.constraint_column_usage ccu,\n information_schema.columns c\n where ccu.table_schema = ANY(in_schema_name_list)\n and ccu.table_schema = c.table_schema\n AND c.table_name = ccu.table_name\n and c.table_name like in_table_name\n AND ccu.column_name = c.column_name\n AND c.column_default is not null\n ORDER BY sequence_name\n LOOP\n EXECUTE 'select max(' || sequence_defs.column_name || ') from ' || sequence_defs.table_name INTO c;\n IF c is null THEN c = 1; else c = c + 1; END IF;\n EXECUTE 'alter sequence ' || sequence_defs.sequence_name || ' restart with ' || c;\n changed_seqs = array_append(changed_seqs, 'alter sequence ' || sequence_defs.sequence_name || ' restart with ' || c);\n END LOOP;\n changed_seqs = array_append(changed_seqs, 'Done');\n\n RETURN changed_seqs;\nEND\n$body$ LANGUAGE plpgsql;\n select *\nfrom unnest(reset_sequences('{\"django\", \"dbaas\", \"metrics\", \"monitor\", \"runner\", \"db_counts\"}'));\n activity_id_seq restart at 22\napi_connection_info_id_seq restart at 4\napi_user_id_seq restart at 1\napplication_contact_id_seq restart at 20\n"
},
{
"answer_id": 64250938,
"author": "Alexi Theodore",
"author_id": 9819342,
"author_profile": "https://Stackoverflow.com/users/9819342",
"pm_score": 1,
"selected": false,
"text": "CREATE OR REPLACE PROCEDURE pg_reset_all_table_sequences(\n IN commit_mode BOOLEAN DEFAULT FALSE\n, IN mask_in TEXT DEFAULT NULL\n) AS\n$$\nDECLARE\n sql_reset TEXT;\n each_sec RECORD;\n new_val TEXT;\nBEGIN\n\nsql_reset :=\n$sql$\nSELECT setval(pg_get_serial_sequence('%1$s.%2$s', '%3$s'), coalesce(max(\"%3$s\"), %4$s), false) FROM %1$s.%2$s;\n$sql$\n;\n\nFOR each_sec IN (\n\n SELECT\n quote_ident(table_schema) as table_schema\n , quote_ident(table_name) as table_name\n , column_name\n , coalesce(identity_start::INT, seqstart) as min_val\n FROM information_schema.columns\n JOIN pg_sequence ON seqrelid = pg_get_serial_sequence(quote_ident(table_schema)||'.'||quote_ident(table_name) , column_name)::regclass\n WHERE\n (is_identity::boolean OR column_default LIKE 'nextval%') -- catches both SERIAL and IDENTITY sequences\n\n -- mask on column address (schema.table.column) if supplied\n AND coalesce( table_schema||'.'||table_name||'.'||column_name = mask_in, TRUE )\n)\nLOOP\n\nIF commit_mode THEN\n EXECUTE format(sql_reset, each_sec.table_schema, each_sec.table_name, each_sec.column_name, each_sec.min_val) INTO new_val;\n RAISE INFO 'Resetting sequence for: %.% (%) to %'\n , each_sec.table_schema\n , each_sec.table_name\n , each_sec.column_name\n , new_val\n ;\nELSE\n RAISE INFO 'Sequence found for resetting: %.% (%)'\n , each_sec.table_schema\n , each_sec.table_name\n , each_sec.column_name\n ;\nEND IF\n;\n\nEND LOOP;\n\nEND\n$$\nLANGUAGE plpgsql\n;\n call pg_reset_all_table_sequences(); call pg_reset_all_table_sequences(true); call pg_reset_all_table_sequences('schema.table.column');"
},
{
"answer_id": 66982974,
"author": "DevonDahon",
"author_id": 931247,
"author_profile": "https://Stackoverflow.com/users/931247",
"pm_score": 5,
"selected": false,
"text": "users public max id SELECT MAX(id) FROM public.users;\n next value SELECT nextval('public.\"users_id_seq\"');\n next value max id SELECT setval('public.\"users_id_seq\"',\n (SELECT MAX(id) FROM public.users)\n);\n nextval() currval()"
},
{
"answer_id": 70908122,
"author": "NemyaNation",
"author_id": 3396971,
"author_profile": "https://Stackoverflow.com/users/3396971",
"pm_score": 0,
"selected": false,
"text": "rails console ActiveRecord::Base.connection.execute(\"SELECT setval(pg_get_serial_sequence('table_name', 'id'), MAX(id)) FROM table_name;\")\n table_name users"
},
{
"answer_id": 74640952,
"author": "Fenerbahce",
"author_id": 15512188,
"author_profile": "https://Stackoverflow.com/users/15512188",
"pm_score": 0,
"selected": false,
"text": "SELECT setval('sequencename', COALESCE((SELECT MAX(id)+1 FROM tablename), 1), false);\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4196/"
] |
244,246
|
<p>I want to create an alias for a class name. The following syntax would be perfect:</p>
<pre><code>public class LongClassNameOrOneThatContainsVersionsOrDomainSpecificName
{
...
}
public class MyName = LongClassNameOrOneThatContainsVersionOrDomainSpecificName;
</code></pre>
<p>but it won't compile.</p>
<hr />
<h2>Example</h2>
<p><strong>Note</strong> This example is provided for convenience only. Don't try to solve this particular problem by suggesting changing the design of the entire system. The presence, or lack, of this example doesn't change the original question.</p>
<p>Some existing code depends on the presence of a static class:</p>
<pre><code>public static class ColorScheme
{
...
}
</code></pre>
<p>This color scheme is the Outlook 2003 color scheme. i want to introduce an Outlook 2007 color scheme, while retaining the Outlook 2003 color scheme:</p>
<pre><code>public static class Outlook2003ColorScheme
{
...
}
public static class Outlook2007ColorScheme
{
...
}
</code></pre>
<p>But i'm still faced with the fact that the code depends on the presence of a static class called <code>ColorScheme</code>. My first thought was to create a <code>ColorScheme</code> class that I will inherit from either <code>Outlook2003</code> or <code>Outlook2007</code>:</p>
<pre><code>public static class ColorScheme : Outlook2007ColorScheme
{
}
</code></pre>
<p>but you cannot inherit from a static class.</p>
<p>My next thought was to create the static <code>ColorScheme</code> class, but make <code>Outlook2003ColorScheme</code> and <code>Outlook2007ColorScheme</code> classes non-static. Then a static variable in the static <code>ColorScheme</code> class can point to either "true" color scheme:</p>
<pre><code>public static class ColorScheme
{
private static CustomColorScheme = new Outlook2007ColorScheme();
...
}
private class CustomColorScheme
{
...
}
private class Outlook2008ColorScheme : CustomColorScheme
{
...
}
private class Outlook2003ColorScheme : CustomColorScheme
{
...
}
</code></pre>
<p>but that would require me to convert a class composed entirly of readonly static Colors into overridable properties, and then my <code>ColorScheme</code> class would need to have the 30 different property getters thunk down into the contained object.</p>
<p>That's just too much typing.</p>
<p>So my next thought was to alias the class:</p>
<pre><code>public static ColorScheme = Outlook2007ColorScheme;
</code></pre>
<p>But that doesn't compile.</p>
<p>How can I alias a static class into another name?</p>
<hr />
<p><strong>Update:</strong> Can someone please add the answer <em>"You cannot do this in C#"</em>, so I can mark that as the accepted answer. Anyone else wanting the answer to the same question will find this question, the accepted answer, and a number of workarounds that might, or might not, be useful.</p>
<p>I just want to close this question out.</p>
|
[
{
"answer_id": 244255,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 7,
"selected": false,
"text": "using typedef using ColorScheme = The.Fully.Qualified.Namespace.Outlook2007ColorScheme;\n"
},
{
"answer_id": 244259,
"author": "dpurrington",
"author_id": 5573,
"author_profile": "https://Stackoverflow.com/users/5573",
"pm_score": 4,
"selected": false,
"text": "using ColorScheme=[fully qualified].Outlook2007ColorScheme\n"
},
{
"answer_id": 244270,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 4,
"selected": false,
"text": "public interface ColorScheme {\n Color TitleBar { get; }\n Color Background{ get; }\n ...\n}\n\npublic static class ColorSchemeFactory {\n\n private static ColorScheme scheme = new Outlook2007ColorScheme();\n\n public static ColorScheme GetColorScheme() { //Add applicable arguments\n return scheme;\n }\n}\n\npublic class Outlook2003ColorScheme: ColorScheme {\n public Color TitleBar {\n get { return Color.LightBlue; }\n }\n\n public Color Background {\n get { return Color.Gray; }\n }\n}\n\npublic class Outlook2007ColorScheme: ColorScheme {\n public Color TitleBar {\n get { return Color.Blue; }\n }\n\n public Color Background {\n get { return Color.White; }\n }\n}\n"
},
{
"answer_id": 244284,
"author": "chills42",
"author_id": 23855,
"author_profile": "https://Stackoverflow.com/users/23855",
"pm_score": 2,
"selected": false,
"text": "IColorScheme"
},
{
"answer_id": 244289,
"author": "mohammedn",
"author_id": 29268,
"author_profile": "https://Stackoverflow.com/users/29268",
"pm_score": 5,
"selected": false,
"text": "using Outlook2007ColorScheme = YourNameSpace.ColorScheme;\n"
},
{
"answer_id": 436588,
"author": "Ian Boyd",
"author_id": 12597,
"author_profile": "https://Stackoverflow.com/users/12597",
"pm_score": 5,
"selected": true,
"text": "using private void button1_Click(object sender, EventArgs e)\n{\n this.BackColor = ColorScheme.ApplyColorScheme(this.BackColor);\n}\n class ColorScheme\n{\n public static Color ApplyColorScheme(Color c) { ... }\n}\n ColorScheme using ColorScheme = Outlook2007ColorScheme;\n\nclass Outlook2007ColorScheme\n{\n public static Color ApplyColorScheme(Color c) { ... }\n}\n ColorScheme using ColorScheme ColorScheme ColorScheme ColorScheme ColorScheme = Outlook2007ColorScheme\n"
},
{
"answer_id": 28787521,
"author": "Timothy",
"author_id": 2946652,
"author_profile": "https://Stackoverflow.com/users/2946652",
"pm_score": 2,
"selected": false,
"text": "using ColorScheme using ColorScheme using CurrentColorScheme = Outlook2007ColorScheme;\npublic static class ColorScheme\n{\n public static Color ApplyColorScheme(Color c)\n {\n return CurrentColorScheme.ApplyColorScheme(c);\n }\n public static Something DoSomethingElse(Param a, Param b)\n {\n return CurrentColorScheme.DoSomethingElse(a, b);\n }\n}\n private void button1_Click(object sender, EventArgs e)\n{\n this.BackColor = ColorScheme.ApplyColorScheme(this.BackColor);\n}\n ColorScheme using CurrentColorScheme = Outlook2008ColorScheme; ColorScheme Outlook2007ColorScheme ColorScheme ColorScheme ColorSchemeOld using CurrentColorScheme = ColorSchemeOld;"
},
{
"answer_id": 31062732,
"author": "percebus",
"author_id": 1361858,
"author_profile": "https://Stackoverflow.com/users/1361858",
"pm_score": 2,
"selected": false,
"text": "public class Child : MyReallyReallyLongNamedClass {}\n class namespace ApiLoginUser DataBaseUser WebPortalLoginUser namespace User namespace using LoginApi = MyCompany.Api.Login;\nusing AuthDB = MyCompany.DataBase.Auth;\nusing ViewModels = MyCompany.BananasPortal.Models;\n\n// ...\nAuthDB.User dbUser;\nusing ( var ctxt = new AuthDB.AuthContext() )\n{\n dbUser = ctxt.Users.Find(userId);\n}\n\nvar apiUser = new LoginApi.Models.User {\n Username = dbUser.EmailAddess,\n Password = \"*****\"\n };\n\nLoginApi.UserSession apiUserSession = await LoginApi.Login(apiUser);\nvar vm = new ViewModels.User(apiUserSession.User.Details);\nreturn View(vm);\n class User namespace"
},
{
"answer_id": 47420103,
"author": "J-Americano",
"author_id": 3317003,
"author_profile": "https://Stackoverflow.com/users/3317003",
"pm_score": 3,
"selected": false,
"text": "using aliasClass = Fully.Qualified.Namespace.Example;\n//Example being the class in the Fully.Qualified.Namespace\n\npublic class Test{\n\n public void Test_Function(){\n\n aliasClass.DoStuff();\n //aliasClass here representing the Example class thus aliasing\n //aliasClass will be in scope for all code in my Test.cs file\n }\n\n}\n"
},
{
"answer_id": 67751762,
"author": "JeanLColombo",
"author_id": 8834550,
"author_profile": "https://Stackoverflow.com/users/8834550",
"pm_score": 0,
"selected": false,
"text": "public class LongClassNameOrOneThatContainsVersionsOrDomainSpecificName\n{\n ...\n}\n\npublic class MyName \n : LongClassNameOrOneThatContainsVersionOrDomainSpecificName\n{\n\n}\n MyName public class MyName \n : LongClassNameOrOneThatContainsVersionOrDomainSpecificName\n{\n public MyName(T1 param1, T2 param2) : base(param1, param2) {} \n}\n T1 T2 LongClassNameOrOneThatContainsVersionOrDomainSpecificName"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12597/"
] |
244,252
|
<p>I've been looking (without great luck) for the perfect reference card with all the basic sorting algos in C (or maybe in pseudo code). Wikipedia is a terrific source of info but this time I'm looking for something definitely more portable (pocket size if possible) and of course printable. Any suggestion would be much appreciated!</p>
|
[
{
"answer_id": 244294,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 2,
"selected": false,
"text": "qsort() qsort() bsearch() qsort()"
},
{
"answer_id": 244632,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 6,
"selected": true,
"text": "#include <stdlib.h>\n#include <string.h>\n\nstatic void swap(int *a, int *b) {\n if (a != b) {\n int c = *a;\n *a = *b;\n *b = c;\n }\n}\n\nvoid bubblesort(int *a, int l) {\n int i, j;\n\n for (i = l - 2; i >= 0; i--)\n for (j = i; j < l - 1 && a[j] > a[j + 1]; j++)\n swap(a + j, a + j + 1);\n}\n\nvoid selectionsort(int *a, int l) {\n int i, j, k;\n for (i = 0; i < l; i++) {\n for (j = (k = i) + 1; j < l; j++)\n if (a[j] < a[k])\n k = j;\n swap(a + i, a + k);\n }\n}\n\nstatic void hsort_helper(int *a, int i, int l) {\n int j;\n\n for (j = 2 * i + 1; j < l; i = j, j = 2 * j + 1)\n if (a[i] < a[j])\n if (j + 1 < l && a[j] < a[j + 1])\n swap(a + i, a + ++j);\n else\n swap(a + i, a + j);\n else if (j + 1 < l && a[i] < a[j + 1])\n swap(a + i, a + ++j);\n else\n break;\n}\n\nvoid heapsort(int *a, int l) {\n int i;\n\n for (i = (l - 2) / 2; i >= 0; i--)\n hsort_helper(a, i, l);\n\n while (l-- > 0) {\n swap(a, a + l);\n hsort_helper(a, 0, l);\n }\n}\n\nstatic void msort_helper(int *a, int *b, int l) {\n int i, j, k, m;\n\n switch (l) {\n case 1:\n a[0] = b[0];\n case 0:\n return;\n }\n\n m = l / 2;\n msort_helper(b, a, m);\n msort_helper(b + m, a + m, l - m);\n for (i = 0, j = 0, k = m; i < l; i++)\n a[i] = b[j < m && !(k < l && b[j] > b[k]) ? j++ : k++];\n}\n\nvoid mergesort(int *a, int l) {\n int *b;\n\n if (l < 0)\n return;\n\n b = malloc(l * sizeof(int));\n memcpy(b, a, l * sizeof(int));\n msort_helper(a, b, l);\n free(b);\n}\n\nstatic int pivot(int *a, int l) {\n int i, j;\n\n for (i = j = 1; i < l; i++)\n if (a[i] <= a[0])\n swap(a + i, a + j++);\n\n swap(a, a + j - 1);\n\n return j;\n}\n\nvoid quicksort(int *a, int l) {\n int m;\n\n if (l <= 1)\n return;\n\n m = pivot(a, l);\n quicksort(a, m - 1);\n quicksort(a + m, l - m);\n}\n\nstruct node {\n int value;\n struct node *left, *right;\n};\n\nvoid btreesort(int *a, int l) {\n int i;\n struct node *root = NULL, **ptr;\n\n for (i = 0; i < l; i++) {\n for (ptr = &root; *ptr;)\n ptr = a[i] < (*ptr)->value ? &(*ptr)->left : &(*ptr)->right;\n *ptr = malloc(sizeof(struct node));\n **ptr = (struct node){.value = a[i]};\n }\n\n for (i = 0; i < l; i++) {\n struct node *node;\n for (ptr = &root; (*ptr)->left; ptr = &(*ptr)->left);\n a[i] = (*ptr)->value;\n node = (*ptr)->right;\n free(*ptr);\n (*ptr) = node;\n }\n}\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6992/"
] |
244,264
|
<p>I am currently trying to learn all new features of C#3.0. I have found a very nice collection of <a href="http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx" rel="nofollow noreferrer">sample to practice LINQ</a> but I can't find something similar for Lambda.</p>
<p>Do you have a place that I could practice Lambda function?</p>
<h2>Update</h2>
<p>LINQpad is great to learn Linq (thx for the one who suggest) and use a little bit Lambda in some expression. But I would be interesting in more specific exercise for Lambda.</p>
|
[
{
"answer_id": 244427,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 2,
"selected": false,
"text": "System.Action<...> System.Func<...> System.Predicate<...> public static void Main()\n{\n // ToString is shown below for clarification\n Func<int,string,string> intAndString = (x, y) => x.ToString() + y.ToString();\n Func<bool, float, string> boolAndFloat = (x, y) => x.ToString() + y.ToString();\n\n // with declared\n Combine(13, \"dog\", intAndString);\n Combine(true, 37.893f, boolAndFloat);\n\n // inline\n Combine(\"a string\", \" with another\", (s1, s2) => s1 + s2);\n // and multiline - note inclusion of return\n Combine(new[] { 1, 2, 3 }, new[] { 6, 7, 8 },\n (arr1, arr2) =>\n {\n var ret = \"\";\n foreach (var i in arr1)\n {\n ret += i.ToString();\n }\n foreach (var n in arr2)\n {\n ret += n.ToString();\n }\n\n return ret;\n }\n );\n\n // addition\n PerformOperation(2, 2, (x, y) => 2 + 2);\n // sum, multi-line\n PerformOperation(new[] { 1, 2, 3 }, new[] { 12, 13, 14 },\n (arr1, arr2) =>\n {\n var ret = 0;\n foreach (var i in arr1)\n ret += i;\n foreach (var i in arr2)\n ret += i;\n return ret;\n }\n );\n\n Console.ReadLine();\n\n}\n\npublic static void Combine<TOne, TTwo>(TOne one, TTwo two, Func<TOne, TTwo, string> vd)\n{\n Console.WriteLine(\"Appended: \" + vd(one, two));\n}\n\npublic static void PerformOperation<T,TResult>(T one, T two, Func<T, T, TResult> func)\n{\n Console.WriteLine(\"{0} operation {1} is {2}.\", one, two, func(one,two));\n}\n var a = new Action(() => Console.WriteLine(\"Yay!\"));\n Action a = () => Console.WriteLine(\"Yay\");\n Action Func Predicate var f = new Func<int, bool>(anInt => anInt > 0);\n // note: no var here, explicit declaration\nFunc<int,bool> f = anInt => anInt > 0;\n Func<int,bool> f = (anInt) => anInt > 0;\n Func<int,bool> f = (anInt) =>\n{\n return anInt > 0;\n}\n Func"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13913/"
] |
244,276
|
<p>A website I'm working on (using AS2 because it's oldschool) has a larger index .swf file that loads sub-swfs using <code>loadMovie("foo1.swf", placeToShowSwf)</code>. There's <code>foo1.swf</code> through 4, which is silly because the only thing that's different between them is a single number in the address of an xml file that tells it what content to load. So I want to reduce this to one file, with a simple function that the index file calls to load the xml file, as seen here.</p>
<pre><code>function setFooNum(i:Number) {
fooNum = i;
//my_xml = new XML(); edit: this line has since been removed and is kept for historical purposes
my_xml.load("foo"+fooNum+".xml");
};
</code></pre>
<p>However, for some reason, the xml file won't load. It loads properly outside the function, but that doesn't do me much good. It changes fooNum properly, but that doesn't do me any good if the wrong xml file is already loading. As far as I can tell, the code behaves as though the <code>my_xml.load("foo"+fooNum+".xml")</code> isn't there at all.</p>
<p>Is this some sort of security measure I don't know about, and is there any way around it?</p>
<p><strong><em>EDIT</em></strong>
As several people pointed out, the <code>my_xml = new XML()</code> line was the culprit. Unfortunately, I'm now getting a new and exciting error. When <code>setFooNum(i)</code> is called immediately after the <code>loadMove()</code> in the index file, a <code>trace(fooNum)</code> inside the <code>setFooNum()</code> function prints that fooNum is set correctly, but a <code>trace(fooNum)</code> inside the <code>onLoad()</code> (which returns a success despite loading apparently nothing, btw) shows that fooNum is undefined! Also, I made a button in the index swf that calls <code>setFooNum(3)</code> (for debugging purposes), which for some reason makes it work fine. So waiting a few seconds for the file to load seems to solve the problem, but that's an incredibly ugly solution. </p>
<p>So how do I wait until everything is completely loaded before calling <code>setFooNum()</code>? </p>
|
[
{
"answer_id": 244414,
"author": "Claudio",
"author_id": 30122,
"author_profile": "https://Stackoverflow.com/users/30122",
"pm_score": 0,
"selected": false,
"text": "function setFooNum(i:Number) {\n fooNum = i;\n my_xml.load(\"foo\"+fooNum+\".xml\");\n};\n"
},
{
"answer_id": 1785414,
"author": "mattbasta",
"author_id": 205229,
"author_profile": "https://Stackoverflow.com/users/205229",
"pm_score": 2,
"selected": true,
"text": "crossdomain.xml"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32139/"
] |
244,280
|
<p>I'm trying to implement a unit test for a function in a project that doesn't have unit tests and this function requires a System.Web.Caching.Cache object as a parameter. I've been trying to create this object by using code such as...</p>
<pre><code>System.Web.Caching.Cache cache = new System.Web.Caching.Cache();
cache.Add(...);
</code></pre>
<p>...and then passing the 'cache' in as a parameter but the Add() function is causing a NullReferenceException. My best guess so far is that I can't create this cache object in a unit test and need to retrieve it from the HttpContext.Current.Cache which I obviously don't have access to in a unit test.</p>
<p>How do you unit test a function that requires a System.Web.Caching.Cache object as a parameter?</p>
|
[
{
"answer_id": 244331,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 4,
"selected": true,
"text": "public interface ICacheWrapper\n{\n ...methods to support\n}\n\npublic class CacheWrapper : ICacheWrapper\n{\n private System.Web.Caching.Cache cache;\n public CacheWrapper( System.Web.Caching.Cache cache )\n {\n this.cache = cache;\n }\n\n ... implement methods using cache ...\n}\n\npublic class MockCacheWrapper : ICacheWrapper\n{\n private MockCache cache;\n public MockCacheWrapper( MockCache cache )\n {\n this.cache = cache;\n }\n\n ... implement methods using mock cache...\n}\n\npublic class MockCache\n{\n ... implement ways to set mock values and retrieve them...\n}\n\n[Test]\npublic void CachingTest()\n{\n ... set up omitted...\n\n ICacheWrapper wrapper = new MockCacheWrapper( new MockCache() );\n\n CacheManager manager = new CacheManager( wrapper );\n\n manager.Insert(item,value);\n\n Assert.AreEqual( value, manager[item] );\n}\n ...\n\nCacheManager manager = new CacheManager( new CacheWrapper( HttpContext.Current.Cache ));\n\nmanager.Add(item,value);\n\n...\n"
},
{
"answer_id": 18019833,
"author": "DarkoM",
"author_id": 2102684,
"author_profile": "https://Stackoverflow.com/users/2102684",
"pm_score": 0,
"selected": false,
"text": "var httpResponse = MockRepository.GenerateMock<HttpResponseBase>();\nvar cache = MockRepository.GenerateMock<HttpCachePolicyBase>();\n cache.Stub(x => x.SetOmitVaryStar(true));\n httpResponse.Stub(x => x.Cache).Return(cache);\n httpContext.Stub(x => x.Response).Return(httpResponse);\n httpContext.Response.Stub(x => x.Cache).Return(cache);\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] |
244,285
|
<p>I've got to get a quick and dirty configuration editor up and running. The flow goes something like this:</p>
<p>configuration (POCOs on server) are serialized to XML.<br>
The XML is well formed at this point. The configuration is sent to the web server in XElements.<br>
On the web server, the XML (Yes, ALL OF IT) is dumped into a textarea for editing.<br>
The user edits the XML directly in the webpage and clicks Submit.<br>
In the response, I retrieve the altered text of the XML configuration. At this point, ALL escapes have been reverted by the process of displaying them in a webpage.<br>
I attempt to load the string into an XML object (XmlElement, XElement, whatever). KABOOM.</p>
<p>The problem is that serialization escapes attribute strings, but this is lost in translation along the way. </p>
<p>For example, let's say I have an object that has a regex. Here's the configuration as it comes to the web server:</p>
<pre><code><Configuration>
<Validator Expression="[^&lt;]" />
</Configuration>
</code></pre>
<p>So, I put this into a textarea, where it looks like this to the user:</p>
<pre><code><Configuration>
<Validator Expression="[^<]" />
</Configuration>
</code></pre>
<p>So the user makes a slight modification and submits the changes back. On the web server, the response string looks like:</p>
<pre><code><Configuration>
<Validator Expression="[^<]" />
<Validator Expression="[^&]" />
</Configuration>
</code></pre>
<p>So, the user added another validator thingie, and now BOTH have attributes with illegal characters. If I try to load this into any XML object, it throws an exception because < and & are not valid within a text string. I CANNOT CANNOT CANNOT CANNOT use any kind of encoding function, as it encodes the entire bloody thing:</p>
<p>var result = Server.HttpEncode(editedConfig);</p>
<p>results in </p>
<pre><code>&lt;Configuration&gt;
&lt;Validator Expression="[^&lt;]" /&gt;
&lt;Validator Expression="[^&amp;]" /&gt;
&lt;/Configuration&gt;
</code></pre>
<p>This is NOT valid XML. If I try to load this into an XML element of any kind I will be hit by a falling anvil. I don't like falling anvils. </p>
<p>SO, the question remains... Is the ONLY way I can get this string XML ready for parsing into an XML object is by using regex replaces? Is there any way to "turn off constraints" when I load? How do you get around this???</p>
<hr>
<p>One last response and then wiki-izing this, as I don't think there is a valid answer.</p>
<p>The XML I place in the textarea IS valid, escaped XML. The process of 1) putting it in the text area 2) sending it to the client 3) displaying it to the client 4) submitting the form it's in 5) sending it back to the server and 6) retrieving the value from the form REMOVES ANY AND ALL ESCAPES. </p>
<p>Let me say this again: I'M not un-escaping ANYTHING. Just displaying it in the browser does this!</p>
<p>Things to mull over: Is there a way to prevent this un-escaping from happening in the first place? Is there a way to take almost-valid XML and "clean" it in a safe manner?</p>
<hr>
<p>This question now has a bounty on it. To collect the bounty, you demonstrate how to edit VALID XML in a browser window WITHOUT a 3rd party/open source tool that doesn't require me to use regex to escape attribute values manually, that doesn't require users to escape their attributes, and that doesn't fail when roundtripping (&amp;amp;amp;amp;etc;)</p>
|
[
{
"answer_id": 244299,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 4,
"selected": true,
"text": "<foo mean-attribute=\"<\">\n <foo mean-attribute=\"&<\">\n"
},
{
"answer_id": 244330,
"author": "mohammedn",
"author_id": 29268,
"author_profile": "https://Stackoverflow.com/users/29268",
"pm_score": 0,
"selected": false,
"text": "HttpServerUtility utility = new HttpServerUtility();\nstring encodedText = utility.HtmlEncode(text);\n"
},
{
"answer_id": 244571,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "private string EscapeAttributes(string configuration)\n{\n var lt = @\"(?<=\\w+\\s*=\\s*\"\"[^\"\"]*)<(?=[^\"\"]*\"\")\";\n configuration = Regex.Replace(configuration, lt, \"<\");\n\n return configuration;\n}\n"
},
{
"answer_id": 246652,
"author": "bobince",
"author_id": 18936,
"author_profile": "https://Stackoverflow.com/users/18936",
"pm_score": 3,
"selected": false,
"text": "<textarea name=\"somexml\">\n <Configuration>\n <Validator Expression=\"[^&lt;]\" />\n <Validator Expression=\"[^&amp;]\" />\n </Configuration>\n</textarea>\n"
},
{
"answer_id": 492890,
"author": "13ren",
"author_id": 50979,
"author_profile": "https://Stackoverflow.com/users/50979",
"pm_score": 1,
"selected": false,
"text": "<textarea cols=\"80\" rows=\"10\" id=\"1\"></textarea>\n\n<script>\nelem = document.getElementById(\"1\");\n\nelem.value = '\\\n<Configuration>\\n\\\n <Validator Expression=\"[^<]\" />\\n\\\n</Configuration>\\\n'\nalert(elem.value);\n</script>\n <Configuration>\n <Validator Expression=\"[^<]\" />\n</Configuration>\n < & < &lt; < <Configuration>\n <Validator Expression=\"[^\"<]\" />\n</Configuration>\n /[^\"<]/\n <Configuration>\n <Expression></Expression></Expression>\n</Configuration>\n & & \\ \\\\ <"
},
{
"answer_id": 522986,
"author": "13ren",
"author_id": 50979,
"author_profile": "https://Stackoverflow.com/users/50979",
"pm_score": 1,
"selected": false,
"text": " <Configuration>\n <Validator Expression=\"<![CDATA[ [^<] ]]>\" />\n </Configuration>\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
244,295
|
<p>s it possible to do the following in subsonic.</p>
<p>SELECT * FROM TABLE1</p>
<p>WHERE Column1 > Column2 or Column1 < Colum3</p>
<p>All examples that I've seen assume you now a value to pass to the where clause. I'm trying to do this without creating a view.</p>
<p>Thanks</p>
|
[
{
"answer_id": 716887,
"author": "Rick Rat",
"author_id": 43754,
"author_profile": "https://Stackoverflow.com/users/43754",
"pm_score": -1,
"selected": false,
"text": "Dim TableList As Generic.List(Of Database.Table1) = _\n New SubSonic.Select().From(\"Table1\"). _\n Where(\"Col1\").IsGreaterThan(\"Col2\"). _\n Or(\"Col1\").IsLessThan(\"Col3\").ExecuteTypedList(Of Database.Table1)()\n"
},
{
"answer_id": 4574293,
"author": "Dave Neeley",
"author_id": 9660,
"author_profile": "https://Stackoverflow.com/users/9660",
"pm_score": 0,
"selected": false,
"text": "public bool ParameterIsTableColumn\n{\n get { return ParameterValue is TableSchema.TableColumn ; }\n}\n foreach(Constraint c in qry.Constraints)\n{\n if (c.ConstructionFragment == \"##\" || c.ParameterIsTableColumn)\n continue;\n //add this at the top of the method\nint currentConstraintIndex = query.Constraints.IndexOf(c);\n\n///the statement 'c.ParameterName = ' occurs four times in this method\n///use this line the first three times, and a slight variation of it on the fourth\nc.ParameterName = (c.ParameterIsTableColumn ? ((TableSchema.TableColumn)c.ParameterValue).QualifiedName : String.Concat(col.ParameterName, currentConstraintIndex));\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2526/"
] |
244,316
|
<p>I'm looking for a good reader/writer lock in C++. We have a use case of a single infrequent writer and many frequent readers and would like to optimize for this. Preferable I would like a cross-platform solution, however a Windows only one would be acceptable. </p>
|
[
{
"answer_id": 244344,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 6,
"selected": true,
"text": "shared_lock unique_lock upgrade_lock shared_mutex"
},
{
"answer_id": 244376,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 5,
"selected": false,
"text": "#include <pthread.h>\n\nstruct rwlock {\n pthread_mutex_t lock;\n pthread_cond_t read, write;\n unsigned readers, writers, read_waiters, write_waiters;\n};\n\nvoid reader_lock(struct rwlock *self) {\n pthread_mutex_lock(&self->lock);\n if (self->writers || self->write_waiters) {\n self->read_waiters++;\n do pthread_cond_wait(&self->read, &self->lock);\n while (self->writers || self->write_waiters);\n self->read_waiters--;\n }\n self->readers++;\n pthread_mutex_unlock(&self->lock);\n}\n\nvoid reader_unlock(struct rwlock *self) {\n pthread_mutex_lock(&self->lock);\n self->readers--;\n if (self->write_waiters)\n pthread_cond_signal(&self->write);\n pthread_mutex_unlock(&self->lock);\n}\n\nvoid writer_lock(struct rwlock *self) {\n pthread_mutex_lock(&self->lock);\n if (self->readers || self->writers) {\n self->write_waiters++;\n do pthread_cond_wait(&self->write, &self->lock);\n while (self->readers || self->writers);\n self->write_waiters--;\n }\n self->writers = 1;\n pthread_mutex_unlock(&self->lock);\n}\n\nvoid writer_unlock(struct rwlock *self) {\n pthread_mutex_lock(&self->lock);\n self->writers = 0;\n if (self->write_waiters)\n pthread_cond_signal(&self->write);\n else if (self->read_waiters)\n pthread_cond_broadcast(&self->read);\n pthread_mutex_unlock(&self->lock);\n}\n\nvoid rwlock_init(struct rwlock *self) {\n self->readers = self->writers = self->read_waiters = self->write_waiters = 0;\n pthread_mutex_init(&self->lock, NULL);\n pthread_cond_init(&self->read, NULL);\n pthread_cond_init(&self->write, NULL);\n}\n pthreads writer_unlock pthread_rwlock_* pthreads pthreads pthreads"
},
{
"answer_id": 244442,
"author": "Dong Hoon",
"author_id": 31330,
"author_profile": "https://Stackoverflow.com/users/31330",
"pm_score": 2,
"selected": false,
"text": "ACE_RW_Process_Mutex ACE_Write_Guard ACE_Read_Guard ACE_Condition"
},
{
"answer_id": 6450579,
"author": "Yochai Timmer",
"author_id": 536086,
"author_profile": "https://Stackoverflow.com/users/536086",
"pm_score": 6,
"selected": false,
"text": "#include <shared_mutex>\n\ntypedef std::shared_mutex Lock;\ntypedef std::unique_lock< Lock > WriteLock;\ntypedef std::shared_lock< Lock > ReadLock;\n\nLock myLock;\n\nvoid ReadFunction()\n{\n ReadLock r_lock(myLock);\n //Do reader stuff\n}\n\nvoid WriteFunction()\n{\n WriteLock w_lock(myLock);\n //Do writer stuff\n}\n #include <boost/thread/locks.hpp>\n#include <boost/thread/shared_mutex.hpp>\n\ntypedef boost::shared_mutex Lock;\ntypedef boost::unique_lock< Lock > WriteLock;\ntypedef boost::shared_lock< Lock > ReadLock;\n"
},
{
"answer_id": 44228638,
"author": "Serge Rogatch",
"author_id": 1915854,
"author_profile": "https://Stackoverflow.com/users/1915854",
"pm_score": 3,
"selected": false,
"text": "std::shared_mutex"
},
{
"answer_id": 72283766,
"author": "Faker",
"author_id": 12914986,
"author_profile": "https://Stackoverflow.com/users/12914986",
"pm_score": 0,
"selected": false,
"text": "#include <shared_mutex>\n\nclass Foo {\n public:\n void Write() {\n std::unique_lock lock{mutex_};\n // ... \n }\n\n void Read() {\n std::shared_lock lock{mutex_};\n // ... \n }\n\n private:\n std::shared_mutex mutex_;\n};\n\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/852/"
] |
244,329
|
<p>Something happened that I'm not sure should be possible. Obviously it is, because I've seen it, but I need to find the root cause & I was hoping you all could help.</p>
<p>We have a system that looks up latitude & longitude for a zipcode. Rather than access it every time, we cache the results in a cheap in-memory HashTable cache, since the lat & long of a zip code tend to change less often than we release.</p>
<p>Anyway, the hash is surrounded by a class that has a "get" and "add" method that are both synchronized. We access this class as a singleton.</p>
<p>I'm not claiming this is the best setup, but it's where we're at. (I plan to change to wrap the Map in a Collections.synchronizedMap() call ASAP.)</p>
<p>We use this cache in a multi-threaded environment, where we thread 2 calls for 2 zips (so we can calculate the distance between the two). These sometimes happen at very nearly the same time, so its very possible that both calls access the map at the same time.</p>
<p>Just recently we had an incident where two different zip codes returned the same value. Assuming that the initial values were actually different, is there any way that writing the values into the Map would cause the same value to be written for two different keys? Or, is there any way that 2 "gets" could cross wires and accidentally return the same value?</p>
<p>The only other explanation I have is that the initial data was corrupt (wrong values), but it seems very unlikely.</p>
<p>Any ideas would be appreciated.
Thanks,
Peter</p>
<p>(PS: Let me know if you need more info, code, etc.)</p>
<pre><code>public class InMemoryGeocodingCache implements GeocodingCache
{
private Map cache = new HashMap();
private static GeocodingCache instance = new InMemoryGeocodingCache();
public static GeocodingCache getInstance()
{
return instance;
}
public synchronized LatLongPair get(String zip)
{
return (LatLongPair) cache.get(zip);
}
public synchronized boolean has(String zip)
{
return cache.containsKey(zip);
}
public synchronized void add(String zip, double lat, double lon)
{
cache.put(zip, new LatLongPair(lat, lon));
}
}
public class LatLongPair {
double lat;
double lon;
LatLongPair(double lat, double lon)
{
this.lat = lat;
this.lon = lon;
}
public double getLatitude()
{
return this.lat;
}
public double getLongitude()
{
return this.lon;
}
}
</code></pre>
|
[
{
"answer_id": 244819,
"author": "Vladimir Dyuzhev",
"author_id": 1163802,
"author_profile": "https://Stackoverflow.com/users/1163802",
"pm_score": 3,
"selected": false,
"text": "LatLongPair llp = InMemoryGeocodingCache.getInstance().get(ZIP1);\nllp.lat = x;\nllp.lon = y;\n"
},
{
"answer_id": 268376,
"author": "Michael Rutherfurd",
"author_id": 33889,
"author_profile": "https://Stackoverflow.com/users/33889",
"pm_score": 0,
"selected": false,
"text": "GeocodingCache cache = InMemoryGeocodingCache.getInstance();\n\nif (!cache.has(ZIP)) {\n cache.add(ZIP, x, y);\n}\n public synchronized void add(String zip, double lat, double lon) {\n if (cache.containsKey(zip)) return;\n cache.put(zip, new LatLongPair(lat, lon));\n}\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7773/"
] |
244,340
|
<p>I am getting a DC for a window handle of an object in another program using win32gui.GetDC which returns an int/long. I need to blit this DC into a memory DC in python. The only thing I can't figure out how to do is get a wxDC derived object from the int/long that win32gui returns. None of the wxDC objects allow me to pass an actual DC handle to them from what I can tell. This of course keeps me from doing my blit. Is there any way to do this?</p>
|
[
{
"answer_id": 1821168,
"author": "FogleBird",
"author_id": 90308,
"author_profile": "https://Stackoverflow.com/users/90308",
"pm_score": 2,
"selected": true,
"text": "window = wx.Frame(None, -1, '')\nwindow.AssociateHandle(hwnd)\ndc = wx.WindowDC(window)\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13036/"
] |
244,345
|
<p>I was watching Rob Connerys webcasts on the MVCStoreFront App, and I noticed he was unit testing even the most mundane things, things like:</p>
<pre><code>public Decimal DiscountPrice
{
get
{
return this.Price - this.Discount;
}
}
</code></pre>
<p>Would have a test like:</p>
<pre><code>[TestMethod]
public void Test_DiscountPrice
{
Product p = new Product();
p.Price = 100;
p.Discount = 20;
Assert.IsEqual(p.DiscountPrice,80);
}
</code></pre>
<p>While, I am all for unit testing, I sometimes wonder if this form of test first development is really beneficial, for example, in a real process, you have 3-4 layers above your code (Business Request, Requirements Document, Architecture Document), where the actual defined business rule (Discount Price is Price - Discount) could be misdefined.</p>
<p>If that's the situation, your unit test means nothing to you.</p>
<p>Additionally, your unit test is another point of failure:</p>
<pre><code>[TestMethod]
public void Test_DiscountPrice
{
Product p = new Product();
p.Price = 100;
p.Discount = 20;
Assert.IsEqual(p.DiscountPrice,90);
}
</code></pre>
<p>Now the test is flawed. Obviously in a simple test, it's no big deal, but say we were testing a complicated business rule. What do we gain here?</p>
<p>Fast forward two years into the application's life, when maintenance developers are maintaining it. Now the business changes its rule, and the test breaks again, some rookie developer then fixes the test incorrectly...we now have another point of failure.</p>
<p>All I see is more possible points of failure, with no real beneficial return, if the discount price is wrong, the test team will still find the issue, how did unit testing save any work?</p>
<p>What am I missing here? Please teach me to love TDD, as I'm having a hard time accepting it as useful so far. I want too, because I want to stay progressive, but it just doesn't make sense to me.</p>
<p>EDIT: A couple people keep mentioned that testing helps enforce the spec. It has been my experience that the spec has been wrong as well, more often than not, but maybe I'm doomed to work in an organization where the specs are written by people who shouldn't be writing specs.</p>
|
[
{
"answer_id": 249579,
"author": "philant",
"author_id": 18804,
"author_profile": "https://Stackoverflow.com/users/18804",
"pm_score": 3,
"selected": false,
"text": "Assert.IsEqual(p.DiscountPrice,90);\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] |
244,385
|
<p>I'm trying to run a shell command using the backtick operators, but the fact that the child process inherits php's open file descriptors is problematic. Is there a way to keep this from happening?</p>
<p>I'm running PHP 5.1.2</p>
|
[
{
"answer_id": 32634046,
"author": "Greg",
"author_id": 329062,
"author_profile": "https://Stackoverflow.com/users/329062",
"pm_score": 0,
"selected": false,
"text": "$cmd_to_run = escapeshellarg('/path/to/file --args');\n`echo $cmd_to_run | /bin/at now`;\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] |
244,390
|
<p>Right now, I have </p>
<pre><code>SELECT gp_id FROM gp.keywords
WHERE keyword_id = 15
AND (SELECT practice_link FROM gp.practices
WHERE practice_link IS NOT NULL
AND id = gp_id)
</code></pre>
<p>This does not provide a syntax error, however for values where it should return row(s), it just returns 0 rows.</p>
<p>What I'm trying to do is get the gp_id from gp.keywords where the the keywords table keyword_id column is a specific value and the practice_link is the practices table corresponds to the gp_id that I have, which is stored in the id column of that table.</p>
|
[
{
"answer_id": 244405,
"author": "SquareCog",
"author_id": 15962,
"author_profile": "https://Stackoverflow.com/users/15962",
"pm_score": 1,
"selected": false,
"text": "\nselect k.gp_id \nfrom gp.keywords as k,\n gp.practices as p\nwhere\nkeyword_id=15\nand practice_link is not null\nand p.id=k.gp_id\n"
},
{
"answer_id": 244406,
"author": "Guido",
"author_id": 12388,
"author_profile": "https://Stackoverflow.com/users/12388",
"pm_score": 0,
"selected": false,
"text": "SELECT k.gp_id\nFROM gp.keywords k, gp.practices p\nWHERE \n p.id = k.gp_id.AND\n k.keyword_id = 15 AND\n p.practice_link is not null\n"
},
{
"answer_id": 244407,
"author": "Elie",
"author_id": 23249,
"author_profile": "https://Stackoverflow.com/users/23249",
"pm_score": 0,
"selected": false,
"text": "SELECT g.gp_id, p.practice_link FROM gp.keywords g, gp.practices p \nWHERE\ng.keyword_id = 15 AND p.practice_link IS NOT NULL AND p.id = g.gp_id\n"
},
{
"answer_id": 244411,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 3,
"selected": true,
"text": "SELECT gp_id\nFROM gp.keywords\nWHERE keyword_id = 15\n AND (SELECT practice_link FROM gp.practices WHERE practice_link IS NOT NULL AND id = gp_id)\n SELECT kw.gp_id, p.practice_link\nFROM gp.keywords AS kw\nINNER JOIN gp.practices AS p\n ON p.id = kw.gp_id\nWHERE kw.keyword_id = 15\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] |
244,392
|
<p>Here's the quick and skinny of my issue:</p>
<pre>$("a").toggle(function() { /*function A*/ }, function() { /*function B*/ });</pre>
<p>Inside <code>function A</code> a form is displayed. If the user successfully completes the form, the form is hidden again (returning to it's original state).</p>
<p>Inside <code>function B</code> the same form is hidden.</p>
<p>The theory behind this is that the user can choose to display the form and fill it out, or they can click again and have the form go back into hiding. </p>
<p>Now my question is this: currently, if the user fills out the form successfully--and it goes into hiding--the user would have to click on the link <strong><em>twice</em></strong> before returning to the toggle state that displays the form.</p>
<p>Is there anyway to programmatically reset the toggle switch to its initial state?</p>
|
[
{
"answer_id": 244468,
"author": "foxy",
"author_id": 30119,
"author_profile": "https://Stackoverflow.com/users/30119",
"pm_score": 5,
"selected": true,
"text": ".toggle() .toggle() .toggle(even, odd) $(\"a\").click(function() {\n $(\"#theForm\").toggle();\n});\n"
},
{
"answer_id": 244599,
"author": "neezer",
"author_id": 32154,
"author_profile": "https://Stackoverflow.com/users/32154",
"pm_score": 2,
"selected": false,
"text": "toggle(even,odd); function A function B toggle(); toggle();"
},
{
"answer_id": 1750472,
"author": "Michal Zuber",
"author_id": 213102,
"author_profile": "https://Stackoverflow.com/users/213102",
"pm_score": 3,
"selected": false,
"text": "$(document).ready(function() {\n $('#listing_position').click(function() {\n\n var div_form = $('#listing_position_input');\n if (div_form.hasClass('hide')) {\n div_form.removeClass('hide');\n } else {\n div_form.addClass('hide');\n }\n }); \n});\n"
},
{
"answer_id": 4918065,
"author": "xiatica",
"author_id": 564811,
"author_profile": "https://Stackoverflow.com/users/564811",
"pm_score": 2,
"selected": false,
"text": "$(\"#clickie\").click(function(){\n if ( $(\"#mydiv\").css(\"display\") == \"none\" ){\n $(\"#mydiv\").show();\n } else {\n $(\"#mydiv\").hide();\n}\n"
},
{
"answer_id": 8540165,
"author": "Nicky Vandevoorde",
"author_id": 698371,
"author_profile": "https://Stackoverflow.com/users/698371",
"pm_score": 5,
"selected": false,
"text": ".is(\":hidden\") $(\"#div_clicked\").click(function() {\n if ($(\"#toggle_div\").is(\":hidden\")) {\n // do this\n } else {\n // do that\n}\n}); # add missing closing\n"
},
{
"answer_id": 27014328,
"author": "Vishal Patel",
"author_id": 2578899,
"author_profile": "https://Stackoverflow.com/users/2578899",
"pm_score": -1,
"selected": false,
"text": "$(\"#div_clicked\").click(function() {\n if ($(\"#toggle_div\").is(\":visible\")) {\n // do this\n } else {\n // do that\n}\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32154/"
] |
244,408
|
<p>I've got two collections (generic Lists), let's call them ListA and ListB.</p>
<p>In ListA I've got a few items of type A. In ListB I've got some items of type B that have the SAME ID (but not same type) as the items in ListA, plus many more. I want to remove all the items from ListB that have the same ID as the ones in ListA. What's the best way of doing this? Is Linq to objects a nice fit? What algorithm would you use?</p>
<p>Example</p>
<p>ListA: ItemWithID1, ItemWithID2¨</p>
<p>ListB: ItemWithID1, ItemWithID2, ItemWithID3, ItemWithID4</p>
<p>EDIT: I forgot to mention in my original question that ListA and ListB doesn't contain the same types. So the only way to compare them is through the .Id property. Which invalidates the answers I've gotten so far.</p>
|
[
{
"answer_id": 244426,
"author": "Elie",
"author_id": 23249,
"author_profile": "https://Stackoverflow.com/users/23249",
"pm_score": 0,
"selected": false,
"text": "for (item i: LISTA) {\n removeItem(i, LISTB);\n}\n\n\nmethod removeItem(Item, List) {\n for (Item i: List) {\n if (Item == i)\n List.removeItem(i);\n }\n}\n"
},
{
"answer_id": 244429,
"author": "Matthew Brubaker",
"author_id": 21311,
"author_profile": "https://Stackoverflow.com/users/21311",
"pm_score": 0,
"selected": false,
"text": "foreach Object o in ListA\n If ListB.contains(o)\n ListB.remove(o)\n"
},
{
"answer_id": 244437,
"author": "Todd White",
"author_id": 30833,
"author_profile": "https://Stackoverflow.com/users/30833",
"pm_score": 4,
"selected": false,
"text": "listB.RemoveAll(listA.Contains);\n\n\nforeach (string str in listA.Intersect(listB))\n listB.Remove(str);\n"
},
{
"answer_id": 245813,
"author": "Marcus Griep",
"author_id": 28645,
"author_profile": "https://Stackoverflow.com/users/28645",
"pm_score": 0,
"selected": false,
"text": "RemoveAll RetainAll RemoveAll ListB.RetainAll(ListA) { Item1, Item2 } ListB.RemoveAll(ListA) { Item3, Item4 }"
},
{
"answer_id": 262112,
"author": "Peter Evjan",
"author_id": 3397,
"author_profile": "https://Stackoverflow.com/users/3397",
"pm_score": 3,
"selected": true,
"text": "foreach(TypeA objectA in listA){\n listB.RemoveAll(objectB => objectB.Id == objectA.Id);\n}\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3397/"
] |
244,431
|
<p>I have two assemblies with the same name in the Global Assembly cache, but with different version numbers. How do I tell my program which version to reference?</p>
<p>For the record, this is a VB.Net page in an ASP.Net web site.</p>
|
[
{
"answer_id": 244469,
"author": "Ady",
"author_id": 31395,
"author_profile": "https://Stackoverflow.com/users/31395",
"pm_score": 2,
"selected": false,
"text": "<add assembly=\"Foo.Bar, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A\"/>\n <add assembly=\"Foo.Bar, Version=2.5.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A\"/>\n"
},
{
"answer_id": 244473,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 4,
"selected": true,
"text": "<system.web>\n\n <compilation>\n <assemblies>\n <add assembly=\"CrystalDecisions.Web, Version=11.5.3700.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304\"/>\n <add assembly=\"CrystalDecisions.Shared, Version=11.5.3700.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304\"/>\n <add assembly=\"CrystalDecisions.ReportSource, Version=11.5.3700.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304\"/>\n <add assembly=\"CrystalDecisions.Enterprise.Framework, Version=11.5.3300.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304\"/>\n </assemblies>\n </compilation>\n\n</system.web>\n"
},
{
"answer_id": 244476,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 3,
"selected": false,
"text": "<configuration>\n <system.web>\n <compilation>\n <assemblies>\n <add assembly=\"System.Data, Version=1.0.2411.0, \n Culture=neutral, \n PublicKeyToken=b77a5c561934e089\"/>\n </assemblies>\n </compilation>\n </system.web>\n</configuration>\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19074/"
] |
244,438
|
<p>Imagine I have these python lists:</p>
<pre><code>keys = ['name', 'age']
values = ['Monty', 42, 'Matt', 28, 'Frank', 33]
</code></pre>
<p>Is there a direct or at least a simple way to produce the following list of dictionaries ?</p>
<pre><code>[
{'name': 'Monty', 'age': 42},
{'name': 'Matt', 'age': 28},
{'name': 'Frank', 'age': 33}
]
</code></pre>
|
[
{
"answer_id": 244455,
"author": "Cheery",
"author_id": 21711,
"author_profile": "https://Stackoverflow.com/users/21711",
"pm_score": 2,
"selected": false,
"text": "def fields_from_list(keys, values):\n iterator = iter(values)\n while True:\n yield dict((key, iterator.next()) for key in keys)\n\nlist(fields_from_list(keys, values)) # to produce a list.\n"
},
{
"answer_id": 244461,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "zip $ python\n>>> keys = ['name', 'age']\n>>> values = ['Monty', 42, 'Matt', 28, 'Frank', 33]\n>>> dict(zip(keys, values))\n{'age': 42, 'name': 'Monty'}\n from itertoos import cycle\n\nkeys = ['name', 'age']\nvalues = ['Monty', 42, 'Matt', 28, 'Frank', 33]\n\nx = zip(cycle(keys), values)\nmap(lambda a: dict(a), zip(x[::2], x[1::2]))\n"
},
{
"answer_id": 244471,
"author": "David Locke",
"author_id": 1447,
"author_profile": "https://Stackoverflow.com/users/1447",
"pm_score": 1,
"selected": false,
"text": "def pack(keys, values):\n \"\"\"This function destructively creates a list of dictionaries from the input lists.\"\"\"\n retval = []\n while values:\n d = {}\n for x in keys:\n d[x] = values.pop(0)\n retval.append(d)\n return retval\n"
},
{
"answer_id": 244515,
"author": "Cheery",
"author_id": 21711,
"author_profile": "https://Stackoverflow.com/users/21711",
"pm_score": 1,
"selected": false,
"text": "def split_seq(seq, count):\n i = iter(seq)\n while True:\n yield [i.next() for _ in xrange(count)]\n\n>>> [dict(zip(keys, rec)) for rec in split_seq(values, len(keys))]\n[{'age': 42, 'name': 'Monty'},\n {'age': 28, 'name': 'Matt'},\n {'age': 33, 'name': 'Frank'}]\n"
},
{
"answer_id": 244551,
"author": "Toni Ruža",
"author_id": 6267,
"author_profile": "https://Stackoverflow.com/users/6267",
"pm_score": 5,
"selected": true,
"text": "def mapper(keys, values):\n n = len(keys)\n return [dict(zip(keys, values[i:i + n]))\n for i in range(0, len(values), n)]\n"
},
{
"answer_id": 244618,
"author": "ddaa",
"author_id": 11549,
"author_profile": "https://Stackoverflow.com/users/11549",
"pm_score": 2,
"selected": false,
"text": "keys = ['name', 'age']\nvalues = ['Monty', 42, 'Matt', 28, 'Frank', 33]\niter_values = iter(values)\n[dict(zip(keys, iter_values)) for _ in range(len(values) // len(keys))]\n keys itertools .cycle() keys def iter_cut(seq, size):\n for i in range(len(seq) / size):\n yield seq[i*size:(i+1)*size]\n\nkeys = ['name', 'age']\nvalues = ['Monty', 42, 'Matt', 28, 'Frank', 33]\n[dict(zip(keys, some_values)) for some_values in iter_cut(values, len(keys))]\n"
},
{
"answer_id": 244664,
"author": "jblocksom",
"author_id": 20626,
"author_profile": "https://Stackoverflow.com/users/20626",
"pm_score": 2,
"selected": false,
"text": "[dict(zip(keys, a)) for a in zip(values[::2], values[1::2])]\n"
},
{
"answer_id": 247862,
"author": "Tim Ottinger",
"author_id": 15929,
"author_profile": "https://Stackoverflow.com/users/15929",
"pm_score": 0,
"selected": false,
"text": "[dict(zip(keys,values[n:n+len(keys)])) for n in xrange(0,len(values),len(keys)) ]\n def dictizer(keys, values):\n steps = xrange(0,len(values),len(keys))\n bites = ( values[n:n+len(keys)] for n in steps)\n return ( dict(zip(keys,bite)) for bite in bites )\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12388/"
] |
244,445
|
<p>If, like me, you shiver at the site of a While (True) loop, then you too must have thought long and hard about the best way to refactor it away. I've seen several different implementations, none really better than any other, such as the timer & delegate combination.</p>
<p>So what's the best way you've come up with or seen to refactor the dreaded While (True) loop?</p>
<p><b>Edit</b>: As some comments mentioned, my intent was for this question to be an "infinite loop" refactoring, such as running a Windows style service where the only stop conditions would be OnStop or a fatal exception.</p>
|
[
{
"answer_id": 244459,
"author": "Jon B",
"author_id": 27414,
"author_profile": "https://Stackoverflow.com/users/27414",
"pm_score": 4,
"selected": false,
"text": "volatile bool m_shutdown = false;\nvoid Run()\n{\n while (!m_shutdown)\n { ... }\n}\n"
},
{
"answer_id": 244483,
"author": "Jim Nelson",
"author_id": 32168,
"author_profile": "https://Stackoverflow.com/users/32168",
"pm_score": 4,
"selected": false,
"text": "for(;;)"
},
{
"answer_id": 244497,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 3,
"selected": false,
"text": "someMode= True\nwhile someMode:\n try:\n ... do stuff ...\n except SomeException, e:\n log.exception( e )\n # will keep running\n except OtherException, e:\n log.info( \"stopping now\" )\n someMode= False\n someMode False"
},
{
"answer_id": 244602,
"author": "Andrew Coleson",
"author_id": 2072,
"author_profile": "https://Stackoverflow.com/users/2072",
"pm_score": 3,
"selected": false,
"text": "#define ever 1\nfor (;ever;)\n"
},
{
"answer_id": 244644,
"author": "fizzer",
"author_id": 18167,
"author_profile": "https://Stackoverflow.com/users/18167",
"pm_score": 6,
"selected": false,
"text": "start:\n\n // code goes here\n\ngoto start;\n"
},
{
"answer_id": 37287071,
"author": "12431234123412341234123",
"author_id": 6082851,
"author_profile": "https://Stackoverflow.com/users/6082851",
"pm_score": -1,
"selected": false,
"text": "void whiletrue_sim(void)\n {\n //some code\n whiletrue_sim();\n }\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27498/"
] |
244,452
|
<h1>My situation</h1>
<ul>
<li>Input: a set of rectangles </li>
<li>each rect is comprised of 4 doubles like this: (x0,y0,x1,y1)</li>
<li>they are not "rotated" at any angle, all they are "normal" rectangles that go "up/down" and "left/right" with respect to the screen</li>
<li>they are randomly placed - they may be touching at the edges, overlapping , or not have any contact</li>
<li>I will have several hundred rectangles</li>
<li>this is implemented in C#</li>
</ul>
<h1>I need to find</h1>
<ul>
<li>The area that is formed by their overlap - all the area in the canvas that more than one rectangle "covers" (for example with two rectangles, it would be the intersection)</li>
<li>I don't need the geometry of the overlap - just the area (example: 4 sq inches)</li>
<li>Overlaps shouldn't be counted multiple times - so for example imagine 3 rects that have the same size and position - they are right on top of each other - this area should be counted once (not three times)</li>
</ul>
<h1>Example</h1>
<ul>
<li>The image below contains thre rectangles: A,B,C</li>
<li>A and B overlap (as indicated by dashes)</li>
<li>B and C overlap (as indicated by dashes)</li>
<li>What I am looking for is the area where the dashes are shown</li>
</ul>
<p>-</p>
<pre><code>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAA--------------BBB
AAAAAAAAAAAAAAAA--------------BBB
AAAAAAAAAAAAAAAA--------------BBB
AAAAAAAAAAAAAAAA--------------BBB
BBBBBBBBBBBBBBBBB
BBBBBBBBBBBBBBBBB
BBBBBBBBBBBBBBBBB
BBBBBB-----------CCCCCCCC
BBBBBB-----------CCCCCCCC
BBBBBB-----------CCCCCCCC
CCCCCCCCCCCCCCCCCCC
CCCCCCCCCCCCCCCCCCC
CCCCCCCCCCCCCCCCCCC
CCCCCCCCCCCCCCCCCCC
</code></pre>
|
[
{
"answer_id": 244458,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 0,
"selected": false,
"text": "int LineOverlap(int line1a, line1b, line2a, line2b) \n{\n // assume line1a <= line1b and line2a <= line2b\n if (line1a < line2a) \n {\n if (line1b > line2b)\n return line2b-line2a;\n else if (line1b > line2a)\n return line1b-line2a;\n else \n return 0;\n }\n else if (line2a < line1b)\n return line2b-line1a;\n else \n return 0;\n}\n\n\nint RectangleOverlap(Rect rectA, rectB) \n{\n return LineOverlap(rectA.x1, rectA.x2, rectB.x1, rectB.x2) *\n LineOverlap(rectA.y1, rectA.y2, rectB.y1, rectB.y2);\n}\n"
},
{
"answer_id": 244686,
"author": "LeppyR64",
"author_id": 16592,
"author_profile": "https://Stackoverflow.com/users/16592",
"pm_score": 3,
"selected": false,
"text": "public class Rect\n{\n public int t, b, l, r;\n\n public Rect(int _l, int _b, int _r, int _t)\n {\n t = _t;\n b = _b;\n l = _l;\n r = _r;\n } \n\n public bool Intersects(Rect R)\n {\n return !(l > R.r || R.l > r || R.b > t || b > R.t);\n }\n\n public Rect Intersection(Rect R)\n {\n if(!this.Intersects(R))\n return new Rect(0,0,0,0);\n int [] horiz = {l, r, R.l, R.r};\n Array.Sort(horiz);\n int [] vert = {b, t, R.b, R.t};\n Array.Sort(vert);\n\n return new Rect(horiz[1], vert[1], horiz[2], vert[2]);\n } \n\n public int Area()\n {\n return (t - b)*(r-l);\n }\n\n public override string ToString()\n {\n return l + \" \" + b + \" \" + r + \" \" + t;\n }\n}\n"
},
{
"answer_id": 245078,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 3,
"selected": false,
"text": "aaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbb\naaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbb\naaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbb\naaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbb\naaaaaaaadddddddddddddddddddddddddddddbbbbbb\naaaaaaaadddddddddddddddddddddddddddddbbbbbb\n ddddddddddddddddddddddddddddd\n ddddddddddddddddddddddddddddd\n ddddddddddddddeeeeeeeeeeeeeeeeee\n ddddddddddddddeeeeeeeeeeeeeeeeee\n ddddddddddddddeeeeeeeeeeeeeeeeee\nccccccccddddddddddddddeeeeeeeeeeeeeeeeee\nccccccccddddddddddddddeeeeeeeeeeeeeeeeee\ncccccccccccc eeeeeeeeeeeeeeeeee\ncccccccccccc eeeeeeeeeeeeeeeeee\ncccccccccccc\ncccccccccccc\n v v v v v v v v v \n|aaaaaaa|aa|aaaa | bbbbbbbbbb|bb|bbb\n|aaaaaaa|aa|aaaa | bbbbbbbbbb|bb|bbb\n|aaaaaaa|aa|aaaa | bbbbbbbbbb|bb|bbb\n|aaaaaaa|aa|aaaa | bbbbbbbbbb|bb|bbb\n|aaaaaaaddd|dddddddddd|ddddddddddddddbb|bbb\n|aaaaaaaddd|dddddddddd|ddddddddddddddbb|bbb\n| ddd|dddddddddd|dddddddddddddd |\n| ddd|dddddddddd|dddddddddddddd |\n| ddd|ddddddddddeeeeeeeeeeeeeeeeee\n| ddd|ddddddddddeeeeeeeeeeeeeeeeee\n| ddd|ddddddddddeeeeeeeeeeeeeeeeee\nccccccccddd|ddddddddddeeeeeeeeeeeeeeeeee\nccccccccddd|ddddddddddeeeeeeeeeeeeeeeeee\ncccccccccccc eeeeeeeeeeeeeeeeee\ncccccccccccc eeeeeeeeeeeeeeeeee\ncccccccccccc\ncccccccccccc\n 0: +a, +c\n1: +d\n2: -c\n3: -a\n4: +e\n5: +b\n6: -d\n7: -e\n8: -b\n 0-1: a, c\n1-2: a, d, c\n2-3: a, d\n3-4: d\n4-5: d, e\n5-6: b, d, e\n6-7: b, e\n7-8: b\n 0-1: none\n1-2: a/d, d/c\n2-3: a/d\n3-4: none\n4-5: d/e\n5-6: b/d, d/e\n6-7: none\n7-8: none\n 0. empty set, zero sum\n1. enter a, add a to set (1 rectangle in set)\n2. enter d, add d to set (>1 rectangles in set = overlap, store this y-coordinate)\n3. leave a, remove a from set (now back from >1 rectangles in set, add to sum: y - stored_y\n4. enter c, add c to set (>1 rectangles in set = overlap, store this y-coordinate)\n5. leave d, remove d from set (now back from >1 rectangles in set, add to sum: y - stored_y)\n6. multiply sum with width of strip to get overlapping areas\n"
},
{
"answer_id": 2627027,
"author": "extraeee",
"author_id": 183487,
"author_profile": "https://Stackoverflow.com/users/183487",
"pm_score": 2,
"selected": false,
"text": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\n\nclass Rectangle {\npublic:\n int x[2], y[2];\n\n Rectangle(int x1, int y1, int x2, int y2) {\n x[0] = x1;\n y[0] = y1;\n x[1] = x2;\n y[1] = y2; \n };\n void print(void) {\n cout << \"Rect: \" << x[0] << \" \" << y[0] << \" \" << x[1] << \" \" << y[1] << \" \" <<endl;\n };\n};\n\n// return the iterator of rec in list\nvector<Rectangle *>::iterator bin_search(vector<Rectangle *> &list, int begin, int end, Rectangle *rec) {\n cout << begin << \" \" <<end <<endl;\n int mid = (begin+end)/2;\n if (list[mid]->y[0] == rec->y[0]) {\n if (list[mid]->y[1] == rec->y[1])\n return list.begin() + mid;\n else if (list[mid]->y[1] < rec->y[1]) {\n if (mid == end)\n return list.begin() + mid+1;\n return bin_search(list,mid+1,mid,rec);\n }\n else {\n if (mid == begin)\n return list.begin()+mid;\n return bin_search(list,begin,mid-1,rec);\n }\n }\n else if (list[mid]->y[0] < rec->y[0]) {\n if (mid == end) {\n return list.begin() + mid+1;\n }\n return bin_search(list, mid+1, end, rec);\n }\n else {\n if (mid == begin) {\n return list.begin() + mid;\n }\n return bin_search(list, begin, mid-1, rec);\n }\n}\n\n// add rect to rects\nvoid add_rec(Rectangle *rect, vector<Rectangle *> &rects) {\n if (rects.size() == 0) {\n rects.push_back(rect);\n }\n else {\n vector<Rectangle *>::iterator it = bin_search(rects, 0, rects.size()-1, rect);\n rects.insert(it, rect);\n }\n}\n\n// remove rec from rets\nvoid remove_rec(Rectangle *rect, vector<Rectangle *> &rects) {\n vector<Rectangle *>::iterator it = bin_search(rects, 0, rects.size()-1, rect);\n rects.erase(it);\n}\n\n// calculate the total vertical length covered by rectangles in the active set\nint vert_dist(vector<Rectangle *> as) {\n int n = as.size();\n\n int totallength = 0;\n int start, end;\n\n int i = 0;\n while (i < n) {\n start = as[i]->y[0];\n end = as[i]->y[1];\n while (i < n && as[i]->y[0] <= end) {\n if (as[i]->y[1] > end) {\n end = as[i]->y[1];\n }\n i++;\n }\n totallength += end-start;\n }\n return totallength;\n}\n\nbool mycomp1(Rectangle* a, Rectangle* b) {\n return (a->x[0] < b->x[0]);\n}\n\nbool mycomp2(Rectangle* a, Rectangle* b) {\n return (a->x[1] < b->x[1]);\n}\n\nint findarea(vector<Rectangle *> rects) {\n vector<Rectangle *> start = rects;\n vector<Rectangle *> end = rects;\n sort(start.begin(), start.end(), mycomp1);\n sort(end.begin(), end.end(), mycomp2);\n\n // active set\n vector<Rectangle *> as;\n\n int n = rects.size();\n\n int totalarea = 0;\n int current = start[0]->x[0];\n int next;\n int i = 0, j = 0;\n // big loop\n while (j < n) {\n cout << \"loop---------------\"<<endl;\n // add all recs that start at current\n while (i < n && start[i]->x[0] == current) {\n cout << \"add\" <<endl;\n // add start[i] to AS\n add_rec(start[i], as);\n cout << \"after\" <<endl;\n i++;\n }\n // remove all recs that end at current\n while (j < n && end[j]->x[1] == current) {\n cout << \"remove\" <<endl;\n // remove end[j] from AS\n remove_rec(end[j], as);\n cout << \"after\" <<endl;\n j++;\n }\n\n // find next event x\n if (i < n && j < n) {\n if (start[i]->x[0] <= end[j]->x[1]) {\n next = start[i]->x[0];\n }\n else {\n next = end[j]->x[1];\n }\n }\n else if (j < n) {\n next = end[j]->x[1];\n }\n\n // distance to next event\n int horiz = next - current;\n cout << \"horiz: \" << horiz <<endl;\n\n // figure out vertical dist\n int vert = vert_dist(as);\n cout << \"vert: \" << vert <<endl;\n\n totalarea += vert * horiz;\n\n current = next;\n }\n return totalarea;\n}\n\nint main() {\n vector<Rectangle *> rects;\n rects.push_back(new Rectangle(0,0,1,1));\n\n rects.push_back(new Rectangle(1,0,2,3));\n\n rects.push_back(new Rectangle(0,0,3,3));\n\n rects.push_back(new Rectangle(1,0,5,1));\n\n cout << findarea(rects) <<endl;\n}\n"
},
{
"answer_id": 20800862,
"author": "Torsten Fehre",
"author_id": 3139440,
"author_profile": "https://Stackoverflow.com/users/3139440",
"pm_score": 0,
"selected": false,
"text": "GridLocation gl = new GridLocation(curX, curY);\nif(usedLocations.contains(gl) && usedLocations2.add(gl)) {\n ret += width*height;\n} else {\n usedLocations.add(gl);\n}\n"
},
{
"answer_id": 25355331,
"author": "Rose Perrone",
"author_id": 365298,
"author_profile": "https://Stackoverflow.com/users/365298",
"pm_score": 4,
"selected": false,
"text": "import numpy as np\n\nA = np.zeros((100, 100))\nB = np.zeros((100, 100))\n\nA[rect1.top : rect1.bottom, rect1.left : rect1.right] = 1\nB[rect2.top : rect2.bottom, rect2.left : rect2.right] = 1\n\narea_of_union = np.sum((A + B) > 0)\narea_of_intersect = np.sum((A + B) > 1)\n sum(A+B > 0) sum(A+B > 1)"
},
{
"answer_id": 34624421,
"author": "tick_tack_techie",
"author_id": 2529478,
"author_profile": "https://Stackoverflow.com/users/2529478",
"pm_score": 2,
"selected": false,
"text": "import java.io.*;\nimport java.util.*;\n\nclass Solution {\n\nstatic class Rectangle{\n int x;\n int y;\n int dx;\n int dy;\n\n Rectangle(int x, int y, int dx, int dy){\n this.x = x;\n this.y = y;\n this.dx = dx;\n this.dy = dy;\n }\n\n Range getBottomLeft(){\n return new Range(x, y);\n }\n\n Range getTopRight(){\n return new Range(x + dx, y + dy);\n }\n\n @Override\n public int hashCode(){\n return (x+y+dx+dy)/4;\n }\n\n @Override\n public boolean equals(Object other){\n Rectangle o = (Rectangle) other;\n return o.x == this.x && o.y == this.y && o.dx == this.dx && o.dy == this.dy;\n }\n\n @Override\n public String toString(){\n return String.format(\"X = %d, Y = %d, dx : %d, dy : %d\", x, y, dx, dy);\n }\n } \n\n static class RW{\n Rectangle r;\n boolean start;\n\n RW (Rectangle r, boolean start){\n this.r = r;\n this.start = start;\n }\n\n @Override\n public int hashCode(){\n return r.hashCode() + (start ? 1 : 0);\n }\n\n @Override\n public boolean equals(Object other){\n RW o = (RW)other;\n return o.start == this.start && o.r.equals(this.r);\n }\n\n @Override\n public String toString(){\n return \"Rectangle : \" + r.toString() + \", start = \" + this.start;\n }\n }\n\n static class Range{\n int l;\n int u; \n\n public Range(int l, int u){\n this.l = l;\n this.u = u;\n }\n\n @Override\n public int hashCode(){\n return (l+u)/2;\n }\n\n @Override\n public boolean equals(Object other){\n Range o = (Range) other;\n return o.l == this.l && o.u == this.u;\n }\n\n @Override\n public String toString(){\n return String.format(\"L = %d, U = %d\", l, u);\n }\n }\n\n static class XComp implements Comparator<RW>{\n @Override\n public int compare(RW rw1, RW rw2){\n //TODO : revisit these values.\n Integer x1 = -1;\n Integer x2 = -1;\n\n if(rw1.start){\n x1 = rw1.r.x;\n }else{\n x1 = rw1.r.x + rw1.r.dx;\n } \n\n if(rw2.start){\n x2 = rw2.r.x;\n }else{\n x2 = rw2.r.x + rw2.r.dx;\n }\n\n return x1.compareTo(x2);\n }\n }\n\n static class YComp implements Comparator<RW>{\n @Override\n public int compare(RW rw1, RW rw2){\n //TODO : revisit these values.\n Integer y1 = -1;\n Integer y2 = -1;\n\n if(rw1.start){\n y1 = rw1.r.y;\n }else{\n y1 = rw1.r.y + rw1.r.dy;\n } \n\n if(rw2.start){\n y2 = rw2.r.y;\n }else{\n y2 = rw2.r.y + rw2.r.dy;\n }\n\n return y1.compareTo(y2);\n }\n }\n\n public static void main(String []args){\n Rectangle [] rects = new Rectangle[4];\n\n rects[0] = new Rectangle(10, 10, 10, 10);\n rects[1] = new Rectangle(15, 10, 10, 10);\n rects[2] = new Rectangle(20, 10, 10, 10);\n rects[3] = new Rectangle(25, 10, 10, 10);\n\n int totalArea = getArea(rects, false);\n System.out.println(\"Total Area : \" + totalArea);\n\n int overlapArea = getArea(rects, true); \n System.out.println(\"Overlap Area : \" + overlapArea);\n }\n\n\n static int getArea(Rectangle []rects, boolean overlapOrTotal){\n printArr(rects);\n\n // step 1: create two wrappers for every rectangle\n RW []rws = getWrappers(rects); \n\n printArr(rws); \n\n // steps 2 : sort rectangles by their x-coordinates\n Arrays.sort(rws, new XComp()); \n\n printArr(rws); \n\n // step 3 : group the rectangles in every range.\n Map<Range, List<Rectangle>> rangeGroups = groupRects(rws, true);\n\n for(Range xrange : rangeGroups.keySet()){\n List<Rectangle> xRangeRects = rangeGroups.get(xrange);\n System.out.println(\"Range : \" + xrange);\n System.out.println(\"Rectangles : \");\n for(Rectangle rectx : xRangeRects){\n System.out.println(\"\\t\" + rectx); \n }\n } \n\n // step 4 : iterate through each of the pairs and their rectangles\n\n int sum = 0;\n for(Range range : rangeGroups.keySet()){\n List<Rectangle> rangeRects = rangeGroups.get(range);\n sum += getOverlapOrTotalArea(rangeRects, range, overlapOrTotal);\n }\n return sum; \n } \n\n static Map<Range, List<Rectangle>> groupRects(RW []rws, boolean isX){\n //group the rws with either x or y coordinates.\n\n Map<Range, List<Rectangle>> rangeGroups = new HashMap<Range, List<Rectangle>>();\n\n List<Rectangle> rangeRects = new ArrayList<Rectangle>(); \n\n int i=0;\n int prev = Integer.MAX_VALUE;\n\n while(i < rws.length){\n int curr = isX ? (rws[i].start ? rws[i].r.x : rws[i].r.x + rws[i].r.dx): (rws[i].start ? rws[i].r.y : rws[i].r.y + rws[i].r.dy);\n\n if(prev < curr){\n Range nRange = new Range(prev, curr);\n rangeGroups.put(nRange, rangeRects);\n rangeRects = new ArrayList<Rectangle>(rangeRects);\n }\n prev = curr;\n\n if(rws[i].start){\n rangeRects.add(rws[i].r);\n }else{\n rangeRects.remove(rws[i].r);\n }\n\n i++;\n }\n return rangeGroups;\n }\n\n static int getOverlapOrTotalArea(List<Rectangle> rangeRects, Range range, boolean isOverlap){\n //create horizontal sweep lines similar to vertical ones created above\n\n // Step 1 : create wrappers again\n RW []rws = getWrappers(rangeRects);\n\n // steps 2 : sort rectangles by their y-coordinates\n Arrays.sort(rws, new YComp());\n\n // step 3 : group the rectangles in every range.\n Map<Range, List<Rectangle>> yRangeGroups = groupRects(rws, false);\n\n //step 4 : for every range if there are more than one rectangles then computer their area only once.\n\n int sum = 0;\n for(Range yRange : yRangeGroups.keySet()){\n List<Rectangle> yRangeRects = yRangeGroups.get(yRange);\n\n if(isOverlap){\n if(yRangeRects.size() > 1){\n sum += getArea(range, yRange);\n }\n }else{\n if(yRangeRects.size() > 0){\n sum += getArea(range, yRange);\n }\n }\n } \n return sum;\n } \n\n static int getArea(Range r1, Range r2){\n return (r2.u-r2.l)*(r1.u-r1.l); \n }\n\n static RW[] getWrappers(Rectangle []rects){\n RW[] wrappers = new RW[rects.length * 2];\n\n for(int i=0,j=0;i<rects.length;i++, j+=2){\n wrappers[j] = new RW(rects[i], true); \n wrappers[j+1] = new RW(rects[i], false); \n }\n return wrappers;\n }\n\n static RW[] getWrappers(List<Rectangle> rects){\n RW[] wrappers = new RW[rects.size() * 2];\n\n for(int i=0,j=0;i<rects.size();i++, j+=2){\n wrappers[j] = new RW(rects.get(i), true); \n wrappers[j+1] = new RW(rects.get(i), false); \n }\n return wrappers;\n }\n\n static void printArr(Object []a){\n for(int i=0; i < a.length;i++){\n System.out.println(a[i]);\n }\n System.out.println();\n } \n"
},
{
"answer_id": 39825950,
"author": "user3048546",
"author_id": 3048546,
"author_profile": "https://Stackoverflow.com/users/3048546",
"pm_score": 0,
"selected": false,
"text": " #include <iostream>\nusing namespace std;\n\nint rectoverlap (int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2)\n{\n int width, heigh, area;\n\n if (ax2<bx1 || ay2<by1 || ax1>bx2 || ay1>by2) {\n cout << \"Rectangles are not overlapped\" << endl;\n return 0;\n }\n if (ax2>=bx2 && bx1>=ax1){\n width=bx2-bx1;\n heigh=by2-by1;\n } else if (bx2>=ax2 && ax1>=bx1) {\n width=ax2-ax1;\n heigh=ay2-ay1;\n } else {\n if (ax2>bx2){\n width=bx2-ax1;\n } else {\n width=ax2-bx1;\n }\n if (ay2>by2){\n heigh=by2-ay1;\n } else {\n heigh=ay2-by1;\n }\n }\n area= heigh*width;\n return (area);\n}\n\nint main()\n{\n int ax1,ay1,ax2,ay2,bx1,by1,bx2,by2;\n cout << \"Inter the x value for bottom left for rectangle A\" << endl;\n cin >> ax1;\n cout << \"Inter the y value for bottom left for rectangle A\" << endl;\n cin >> ay1;\n cout << \"Inter the x value for top right for rectangle A\" << endl;\n cin >> ax2;\n cout << \"Inter the y value for top right for rectangle A\" << endl;\n cin >> ay2;\n cout << \"Inter the x value for bottom left for rectangle B\" << endl;\n cin >> bx1;\n cout << \"Inter the y value for bottom left for rectangle B\" << endl;\n cin >> by1;\n cout << \"Inter the x value for top right for rectangle B\" << endl;\n cin >> bx2;\n cout << \"Inter the y value for top right for rectangle B\" << endl;\n cin >> by2;\n cout << \"The overlapped area is \" << rectoverlap (ax1, ay1, ax2, ay2, bx1, by1, bx2, by2) << endl;\n}\n"
},
{
"answer_id": 46772288,
"author": "ephraim",
"author_id": 3225391,
"author_profile": "https://Stackoverflow.com/users/3225391",
"pm_score": 1,
"selected": false,
"text": "var totArea = rects.Sum(x => x.Width * x.Height);\n var overlappingArea =totArea-GetArea(rects)\n #region rectangle overlapping\n /// <summary>\n /// see algorithm for detecting overlapping areas here: https://stackoverflow.com/a/245245/3225391\n /// or easier here:\n /// http://codercareer.blogspot.co.il/2011/12/no-27-area-of-rectangles.html\n /// </summary>\n /// <param name=\"dim\"></param>\n /// <returns></returns>\n public static float GetArea(RectangleF[] rects)\n {\n List<float> xs = new List<float>();\n foreach (var item in rects)\n {\n xs.Add(item.X);\n xs.Add(item.Right);\n }\n xs = xs.OrderBy(x => x).Cast<float>().ToList();\n rects = rects.OrderBy(rec => rec.X).Cast<RectangleF>().ToArray();\n float area = 0f;\n for (int i = 0; i < xs.Count - 1; i++)\n {\n if (xs[i] == xs[i + 1])//not duplicate\n continue;\n int j = 0;\n while (rects[j].Right < xs[i])\n j++;\n List<Range> rangesOfY = new List<Range>();\n var rangeX = new Range(xs[i], xs[i + 1]);\n GetRangesOfY(rects, j, rangeX, out rangesOfY);\n area += GetRectArea(rangeX, rangesOfY);\n }\n return area;\n }\n\n private static void GetRangesOfY(RectangleF[] rects, int rectIdx, Range rangeX, out List<Range> rangesOfY)\n {\n rangesOfY = new List<Range>();\n for (int j = rectIdx; j < rects.Length; j++)\n {\n if (rangeX.less < rects[j].Right && rangeX.greater > rects[j].Left)\n {\n rangesOfY = Range.AddRange(rangesOfY, new Range(rects[j].Top, rects[j].Bottom));\n#if DEBUG\n Range rectXRange = new Range(rects[j].Left, rects[j].Right);\n#endif\n }\n }\n }\n\n static float GetRectArea(Range rangeX, List<Range> rangesOfY)\n {\n float width = rangeX.greater - rangeX.less,\n area = 0;\n\n foreach (var item in rangesOfY)\n {\n float height = item.greater - item.less;\n area += width * height;\n }\n return area;\n }\n\n internal class Range\n {\n internal static List<Range> AddRange(List<Range> lst, Range rng2add)\n {\n if (lst.isNullOrEmpty())\n {\n return new List<Range>() { rng2add };\n }\n\n for (int i = lst.Count - 1; i >= 0; i--)\n {\n var item = lst[i];\n if (item.IsOverlapping(rng2add))\n {\n rng2add.Merge(item);\n lst.Remove(item);\n }\n }\n lst.Add(rng2add);\n return lst;\n }\n internal float greater, less;\n public override string ToString()\n {\n return $\"ln{less} gtn{greater}\";\n }\n\n internal Range(float less, float greater)\n {\n this.less = less;\n this.greater = greater;\n }\n\n private void Merge(Range rng2add)\n {\n this.less = Math.Min(rng2add.less, this.less);\n this.greater = Math.Max(rng2add.greater, this.greater);\n }\n private bool IsOverlapping(Range rng2add)\n {\n return !(less > rng2add.greater || rng2add.less > greater);\n //return\n // this.greater < rng2add.greater && this.greater > rng2add.less\n // || this.less > rng2add.less && this.less < rng2add.greater\n\n // || rng2add.greater < this.greater && rng2add.greater > this.less\n // || rng2add.less > this.less && rng2add.less < this.greater;\n }\n }\n #endregion rectangle overlapping\n"
},
{
"answer_id": 63019355,
"author": "landonvg",
"author_id": 2048503,
"author_profile": "https://Stackoverflow.com/users/2048503",
"pm_score": 0,
"selected": false,
"text": "int rectoverlap (int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2)\n{\n int width, height, area;\n\n if (ax2<bx1 || ay2<by1 || ax1>bx2 || ay1>by2) {\n cout << \"Rectangles are not overlapped\" << endl;\n return 0;\n }\n\n if (ax2>=bx2 && bx1>=ax1){\n width=bx2-bx1;\n } else if (bx2>=ax2 && ax1>=bx1) {\n width=ax2-ax1;\n } else if (ax2>bx2) {\n width=bx2-ax1;\n } else {\n width=ax2-bx1;\n }\n\n if (ay2>=by2 && by1>=ay1){\n height=by2-by1;\n } else if (by2>=ay2 && ay1>=by1) {\n height=ay2-ay1;\n } else if (ay2>by2) {\n height=by2-ay1;\n } else {\n height=ay2-by1;\n }\n\n area = heigh*width;\n return (area);\n}\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13477/"
] |
244,482
|
<p>Developing a heavily XML-based Java-application, I recently encountered an interesting problem on Ubuntu Linux.</p>
<p>My application, using the <a href="http://jpf.sourceforge.net/" rel="noreferrer">Java Plugin Framework</a>, appears unable to convert a <a href="http://www.dom4j.org/" rel="noreferrer">dom4j</a>-created XML document to <a href="http://xmlgraphics.apache.org/batik/" rel="noreferrer">Batik's</a> implementation of the SVG specification.</p>
<p>On the console, I learn that an error occurs:</p>
<pre>
Exception in thread "AWT-EventQueue-0" java.lang.LinkageError: loader constraint violation in interface itable initialization: when resolving method "org.apache.batik.dom.svg.SVGOMDocument.createAttribute(Ljava/lang/String;)Lorg/w3c/dom/Attr;" the class loader (instance of org/java/plugin/standard/StandardPluginClassLoader) of the current class, org/apache/batik/dom/svg/SVGOMDocument, and the class loader (instance of <bootloader>) for interface org/w3c/dom/Document have different Class objects for the type org/w3c/dom/Attr used in the signature
at org.apache.batik.dom.svg.SVGDOMImplementation.createDocument(SVGDOMImplementation.java:149)
at org.dom4j.io.DOMWriter.createDomDocument(DOMWriter.java:361)
at org.dom4j.io.DOMWriter.write(DOMWriter.java:138)
</pre>
<p>I figure that the problem is caused by a conflict between the original classloader from the JVM and the classloader deployed by the plugin framework.</p>
<p>To my knowledge, it's not possible to specify a classloader for the framework to use. It might be possible to hack it, but I would prefer a less aggressive approach to solving this problem, since (for whatever reason) it only occurs on Linux systems.</p>
<p>Has one of you encountered such a problem and has any idea how to fix it or at least get to the core of the issue?</p>
|
[
{
"answer_id": 244707,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 5,
"selected": false,
"text": "parent-first"
},
{
"answer_id": 244727,
"author": "Adam Crume",
"author_id": 25498,
"author_profile": "https://Stackoverflow.com/users/25498",
"pm_score": 3,
"selected": false,
"text": "Thread thread = Thread.currentThread();\nClassLoader contextClassLoader = thread.getContextClassLoader();\ntry {\n thread.setContextClassLoader(yourClassLoader);\n callDom4j();\n} finally {\n thread.setContextClassLoader(contextClassLoader);\n}\n"
},
{
"answer_id": 245038,
"author": "Alex Miller",
"author_id": 7671,
"author_profile": "https://Stackoverflow.com/users/7671",
"pm_score": 7,
"selected": true,
"text": "Exception in thread \"AWT-EventQueue-0\" java.lang.LinkageError: \nloader constraint violation in interface itable initialization: \nwhen resolving method \"org.apache.batik.dom.svg.SVGOMDocument.createAttribute(Ljava/lang/String;)Lorg/w3c/dom/Attr;\" \nthe class loader (instance of org/java/plugin/standard/StandardPluginClassLoader) \nof the current class, org/apache/batik/dom/svg/SVGOMDocument, \nand the class loader (instance of ) for interface org/w3c/dom/Document \nhave different Class objects for the type org/w3c/dom/Attr used in the signature\n"
},
{
"answer_id": 24395292,
"author": "vineetv2821993",
"author_id": 2523281,
"author_profile": "https://Stackoverflow.com/users/2523281",
"pm_score": 3,
"selected": false,
"text": "<dependency>\n <groupId>org.slf4j</groupId>\n <artifactId>slf4j-api</artifactId>\n <version>1.7.7</version>\n</dependency>\n<dependency>\n <groupId>org.slf4j</groupId>\n <artifactId>slf4j-log4j12</artifactId>\n <version>1.7.7</version>\n</dependency>\n"
},
{
"answer_id": 54743902,
"author": "Per Lundberg",
"author_id": 227779,
"author_profile": "https://Stackoverflow.com/users/227779",
"pm_score": 1,
"selected": false,
"text": "-verbose:class [Opened /usr/java/j2sdk1.4.1/jre/lib/rt.jar]\n[Opened /usr/java/j2sdk1.4.1/jre/lib/sunrsasign.jar]\n[Opened /usr/java/j2sdk1.4.1/jre/lib/jsse.jar]\n[Opened /usr/java/j2sdk1.4.1/jre/lib/jce.jar]\n[Opened /usr/java/j2sdk1.4.1/jre/lib/charsets.jar]\n[Loaded java.lang.Object from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]\n[Loaded java.io.Serializable from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]\n[Loaded java.lang.Comparable from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]\n[Loaded java.lang.CharSequence from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]\n[Loaded java.lang.String from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25141/"
] |
244,489
|
<p>I have a managed dll that calls into a native library. This native library generally returns IntPtrs. These can be passed in to other methods in the native library to do things, or to tell the library to free the instance associated with the IntPtr. But only some of the instances need to freed in this way, others are managed by the library. The problem is that the documentation is not always clear about which instances must be freed and which must not.</p>
<p>What I want to know is if there is a way that I can tell if my code has kept references to any of the pointers which must be freed, and so is causing memory to leak?</p>
|
[
{
"answer_id": 244707,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 5,
"selected": false,
"text": "parent-first"
},
{
"answer_id": 244727,
"author": "Adam Crume",
"author_id": 25498,
"author_profile": "https://Stackoverflow.com/users/25498",
"pm_score": 3,
"selected": false,
"text": "Thread thread = Thread.currentThread();\nClassLoader contextClassLoader = thread.getContextClassLoader();\ntry {\n thread.setContextClassLoader(yourClassLoader);\n callDom4j();\n} finally {\n thread.setContextClassLoader(contextClassLoader);\n}\n"
},
{
"answer_id": 245038,
"author": "Alex Miller",
"author_id": 7671,
"author_profile": "https://Stackoverflow.com/users/7671",
"pm_score": 7,
"selected": true,
"text": "Exception in thread \"AWT-EventQueue-0\" java.lang.LinkageError: \nloader constraint violation in interface itable initialization: \nwhen resolving method \"org.apache.batik.dom.svg.SVGOMDocument.createAttribute(Ljava/lang/String;)Lorg/w3c/dom/Attr;\" \nthe class loader (instance of org/java/plugin/standard/StandardPluginClassLoader) \nof the current class, org/apache/batik/dom/svg/SVGOMDocument, \nand the class loader (instance of ) for interface org/w3c/dom/Document \nhave different Class objects for the type org/w3c/dom/Attr used in the signature\n"
},
{
"answer_id": 24395292,
"author": "vineetv2821993",
"author_id": 2523281,
"author_profile": "https://Stackoverflow.com/users/2523281",
"pm_score": 3,
"selected": false,
"text": "<dependency>\n <groupId>org.slf4j</groupId>\n <artifactId>slf4j-api</artifactId>\n <version>1.7.7</version>\n</dependency>\n<dependency>\n <groupId>org.slf4j</groupId>\n <artifactId>slf4j-log4j12</artifactId>\n <version>1.7.7</version>\n</dependency>\n"
},
{
"answer_id": 54743902,
"author": "Per Lundberg",
"author_id": 227779,
"author_profile": "https://Stackoverflow.com/users/227779",
"pm_score": 1,
"selected": false,
"text": "-verbose:class [Opened /usr/java/j2sdk1.4.1/jre/lib/rt.jar]\n[Opened /usr/java/j2sdk1.4.1/jre/lib/sunrsasign.jar]\n[Opened /usr/java/j2sdk1.4.1/jre/lib/jsse.jar]\n[Opened /usr/java/j2sdk1.4.1/jre/lib/jce.jar]\n[Opened /usr/java/j2sdk1.4.1/jre/lib/charsets.jar]\n[Loaded java.lang.Object from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]\n[Loaded java.io.Serializable from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]\n[Loaded java.lang.Comparable from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]\n[Loaded java.lang.CharSequence from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]\n[Loaded java.lang.String from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
244,492
|
<p>Is there something like a panel that I can use in a MFC application. This is to overlay the default window in MFC (a dialog application). Then to paint the panel black and paint some random stuff on top of it. Something like a view port.</p>
<p>is there a better option than this to achieve the same effect ?</p>
|
[
{
"answer_id": 37513811,
"author": "Devolus",
"author_id": 2282011,
"author_profile": "https://Stackoverflow.com/users/2282011",
"pm_score": 0,
"selected": false,
"text": "CDialog Create() Show()"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1781/"
] |
244,493
|
<p>I have a certain POJO which needs to be persisted on a database, current design specifies its field as a single string column, and adding additional fields to the table is not an option.</p>
<p>Meaning, the objects need to be serialized in some way. So just for the basic implementation I went and designed my own serialized form of the object which meant concatenating all it's fields into one nice string, separated by a delimiter I chose. But this is rather ugly, and can cause problems, say if one of the fields contains my delimiter.</p>
<p>So I tried basic Java serialization, but from a basic test I conducted, this somehow becomes a very costly operation (building a ByteArrayOutputStream, an ObjectOutputStream, and so on, same for the deserialization).</p>
<p>So what are my options? What is the preferred way for serializing objects to go on a database?</p>
<p><strong>Edit:</strong> this is going to be a very common operation in my project, so overhead must be kept to a minimum, and performance is crucial. Also, third-party solutions are nice, but irrelevant (and usually generate overhead which I am trying to avoid)</p>
|
[
{
"answer_id": 244511,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 2,
"selected": false,
"text": "Properties load()/store() public String getFieldsAsString() {\n Properties data = new Properties();\n data.setProperty( \"foo\", this.getFoo() );\n data.setProperty( \"bar\", this.getBar() );\n ...\n ByteArrayOutputStream out = new ByteArrayOutputStream();\n data.store( out, \"\" );\n return new String( out.toByteArray(), \"8859-1\" ); //store() always uses this encoding\n}\n Properties load()"
},
{
"answer_id": 245030,
"author": "oxbow_lakes",
"author_id": 16853,
"author_profile": "https://Stackoverflow.com/users/16853",
"pm_score": 2,
"selected": false,
"text": "java.beans.XMLEncoder\njava.beans.XMLDecoder\n <object class=\"java.util.HashMap\">\n <void method=\"put\">\n <string>Hello</string>\n <float>1</float>\n </void>\n</object>\n PersistenceDelegate"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24545/"
] |
244,506
|
<p>Given a list of urls, I would like to check that each url:</p>
<ul>
<li>Returns a 200 OK status code</li>
<li>Returns a response within X amount of time</li>
</ul>
<p>The end goal is a system that is capable of flagging urls as potentially broken so that an administrator can review them.</p>
<p>The script will be written in PHP and will most likely run on a daily basis via cron.</p>
<p>The script will be processing approximately 1000 urls at a go.</p>
<p>Question has two parts:</p>
<ul>
<li>Are there any bigtime gotchas with an operation like this, what issues have you run into?</li>
<li>What is the best method for checking the status of a url in PHP considering both accuracy and performance?</li>
</ul>
|
[
{
"answer_id": 244669,
"author": "Henning",
"author_id": 29549,
"author_profile": "https://Stackoverflow.com/users/29549",
"pm_score": 5,
"selected": true,
"text": "function is_available($url, $timeout = 30) {\n $ch = curl_init(); // get cURL handle\n\n // set cURL options\n $opts = array(CURLOPT_RETURNTRANSFER => true, // do not output to browser\n CURLOPT_URL => $url, // set URL\n CURLOPT_NOBODY => true, // do a HEAD request only\n CURLOPT_TIMEOUT => $timeout); // set timeout\n curl_setopt_array($ch, $opts); \n\n curl_exec($ch); // do it!\n\n $retval = curl_getinfo($ch, CURLINFO_HTTP_CODE) == 200; // check if HTTP OK\n\n curl_close($ch); // close handle\n\n return $retval;\n}\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3238/"
] |
244,509
|
<p>I'm planning to make a very simple program using php and mySQL. The main page will take information and make a new row in the database with that information. However, I need a number to put in for the primary key. Unfortunately, I have no idea about the normal way to determine what umber to use. Preferably, if I delete a row, that row's key won't ever be reused.</p>
<p>A preliminary search has turned up the AUTOINCREMENT keyword in mySQL. However, I'd still like to know if that will work for what I want and what the common solution to this issue is.</p>
|
[
{
"answer_id": 244516,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 5,
"selected": true,
"text": "CREATE TABLE animals (\n id MEDIUMINT NOT NULL AUTO_INCREMENT,\n name CHAR(30) NOT NULL,\n PRIMARY KEY (id)\n );\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25680/"
] |
244,517
|
<p>Where is a reliable registry key to find install location of Excel 2007?</p>
|
[
{
"answer_id": 244580,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 4,
"selected": true,
"text": "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Office\\X.0\\Common\\InstallRoot]\n"
},
{
"answer_id": 244734,
"author": "Jason",
"author_id": 16794,
"author_profile": "https://Stackoverflow.com/users/16794",
"pm_score": 0,
"selected": false,
"text": "[HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Installer\\UserData\\S-1-5-18\\Components\\9B905EB838DBFEE4991CF8E66F518BBF]\n [HKLM\\SOFTWARE\\Microsoft\\Office\\X.0\\Common\\InstallRoot]\n"
},
{
"answer_id": 289009,
"author": "saschabeaumont",
"author_id": 592,
"author_profile": "https://Stackoverflow.com/users/592",
"pm_score": 3,
"selected": false,
"text": "[HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\excel.exe]\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16794/"
] |
244,522
|
<p>I am writing a web application that will run in kiosk mode on a touch screen. I am currently only targeting it for running on Firefox 3. A few of the use cases I have need to visit external sites. I wish to do so with an embedded browser, which I'm tackling with the help of an <code><iframe></code>. I need back/forward buttons for the embedded home page. </p>
<p>I've managed to access the history object of the iframe with</p>
<pre><code>var w = document.getElementById('embeddedBrowser').contentWindow;
w.history.back();
</code></pre>
<p>The <code>history</code> of the embedded window is the same as that of the parent window. Therefore for a newly loaded <code><iframe></code>, this call will go back to the previous page of the system.</p>
<p>Is there any way to avoid this or a more correct way of solving this?</p>
|
[
{
"answer_id": 245084,
"author": "Borgar",
"author_id": 27388,
"author_profile": "https://Stackoverflow.com/users/27388",
"pm_score": 3,
"selected": true,
"text": "window.history.current window.history.previous window.history.current <iframe src=\"somepage.html\" name=\"myframe\"></iframe>\n<p><a href=\"#\" id=\"backBtn\">Back</a></p>\n\n<script type=\"text/javascript\">\n\n document.getElementById('backBtn').onclick = function () {\n if (window.frames['myframe'].location.hash !== '#stopper') {\n window.history.back();\n }\n // ... else hide the button?\n return false; // pop event bubble\n };\n window.frames['myframe'].onload = function () {\n this.location.hash = 'stopper';\n };\n\n</script>\n"
}
] |
2008/10/28
|
[
"https://Stackoverflow.com/questions/244522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27349/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.