qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
103,519
|
<p>I'm running some JUnit tests on my applications. Every test has a for loop calling respective method 10000 times.
The tested methods produce a lot of log.
These logs are also automatically collected by JUnit as test output.
This situation takes to OutOfMemoryError because the string buffer where JUnit keeps the output becomes too large.
I dont' need these logs during tests, so if there is a way to tell JUnit "don't keep program output" it would be enough.
Any ideas?</p>
|
[
{
"answer_id": 103535,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 1,
"selected": false,
"text": "-Xmx <some number>M -Xmx 256M"
},
{
"answer_id": 106252,
"author": "shoover",
"author_id": 18356,
"author_profile": "https://Stackoverflow.com/users/18356",
"pm_score": 0,
"selected": false,
"text": "// Save the original stdout and stderr\nPrintStream psOut = System.out;\nPrintStream psErr = System.err;\nPrintStream psDevNull = null;\ntry\n{\n // Send stdout and stderr to /dev/null\n psDevNull = new PrintStream(new ByteArrayOutputStream());\n System.setOut(psDevNull);\n System.setErr(psDevNull);\n // run tests in loop\n for (...)\n {\n }\n}\nfinally\n{\n // Restore stdout and stderr\n System.setOut(psOut);\n System.setErr(psErr);\n if (psDevNull != null)\n {\n psDevNull.close();\n psDevNull = null;\n }\n}\n ant test &> /dev/null\n"
},
{
"answer_id": 832265,
"author": "Ewen Cartwright",
"author_id": 41595,
"author_profile": "https://Stackoverflow.com/users/41595",
"pm_score": 0,
"selected": false,
"text": "outputtoformatters=\"no\""
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/103519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18119/"
] |
103,532
|
<p>If you need to open a SqlConnection before issuing queries, can you simply handle all non-Open ConnectionStates in the same way? For example:</p>
<pre><code> if (connection.State != ConnectionState.Open)
{
connection.Open();
}
</code></pre>
<p>I read somewhere that for ConnectionState.Broken the connection needs to be closed before its re-opened. Does anyone have experience with this? Thanks-</p>
|
[
{
"answer_id": 103832,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 3,
"selected": false,
"text": "using(SqlConnection connection = new SqlConnection(...))\n{\n connection.Open();\n // ... do your stuff here\n\n} // Connection is disposed and closed here, even if an exception is thrown\n"
},
{
"answer_id": 12537293,
"author": "Rudy Hinojosa",
"author_id": 1689760,
"author_profile": "https://Stackoverflow.com/users/1689760",
"pm_score": 2,
"selected": false,
"text": "if (context.Connection.State == System.Data.ConnectionState.Broken)\n{\n context.Connection.Close();\n context.Connection.Open();\n}\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/103532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/815/"
] |
103,560
|
<p>I have an ASP.net application that works fine in the development environment but in the production environment throws the following exception when clicking a link that performs a postback. Any ideas?</p>
<blockquote>
<p>Invalid postback or callback argument.
Event validation is enabled using
in configuration or <%@ Page
EnableEventValidation="true" %> in a
page. For security purposes, this
feature verifies that arguments to
postback or callback events originate
from the server control that
originally rendered them. If the data
is valid and expected, use the
ClientScriptManager.RegisterForEventValidation
method in order to register the
postback or callback data for
validation.</p>
</blockquote>
<p><strong>Edit:</strong> This seems to only be happening when viewed with IE6 but not with IE7, any ideas?</p>
|
[
{
"answer_id": 103599,
"author": "azamsharp",
"author_id": 3797,
"author_profile": "https://Stackoverflow.com/users/3797",
"pm_score": 0,
"selected": false,
"text": "<%@ Page ... EnableEventValidation = \"false\" />\n"
},
{
"answer_id": 278893,
"author": "dnord",
"author_id": 3248,
"author_profile": "https://Stackoverflow.com/users/3248",
"pm_score": 0,
"selected": false,
"text": "<form> EnableEventValidation = \"false\" <form> <form>"
},
{
"answer_id": 26012819,
"author": "user1089766",
"author_id": 1089766,
"author_profile": "https://Stackoverflow.com/users/1089766",
"pm_score": 2,
"selected": false,
"text": "function HTMLEncodeAngularBrackets(someString)\n{\nvar modifiedString = someString.replace(\"<\",\"<\");\nmodifiedString = modifiedString.replace(\">\",\">\");\nreturn modifiedString;\n}\n protected override void Render(HtmlTextWriter writer)\n{\nClientScript.RegisterForEventValidation(myButton.UniqueID.ToString());\nbase.Render(writer);\n}\n protected void Page_Load(object sender, EventArgs e)\n{\nif(!Page.IsPostback)\n{\n// Create controls\n// Bind Grid\n}\n}\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/103560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3111/"
] |
103,561
|
<p>I am taking on a maintenance team and would like to introduce tools like FxCop and StyleCop to help improve the code and introduce the developers to better programming techniques and standards. Since we are maintaining code and not making significant enhancements, we will probably only deal with a couple of methods/routines at a time when making changes. </p>
<p>Is it possible to target FxCop/StyleCop to specific areas of code within Visual Studio to avoid getting overwhelmed with all of the issues that would get raised when analyzing a whole class or project? If it is possible, how do you go about it?</p>
<p>Thanks,
Matt</p>
|
[
{
"answer_id": 168262,
"author": "alexandrul",
"author_id": 19756,
"author_profile": "https://Stackoverflow.com/users/19756",
"pm_score": 3,
"selected": true,
"text": "/types:<type list> [Short form: /t:<type list>]\nAnalyze only these types and members.\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/103561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3262/"
] |
103,564
|
<p>I am working on an application and one design approach involves extremely heavy use of the <code>instanceof</code> operator. While I know that OO design generally tries to avoid using <code>instanceof</code>, that is a different story and this question is purely related to performance. I was wondering if there is any performance impact? Is is just as fast as <code>==</code>?</p>
<p>For example, I have a base class with 10 subclasses. In a single function that takes the base class, I do checks for if the class is an instance of the subclass and carry out some routine. </p>
<p>One of the other ways I thought of solving it was to use a "type id" integer primitive instead, and use a bitmask to represent categories of the subclasses, and then just do a bit mask comparison of the subclasses "type id" to a constant mask representing the category.</p>
<p>Is <code>instanceof</code> somehow optimized by the JVM to be faster than that? I want to stick to Java but the performance of the app is critical. It would be cool if someone that has been down this road before could offer some advice. Am I nitpicking too much or focusing on the wrong thing to optimize?</p>
|
[
{
"answer_id": 103602,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 2,
"selected": false,
"text": "if (o instanceof Class1)\n doThis();\nelse if (o instanceof Class2)\n doThat();\n//...\n o.doEverything();\n"
},
{
"answer_id": 103683,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 2,
"selected": false,
"text": "if (o instanceof java.lang.String)\n if (objectStruct->iAmInstanceOf == &java_lang_String_class)\n"
},
{
"answer_id": 103802,
"author": "Demian Krige",
"author_id": 8385,
"author_profile": "https://Stackoverflow.com/users/8385",
"pm_score": 1,
"selected": false,
"text": "if (SomeObject instanceOf Integer) {\n [do something]\n}\nif (SomeObject instanceOf Double) {\n [do something different]\n}\n Someobject.doSomething();\n"
},
{
"answer_id": 104633,
"author": "Horcrux7",
"author_id": 12631,
"author_profile": "https://Stackoverflow.com/users/12631",
"pm_score": 2,
"selected": false,
"text": "if(a instanceof AnyObject){\n}\n if(a.getType() == XYZ){\n}\n"
},
{
"answer_id": 111271,
"author": "Scott Stanchfield",
"author_id": 12541,
"author_profile": "https://Stackoverflow.com/users/12541",
"pm_score": 2,
"selected": false,
"text": "package com.javadude.sample;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class StrategyExample {\n static class SomeCommonSuperType {}\n static class SubType1 extends SomeCommonSuperType {}\n static class SubType2 extends SomeCommonSuperType {}\n static class SubType3 extends SomeCommonSuperType {}\n\n static interface Handler<T extends SomeCommonSuperType> {\n Object handle(T object);\n }\n\n static class HandlerMap {\n private Map<Class<? extends SomeCommonSuperType>, Handler<? extends SomeCommonSuperType>> handlers_ =\n new HashMap<Class<? extends SomeCommonSuperType>, Handler<? extends SomeCommonSuperType>>();\n public <T extends SomeCommonSuperType> void add(Class<T> c, Handler<T> handler) {\n handlers_.put(c, handler);\n }\n @SuppressWarnings(\"unchecked\")\n public <T extends SomeCommonSuperType> Object handle(T o) {\n return ((Handler<T>) handlers_.get(o.getClass())).handle(o);\n }\n }\n\n public static void main(String[] args) {\n HandlerMap handlerMap = new HandlerMap();\n\n handlerMap.add(SubType1.class, new Handler<SubType1>() {\n @Override public Object handle(SubType1 object) {\n System.out.println(\"Handling SubType1\");\n return null;\n } });\n handlerMap.add(SubType2.class, new Handler<SubType2>() {\n @Override public Object handle(SubType2 object) {\n System.out.println(\"Handling SubType2\");\n return null;\n } });\n handlerMap.add(SubType3.class, new Handler<SubType3>() {\n @Override public Object handle(SubType3 object) {\n System.out.println(\"Handling SubType3\");\n return null;\n } });\n\n SubType1 subType1 = new SubType1();\n handlerMap.handle(subType1);\n SubType2 subType2 = new SubType2();\n handlerMap.handle(subType2);\n SubType3 subType3 = new SubType3();\n handlerMap.handle(subType3);\n }\n}\n"
},
{
"answer_id": 1659318,
"author": "brianegge",
"author_id": 14139,
"author_profile": "https://Stackoverflow.com/users/14139",
"pm_score": 4,
"selected": false,
"text": "InstanceOf 3156\nclass== 2925 \nOO 3083 \nId 3067 \n"
},
{
"answer_id": 6716713,
"author": "irreputable",
"author_id": 218978,
"author_profile": "https://Stackoverflow.com/users/218978",
"pm_score": 4,
"selected": false,
"text": "instanceof X instanceof x instanceof X \n==> x.getClass()==X.class \n==> x.classID == constant_X_ID\n X"
},
{
"answer_id": 6845904,
"author": "Salix alba",
"author_id": 865481,
"author_profile": "https://Stackoverflow.com/users/865481",
"pm_score": 1,
"selected": false,
"text": "static final int ID_A = 0;\nstatic final int ID_B = 1;\nabstract class Base {\n final int id;\n Base(int i) { id = i; }\n}\nclass A extends Base {\n A() { super(ID_A); }\n}\nclass B extends Base {\n B() { super(ID_B); }\n}\n...\nBase obj = ...\nswitch(obj.id) {\ncase ID_A: .... break;\ncase ID_B: .... break;\n}\n"
},
{
"answer_id": 9845094,
"author": "Xtra Coder",
"author_id": 1141564,
"author_profile": "https://Stackoverflow.com/users/1141564",
"pm_score": 4,
"selected": false,
"text": "for 10 child classes - instanceof: 1200ms vs switch: 470ms\nfor 5 child classes - instanceof: 375ms vs switch: 204ms\n import java.util.Date;\n\npublic class InstanceOfVsEnum {\n\n public static int c1, c2, c3, c4, c5, c6, c7, c8, c9, cA;\n\n public static class Handler {\n public enum Type { Type1, Type2, Type3, Type4, Type5, Type6, Type7, Type8, Type9, TypeA }\n protected Handler(Type type) { this.type = type; }\n public final Type type;\n\n public static void addHandlerInstanceOf(Handler h) {\n if( h instanceof H1) { c1++; }\n else if( h instanceof H2) { c2++; }\n else if( h instanceof H3) { c3++; }\n else if( h instanceof H4) { c4++; }\n else if( h instanceof H5) { c5++; }\n else if( h instanceof H6) { c6++; }\n else if( h instanceof H7) { c7++; }\n else if( h instanceof H8) { c8++; }\n else if( h instanceof H9) { c9++; }\n else if( h instanceof HA) { cA++; }\n }\n\n public static void addHandlerSwitch(Handler h) {\n switch( h.type ) {\n case Type1: c1++; break;\n case Type2: c2++; break;\n case Type3: c3++; break;\n case Type4: c4++; break;\n case Type5: c5++; break;\n case Type6: c6++; break;\n case Type7: c7++; break;\n case Type8: c8++; break;\n case Type9: c9++; break;\n case TypeA: cA++; break;\n }\n }\n }\n\n public static class H1 extends Handler { public H1() { super(Type.Type1); } }\n public static class H2 extends Handler { public H2() { super(Type.Type2); } }\n public static class H3 extends Handler { public H3() { super(Type.Type3); } }\n public static class H4 extends Handler { public H4() { super(Type.Type4); } }\n public static class H5 extends Handler { public H5() { super(Type.Type5); } }\n public static class H6 extends Handler { public H6() { super(Type.Type6); } }\n public static class H7 extends Handler { public H7() { super(Type.Type7); } }\n public static class H8 extends Handler { public H8() { super(Type.Type8); } }\n public static class H9 extends Handler { public H9() { super(Type.Type9); } }\n public static class HA extends Handler { public HA() { super(Type.TypeA); } }\n\n final static int cCycles = 10000000;\n\n public static void main(String[] args) {\n H1 h1 = new H1();\n H2 h2 = new H2();\n H3 h3 = new H3();\n H4 h4 = new H4();\n H5 h5 = new H5();\n H6 h6 = new H6();\n H7 h7 = new H7();\n H8 h8 = new H8();\n H9 h9 = new H9();\n HA hA = new HA();\n\n Date dtStart = new Date();\n for( int i = 0; i < cCycles; i++ ) {\n Handler.addHandlerInstanceOf(h1);\n Handler.addHandlerInstanceOf(h2);\n Handler.addHandlerInstanceOf(h3);\n Handler.addHandlerInstanceOf(h4);\n Handler.addHandlerInstanceOf(h5);\n Handler.addHandlerInstanceOf(h6);\n Handler.addHandlerInstanceOf(h7);\n Handler.addHandlerInstanceOf(h8);\n Handler.addHandlerInstanceOf(h9);\n Handler.addHandlerInstanceOf(hA);\n }\n System.out.println(\"Instance of - \" + (new Date().getTime() - dtStart.getTime()));\n\n dtStart = new Date();\n for( int i = 0; i < cCycles; i++ ) {\n Handler.addHandlerSwitch(h1);\n Handler.addHandlerSwitch(h2);\n Handler.addHandlerSwitch(h3);\n Handler.addHandlerSwitch(h4);\n Handler.addHandlerSwitch(h5);\n Handler.addHandlerSwitch(h6);\n Handler.addHandlerSwitch(h7);\n Handler.addHandlerSwitch(h8);\n Handler.addHandlerSwitch(h9);\n Handler.addHandlerSwitch(hA);\n }\n System.out.println(\"Switch of - \" + (new Date().getTime() - dtStart.getTime()));\n }\n}\n"
},
{
"answer_id": 18213428,
"author": "mike",
"author_id": 1809463,
"author_profile": "https://Stackoverflow.com/users/1809463",
"pm_score": 0,
"selected": false,
"text": "getType() public abstract class Base\n{\n protected enum TYPE\n {\n DERIVED_A, DERIVED_B\n }\n\n public abstract TYPE getType();\n\n class DerivedA extends Base\n {\n @Override\n public TYPE getType()\n {\n return TYPE.DERIVED_A;\n }\n }\n\n class DerivedB extends Base\n {\n @Override\n public TYPE getType()\n {\n return TYPE.DERIVED_B;\n }\n }\n}\n"
},
{
"answer_id": 26514984,
"author": "Michael Dorner",
"author_id": 1864294,
"author_profile": "https://Stackoverflow.com/users/1864294",
"pm_score": 8,
"selected": false,
"text": "instanceof @Override getClass() == _.class instanceof getClass()"
},
{
"answer_id": 46765418,
"author": "Michael Kay",
"author_id": 415448,
"author_profile": "https://Stackoverflow.com/users/415448",
"pm_score": 0,
"selected": false,
"text": "if (!(seq instanceof SingleItem)) {\n seq = seq.head();\n}\n seq = seq.head();\n"
},
{
"answer_id": 56712753,
"author": "salexinx",
"author_id": 6795424,
"author_profile": "https://Stackoverflow.com/users/6795424",
"pm_score": 3,
"selected": false,
"text": "Benchmark Mode Cnt Score Error Units\nMyBenchmark.getClasses thrpt 30 510.818 ± 4.190 ops/us\nMyBenchmark.instanceOf thrpt 30 503.826 ± 5.546 ops/us\n public class MyBenchmark {\n\npublic static final Object a = new LinkedHashMap<String, String>();\n\n@Benchmark\n@BenchmarkMode(Mode.Throughput)\n@OutputTimeUnit(TimeUnit.MICROSECONDS)\npublic boolean instanceOf() {\n return a instanceof Map;\n}\n\n@Benchmark\n@BenchmarkMode(Mode.Throughput)\n@OutputTimeUnit(TimeUnit.MICROSECONDS)\npublic boolean getClasses() {\n return a.getClass() == HashMap.class;\n}\n\npublic static void main(String[] args) throws RunnerException {\n Options opt =\n new OptionsBuilder().include(MyBenchmark.class.getSimpleName()).warmupIterations(20).measurementIterations(30).forks(1).build();\n new Runner(opt).run();\n}\n}\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/103564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2204759/"
] |
103,569
|
<p>I've looked for some other articles on this problem and even tried some of the ideas in <a href="https://stackoverflow.com/questions/8440/visual-studio-optimizations#8539">this thread</a>; however, nothing has solved the issue yet. So, on to the issue.</p>
<p>Something happens when working in Visual Studio (usually C#) that causes the IDE to become a bit wonky when saving a file. I will be working along just fine for a while then at some point I notice that every time I save a file (<kbd>Ctrl</kbd>+<kbd>S</kbd>) it becomes very slow.</p>
<p>The behavior I notice is this; I hit save in some fashion (<kbd>Ctrl</kbd>+<kbd>S</kbd>, menu, etc...) and in the status bar I see the word <strong>Searching</strong> show up. It looks like it is scanning through all of the loaded namespaces for something, although I have no idea for what or why it is doing so. It causes a real hiccup in workflow since typically I will hit <kbd>Ctrl</kbd>+<kbd>S</kbd> often and keep typing.</p>
<p>I have been unable to track down what exactly causes this to start happening. It has happened in multiple project types (web, WPF, console).</p>
<p>Has anyone seen this behavior or have any suggestions?</p>
|
[
{
"answer_id": 13626423,
"author": "Yash Gadhiya",
"author_id": 1026511,
"author_profile": "https://Stackoverflow.com/users/1026511",
"pm_score": 3,
"selected": false,
"text": "<script src=\"//translate.google.com/translate_a... //"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/103569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/312/"
] |
103,575
|
<p>I am trying to validate the WPF form against an object. The validation fires when I type something in the textbox lose focus come back to the textbox and then erase whatever I have written. But if I just load the WPF application and tab off the textbox without writing and erasing anything from the textbox, then it is not fired. </p>
<p>Here is the Customer.cs class: </p>
<pre><code>public class Customer : IDataErrorInfo
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Error
{
get { throw new NotImplementedException(); }
}
public string this[string columnName]
{
get
{
string result = null;
if (columnName.Equals("FirstName"))
{
if (String.IsNullOrEmpty(FirstName))
{
result = "FirstName cannot be null or empty";
}
}
else if (columnName.Equals("LastName"))
{
if (String.IsNullOrEmpty(LastName))
{
result = "LastName cannot be null or empty";
}
}
return result;
}
}
}
</code></pre>
<p>And here is the WPF code: </p>
<pre><code><TextBlock Grid.Row="1" Margin="10" Grid.Column="0">LastName</TextBlock>
<TextBox Style="{StaticResource textBoxStyle}" Name="txtLastName" Margin="10"
VerticalAlignment="Top" Grid.Row="1" Grid.Column="1">
<Binding Source="{StaticResource CustomerKey}" Path="LastName"
ValidatesOnExceptions="True" ValidatesOnDataErrors="True"
UpdateSourceTrigger="LostFocus"/>
</TextBox>
</code></pre>
|
[
{
"answer_id": 914289,
"author": "w4g3n3r",
"author_id": 36745,
"author_profile": "https://Stackoverflow.com/users/36745",
"pm_score": 3,
"selected": false,
"text": "<Binding \n Source=\"{StaticResource CustomerKey}\" \n Path=\"LastName\" \n ValidatesOnExceptions=\"True\" \n ValidatesOnDataErrors=\"True\" \n UpdateSourceTrigger=\"LostFocus\">\n <Binding.ValidationRules>\n <DataErrorValidationRule\n ValidatesOnTargetUpdated=\"True\" />\n </Binding.ValidationRules>\n</Binding>\n"
},
{
"answer_id": 1347399,
"author": "Bermo",
"author_id": 5110,
"author_profile": "https://Stackoverflow.com/users/5110",
"pm_score": 5,
"selected": true,
"text": "<TextBox LostFocus=\"TextBox_LostFocus\" ....\n private void TextBox_LostFocus(object sender, RoutedEventArgs e)\n{\n ((Control)sender).GetBindingExpression(TextBox.TextProperty).UpdateSource();\n}\n"
},
{
"answer_id": 5672473,
"author": "AbstractDissonance",
"author_id": 576287,
"author_profile": "https://Stackoverflow.com/users/576287",
"pm_score": 0,
"selected": false,
"text": "public static class PreValidation\n{\n\n public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject\n {\n if (depObj != null)\n {\n for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)\n {\n DependencyObject child = VisualTreeHelper.GetChild(depObj, i);\n if (child != null && child is T)\n {\n yield return (T)child;\n }\n\n foreach (T childOfChild in FindVisualChildren<T>(child))\n {\n yield return childOfChild;\n }\n }\n }\n }\n\n\n public static void Validate(DependencyObject depObj)\n {\n foreach(var c in FindVisualChildren<FrameworkElement>(depObj))\n {\n DependencyProperty p = null;\n\n if (c is TextBlock)\n p = TextBlock.TextProperty;\n else if (c is TextBox)\n p = TextBox.TextProperty;\n\n if (p != null && c.GetBindingExpression(p) != null) c.GetBindingExpression(p).UpdateSource();\n }\n\n }\n}\n"
},
{
"answer_id": 8528810,
"author": "theDoke",
"author_id": 1089031,
"author_profile": "https://Stackoverflow.com/users/1089031",
"pm_score": 1,
"selected": false,
"text": " private void dbaseNameTextBox_LostFocus(object sender, RoutedEventArgs e)\n {\n if (string.IsNullOrWhiteSpace(dbaseNameTextBox.Text))\n {\n dbaseNameTextBox.Text = string.Empty;\n }\n }\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/103575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3797/"
] |
103,576
|
<p>I'm trying a very basic XPath on <a href="http://pastebin.com/f14a20a30" rel="noreferrer">this xml</a> (same as below), and it doesn't find anything.
I'm trying both .NET and <a href="http://www.xmlme.com/XpathTool.aspx" rel="noreferrer">this website</a>, and XPaths such as <code>//PropertyGroup</code>, <code>/PropertyGroup</code> and <code>//MSBuildCommunityTasksPath</code> are simply not working for me (they compiled but return zero results).</p>
<p>Source XML:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<!-- $Id: FxCop.proj 114 2006-03-14 06:32:46Z pwelter34 $ -->
<PropertyGroup>
<MSBuildCommunityTasksPath>$(MSBuildProjectDirectory)\MSBuild.Community.Tasks\bin\Debug</MSBuildCommunityTasksPath>
</PropertyGroup>
<Import
Project="$(MSBuildProjectDirectory)\MSBuild.Community.Tasks\MSBuild.Community.Tasks.Targets" />
<Target Name="DoFxCop">
<FxCop TargetAssemblies="$(MSBuildCommunityTasksPath)\MSBuild.Community.Tasks.dll"
RuleLibraries="@(FxCopRuleAssemblies)"
AnalysisReportFileName="Test.html"
DependencyDirectories="$(MSBuildCommunityTasksPath)"
FailOnError="True"
ApplyOutXsl="True"
OutputXslFileName="C:\Program Files\Microsoft FxCop 1.32\Xml\FxCopReport.xsl" />
</Target>
</Project>
</code></pre>
|
[
{
"answer_id": 103905,
"author": "Jesse Millikan",
"author_id": 7526,
"author_profile": "https://Stackoverflow.com/users/7526",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Xml;\n\npublic class XPathNamespace {\n public static void Main(string[] args) {\n XmlDocument xmlDocument = new XmlDocument();\n xmlDocument.LoadXml(\n @\"<?xml version=\"\"1.0\"\" encoding=\"\"utf-8\"\"?>\n<Project xmlns=\"\"http://schemas.microsoft.com/developer/msbuild/2003\"\">\n <!-- $Id: FxCop.proj 114 2006-03-14 06:32:46Z pwelter34 $ -->\n\n <PropertyGroup>\n <MSBuildCommunityTasksPath>$(MSBuildProjectDirectory)\\MSBuild.Community.Tasks\\bin\\Debug</MSBuildCommunityTasksPath>\n </PropertyGroup>\n\n <Import Project=\"\"$(MSBuildProjectDirectory)\\MSBuild.Community.Tasks\\MSBuild.Community.Tasks.Targets\"\"/>\n\n <Target Name=\"\"DoFxCop\"\">\n\n <FxCop \n TargetAssemblies=\"\"$(MSBuildCommunityTasksPath)\\MSBuild.Community.Tasks.dll\"\"\n RuleLibraries=\"\"@(FxCopRuleAssemblies)\"\" \n AnalysisReportFileName=\"\"Test.html\"\"\n DependencyDirectories=\"\"$(MSBuildCommunityTasksPath)\"\"\n FailOnError=\"\"True\"\"\n ApplyOutXsl=\"\"True\"\"\n OutputXslFileName=\"\"C:\\Program Files\\Microsoft FxCop 1.32\\Xml\\FxCopReport.xsl\"\"\n />\n </Target>\n\n</Project>\");\n\n XmlNamespaceManager namespaceManager = new\n XmlNamespaceManager(xmlDocument.NameTable);\n namespaceManager.AddNamespace(\"msbuild\", \"http://schemas.microsoft.com/developer/msbuild/2003\");\n foreach (XmlNode n in xmlDocument.SelectNodes(\"//msbuild:MSBuildCommunityTasksPath\", namespaceManager)) {\n Console.WriteLine(n.InnerText);\n }\n }\n}\n"
},
{
"answer_id": 104404,
"author": "b w",
"author_id": 4126,
"author_profile": "https://Stackoverflow.com/users/4126",
"pm_score": 5,
"selected": true,
"text": "//*[local-name()='PropertyGroup']\n//*[local-name()='MSBuildCommunityTasksPath']\n //*[name()='PropertyGroup']\n//*[name()='MSBuildCommunityTasksPath']\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/103576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11236/"
] |
103,583
|
<p>This is written in PHP, but it's really language agnostic.</p>
<pre><code>try
{
try
{
$issue = new DM_Issue($core->db->escape_string($_GET['issue']));
}
catch(DM_Exception $e)
{
throw new Error_Page($tpl, ERR_NOT_FOUND, $e->getMessage());
}
}
catch(Error_Page $e)
{
die($e);
}
</code></pre>
<p>Is nested try, catch blocks a good practice to follow? It seems a little bulky just for an error page - however my Issue Datamanager throws an Exception if an error occurs and I consider that to be a good way of error detecting.</p>
<p>The Error_Page exception is simply an error page compiler.</p>
<p>I might just be pedantic, but do you think this is a good way to report errors and if so can you suggest a better way to write this?</p>
<p>Thanks</p>
|
[
{
"answer_id": 103625,
"author": "oglester",
"author_id": 2017,
"author_profile": "https://Stackoverflow.com/users/2017",
"pm_score": 2,
"selected": false,
"text": "try{\n Something();\n}\ncatch( SpecificException se )\n{blah();}\ncatch( AnotherException ae )\n{blah();}\n"
},
{
"answer_id": 103859,
"author": "Aeon",
"author_id": 13289,
"author_profile": "https://Stackoverflow.com/users/13289",
"pm_score": 0,
"selected": false,
"text": "try {\n $issue = DM_Issue::fetch($core->db->escape_string($_GET['issue']));\n}\ncatch (SQLException $e) {\n log_error('SQL Error: DM_Issue::fetch()', $e->get_message());\n}\ncatch (Exception $e) {\n log_error('Exception: DM_Issue::fetch()', $e->get_message());\n}\n\nif(!$issue) {\n display_error_page($tpl, ERR_NOT_FOUND);\n}\nelse\n{\n // ... do stuff with $issue object.\n}\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/103583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2025/"
] |
103,593
|
<p>I have:</p>
<pre><code><?php
$file=fopen(date("Y-m-d").".txt","r+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
fwrite($file,$_POST["lastname"]."\n");
}
fclose($file);
?>
</code></pre>
<p>but it overwrites the beginning of the file. How do I make it insert?</p>
|
[
{
"answer_id": 103609,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 6,
"selected": true,
"text": "a+ r+ $file=fopen(date(\"Y-m-d\").\".txt\",\"a+\") or exit(\"Unable to open file!\");\n\nif ($_POST[\"lastname\"] <> \"\")\n{\n fwrite($file,$_POST[\"lastname\"].\"\\n\");\n}\n\nfclose($file);\n file_get_contents $old_content = file_get_contents($file);\nfwrite($file, $new_content.\"\\n\".$old_content);\n file_get_conents rewind($file) rewind() a a+"
},
{
"answer_id": 103617,
"author": "SeanDowney",
"author_id": 5261,
"author_profile": "https://Stackoverflow.com/users/5261",
"pm_score": 0,
"selected": false,
"text": "<?php\n\n$file=fopen(date(\"Y-m-d\").\".txt\",\"r+\") or exit(\"Unable to open file!\");\n\nif ($_POST[\"lastname\"] <> \"\")\n{ \n $existingText = file_get_contents($file);\n fwrite($file, $existingText . $_POST[\"lastname\"].\"\\n\");\n}\n\nfclose($file);\n\n?>\n"
},
{
"answer_id": 103675,
"author": "Eduardo Campañó",
"author_id": 12091,
"author_profile": "https://Stackoverflow.com/users/12091",
"pm_score": 0,
"selected": false,
"text": "<?php\n$file=fopen(date(\"Y-m-d\").\".txt\",\"a+\") or exit(\"Unable to open file!\");\nif ($_POST[\"lastname\"] <> \"\")\n{\n fwrite($file,$_POST[\"lastname\"].\"\\n\");\n}\nfclose($file);\n?>\n"
},
{
"answer_id": 26093658,
"author": "oskarth",
"author_id": 1062912,
"author_profile": "https://Stackoverflow.com/users/1062912",
"pm_score": 1,
"selected": false,
"text": "function finsert($handle, $string, $bufferSize = 16384) {\n $insertionPoint = ftell($handle);\n\n // Create a temp file to stream into\n $tempPath = tempnam(sys_get_temp_dir(), \"file-chainer\");\n $lastPartHandle = fopen($tempPath, \"w+\");\n\n // Read in everything from the insertion point and forward\n while (!feof($handle)) {\n fwrite($lastPartHandle, fread($handle, $bufferSize), $bufferSize);\n }\n\n // Rewind to the insertion point\n fseek($handle, $insertionPoint);\n\n // Rewind the temporary stream\n rewind($lastPartHandle);\n\n // Write back everything starting with the string to insert\n fwrite($handle, $string);\n while (!feof($lastPartHandle)) {\n fwrite($handle, fread($lastPartHandle, $bufferSize), $bufferSize);\n }\n\n // Close the last part handle and delete it\n fclose($lastPartHandle);\n unlink($tempPath);\n\n // Re-set pointer\n fseek($handle, $insertionPoint + strlen($string));\n}\n\n$handle = fopen(\"file.txt\", \"w+\");\nfwrite($handle, \"foobar\");\nrewind($handle);\nfinsert($handle, \"baz\");\n\n// File stream is now: bazfoobar\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/103593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
103,598
|
<p>Why was the <code>arguments.callee.caller</code> property deprecated in JavaScript?</p>
<p>It was added and then deprecated in JavaScript, but it was omitted altogether by ECMAScript. Some browser (Mozilla, IE) have always supported it and don't have any plans on the map to remove support. Others (Safari, Opera) have adopted support for it, but support on older browsers is unreliable.</p>
<p>Is there a good reason to put this valuable functionality in limbo?</p>
<p>(Or alternately, is there a better way to grab a handle on the calling function?)</p>
|
[
{
"answer_id": 103961,
"author": "Zach",
"author_id": 9128,
"author_profile": "https://Stackoverflow.com/users/9128",
"pm_score": 5,
"selected": false,
"text": " function foo () {\n ... foo() ...\n }\n function () {\n ... arguments.callee() ...\n }\n function foo () {\n alert(foo.caller);\n }\n function foo () {\n alert(arguments.callee.caller);\n }\n"
},
{
"answer_id": 235760,
"author": "olliej",
"author_id": 784,
"author_profile": "https://Stackoverflow.com/users/784",
"pm_score": 9,
"selected": true,
"text": " // This snippet will work:\n function factorial(n) {\n return (!(n>1))? 1 : factorial(n-1)*n;\n }\n [1,2,3,4,5].map(factorial);\n\n\n // But this snippet will not:\n [1,2,3,4,5].map(function(n) {\n return (!(n>1))? 1 : /* what goes here? */ (n-1)*n;\n });\n arguments.callee [1,2,3,4,5].map(function(n) {\n return (!(n>1))? 1 : arguments.callee(n-1)*n;\n });\n this var global = this;\nvar sillyFunction = function (recursed) {\n if (!recursed)\n return arguments.callee(true);\n if (this !== global)\n alert(\"This is: \" + this);\n else\n alert(\"This is the global\");\n}\nsillyFunction();\n [1,2,3,4,5].map(function factorial(n) {\n return (!(n>1))? 1 : factorial(n-1)*n;\n });\n this arguments.callee.caller Function.caller f f function f(a, b, c, d, e) { return a ? b * c : d * e; }\n"
},
{
"answer_id": 1335595,
"author": "James Wheare",
"author_id": 115076,
"author_profile": "https://Stackoverflow.com/users/115076",
"pm_score": 7,
"selected": false,
"text": "arguments.callee.caller Function.caller arguments.callee Function.caller arguments.caller Function.caller Function.caller arguments.callee"
},
{
"answer_id": 28084391,
"author": "FERcsI",
"author_id": 2531161,
"author_profile": "https://Stackoverflow.com/users/2531161",
"pm_score": 0,
"selected": false,
"text": "[1,2,3,4,5].map(function factorial(n) {\n console.log(this);\n return (!(n>1))? 1 : factorial(n-1)*n;\n}, {foo:true} );\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/103598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15992/"
] |
103,630
|
<p>Is it possible to use an <a href="http://en.wikipedia.org/wiki/ASP.NET" rel="noreferrer">ASP.NET</a> web.sitemap with a jQuery <a href="http://users.tpg.com.au/j_birch/plugins/superfish/" rel="noreferrer">Superfish</a> menu? </p>
<p>If not, are there any standards based browser agnostic plugins available that work with the web.sitemap file?</p>
|
[
{
"answer_id": 647656,
"author": "Conceptdev",
"author_id": 25673,
"author_profile": "https://Stackoverflow.com/users/25673",
"pm_score": 6,
"selected": true,
"text": "siteMap Masterpage.master head <head runat=\"server\">\n <script type=\"text/javascript\" src=\"/script/jquery-1.3.2.min.js\"></script>\n <script type=\"text/javascript\" src=\"/script/superfish.js\"></script>\n <link href=\"~/css/superfish.css\" type=\"text/css\" rel=\"stylesheet\" media=\"screen\" runat=\"server\" />\n <script type=\"text/javascript\">\n\n $(document).ready(function() {\n $('ul.AspNet-Menu').superfish();\n }); \n\n</script>\n</head>\n <asp:SiteMapDataSource ID=\"SiteMapDataSource\" runat=\"server\"\n ShowStartingNode=\"false\" />\n<asp:Menu ID=\"Menu1\" runat=\"server\" \n DataSourceID=\"SiteMapDataSource\"\n Orientation=\"Horizontal\" CssClass=\"sf-menu\">\n</asp:Menu>\n CssClass=\"sf-menu\" <ul> class=\"AspNet-Menu\" $('ul.AspNet-Menu').superfish(); superfish.css asp:Menu <ul>"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/103630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3742/"
] |
103,633
|
<p><a href="http://en.wikibooks.org/wiki/Combinatorics/Subsets_of_a_set-The_Binomial_Coefficient" rel="nofollow noreferrer">Pascal's rule</a> on counting the subset's of a set works great, when the set contains unique entities.</p>
<p>Is there a modification to this rule for when the set contains duplicate items?</p>
<p>For instance, when I try to find the count of the combinations of the letters A,B,C,D, it's easy to see that it's 1 + 4 + 6 + 4 + 1 (from Pascal's Triangle) = 16, or 15 if I remove the "use none of the letters" entry.</p>
<p>Now, what if the set of letters is A,B,B,B,C,C,D? Computing by hand, I can determine that the sum of subsets is: 1 + 4 + 8 + 11 + 11 + 8 + 4 + 1 = 48, but this doesn't conform to the Triangle I know.</p>
<p>Question: How do you modify Pascal's Triangle to take into account duplicate entities in the set?</p>
|
[
{
"answer_id": 104046,
"author": "Thomas Andrews",
"author_id": 7061,
"author_profile": "https://Stackoverflow.com/users/7061",
"pm_score": 2,
"selected": false,
"text": "p1^a1.p2^a2....pn^an\n"
},
{
"answer_id": 104091,
"author": "user11318",
"author_id": 11318,
"author_profile": "https://Stackoverflow.com/users/11318",
"pm_score": 3,
"selected": true,
"text": "(1 + x) (1 + x + x^2 + x^3) (1 + x + x^2) (1 + x)\n = (1 + 2x + 2x^2 + 2x^3 + x^4)(1 + 2x + 2x^2 + x^3)\n = 1 + 2x + 2x^2 + x^3 +\n 2x + 4x^2 + 4x^3 + 2x^4 +\n 2x^2 + 4x^3 + 4x^4 + 2x^5 +\n 2x^3 + 4x^4 + 4x^5 + 2x^6 +\n x^4 + 2x^5 + 2x^6 + x^7\n = 1 + 4x + 8x^2 + 11x^3 + 11x^4 + 8x^5 + 4x^6 + x^7\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/103633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13824/"
] |
103,654
|
<p>In several modern programming languages (including C++, Java, and C#), the language allows <a href="http://en.wikipedia.org/wiki/Integer_overflow" rel="noreferrer">integer overflow</a> to occur at runtime without raising any kind of error condition.</p>
<p>For example, consider this (contrived) C# method, which does not account for the possibility of overflow/underflow. (For brevity, the method also doesn't handle the case where the specified list is a null reference.)</p>
<pre class="lang-c# prettyprint-override"><code>//Returns the sum of the values in the specified list.
private static int sumList(List<int> list)
{
int sum = 0;
foreach (int listItem in list)
{
sum += listItem;
}
return sum;
}
</code></pre>
<p>If this method is called as follows:</p>
<pre class="lang-c# prettyprint-override"><code>List<int> list = new List<int>();
list.Add(2000000000);
list.Add(2000000000);
int sum = sumList(list);
</code></pre>
<p>An overflow will occur in the <code>sumList()</code> method (because the <code>int</code> type in C# is a 32-bit signed integer, and the sum of the values in the list exceeds the value of the maximum 32-bit signed integer). The sum variable will have a value of -294967296 (not a value of 4000000000); this most likely is not what the (hypothetical) developer of the sumList method intended.</p>
<p>Obviously, there are various techniques that can be used by developers to avoid the possibility of integer overflow, such as using a type like Java's <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigInteger.html" rel="noreferrer"><code>BigInteger</code></a>, or the <a href="http://msdn.microsoft.com/en-us/library/74b4xzyw.aspx" rel="noreferrer"><code>checked</code></a> keyword and <a href="http://msdn.microsoft.com/en-us/library/h25wtyxf.aspx" rel="noreferrer"><code>/checked</code></a> compiler switch in C#.</p>
<p>However, the question that I'm interested in is why these languages were designed to by default allow integer overflows to happen in the first place, instead of, for example, raising an exception when an operation is performed at runtime that would result in an overflow. It seems like such behavior would help avoid bugs in cases where a developer neglects to account for the possibility of overflow when writing code that performs an arithmetic operation that could result in overflow. (These languages could have included something like an "unchecked" keyword that could designate a block where integer overflow is permitted to occur without an exception being raised, in those cases where that behavior is explicitly intended by the developer; C# actually <a href="http://msdn.microsoft.com/en-us/library/a569z7k8.aspx" rel="noreferrer">does have this</a>.)</p>
<p>Does the answer simply boil down to performance -- the language designers didn't want their respective languages to default to having "slow" arithmetic integer operations where the runtime would need to do extra work to check whether an overflow occurred, on every applicable arithmetic operation -- and this performance consideration outweighed the value of avoiding "silent" failures in the case that an inadvertent overflow occurs?</p>
<p>Are there other reasons for this language design decision as well, other than performance considerations?</p>
|
[
{
"answer_id": 103711,
"author": "Doug T.",
"author_id": 8123,
"author_profile": "https://Stackoverflow.com/users/8123",
"pm_score": 4,
"selected": false,
"text": "int main()\n{\n uint32_t shipsHeadingInDegrees= 0;\n\n // Rotate by a bunch of degrees\n shipsHeadingInDegrees += 0x80000000; // 180 degrees\n shipsHeadingInDegrees += 0x80000000; // another 180 degrees, overflows \n shipsHeadingInDegrees += 0x80000000; // another 180 degrees\n\n // Ships heading now will be 180 degrees\n cout << \"Ships Heading Is\" << (double(shipsHeadingInDegrees) / double(0xffffffff)) * 360.0 << std::endl;\n\n}\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/103654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12484/"
] |
103,679
|
<p>First off: I'm using a rather obscure implementation of javascript embedded as a scripting engine for Adobe InDesign CS3. This implementation sometimes diverges from "standard" javascript, hence my problem.</p>
<p>I'm using <a href="http://ejohn.org/projects/javascript-diff-algorithm/" rel="nofollow noreferrer">John Resig's jsdiff library</a> (<a href="http://ejohn.org/files/jsdiff.js" rel="nofollow noreferrer">source here</a>) to compare selections of text between two documents. jsdiff uses vanilla objects as associative arrays to map a word from the text to another object. (See the "ns" and "os" variables in jsdiff.js, around line 129.)</p>
<p>My headaches start when the word "reflect" comes up in the text. "reflect" is a default, <em>read-only</em> property on <em>all</em> objects. When jsdiff tries to assign a value on the associative array to ns['reflect'], everything explodes.</p>
<p>My question: is there a way around this? Is there a way to do a hash table in javascript without using the obvious vanilla object?</p>
<p><strong>Ground rules:</strong> switching scripting engines isn't an option. :)</p>
|
[
{
"answer_id": 104018,
"author": "Joel Anair",
"author_id": 7441,
"author_profile": "https://Stackoverflow.com/users/7441",
"pm_score": 1,
"selected": false,
"text": "if(object.hasOwnProperty('testProperty')){\n // do something\n}\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/103679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18950/"
] |
103,725
|
<p>I'm working on a project that generates PDFs that can contain fairly complex math and science formulas. The text is rendered in Times New Roman, which has pretty good Unicode coverage, but not complete. We have a system in place to swap in a more Unicode complete font for code points that don't have a glyph in TNR (like most of the "stranger" math symbols,) but I can't seem to find a way to query the *.ttf file to see if a given glyph is present. So far, I've just hard-coded a lookup table of which code points are present, but I'd much prefer an automatic solution.</p>
<p>I'm using VB.Net in a web system under ASP.net, but solutions in any programming language/environment would be appreciated.</p>
<p>Edit: The win32 solution looks excellent, but the specific case I'm trying to solve is in an ASP.Net web system. Is there a way to do this without including the windows API DLLs into my web site?</p>
|
[
{
"answer_id": 103858,
"author": "Scott Nichols",
"author_id": 4299,
"author_profile": "https://Stackoverflow.com/users/4299",
"pm_score": 4,
"selected": false,
"text": "[DllImport(\"gdi32.dll\")]\npublic static extern uint GetFontUnicodeRanges(IntPtr hdc, IntPtr lpgs);\n\n[DllImport(\"gdi32.dll\")]\npublic extern static IntPtr SelectObject(IntPtr hDC, IntPtr hObject);\n\npublic struct FontRange\n{\n public UInt16 Low;\n public UInt16 High;\n}\n\npublic List<FontRange> GetUnicodeRangesForFont(Font font)\n{\n Graphics g = Graphics.FromHwnd(IntPtr.Zero);\n IntPtr hdc = g.GetHdc();\n IntPtr hFont = font.ToHfont();\n IntPtr old = SelectObject(hdc, hFont);\n uint size = GetFontUnicodeRanges(hdc, IntPtr.Zero);\n IntPtr glyphSet = Marshal.AllocHGlobal((int)size);\n GetFontUnicodeRanges(hdc, glyphSet);\n List<FontRange> fontRanges = new List<FontRange>();\n int count = Marshal.ReadInt32(glyphSet, 12);\n for (int i = 0; i < count; i++)\n {\n FontRange range = new FontRange();\n range.Low = (UInt16)Marshal.ReadInt16(glyphSet, 16 + i * 4);\n range.High = (UInt16)(range.Low + Marshal.ReadInt16(glyphSet, 18 + i * 4) - 1);\n fontRanges.Add(range);\n }\n SelectObject(hdc, old);\n Marshal.FreeHGlobal(glyphSet);\n g.ReleaseHdc(hdc);\n g.Dispose();\n return fontRanges;\n}\n\npublic bool CheckIfCharInFont(char character, Font font)\n{\n UInt16 intval = Convert.ToUInt16(character);\n List<FontRange> ranges = GetUnicodeRangesForFont(font);\n bool isCharacterPresent = false;\n foreach (FontRange range in ranges)\n {\n if (intval >= range.Low && intval <= range.High)\n {\n isCharacterPresent = true;\n break;\n }\n }\n return isCharacterPresent;\n}\n if (!CheckIfCharInFont(toCheck, theFont) {\n // not present\n}\n <DllImport(\"gdi32.dll\")> _\nPublic Shared Function GetFontUnicodeRanges(ByVal hds As IntPtr, ByVal lpgs As IntPtr) As UInteger\nEnd Function \n\n<DllImport(\"gdi32.dll\")> _\nPublic Shared Function SelectObject(ByVal hDc As IntPtr, ByVal hObject As IntPtr) As IntPtr\nEnd Function \n\nPublic Structure FontRange\n Public Low As UInt16\n Public High As UInt16\nEnd Structure \n\nPublic Function GetUnicodeRangesForFont(ByVal font As Font) As List(Of FontRange)\n Dim g As Graphics\n Dim hdc, hFont, old, glyphSet As IntPtr\n Dim size As UInteger\n Dim fontRanges As List(Of FontRange)\n Dim count As Integer\n\n g = Graphics.FromHwnd(IntPtr.Zero)\n hdc = g.GetHdc()\n hFont = font.ToHfont()\n old = SelectObject(hdc, hFont)\n size = GetFontUnicodeRanges(hdc, IntPtr.Zero)\n glyphSet = Marshal.AllocHGlobal(CInt(size))\n GetFontUnicodeRanges(hdc, glyphSet)\n fontRanges = New List(Of FontRange)\n count = Marshal.ReadInt32(glyphSet, 12)\n\n For i = 0 To count - 1\n Dim range As FontRange = New FontRange\n range.Low = Marshal.ReadInt16(glyphSet, 16 + (i * 4))\n range.High = range.Low + Marshal.ReadInt16(glyphSet, 18 + (i * 4)) - 1\n fontRanges.Add(range)\n Next\n\n SelectObject(hdc, old)\n Marshal.FreeHGlobal(glyphSet)\n g.ReleaseHdc(hdc)\n g.Dispose()\n\n Return fontRanges\nEnd Function \n\nPublic Function CheckIfCharInFont(ByVal character As Char, ByVal font As Font) As Boolean\n Dim intval As UInt16 = Convert.ToUInt16(character)\n Dim ranges As List(Of FontRange) = GetUnicodeRangesForFont(font)\n Dim isCharacterPresent As Boolean = False\n\n For Each range In ranges\n If intval >= range.Low And intval <= range.High Then\n isCharacterPresent = True\n Exit For\n End If\n Next range\n Return isCharacterPresent\nEnd Function \n"
},
{
"answer_id": 1278132,
"author": "FarmerDave",
"author_id": 156516,
"author_profile": "https://Stackoverflow.com/users/156516",
"pm_score": 0,
"selected": false,
"text": "Protected Function Unsign(ByVal Input As Int16) As UInt16\n If Input > -1 Then\n Return CType(Input, UInt16)\n Else\n Return UInt16.MaxValue - (Not Input)\n End If\nEnd Function\n For i As Integer = 0 To count - 1\n Dim range As FontRange = New FontRange\n range.Low = Unsign(Marshal.ReadInt16(glyphSet, 16 + (i * 4)))\n range.High = range.Low + Unsign(Marshal.ReadInt16(glyphSet, 18 + (i * 4)) - 1)\n fontRanges.Add(range)\nNext\n"
},
{
"answer_id": 11333802,
"author": "David Thielen",
"author_id": 509627,
"author_profile": "https://Stackoverflow.com/users/509627",
"pm_score": 2,
"selected": false,
"text": " [DllImport(\"gdi32.dll\", EntryPoint = \"CreateDC\", CharSet = CharSet.Auto, SetLastError = true)]\n private static extern IntPtr CreateDC(string lpszDriver, string lpszDeviceName, string lpszOutput, IntPtr devMode);\n\n [DllImport(\"gdi32.dll\", ExactSpelling = true, SetLastError = true)]\n private static extern bool DeleteDC(IntPtr hdc);\n\n [DllImport(\"Gdi32.dll\")]\n private static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj);\n\n [DllImport(\"Gdi32.dll\", CharSet = CharSet.Unicode)]\n private static extern int GetGlyphIndices(IntPtr hdc, [MarshalAs(UnmanagedType.LPWStr)] string lpstr, int c,\n Int16[] pgi, int fl);\n\n /// <summary>\n /// Returns true if the passed in string can be displayed using the passed in fontname. It checks the font to \n /// see if it has glyphs for all the chars in the string.\n /// </summary>\n /// <param name=\"fontName\">The name of the font to check.</param>\n /// <param name=\"text\">The text to check for glyphs of.</param>\n /// <returns></returns>\n public static bool CanDisplayString(string fontName, string text)\n {\n try\n {\n IntPtr hdc = CreateDC(\"DISPLAY\", null, null, IntPtr.Zero);\n if (hdc != IntPtr.Zero)\n {\n using (Font font = new Font(new FontFamily(fontName), 12, FontStyle.Regular, GraphicsUnit.Point))\n {\n SelectObject(hdc, font.ToHfont());\n int count = text.Length;\n Int16[] rtcode = new Int16[count];\n GetGlyphIndices(hdc, text, count, rtcode, 0xffff);\n DeleteDC(hdc);\n\n foreach (Int16 code in rtcode)\n if (code == 0)\n return false;\n }\n }\n }\n catch (Exception)\n {\n // nada - return true\n Trap.trap();\n }\n return true;\n }\n"
},
{
"answer_id": 55349185,
"author": "brewmanz",
"author_id": 2821586,
"author_profile": "https://Stackoverflow.com/users/2821586",
"pm_score": 0,
"selected": false,
"text": " Dim fnt As System.Drawing.Font, size_M As Drawing.Size, size_i As Drawing.Size, size_HTab As Drawing.Size, isMonospace As Boolean\n Dim ifc = New Drawing.Text.InstalledFontCollection\n Dim bm As Drawing.Bitmap = New Drawing.Bitmap(640, 64), gr = Drawing.Graphics.FromImage(bm)\n Dim tf As Windows.Media.Typeface, gtf As Windows.Media.GlyphTypeface = Nothing, ok As Boolean, gtfName = \"\"\n\n For Each item In ifc.Families\n 'TestContext_WriteTimedLine($\"N={item.Name}.\")\n fnt = New Drawing.Font(item.Name, 24.0)\n Assert.IsNotNull(fnt)\n\n tf = New Windows.Media.Typeface(item.Name)\n Assert.IsNotNull(tf, $\"item.Name={item.Name}\")\n\n size_M = System.Windows.Forms.TextRenderer.MeasureText(\"M\", fnt)\n size_i = System.Windows.Forms.TextRenderer.MeasureText(\"i\", fnt)\n size_HTab = System.Windows.Forms.TextRenderer.MeasureText(ChrW(&H2409), fnt)\n isMonospace = size_M.Width = size_i.Width\n Assert.AreEqual(size_M.Height, size_i.Height, $\"fnt={fnt.Name}\")\n\n If isMonospace Then\n\n gtfName = \"-\"\n ok = tf.TryGetGlyphTypeface(gtf)\n If ok Then\n Assert.AreEqual(True, ok, $\"item.Name={item.Name}\")\n Assert.IsNotNull(gtf, $\"item.Name={item.Name}\")\n gtfName = $\"{gtf.FamilyNames(Globalization.CultureInfo.CurrentUICulture)}\"\n\n Assert.AreEqual(True, gtf.CharacterToGlyphMap().ContainsKey(AscW(\"M\")), $\"item.Name={item.Name}\")\n Assert.AreEqual(True, gtf.CharacterToGlyphMap().ContainsKey(AscW(\"i\")), $\"item.Name={item.Name}\")\n\n Dim t = 0, nMin = &HFFFF, nMax = 0\n For n = 0 To &HFFFF\n If gtf.CharacterToGlyphMap().ContainsKey(n) Then\n If n < nMin Then nMin = n\n If n > nMax Then nMax = n\n t += 1\n End If\n Next\n gtfName &= $\",[x{nMin:X}-x{nMax:X}]#{t}\"\n\n ok = gtf.CharacterToGlyphMap().ContainsKey(AscW(ChrW(&H2409)))\n If ok Then\n gtfName &= \",U+2409\"\n End If\n ok = gtf.CharacterToGlyphMap().ContainsKey(AscW(ChrW(&H2026)))\n If ok Then\n gtfName &= \",U+2026\"\n End If\n End If\n\n Debug.WriteLine($\"{IIf(isMonospace, \"*M*\", \"\")} N={fnt.Name}, gtf={gtfName}.\")\n gr.Clear(Drawing.Color.White)\n gr.DrawString($\"Mi{ChrW(&H2409)} {fnt.Name}\", fnt, New Drawing.SolidBrush(Drawing.Color.Black), 10, 10)\n bm.Save($\"{fnt.Name}_MiHT.bmp\")\n End If\n Next\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/103725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19074/"
] |
103,727
|
<p>As an example, Google App Engine uses Google Datastore, not a standard database, to store data. Does anybody have any tips for using Google Datastore instead of databases? It seems I've trained my mind to think 100% in object relationships that map directly to table structures, and now it's hard to see anything differently. I can understand some of the benefits of Google Datastore (e.g. performance and the ability to distribute data), but some good database functionality is sacrificed (e.g. joins).</p>
<p>Does anybody who has worked with Google Datastore or BigTable have any good advice to working with them?</p>
|
[
{
"answer_id": 711322,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "class League(BaseModel):\n name = db.StringProperty() \n managers = db.ListProperty(db.Key) #all the users who can view/edit this league\n coaches = db.ListProperty(db.Key) #all the users who are able to view this league\n\n def get_managers(self):\n # This returns the models themselves, not just the keys that are stored in teams\n return UserPrefs.get(self.managers)\n\n def get_coaches(self):\n # This returns the models themselves, not just the keys that are stored in teams\n return UserPrefs.get(self.coaches) \n\n def __str__(self):\n return self.name\n\n # Need to delete all the associated games, teams and players\n def delete(self):\n for player in self.leagues_players:\n player.delete()\n for game in self.leagues_games:\n game.delete()\n for team in self.leagues_teams:\n team.delete() \n super(League, self).delete()\n\nclass UserPrefs(db.Model):\n user = db.UserProperty()\n league_ref = db.ReferenceProperty(reference_class=League,\n collection_name='users') #league the users are managing\n\n def __str__(self):\n return self.user.nickname\n\n # many-to-many relationship, a user can coach many leagues, a league can be\n # coached by many users\n @property\n def managing(self):\n return League.gql('WHERE managers = :1', self.key())\n\n @property\n def coaching(self):\n return League.gql('WHERE coaches = :1', self.key())\n\n # remove all references to me when I'm deleted\n def delete(self):\n for manager in self.managing:\n manager.managers.remove(self.key())\n manager.put()\n for coach in self.managing:\n coach.coaches.remove(self.key())\n coaches.put() \n super(UserPrefs, self).delete() \n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/103727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/681/"
] |
103,765
|
<p>Here's the situation: I have a label's text set, immediately followed by a response.redirect() call as follows (this is just an example, but I believe it describes my situation accurately):</p>
<p>aspx:</p>
<pre><code><asp:Label runat="server" Text="default text" />
</code></pre>
<p>Code-behind (code called on an onclick event):</p>
<pre><code>Label.Text = "foo";
Response.Redirect("Default.aspx");
</code></pre>
<p>When the page renders, the label says "default text". What do I need to do differently? My understanding was that such changes would be done automatically behind the scenes, but apparently, not in this case. Thanks.</p>
<p>For a little extra background, the code-behind snippet is called inside a method that's invoked upon an onclick event. There is more to it, but I only included that which is of interest to this issue.</p>
|
[
{
"answer_id": 103816,
"author": "Adrian Clark",
"author_id": 148,
"author_profile": "https://Stackoverflow.com/users/148",
"pm_score": 2,
"selected": false,
"text": "Response.Redirect Response.Redirect"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/103765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13578/"
] |
103,766
|
<p>I need to store user entered changes to a particular table, but not show those changes until they have been viewed and approved by an administrative user. While those changes are still in a pending state, I would still display the old version of the data. What would be the best way of storing these changes waiting for approval?</p>
<p>I have thought of several ways, but can't figure out what is the best method. This is a very small web app. One way would be to have a PendingChanges table that mimics the other table's schema, and then once the change is approved, I could update the real table with the information. Another approach would be to do some sort of record versioning where I store multiple versions of the data in the table and then always pull the record with the highest version number that has been marked approved. That would limit the number of extra tables (I need to do this for multiple tables), but would require me to do extra processing every time I pull out a set of records to make sure I get the right ones.</p>
<p>Any personal experiences with these methods or others that might be good?</p>
<p>Update: Just to clarify, in this particular situation I am not interested so much in historical data. I just need some way of approving any changes that are made by a user before they go live on the site. So, a user will edit their "profile" and then an administrator will look at that modification and approve it. Once approved, that will become the displayed value and the old version does not need to be kept.</p>
<p>Anybody tried the solution below where you store pending changes from any table that needs to track them as XML in a special PendingChanges table? Each record would have a column that said which table the changes were for, a column that maybe stored the id of the record that would be changed (null if it's a new record), a datetime column to store when the change was made, and a column to store the xml of the changed record (could maybe serialize my data object). Since I don't need history, after a change was approved, the real table would be updated and the PendingChange record could be deleted.</p>
<p>Any thoughts about that method? </p>
|
[
{
"answer_id": 104402,
"author": "borjab",
"author_id": 16206,
"author_profile": "https://Stackoverflow.com/users/16206",
"pm_score": 2,
"selected": false,
"text": " CREATE OR REPLACE VIEW AS \n\n SELECT * FROM my_table where approved = 1\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/103766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19090/"
] |
103,785
|
<p>I've found that on some occasions I can edit the source while debugging. Are there any other advantages of using the Visual Studio built-in webserver instead of a virtual directory in IIS?</p>
<p>I'm using Windows XP on my development environment, and a local instance of IIS 5. I work on several projects, so I use multiple virtual directories to manage all the different sites.</p>
<p>Are there any disadvantages?</p>
|
[
{
"answer_id": 103879,
"author": "Simon_Weaver",
"author_id": 16940,
"author_profile": "https://Stackoverflow.com/users/16940",
"pm_score": 3,
"selected": false,
"text": "// http://localhost:52632/main//images/logo.jpg //"
},
{
"answer_id": 103959,
"author": "Simon_Weaver",
"author_id": 16940,
"author_profile": "https://Stackoverflow.com/users/16940",
"pm_score": 2,
"selected": false,
"text": "http://simon-laptop:37473/app1 http://ipv4.fiddler:37473"
},
{
"answer_id": 104172,
"author": "Doron Yaacoby",
"author_id": 3389,
"author_profile": "https://Stackoverflow.com/users/3389",
"pm_score": 0,
"selected": false,
"text": "\\aspnet_client"
},
{
"answer_id": 105303,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "IPrincipal IIdentity AppDomains"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/103785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5018/"
] |
103,791
|
<p>A coworker has been struggling with this problem.</p>
<p>The desired result is an installable plugin for Notes that will add a button emails with attachments that will let users save the attachment to a document management system.</p>
<p>Finding documentation on doing this for Notes has been an uphill battle to say the least.</p>
<p>Writing the actual java to do the work isn't a problem, but figuring out how to extend Notes is.</p>
<p>So, is there a way to add a button/icon to the toolbar, or is it just a matter of adding a new toolbar? If we add a new toolbar then can we make it only visible (or just grey it out otherwise) when no email is open?</p>
|
[
{
"answer_id": 1063575,
"author": "stwissel",
"author_id": 131021,
"author_profile": "https://Stackoverflow.com/users/131021",
"pm_score": 0,
"selected": false,
"text": "@Command([ToolsRunMacro];\"(ExportDocumentsTo[yourSystemNameHere])\")\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/103791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2719/"
] |
103,829
|
<p>Given the following:</p>
<pre><code>declare @a table
(
pkid int,
value int
)
declare @b table
(
otherID int,
value int
)
insert into @a values (1, 1000)
insert into @a values (1, 1001)
insert into @a values (2, 1000)
insert into @a values (2, 1001)
insert into @a values (2, 1002)
insert into @b values (-1, 1000)
insert into @b values (-1, 1001)
insert into @b values (-1, 1002)
</code></pre>
<p>How do I query for all the values in @a that completely match up with @b? </p>
<p><code>{@a.pkid = 1, @b.otherID = -1}</code> would not be returned (only 2 of 3 values match)</p>
<p><code>{@a.pkid = 2, @b.otherID = -1}</code> would be returned (3 of 3 values match)</p>
<p>Refactoring tables can be an option.</p>
<p><strong>EDIT:</strong> I've had success with the answers from James and Tom H. </p>
<p>When I add another case in @b, they fall a little short.</p>
<pre><code>insert into @b values (-2, 1000)
</code></pre>
<p>Assuming this should return two additional rows (<code>{@a.pkid = 1, @b.otherID = -2}</code> and <code>{@a.pkid = 2, @b.otherID = -2}</code>, it doesn't work. However, for my project this is not an issue.</p>
|
[
{
"answer_id": 103910,
"author": "Cruachan",
"author_id": 7315,
"author_profile": "https://Stackoverflow.com/users/7315",
"pm_score": 0,
"selected": false,
"text": "create view qryMyUinion as\nselect * from table1 \nunion all\nselect * from table2\n select count( * ), [field list here] \nfrom qryMyUnion\ngroup by [field list here]\nhaving count( * ) > 1\n"
},
{
"answer_id": 104001,
"author": "James",
"author_id": 2719,
"author_profile": "https://Stackoverflow.com/users/2719",
"pm_score": 4,
"selected": true,
"text": "SELECT a.pkId,b.otherId FROM\n (SELECT a.pkId,CHECKSUM_AGG(DISTINCT a.value) as 'ValueHash' FROM @a a GROUP BY a.pkId) a\n INNER JOIN (SELECT b.otherId,CHECKSUM_AGG(DISTINCT b.value) as 'ValueHash' FROM @b b GROUP BY b.otherId) b\nON a.ValueHash = b.ValueHash\n"
},
{
"answer_id": 104007,
"author": "Dave DuPlantis",
"author_id": 8174,
"author_profile": "https://Stackoverflow.com/users/8174",
"pm_score": 0,
"selected": false,
"text": "select \n a.pkid,\n a.value\nfrom\n @a a\nwhere\n a.pkid in\n (\n select\n pkid\n from\n (\n select \n c.pkid,\n c.otherid,\n count(*) matching_count\n from \n (\n select \n a.pkid,\n a.value,\n b.otherid\n from \n @a a inner join @b b \n on a.value = b.value\n ) c\n group by \n c.pkid,\n c.otherid\n ) d\n inner join\n (\n select \n b.otherid,\n count(*) b_record_count\n from\n @b b\n group by\n b.otherid\n ) e\n on d.otherid = e.otherid\n and d.matching_count = e.b_record_count\n inner join\n (\n select \n a.pkid match_pkid,\n count(*) a_record_count\n from\n @a a\n group by\n a.pkid\n ) f\n on d.pkid = f.match_pkid\n and d.matching_count = f.a_record_count\n )\n"
},
{
"answer_id": 104049,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 1,
"selected": false,
"text": "SELECT\n SQ1.pkid\nFROM\n (\n SELECT\n a.pkid, COUNT(*) AS cnt\n FROM\n @a AS a\n GROUP BY\n a.pkid\n ) SQ1\nINNER JOIN\n (\n SELECT\n a1.pkid, b1.otherID, COUNT(*) AS cnt\n FROM\n @a AS a1\n INNER JOIN @b AS b1 ON b1.value = a1.value\n GROUP BY\n a1.pkid, b1.otherID\n ) SQ2 ON\n SQ2.pkid = SQ1.pkid AND\n SQ2.cnt = SQ1.cnt\nINNER JOIN\n (\n SELECT\n b2.otherID, COUNT(*) AS cnt\n FROM\n @b AS b2\n GROUP BY\n b2.otherID\n ) SQ3 ON\n SQ3.otherID = SQ2.otherID AND\n SQ3.cnt = SQ1.cnt\n"
},
{
"answer_id": 104064,
"author": "Dave Jackson",
"author_id": 12328,
"author_profile": "https://Stackoverflow.com/users/12328",
"pm_score": -1,
"selected": false,
"text": "Select * -- all columns but only from #a\nfrom #a \ninner join #b \non #a.value = #b.value -- only return matching rows\nwhere #a.pkid = 2\n"
},
{
"answer_id": 104204,
"author": "boes",
"author_id": 17746,
"author_profile": "https://Stackoverflow.com/users/17746",
"pm_score": 2,
"selected": false,
"text": "select A.pkid, B.otherId\n from @a A, @b B \n where A.value = B.value\n group by A.pkid, B.otherId\n having count(B.value) = (\n select count(*) from @b BB where B.otherId = BB.otherId)\n"
},
{
"answer_id": 104240,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "select a.*\nfrom @a a \ninner join @b b on a.value = b.value\n"
},
{
"answer_id": 104327,
"author": "user19143",
"author_id": 19143,
"author_profile": "https://Stackoverflow.com/users/19143",
"pm_score": 1,
"selected": false,
"text": "declare @a table\n(\n pkid int,\n value int\n)\n\ndeclare @b table\n(\n otherID int,\n value int\n)\n\n\ninsert into @a values (1, 1000)\ninsert into @a values (1, 1001)\n\ninsert into @a values (2, 1000)\ninsert into @a values (2, 1001)\ninsert into @a values (2, 1002)\n\ninsert into @a values (3, 1000)\ninsert into @a values (3, 1001)\ninsert into @a values (3, 1001)\n\ninsert into @a values (4, 1000)\ninsert into @a values (4, 1000)\ninsert into @a values (4, 1001)\n\n\ninsert into @b values (-1, 1000)\ninsert into @b values (-1, 1001)\ninsert into @b values (-1, 1002)\n\ninsert into @b values (-2, 1001)\ninsert into @b values (-2, 1002)\n\ninsert into @b values (-3, 1000)\ninsert into @b values (-3, 1001)\ninsert into @b values (-3, 1001)\n\n\n\nSELECT Matches.pkid, Matches.otherId\nFROM\n(\n SELECT a.pkid, b.otherId, n = COUNT(*)\n FROM @a a\n INNER JOIN @b b\n ON a.Value = b.Value\n GROUP BY a.pkid, b.otherId\n) AS Matches\n\nINNER JOIN \n(\n SELECT\n pkid,\n n = COUNT(DISTINCT value)\n FROM @a\n GROUP BY pkid\n) AS ACount\nON Matches.pkid = ACount.pkid\n\nINNER JOIN\n(\n SELECT\n otherId,\n n = COUNT(DISTINCT value)\n FROM @b\n GROUP BY otherId\n) AS BCount\n ON Matches.otherId = BCount.otherId\n\nWHERE Matches.n = ACount.n AND Matches.n = BCount.n\n"
},
{
"answer_id": 105108,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "declare @a table( pkid int, value int)\ndeclare @b table( otherID int, value int)\n\ninsert into @a values (1, 1000)\ninsert into @a values (1, 1001)\ninsert into @a values (2, 1000)\ninsert into @a values (2, 1001)\ninsert into @a values (2, 1002)\ninsert into @a values (3, 1000) \ninsert into @a values (3, 1001)\ninsert into @a values (4, 1000)\ninsert into @a values (4, 1001)\ninsert into @b values (-1, 1000)\ninsert into @b values (-1, 1001)\ninsert into @b values (-1, 1002)\ninsert into @b values (-2, 1001)\ninsert into @b values (-2, 1002)\ninsert into @b values (-3, 1000)\ninsert into @b values (-3, 1001)\n\n select cntok.cntid1 as cntid1, cntok.cntid2 as cntid2\n from\n (select cnt.cnt, cnt.cntid1, cnt.cntid2 from\n (select acnt.cnt as cnt, acnt.cntid as cntid1, bcnt.cntid as cntid2 from\n (select count(pkid) as cnt, pkid as cntid from @a group by pkid)\n as acnt\n full join \n (select count(otherID) as cnt, otherID as cntid from @b group by otherID)\n as bcnt\n on acnt.cnt = bcnt.cnt)\n as cnt\n where cntid1 is not null and cntid2 is not null)\n as cntok \ninner join \n(select count(1) as cnt, cnta.cntid1 as cntid1, cnta.cntid2 as cntid2\nfrom\n (select cnt, cntid1, cntid2, a.value as value1 \n from\n (select cnt.cnt, cnt.cntid1, cnt.cntid2 from\n (select acnt.cnt as cnt, acnt.cntid as cntid1, bcnt.cntid as cntid2 from\n (select count(pkid) as cnt, pkid as cntid from @a group by pkid)\n as acnt\n full join \n (select count(otherID) as cnt, otherID as cntid from @b group by otherID)\n as bcnt\n on acnt.cnt = bcnt.cnt)\n as cnt\n where cntid1 is not null and cntid2 is not null)\n as cntok \n inner join @a as a on a.pkid = cntok.cntid1)\n as cnta\n inner join\n\n (select cnt, cntid1, cntid2, b.value as value2 \n from\n (select cnt.cnt, cnt.cntid1, cnt.cntid2 from\n (select acnt.cnt as cnt, acnt.cntid as cntid1, bcnt.cntid as cntid2 from\n (select count(pkid) as cnt, pkid as cntid from @a group by pkid)\n as acnt\n full join \n (select count(otherID) as cnt, otherID as cntid from @b group by otherID)\n as bcnt\n on acnt.cnt = bcnt.cnt)\n as cnt\n where cntid1 is not null and cntid2 is not null)\n as cntok \n inner join @b as b on b.otherid = cntok.cntid2)\n as cntb\n on cnta.cntid1 = cntb.cntid1 and cnta.cntid2 = cntb.cntid2 and cnta.value1 = cntb.value2\n group by cnta.cntid1, cnta.cntid2) \n as cntequals\n on cntok.cnt = cntequals.cnt and cntok.cntid1 = cntequals.cntid1 and cntok.cntid2 = cntequals.cntid2\n"
},
{
"answer_id": 105562,
"author": "user19164",
"author_id": 19164,
"author_profile": "https://Stackoverflow.com/users/19164",
"pm_score": 1,
"selected": false,
"text": " select\n matches.pkid\n ,matches.otherID\nfrom\n(\n select \n a.pkid\n ,b.otherID\n ,count(1) as cnt\n from @a a\n inner join @b b\n on b.value = a.value\n group by \n a.pkid\n ,b.otherID\n) as matches\ninner join\n(\n select\n otherID\n ,count(1) as cnt\n from @b\n group by otherID\n) as b_counts\non b_counts.otherID = matches.otherID\nwhere matches.cnt = b_counts.cnt\n"
},
{
"answer_id": 713969,
"author": "Quassnoi",
"author_id": 55159,
"author_profile": "https://Stackoverflow.com/users/55159",
"pm_score": 3,
"selected": false,
"text": "TOP 1 COUNT (-2, 1000) SELECT *\nFROM (\n SELECT ab.pkid, ab.otherID,\n (\n SELECT TOP 1 COALESCE(ai.value, bi.value)\n FROM (\n SELECT *\n FROM @a aii\n WHERE aii.pkid = ab.pkid\n ) ai\n FULL OUTER JOIN\n (\n SELECT *\n FROM @b bii\n WHERE bii.otherID = ab.otherID\n ) bi\n ON ai.value = bi.value\n WHERE ai.pkid IS NULL OR bi.otherID IS NULL\n ) unmatch\n FROM\n (\n SELECT DISTINCT pkid, otherid\n FROM @a a , @b b\n ) ab\n ) q\nWHERE unmatch IS NOT NULL\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/103829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4068/"
] |
103,844
|
<p>List Comprehension for me seems to be like the opaque block of granite that regular expressions are for me. I need pointers.</p>
<p>Say, I have a 2D list:</p>
<pre><code>li = [[0,1,2],[3,4,5],[6,7,8]]
</code></pre>
<p>I would like to merge this either into one long list</p>
<pre><code>li2 = [0,1,2,3,4,5,6,7,8]
</code></pre>
<p>or into a string with separators:</p>
<pre><code>s = "0,1,2,3,4,5,6,7,8"
</code></pre>
<p>Really, I'd like to know how to do both.</p>
|
[
{
"answer_id": 103873,
"author": "joeld",
"author_id": 19104,
"author_profile": "https://Stackoverflow.com/users/19104",
"pm_score": 0,
"selected": false,
"text": "import itertools\nitertools.flatten( li )\n"
},
{
"answer_id": 103883,
"author": "Eli Bendersky",
"author_id": 8206,
"author_profile": "https://Stackoverflow.com/users/8206",
"pm_score": 0,
"selected": false,
"text": "join"
},
{
"answer_id": 103886,
"author": "Allen",
"author_id": 6043,
"author_profile": "https://Stackoverflow.com/users/6043",
"pm_score": 3,
"selected": false,
"text": "li2 = []\nfor sublist in li:\n li2.extend(sublist)\n itertools chain import itertools\nli2 = list(itertools.chain(*li))\n s = \",\".join(itertools.chain(*li))\n"
},
{
"answer_id": 103887,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 1,
"selected": false,
"text": ">>> print ','.join(str(x) for x in li2)\n\"0,1,2,3,4,5,6,7,8\"\n >>> print \",\".join([\",\".join(str(x) for x in li])\n\"0,1,2,3,4,5,6,7,8\"\n >>> import itertools\n>>> print itertools.flatten(li)\n[0,1,2,3,4,5,6,7,8]\n>>> print \",\".join(str(x) for x in itertools.flatten(li))\n\"0,1,2,3,4,5,6,7,8\"\n"
},
{
"answer_id": 103890,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 3,
"selected": false,
"text": "li2 = sum(li, [])\n s = ','.join(li2)\n sum reduce"
},
{
"answer_id": 103895,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 6,
"selected": true,
"text": "[ item for innerlist in outerlist for item in innerlist ]\n ','.join(str(item) for innerlist in outerlist for item in innerlist)\n for innerlist in outerlist:\n for item in innerlist:\n ...\n"
},
{
"answer_id": 103908,
"author": "Martin Cote",
"author_id": 9936,
"author_profile": "https://Stackoverflow.com/users/9936",
"pm_score": 3,
"selected": false,
"text": "li=[[0,1,2],[3,4,5],[6,7,8]]\nli2 = [ y for x in li for y in x]\n ','.join(map(str,li2))\n"
},
{
"answer_id": 244477,
"author": "Alex",
"author_id": 30181,
"author_profile": "https://Stackoverflow.com/users/30181",
"pm_score": 0,
"selected": false,
"text": "import numpy\nli = [[0,1,2],[3,4,5],[6,7,8]]\nli2=li[0] #first element of array to merge\ni=1 \nwhile i<len(li):\n li2=numpy.concatenate((li2,li[i]))\n i+=1\nprint li2\n"
},
{
"answer_id": 65776145,
"author": "Franco",
"author_id": 13435688,
"author_profile": "https://Stackoverflow.com/users/13435688",
"pm_score": 0,
"selected": false,
"text": "def convert2DArrtostring(ndArr):\n '''converts 2D array to string'''\n arr_str = \"[\"\n for i in ndArr:\n arr_str += \"[\"\n for j in i:\n arr_str += str(j) + \" \"\n arr_str += \"]\\n\"\n arr_str += \"]\"\n return arr_str\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/103844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/577/"
] |
103,918
|
<p>I am trying to install the ibm_db gem so that I can access DB2 from Ruby. When I try:</p>
<pre><code>sudo gem install ibm_db
</code></pre>
<p>I get the following request for clarification:</p>
<pre>
Select which gem to install for your platform (i486-linux)
1. ibm_db 0.10.0 (ruby)
2. ibm_db 0.10.0 (mswin32)
3. ibm_db 0.9.5 (mswin32)
4. ibm_db 0.9.5 (ruby)
5. Skip this gem
6. Cancel installation
</pre>
<p>I am always going to be installing the linux version (which I assume is the "ruby" version), so is there a way to pick which one I will install straight from the gem install command?</p>
<p>The reason this is a problem is that I need to automate this install via a bash script, so I would like to select that I want the "ruby" version ahead of time.</p>
|
[
{
"answer_id": 104102,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 1,
"selected": false,
"text": "sudo gem install --platform ruby ibm_db\n gem help install\n"
},
{
"answer_id": 104163,
"author": "paradoja",
"author_id": 18396,
"author_profile": "https://Stackoverflow.com/users/18396",
"pm_score": 3,
"selected": true,
"text": "sudo gem install ibm_db <<heredoc\n 1\nheredoc\n"
},
{
"answer_id": 104195,
"author": "Josti",
"author_id": 11231,
"author_profile": "https://Stackoverflow.com/users/11231",
"pm_score": 0,
"selected": false,
"text": "sudo gem install ibm_db < <(echo 1)\n"
},
{
"answer_id": 104419,
"author": "Charles Roper",
"author_id": 1944,
"author_profile": "https://Stackoverflow.com/users/1944",
"pm_score": 0,
"selected": false,
"text": "$ sudo gem update --system\n"
},
{
"answer_id": 104490,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 0,
"selected": false,
"text": "sudo gem install path/to/ibm_db-0.10.0.gem\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/103918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
] |
103,919
|
<p>I want to store the current URL in a session variable to reference the previous visited page.</p>
<p>If I store every URL (via a before_filter on ApplicationController), also actions which end in a redirect (create, update, etc) are considered as last visited page.</p>
<p>Is there a way to tell Rails only to execute a function if a template is rendered??</p>
<p><strong>Update</strong></p>
<p>Thanks for the after_filter tip... having written so many before_filters I didn't see the obvious. But the Trick with @performed_redirect doesn't work-</p>
<p>This is what I got so far</p>
<pre><code>class ApplicationController < ActionController::Base
after_filter :set_page_as_previous_page
def set_page_as_previous_page
unless @performed_redirect
flash[:previous_page] = request.request_uri
else
flash[:previous_page] = flash[:previous_page]
end
end
end
</code></pre>
<p>I need to implement a "Go Back" Link, without the use of Javascript, the HTTP Referer. Sorry If I should have mentioned that, I appreciate your help!</p>
<p><strong>Update 2</strong></p>
<p>I found a solution, which is not very elegant and only works if your app follows the standard naming scheme</p>
<pre><code>def after_filter
if File.exists?(File.join(Rails.root,"app","views", controller_path, action_name+".html.erb"))
flash[:previous_page] = request.request_uri
else
flash[:previous_page] = flash[:previous_page]
end
end
</code></pre>
|
[
{
"answer_id": 103975,
"author": "kch",
"author_id": 13989,
"author_profile": "https://Stackoverflow.com/users/13989",
"pm_score": 0,
"selected": false,
"text": "@performed_render\n@performed_redirect\n after_filter"
},
{
"answer_id": 104460,
"author": "kch",
"author_id": 13989,
"author_profile": "https://Stackoverflow.com/users/13989",
"pm_score": 3,
"selected": true,
"text": "@performed_redirect class RedirController < ApplicationController\n after_filter :redir_raise\n\n def raise_true\n redirect_to :action => :whatever\n end\n\n def raise_false\n render :text => 'foo'\n end\n\n private\n\n def redir_raise\n raise @performed_redirect.to_s\n end\n\nend\n flash[:previous_page] = flash[:previous_page]\n flash.keep :previous_page\n"
},
{
"answer_id": 803093,
"author": "Travis",
"author_id": 524373,
"author_profile": "https://Stackoverflow.com/users/524373",
"pm_score": 1,
"selected": false,
"text": "class ApplicationController < ActionController::Base\n\n after_filter :set_page_as_previous_page\n\n def set_page_as_previous_page\n unless 302 == request.status #redirecting\n flash[:previous_page] = request.request_uri\n else\n flash[:previous_page] = flash[:previous_page]\n end\n end\n\nend\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/103919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11231/"
] |
103,938
|
<p>I've been doing code review (mostly using tools like FindBugs) of one of our pet projects and FindBugs marked following code as erroneous (pseudocode):</p>
<pre><code>Connection conn = dataSource.getConnection();
try{
PreparedStatement stmt = conn.prepareStatement();
//initialize the statement
stmt.execute();
ResultSet rs = stmt.getResultSet();
//get data
}finally{
conn.close();
}
</code></pre>
<p>The error was that this code might not release resources. I figured out that the ResultSet and Statement were not closed, so I closed them in finally:</p>
<pre><code>finally{
try{
rs.close()
}catch(SqlException se){
//log it
}
try{
stmt.close();
}catch(SqlException se){
//log it
}
conn.close();
}
</code></pre>
<p>But I encountered the above pattern in many projects (from quite a few companies), and no one was closing ResultSets or Statements.</p>
<p>Did you have troubles with ResultSets and Statements not being closed when the Connection is closed? </p>
<p>I found only <a href="http://www.theserverside.com/discussions/thread.tss?thread_id=41036" rel="noreferrer">this</a> and it refers to Oracle having problems with closing ResultSets when closing Connections (we use Oracle db, hence my corrections). java.sql.api says nothing in Connection.close() javadoc.</p>
|
[
{
"answer_id": 103994,
"author": "neu242",
"author_id": 13365,
"author_profile": "https://Stackoverflow.com/users/13365",
"pm_score": 5,
"selected": false,
"text": "\"ORA-01000: maximum open cursors exceeded\"\n"
},
{
"answer_id": 104123,
"author": "Aaron",
"author_id": 19130,
"author_profile": "https://Stackoverflow.com/users/19130",
"pm_score": 7,
"selected": true,
"text": "connection.close()"
},
{
"answer_id": 104830,
"author": "Stefan Schweizer",
"author_id": 13559,
"author_profile": "https://Stackoverflow.com/users/13559",
"pm_score": 4,
"selected": false,
"text": "public static void closeEverything(ResultSet rs, Statement stmt,\n Connection con) {\n if (rs != null) {\n try {\n rs.close();\n } catch (SQLException e) {\n }\n }\n if (stmt != null) {\n try {\n stmt.close();\n } catch (SQLException e) {\n }\n }\n if (con != null) {\n try {\n con.close();\n } catch (SQLException e) {\n }\n }\n}\n"
},
{
"answer_id": 105088,
"author": "Konrad",
"author_id": 8143,
"author_profile": "https://Stackoverflow.com/users/8143",
"pm_score": 3,
"selected": false,
"text": "<resource-ref>\n <description>My Database</description>\n <res-ref-name>jdbc/jndi/pathtodatasource</res-ref-name>\n <res-type>javax.sql.DataSource</res-type>\n <res-auth>Container</res-auth>\n <res-sharing-scope>Unshareable</res-sharing-scope>\n</resource-ref>\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/103938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7918/"
] |
103,945
|
<p>I've implemented a custom item renderer that I'm using with a combobox on a flex project I'm working on. It displays and icon and some text for each item. The only problem is that when the text is long the width of the menu is not being adjusted properly and the text is being truncated when displayed. I've tried tweaking all of the obvious properties to alleviate this problem but have not had any success. Does anyone know how to make the combobox menu width scale appropriately to whatever data it's rendering?</p>
<p>My custom item renderer implementation is:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml"
styleName="plain" horizontalScrollPolicy="off">
<mx:Image source="{data.icon}" />
<mx:Label text="{data.label}" fontSize="11" fontWeight="bold" truncateToFit="false"/>
</mx:HBox>
</code></pre>
<p>And my combobox uses it like so:</p>
<pre><code> <mx:ComboBox id="quicklinksMenu" change="quicklinkHandler(quicklinksMenu.selectedItem.data);" click="event.stopImmediatePropagation();" itemRenderer="renderers.QuickLinkItemRenderer" width="100%"/>
</code></pre>
<p>EDIT:
I should clarify on thing: I can set the dropdownWidth property on the combobox to some arbitrarily large value - this will make everything fit, but it will be too wide. Since the data being displayed in this combobox is generic, I want it to automatically size itself to the largest element in the dataprovider (the flex documentation says it will do this, but I have the feeling my custom item renderer is somehow breaking that behavior)</p>
|
[
{
"answer_id": 104314,
"author": "defmeta",
"author_id": 10875,
"author_profile": "https://Stackoverflow.com/users/10875",
"pm_score": 0,
"selected": false,
"text": "protected override function calculatePreferredSizeFromData(count:int):Object\n"
},
{
"answer_id": 1432078,
"author": "Mario Ruggier",
"author_id": 2185854,
"author_profile": "https://Stackoverflow.com/users/2185854",
"pm_score": 0,
"selected": false,
"text": "mx.controls.Text dropdownFactory.variableRowHeight=true comboBox.dropdownWidth comboBox.widt"
},
{
"answer_id": 1688600,
"author": "Ryan Lynch",
"author_id": 194784,
"author_profile": "https://Stackoverflow.com/users/194784",
"pm_score": 0,
"selected": false,
"text": "measure mx.controls.ComboBase measuredMinWidth // Text fields have 4 pixels of white space added to each side\n // by the player, so fudge this amount.\n // If we don't have any data, measure a single space char for defaults\n if (collection && collection.length > 0)\n {\n var prefSize:Object = calculatePreferredSizeFromData(collection.length);\n\n var bm:EdgeMetrics = borderMetrics;\n\n var textWidth:Number = prefSize.width + bm.left + bm.right + 8;\n var textHeight:Number = prefSize.height + bm.top + bm.bottom \n + UITextField.TEXT_HEIGHT_PADDING;\n\n measuredMinWidth = measuredWidth = textWidth + buttonWidth;\n measuredMinHeight = measuredHeight = Math.max(textHeight, buttonHeight);\n }\n calculatePreferredSizeFromData mx.controls.ComboBox flash.text.lineMetrics data ComboBox mx.controls.ComboBox calculatePreferredSizeFromData override protected function calculatePreferredSizeFromData(count:int):Object\n {\n var prefSize:Object = super.calculatePrefferedSizeFromData(count);\n var maxW:Number = 0;\n var maxH:Number = 0;\n var bookmark:CursorBookmark = iterator ? iterator.bookmark : null;\n var more:Boolean = iterator != null;\n\n for ( var i:int = 0 ; i < count ; i++)\n {\n var data:Object;\n if (more) data = iterator ? iterator.current : null;\n else data = null;\n if(data)\n {\n var imgH:Number;\n var imgW:Number;\n\n //calculate the image height and width using the data object here\n\n maxH = Math.max(maxH, prefSize.height + imgH);\n maxW = Math.max(maxW, prefSize.width + imgW);\n }\n if(iterator) iterator.moveNext();\n }\n\n if(iterator) iterator.seek(bookmark, 0);\n return {width: maxW, height: maxH};\n }\n imgH imgW maxH maxW"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/103945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2327/"
] |
103,980
|
<p>I'm working on a document "wizard" for the company that I work for. It's a .dot file with a header consisting of some text and some form fields, and a lot of VBA code. The body of the document is pulled in as an OLE object from a separate .doc file.</p>
<p>Currently, this is being done as a <code>Shape</code>, rather than an <code>InlineShape</code>. I did this because I can absolutely position the Shape, whereas the InlineShape always appears at the beginning of the document.</p>
<p>The problem with this is that a <code>Shape</code> doesn't move when the size of the header changes. If someone needs to add or remove a line from the header due to a special case, they also need to move the object that defines the body. This is a pain, and I'd like to avoid it if possible.</p>
<p>Long story short, how do I position an <code>InlineShape</code> using VBA in Word?</p>
<p>The version I'm using is Word 97.</p>
|
[
{
"answer_id": 104116,
"author": "GSerg",
"author_id": 11683,
"author_profile": "https://Stackoverflow.com/users/11683",
"pm_score": 3,
"selected": true,
"text": "ThisDocument.Range(15).InlineShapes.AddPicture \"1.gif\"\n"
},
{
"answer_id": 128344,
"author": "Branan",
"author_id": 13894,
"author_profile": "https://Stackoverflow.com/users/13894",
"pm_score": -1,
"selected": false,
"text": "ThisDocument.Paragraphs Range"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/103980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13894/"
] |
103,989
|
<p>I need to implement an in-memory tuple-of-strings matching feature in C. There will be large list of tuples associated with different actions and a high volume of events to be matched against the list.</p>
<p>List of tuples:</p>
<pre><code>("one", "four")
("one")
("three")
("four", "five")
("six")
</code></pre>
<p>event ("one", "two", "three", "four") should match list item ("one", "four") and ("one") and ("three") but not ("four", "five") and not ("six")</p>
<p>my current approach uses a map of all tuple field values as keys for lists of each tuple using that value. there is a lot of redundant hashing and list insertion.</p>
<p>is there a right or classic way to do this?</p>
|
[
{
"answer_id": 104182,
"author": "Frosty",
"author_id": 7476,
"author_profile": "https://Stackoverflow.com/users/7476",
"pm_score": 3,
"selected": true,
"text": "unsigned int hash(char *value){...}\n\ntypedef struct _tuple {\n unsigned int bitvalues;\n void * data\n} tuple;\n\ntuple a,b,c,d;\na.bitvalues = hash(\"one\");\na.bitvalues |= hash(\"four\");\n//a.data = something;\n\nunsigned int event = 0;\n//foreach value in event;\nevent |= hash(string_val);\n\n// foreach tuple\nif(x->bitvalues & test == test)\n{\n //matches\n}\n typedef struct _tuple {\n unsigned int key_one;\n unsigned int key_two;\n _tuple *next;\n void * data;\n} tuple;\n\ntuple a,b,c,d;\na.key_one = hash(\"one\");\na.key_two = hash(\"four\");\n\ntuple * list = malloc(/*big enough for all hash indexes*/\nmemset(/*clear list*/);\n\n//foreach touple item\nif(list[item->key_one])\n put item on the end of the list;\nelse\n list[item->key_one] = item;\n\n\n//foreach event\n //foreach key\n if(item_ptr = list[key])\n while(item_ptr.next)\n if(!item_ptr.key_two || /*item has key_two*/)\n //match\n item_ptr = item_ptr.next;\n"
},
{
"answer_id": 104296,
"author": "LeppyR64",
"author_id": 16592,
"author_profile": "https://Stackoverflow.com/users/16592",
"pm_score": 0,
"selected": false,
"text": " public static void Main()\n {\n List<List<string>> tuples = new List<List<string>>();\n\n string [] tuple = {\"one\", \"four\"};\n tuples.Add(new List<string>(tuple));\n\n tuple = new string [] {\"one\"};\n tuples.Add(new List<string>(tuple));\n\n tuple = new string [] {\"three\"};\n tuples.Add(new List<string>(tuple));\n\n tuple = new string[]{\"four\", \"five\"};\n tuples.Add(new List<string>(tuple));\n\n tuple = new string[]{\"six\"};\n tuples.Add(new List<string>(tuple));\n\n tuple = new string[] {\"one\", \"two\", \"three\", \"four\"};\n\n List<string> checkTuple = new List<string>(tuple);\n\n List<List<string>> result = new List<List<string>>();\n\n foreach (List<string> ls in tuples)\n {\n bool ok = true;\n foreach(string s in ls)\n if(!checkTuple.Contains(s))\n {\n ok = false;\n break;\n }\n if (ok)\n result.Add(ls);\n }\n }\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/103989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7223/"
] |
104,009
|
<p>I'm wanting to get the full value of a char[] variable in the VC6 watch window, but it only shows a truncated version. I can copy the value from a debug memory window, but that contains mixed lines of hex and string values. Surely there is a better way??</p>
|
[
{
"answer_id": 104045,
"author": "Doug T.",
"author_id": 8123,
"author_profile": "https://Stackoverflow.com/users/8123",
"pm_score": 1,
"selected": false,
"text": "char bigArray[1000];\n &bigArray[0]\n&bigArray[100]\n&bigArray[200]\n...\n"
},
{
"answer_id": 104338,
"author": "nruessmann",
"author_id": 10329,
"author_profile": "https://Stackoverflow.com/users/10329",
"pm_score": 1,
"selected": false,
"text": "(char*)textArray;\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19125/"
] |
104,022
|
<p>I'm currently using <code>.resx</code> files to manage my server side resources for .NET.</p>
<p>the application that I am dealing with also allows developers to plugin JavaScript into various event handlers for client side validation, etc.. What is the best way for me to localize my JavaScript messages and strings? </p>
<p>Ideally, I would like to store the strings in the <code>.resx</code> files to keep them with the rest of the localized resources.</p>
<p>I'm open to suggestions.</p>
|
[
{
"answer_id": 104051,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 2,
"selected": false,
"text": "var phrases={};\nphrases['fatalError'] ='On no!';\n"
},
{
"answer_id": 104080,
"author": "Joel Anair",
"author_id": 7441,
"author_profile": "https://Stackoverflow.com/users/7441",
"pm_score": 5,
"selected": false,
"text": "var localizedStrings={\n confirmMessage:{\n 'en/US':'Are you sure?',\n 'fr/FR':'Est-ce que vous êtes certain?',\n ...\n },\n\n ...\n}\n var locale='en/US';\nvar confirm=localizedStrings['confirmMessage'][locale];\n"
},
{
"answer_id": 104157,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "'Hello'.fr = 'Bonjour';\n'Hello'.es = 'Hola';\n var locale = 'en';\nalert( message[locale] );\n"
},
{
"answer_id": 278229,
"author": "Erik Hesselink",
"author_id": 8071,
"author_profile": "https://Stackoverflow.com/users/8071",
"pm_score": 2,
"selected": false,
"text": "Dim rm As New ResourceManager([resource name], [your assembly])\nDim rs As ResourceSet = \n rm.GetResourceSet(Thread.CurrentThread.CurrentCulture, True, True)\nFor Each kvp As DictionaryEntry In rs\n [Write out kvp.Key and kvp.Value]\nNext\n"
},
{
"answer_id": 2489589,
"author": "brunosp86",
"author_id": 100431,
"author_profile": "https://Stackoverflow.com/users/100431",
"pm_score": -1,
"selected": false,
"text": "MSDN"
},
{
"answer_id": 7141901,
"author": "Jaime Botero",
"author_id": 330091,
"author_profile": "https://Stackoverflow.com/users/330091",
"pm_score": 2,
"selected": false,
"text": "\n var localString = {\n appName: \"your app name\",\n message1: \"blah blah\"\n };\n \nvar lang = getQueryString(\"language\");\nlocalization(lang);\nfunction localization(languageCode) {\n try {\n var defaultLang = \"en\";\n var resourcesFolder = \"values/\";\n if(!languageCode || languageCode.length == 0)\n languageCode = defaultLang;\n // var LOCALIZATION = null;\n LazyLoad.js(resourcesFolder + languageCode + \".js\", function() {\n if( typeof LOCALIZATION == 'undefined') {\n LazyLoad.js(resourcesFolder + defaultLang + \".js\", function() {\n for(var propertyName in LOCALIZATION) {\n $(\"#\" + propertyName).html(LOCALIZATION[propertyName]);\n }\n });\n } else {\n for(var propertyName in LOCALIZATION) {\n $(\"#\" + propertyName).html(LOCALIZATION[propertyName]);\n }\n }\n });\n } catch (e) {\n errorEvent(e);\n }\n}\nfunction getQueryString(name)\n{\n name = name.replace(/[\\[]/, \"\\\\\\[\").replace(/[\\]]/, \"\\\\\\]\");\n var regexS = \"[\\\\?&]\" + name + \"=([^&#]*)\";\n var regex = new RegExp(regexS);\n var results = regex.exec(window.location.href);\n if(results == null)\n return \"\";\n else\n return decodeURIComponent(results[1].replace(/\\+/g, \" \"));\n}\n \n span id=\"appName\"\n"
},
{
"answer_id": 14782225,
"author": "Leniel Maccaferri",
"author_id": 114029,
"author_profile": "https://Stackoverflow.com/users/114029",
"pm_score": 4,
"selected": false,
"text": "Resources.js <#@ template language=\"C#\" debug=\"false\" hostspecific=\"true\"#>\n<#@ assembly name=\"System.Windows.Forms\" #>\n<#@ import namespace=\"System.Resources\" #>\n<#@ import namespace=\"System.Collections\" #>\n<#@ import namespace=\"System.IO\" #>\n<#@ output extension=\".js\"#>\n<#\n var path = Path.GetDirectoryName(Host.TemplateFile) + \"/../App_GlobalResources/\";\n var resourceNames = new string[1]\n {\n \"Common\"\n };\n\n#>\n/**\n* Resources\n* ---------\n* This file is auto-generated by a tool\n* 2012 Jochen van Wylick\n**/\nvar Resources = {\n <# foreach (var name in resourceNames) { #>\n <#=name #>: {},\n <# } #>\n};\n<# foreach (var name in resourceNames) {\n var nlFile = Host.ResolvePath(path + name + \".nl.resx\" );\n var enFile = Host.ResolvePath(path + name + \".resx\" );\n ResXResourceSet nlResxSet = new ResXResourceSet(nlFile);\n ResXResourceSet enResxSet = new ResXResourceSet(enFile);\n#>\n\n<# foreach (DictionaryEntry item in nlResxSet) { #>\nResources.<#=name#>.<#=item.Key.ToString()#> = {\n 'nl-NL': '<#= (\"\" + item.Value).Replace(\"\\r\\n\", string.Empty).Replace(\"'\",\"\\\\'\")#>',\n 'en-GB': '<#= (\"\" + enResxSet.GetString(item.Key.ToString())).Replace(\"\\r\\n\", string.Empty).Replace(\"'\",\"\\\\'\")#>'\n };\n<# } #>\n<# } #>\n <script type=\"text/javascript\">\n\n var locale = '<%= System.Threading.Thread.CurrentThread.CurrentCulture.Name %>';\n\n</script>\n\n<script type=\"text/javascript\" src=\"/Scripts/Resources.js\"></script>\n <script type=\"text/javascript\">\n\n // Setting Locale that will be used by JavaScript translations\n var locale = $(\"meta[name='accept-language']\").attr(\"content\");\n\n</script>\n\n<script type=\"text/javascript\" src=\"/Scripts/Resources.js\"></script>\n MetaAcceptLanguage public static IHtmlString MetaAcceptLanguage<T>(this HtmlHelper<T> html)\n{\n var acceptLanguage =\n HttpUtility.HtmlAttributeEncode(\n Thread.CurrentThread.CurrentUICulture.ToString());\n\n return new HtmlString(\n String.Format(\"<meta name=\\\"{0}\\\" content=\\\"{1}\\\">\", \"accept-language\",\n acceptLanguage));\n }\n var msg = Resources.Common.Greeting[locale];\nalert(msg);\n"
},
{
"answer_id": 24460976,
"author": "hhh575",
"author_id": 2923866,
"author_profile": "https://Stackoverflow.com/users/2923866",
"pm_score": -1,
"selected": false,
"text": "protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)\n{\n if (Context.Handler is IRequiresSessionState || Context.Handler is IReadOnlySessionState)\n {\n // Set the current thread's culture\n var culture = (CultureInfo)Session[\"CultureInfo\"];\n if (culture != null)\n {\n Thread.CurrentThread.CurrentCulture = culture;\n Thread.CurrentThread.CurrentUICulture = culture;\n }\n }\n}\n public string GetString(string key)\n{\n return Language.ResourceManager.GetString(key);\n}\n /*\n Retrieve a localized language string given a lookup key.\n Example use:\n var str = language.getString('MyString');\n*/\nvar language = new function () {\n this.getString = function (key) {\n var retVal = '';\n $.ajax({\n url: rootUrl + 'Language/GetString?key=' + key,\n async: false,\n success: function (results) {\n retVal = results;\n }\n });\n return retVal;\n }\n};\n"
},
{
"answer_id": 26422551,
"author": "Morcilla de Arroz",
"author_id": 1410097,
"author_profile": "https://Stackoverflow.com/users/1410097",
"pm_score": 2,
"selected": false,
"text": "en-GB.js\nlang = {\n date_message: 'The start date is incorrect',\n ...\n};\nes-ES.js\nlang = {\n date_message: 'Fecha de inicio incorrecta',\n ...\n};\n Protected Overrides Sub InitializeCulture()\n Dim sLang As String \n sLang = \"es-ES\" \n\n Me.Culture = sLang\n Me.UICulture = sLang\n Page.ClientScript.RegisterClientScriptInclude(sLang & \".js\", \"../Scripts/\" & sLang & \".js\")\n\n MyBase.InitializeCulture()\nEnd Sub\n alert (lang.date_message);\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7215/"
] |
104,055
|
<p>I know how to use rpm to list the contents of a package (<code>rpm -qpil package.rpm</code>). However, this requires knowing the location of the .rpm file on the filesystem. A more elegant solution would be to use the package manager, which in my case is YUM. How can YUM be used to achieve this?</p>
|
[
{
"answer_id": 104087,
"author": "Thomi",
"author_id": 1304,
"author_profile": "https://Stackoverflow.com/users/1304",
"pm_score": 5,
"selected": false,
"text": "rpm -qlp /path/to/fileToList.rpm\n rpm -ql packageName\n"
},
{
"answer_id": 107520,
"author": "Thomas Vander Stichele",
"author_id": 2900,
"author_profile": "https://Stackoverflow.com/users/2900",
"pm_score": 10,
"selected": true,
"text": "yum-utils repoquery $ repoquery --help | grep -E \"list\\ files\" \n -l, --list list files in this package/group\n $ repoquery -l time\n/usr/bin/time\n/usr/share/doc/time-1.7\n/usr/share/doc/time-1.7/COPYING\n/usr/share/doc/time-1.7/NEWS\n/usr/share/doc/time-1.7/README\n/usr/share/info/time.info.gz\n repoquery -l rpm --installed repoquery --installed -l rpm DNF dnf yum-utils $ dnf repoquery -l time\n/usr/bin/time\n/usr/share/doc/time-1.7\n/usr/share/doc/time-1.7/COPYING\n/usr/share/doc/time-1.7/NEWS\n/usr/share/doc/time-1.7/README\n/usr/share/info/time.info.gz\n"
},
{
"answer_id": 9160761,
"author": "Hüseyin Ozan TOK",
"author_id": 1192370,
"author_profile": "https://Stackoverflow.com/users/1192370",
"pm_score": 6,
"selected": false,
"text": "$ yum install -y yum-utils\n\n$ repoquery -l packagename\n"
},
{
"answer_id": 26711409,
"author": "Levite",
"author_id": 1680919,
"author_profile": "https://Stackoverflow.com/users/1680919",
"pm_score": 7,
"selected": false,
"text": "rpm -ql [packageName]\n # rpm -ql php-fpm\n\n/etc/php-fpm.conf\n/etc/php-fpm.d\n/etc/php-fpm.d/www.conf\n/etc/sysconfig/php-fpm\n...\n/run/php-fpm\n/usr/lib/systemd/system/php-fpm.service\n/usr/sbin/php-fpm\n/usr/share/doc/php-fpm-5.6.0\n/usr/share/man/man8/php-fpm.8.gz\n...\n/var/lib/php/sessions\n/var/log/php-fpm\n"
},
{
"answer_id": 40918680,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": ": you can type in anything below, doesnt have to match anything\n\nyum whatprovides \"me with a life\"\n\n: result of the above (some liberties taken with spacing):\n\nLoaded plugins: fastestmirror\nbase | 3.6 kB 00:00 \nextras | 3.4 kB 00:00 \nupdates | 3.4 kB 00:00 \n(1/4): extras/7/x86_64/primary_db | 166 kB 00:00 \n(2/4): base/7/x86_64/group_gz | 155 kB 00:00 \n(3/4): updates/7/x86_64/primary_db | 9.1 MB 00:04 \n(4/4): base/7/x86_64/primary_db | 5.3 MB 00:05 \nDetermining fastest mirrors\n * base: mirrors.xmission.com\n * extras: mirrors.xmission.com\n * updates: mirrors.xmission.com\nbase/7/x86_64/filelists_db | 6.2 MB 00:02 \nextras/7/x86_64/filelists_db | 468 kB 00:00 \nupdates/7/x86_64/filelists_db | 5.3 MB 00:01 \nNo matches found\n\n: the key result above is that \"primary_db\" files were downloaded\n\n: filelists are downloaded EVEN IF you have keepcache=0 in your yum.conf\n\n: note you can limit this to \"primary_db.sqlite\" if you really want\n\nfind /var/cache/yum -name '*.sqlite'\n\n: if you download/install a new repo, run the exact same command again\n: to get the databases for the new repo\n\n: if you know sqlite you can stop reading here\n\n: if not heres a sample command to dump the contents\n\necho 'SELECT packages.name, GROUP_CONCAT(files.name, \", \") AS files FROM files JOIN packages ON (files.pkgKey = packages.pkgKey) GROUP BY packages.name LIMIT 10;' | sqlite3 -line /var/cache/yum/x86_64/7/base/gen/primary_db.sqlite \n\n: remove \"LIMIT 10\" above for the whole list\n\n: format chosen for proof-of-concept purposes, probably can be improved a lot"
},
{
"answer_id": 51822546,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "reopquery dnf yum dnf repoquery -l <pkg-name>\n dnf-utils yum-utils *.rpm rpm -ql yum dnf repoquery"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/742/"
] |
104,063
|
<p>I noticed in another post, someone had done something like:</p>
<pre><code>double d = 3.1415;
int i = Convert.ToInt32(Math.Floor(d));
</code></pre>
<p>Why did they use the convert function, rather than:</p>
<pre><code>double d = 3.1415;
int i = (int)d;
</code></pre>
<p>which has an implicit floor and convert.</p>
<p>Also, more concerning, I noticed in some production code I was reading:</p>
<pre><code>double d = 3.1415;
float f = Convert.ToSingle(d);
</code></pre>
<p>Is that the same as:</p>
<pre><code>float f = (float)d;
</code></pre>
<p>Are all those otherwise implicit conversions just in the Convert class for completeness, or do they serve a purpose? I can understand a need for .ToString(), but not the rest.</p>
|
[
{
"answer_id": 104180,
"author": "NotDan",
"author_id": 3291,
"author_profile": "https://Stackoverflow.com/users/3291",
"pm_score": 1,
"selected": false,
"text": "int i = Convert.ToInt32(\"1234\");\n Convert.ToInt32(\"1234NonNumber\");\n"
},
{
"answer_id": 104387,
"author": "Michael L Perry",
"author_id": 7668,
"author_profile": "https://Stackoverflow.com/users/7668",
"pm_score": 5,
"selected": true,
"text": "double d = -3.14;\nint i = (int)d;\n// i == -3\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15261/"
] |
104,068
|
<p>Let's say we have the following method declaration:</p>
<pre><code>Public Function MyMethod(ByVal param1 As Integer, _
Optional ByVal param2 As Integer = 0, _
Optional ByVal param3 As Integer = 1) As Integer
Return param1 + param2 + param3
End Function
</code></pre>
<p>How does VB.NET make the optional parameters work within the confines of the CLR? Are optional parameters CLS-Compliant?</p>
|
[
{
"answer_id": 104094,
"author": "John Rudy",
"author_id": 14048,
"author_profile": "https://Stackoverflow.com/users/14048",
"pm_score": 3,
"selected": false,
"text": ".method public static int32 MyMethod(int32 param1,\n [opt] int32 param2,\n [opt] int32 param3) cil managed\n{\n .custom instance void [mscorlib]System.CLSCompliantAttribute::.ctor(bool) = ( 01 00 01 00 00 ) \n .param [2] = int32(0x00000000)\n .param [3] = int32(0x00000001)\n // Code size 11 (0xb)\n .maxstack 2\n .locals init ([0] int32 MyMethod)\n IL_0000: nop\n IL_0001: ldarg.0\n IL_0002: ldarg.1\n IL_0003: add.ovf\n IL_0004: ldarg.2\n IL_0005: add.ovf\n IL_0006: stloc.0\n IL_0007: br.s IL_0009\n IL_0009: ldloc.0\n IL_000a: ret\n} // end of method Module1::MyMethod\n"
},
{
"answer_id": 104174,
"author": "MagicKat",
"author_id": 8505,
"author_profile": "https://Stackoverflow.com/users/8505",
"pm_score": 4,
"selected": true,
"text": "public int MyMethod(int param1, \n [Optional, DefaultParameterValue(0)] int param2, \n [Optional, DefaultParameterValue(1)] int param3)\n{\n return ((param1 + param2) + param3);\n}\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14048/"
] |
104,115
|
<p>In most modern IDEs there is a parameter that you can set to ensure javac gets enough heap memory to do its compilation. For reasons that are not worth going into here, we are tied for the time being to JBuilder 2005/2006, and it appears the amount of source code has exceeded what can be handled by javac.</p>
<p>Please keep the answer specific to JBuilder 2005/2006 javac (we cannot migrate away right now, and the Borland Make compiler does not correctly support Java 1.6)</p>
<p>I realize how and what parameters <em>should</em> be passed to javac, the problem is the IDE doesn't seem to allow these to be set anywhere. A lot of configuration is hidden down in the Jbuilder Install\bin*.config files, I feel the answer may be in there somewhere, but have not found it.</p>
|
[
{
"answer_id": 580326,
"author": "Alex B",
"author_id": 6180,
"author_profile": "https://Stackoverflow.com/users/6180",
"pm_score": 0,
"selected": false,
"text": "vmparam -Xms256m \nvmparam -Xmx256m\n"
},
{
"answer_id": 10959286,
"author": "lvr",
"author_id": 1445908,
"author_profile": "https://Stackoverflow.com/users/1445908",
"pm_score": 0,
"selected": false,
"text": "jbuilder.config <1Gb and with a >"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17123/"
] |
104,122
|
<p>I have a crash dump of an application that is supposedly leaking GDI. The app is running on XP and I have no problems loading it into WinDbg to look at it. Previously we have use the <a href="http://msdn.microsoft.com/en-us/library/cc267206.aspx" rel="noreferrer">Gdikdx.dll extension</a> to look at Gdi information but this extension is not supported on XP or Vista. </p>
<p>Does anyone have any pointers for finding GDI object usage in WinDbg. </p>
<p>Alternatively, I do have access to the failing program (and its stress testing suite) so I can reproduce on a running system if you know of any 'live' debugging tools for XP and Vista (or Windows 2000 though this is not our target).</p>
|
[
{
"answer_id": 104150,
"author": "Kris Kumler",
"author_id": 4281,
"author_profile": "https://Stackoverflow.com/users/4281",
"pm_score": 3,
"selected": true,
"text": "!poolused"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5882/"
] |
104,158
|
<p>I came across this recently, up until now I have been happily overriding the equality operator (<strong>==</strong>) and/or <strong>Equals</strong> method in order to see if two references types actually contained the same <strong>data</strong> (i.e. two different instances that look the same).</p>
<p>I have been using this even more since I have been getting more in to automated testing (comparing reference/expected data against that returned).</p>
<p>While looking over some of the <a href="http://msdn.microsoft.com/en-us/library/ms229042(VS.80).aspx" rel="noreferrer">coding standards guidelines in MSDN</a> I came across an <a href="http://msdn.microsoft.com/en-us/library/7h9bszxx(VS.80).aspx" rel="noreferrer">article</a> that advises against it. Now I understand <em>why</em> the article is saying this (because they are not the same <em>instance</em>) but it does not answer the question:</p>
<ol>
<li><strong>What is the best way to compare two reference types?</strong></li>
<li>Should we implement <a href="http://msdn.microsoft.com/en-us/library/system.icomparable.aspx" rel="noreferrer">IComparable</a>? (I have also seen mention that this should be reserved for value types only).</li>
<li>Is there some interface I don't know about?</li>
<li>Should we just roll our own?!</li>
</ol>
<p>Many Thanks ^_^</p>
<h2>Update</h2>
<p>Looks like I had mis-read some of the documentation (it's been a long day) and overriding <a href="http://msdn.microsoft.com/en-us/library/336aedhh(VS.71).aspx" rel="noreferrer">Equals</a> may be the way to go..</p>
<blockquote>
<p>If you are implementing reference
types, you should consider overriding
the Equals method on a reference type
if your type looks like a base type
such as a Point, String, BigNumber,
and so on. Most reference types should
not overload the <strong>equality</strong> operator,
even <strong>if they override Equals</strong>. However,
if you are implementing a reference
type that is intended to have value
semantics, such as a complex number
type, you should override the equality
operator.</p>
</blockquote>
|
[
{
"answer_id": 104197,
"author": "Matt J",
"author_id": 18528,
"author_profile": "https://Stackoverflow.com/users/18528",
"pm_score": 6,
"selected": true,
"text": "class TwoDPoint : System.Object\n{\n public readonly int x, y;\n\n public TwoDPoint(int x, int y) //constructor\n {\n this.x = x;\n this.y = y;\n }\n\n public override bool Equals(System.Object obj)\n {\n // If parameter is null return false.\n if (obj == null)\n {\n return false;\n }\n\n // If parameter cannot be cast to Point return false.\n TwoDPoint p = obj as TwoDPoint;\n if ((System.Object)p == null)\n {\n return false;\n }\n\n // Return true if the fields match:\n return (x == p.x) && (y == p.y);\n }\n\n public bool Equals(TwoDPoint p)\n {\n // If parameter is null return false:\n if ((object)p == null)\n {\n return false;\n }\n\n // Return true if the fields match:\n return (x == p.x) && (y == p.y);\n }\n\n public override int GetHashCode()\n {\n return x ^ y;\n }\n}\n"
},
{
"answer_id": 104209,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 1,
"selected": false,
"text": "public override bool Equals(object obj)\n{\n if (ReferenceEquals(null, obj)) return false;\n if (ReferenceEquals(this, obj)) return true;\n return obj.GetType() == typeof(SecurableResourcePermission) && Equals((SecurableResourcePermission)obj);\n}\n\npublic bool Equals(SecurableResourcePermission obj)\n{\n if (ReferenceEquals(null, obj)) return false;\n if (ReferenceEquals(this, obj)) return true;\n return obj.ResourceUid == ResourceUid && Equals(obj.ActionCode, ActionCode) && Equals(obj.AllowDeny, AllowDeny);\n}\n\npublic override int GetHashCode()\n{\n unchecked\n {\n int result = (int)ResourceUid;\n result = (result * 397) ^ (ActionCode != null ? ActionCode.GetHashCode() : 0);\n result = (result * 397) ^ AllowDeny.GetHashCode();\n return result;\n }\n}\n == Object.ReferenceEquals"
},
{
"answer_id": 104309,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 5,
"selected": false,
"text": "System.IEquatable<T> Equals GetHashCode == != class Point : IEquatable<Point> {\n public int X { get; }\n public int Y { get; }\n\n public Point(int x = 0, int y = 0) { X = x; Y = y; }\n\n public bool Equals(Point other) {\n if (other is null) return false;\n return X.Equals(other.X) && Y.Equals(other.Y);\n }\n\n public override bool Equals(object obj) => Equals(obj as Point);\n\n public static bool operator ==(Point lhs, Point rhs) => object.Equals(lhs, rhs);\n\n public static bool operator !=(Point lhs, Point rhs) => ! (lhs == rhs);\n\n public override int GetHashCode() => X.GetHashCode() ^ Y.GetHashCode();\n} Equals(Point other) GetHashCode() == != Equals(object x) Equals(SecurableResourcePermission x) Equals public bool Equals(Point other) {\n if (other is null) return false;\n if (other.GetType() != GetType()) return false;\n return X.Equals(other.X) && Y.Equals(other.Y);\n}"
},
{
"answer_id": 13905114,
"author": "nawfal",
"author_id": 661933,
"author_profile": "https://Stackoverflow.com/users/661933",
"pm_score": 0,
"selected": false,
"text": "IEquatable<T> Equals GetHashCode object.Equals == != == != Equals public struct Entity : IEquatable<Entity>\n{\n public bool Equals(Entity other)\n {\n throw new NotImplementedException(\"Your equality check here...\");\n }\n\n public override bool Equals(object obj)\n {\n if (obj == null || !(obj is Entity))\n return false;\n\n return Equals((Entity)obj);\n }\n\n public static bool operator ==(Entity e1, Entity e2)\n {\n return e1.Equals(e2);\n }\n\n public static bool operator !=(Entity e1, Entity e2)\n {\n return !(e1 == e2);\n }\n\n public override int GetHashCode()\n {\n throw new NotImplementedException(\"Your lightweight hashing algorithm, consistent with Equals method, here...\");\n }\n}\n == Equals a == b a.Equals(b) == Equals == Equals IsSameAs == Equals GetHashCode == == != Equals GetHashCode IEquatable<T> public class Entity : IEquatable<Entity>\n{\n public bool Equals(Entity other)\n {\n if (ReferenceEquals(this, other))\n return true;\n\n if (ReferenceEquals(null, other))\n return false;\n\n //if your below implementation will involve objects of derived classes, then do a \n //GetType == other.GetType comparison\n throw new NotImplementedException(\"Your equality check here...\");\n }\n\n public override bool Equals(object obj)\n {\n return Equals(obj as Entity);\n }\n\n public override int GetHashCode()\n {\n throw new NotImplementedException(\"Your lightweight hashing algorithm, consistent with Equals method, here...\");\n }\n}\n Equals GetHashCode == != Equals IEquatable<T> public class Entity : IEquatable<Entity>\n{\n public bool Equals(Entity other)\n {\n if (ReferenceEquals(this, other))\n return true;\n\n if (ReferenceEquals(null, other))\n return false;\n\n //if your below implementation will involve objects of derived classes, then do a \n //GetType == other.GetType comparison\n throw new NotImplementedException(\"Your equality check here...\");\n }\n\n public override bool Equals(object obj)\n {\n return Equals(obj as Entity);\n }\n\n public static bool operator ==(Entity e1, Entity e2)\n {\n if (ReferenceEquals(e1, null))\n return ReferenceEquals(e2, null);\n\n return e1.Equals(e2);\n }\n\n public static bool operator !=(Entity e1, Entity e2)\n {\n return !(e1 == e2);\n }\n\n public override int GetHashCode()\n {\n throw new NotImplementedException(\"Your lightweight hashing algorithm, consistent with Equals method, here...\");\n }\n}\n Type Equals IEqualizable<T>"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832/"
] |
104,184
|
<p>There is a case where a map will be constructed, and once it is initialized, it will never be modified again. It will however, be accessed (via get(key) only) from multiple threads. Is it safe to use a <code>java.util.HashMap</code> in this way?</p>
<p>(Currently, I'm happily using a <code>java.util.concurrent.ConcurrentHashMap</code>, and have no measured need to improve performance, but am simply curious if a simple <code>HashMap</code> would suffice. Hence, this question is <em>not</em> "Which one should I use?" nor is it a performance question. Rather, the question is "Would it be safe?")</p>
|
[
{
"answer_id": 1702190,
"author": "Will",
"author_id": 207084,
"author_profile": "https://Stackoverflow.com/users/207084",
"pm_score": 2,
"selected": false,
"text": "Collections.unmodifiableMap(originalMap)"
},
{
"answer_id": 39746361,
"author": "TomWolk",
"author_id": 1037439,
"author_profile": "https://Stackoverflow.com/users/1037439",
"pm_score": 0,
"selected": false,
"text": "public static final HashMap<String, String> map = new HashMap<>();\nstatic {\n map.put(\"A\",\"A\");\n\n}\n class Foo {\n volatile HashMap<String, String> map;\n public void init() {\n final HashMap<String, String> tmp = new HashMap<>();\n tmp.put(\"A\",\"A\");\n // writing to volatile has to be after the modification of the map\n this.map = tmp;\n }\n}\n"
},
{
"answer_id": 41990379,
"author": "BeeOnRope",
"author_id": 149138,
"author_profile": "https://Stackoverflow.com/users/149138",
"pm_score": 7,
"selected": true,
"text": "HashMap HashMap HashMap HashMap class SomeClass {\n public static HashMap<Object, Object> MAP;\n\n public synchronized static setMap(HashMap<Object, Object> m) {\n MAP = m;\n }\n}\n setMap() SomeClass.MAP HashMap<Object,Object> map = SomeClass.MAP;\nif (map != null) {\n .. use the map\n} else {\n .. some default behavior\n}\n SomeObject.MAP HashMap MAP public static volatile HashMap<Object, Object> MAP;\n MAP MAP MAP static final HashMap<> final final static final static final final volatile HashMap HashMap synchronized AtomicReference final"
},
{
"answer_id": 58934205,
"author": "escudero380",
"author_id": 3187094,
"author_profile": "https://Stackoverflow.com/users/3187094",
"pm_score": 3,
"selected": false,
"text": "@ThreadSafe\npublic class SafeStates {\n private final Map<String, String> states;\n\n public SafeStates() {\n states = new HashMap<String, String>();\n states.put(\"alaska\", \"AK\");\n states.put(\"alabama\", \"AL\");\n ...\n states.put(\"wyoming\", \"WY\");\n }\n\n public String getAbbreviation(String s) {\n return states.get(s);\n }\n}\n states final"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3093/"
] |
104,223
|
<p>I have noticed that cURL in PHP returns different data when told to output to a file via <code>CURLOPT_FILE</code> as it does when told to send the output to a string via <code>CURLOPT_RETURNTRANSFER</code>.</p>
<p><code>_RETURNTRANSFER</code> seems to strip newlines and extra white space as if parsing it for display as standard HTML code. <code>_FILE</code> on the other hand preserves the file exactly as it was intended.</p>
<p>I have read through the documentation on php.net but haven't found anything that seems to solve my problem. Ideally, I would like to have <code>_RETURNTRANSFER</code> return the exact contents so I could eliminate an intermediate file, but I don't see any way of making this possible.</p>
<p>Here is the code I am using. The data in question is a CSV file with \r\n line endings.</p>
<pre><code>function update_roster() {
$url = "http://example.com/";
$userID = "xx";
$apikey = "xxx";
$passfields = "userID=$userID&apikey=$apikey";
$file = fopen("roster.csv","w+");
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $passfields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FILE, $file);
$variable_in_question = curl_exec ($ch);
curl_close ($ch);
fclose($file);
return $variable_in_question;
}
</code></pre>
<hr>
<p>Turns out, the error is not in what was being returned, but in the way I was going about parsing it. \r\n is not parsed the way I expected when put in single quotes, switching to double quotes solved my problem. I was not aware that this made a difference inside function calls like that.</p>
<p>This works just fine:<code>$cresult = split("\r\n", $cresult);</code></p>
<p>This does not: <code>$cresult = split('\r\n', $cresult);</code></p>
|
[
{
"answer_id": 104750,
"author": "p4bl0",
"author_id": 12043,
"author_profile": "https://Stackoverflow.com/users/12043",
"pm_score": 0,
"selected": false,
"text": "ob_start(); ob_get_clean(); $ch = curl_init(...);\n// ...\nob_start();\ncurl_exec($ch);\n$yourResult = ob_get_clean();\ncurl_close($ch);\n"
},
{
"answer_id": 106120,
"author": "Melikoth",
"author_id": 1536217,
"author_profile": "https://Stackoverflow.com/users/1536217",
"pm_score": 2,
"selected": true,
"text": "$cresult = split(\"\\r\\n\", $cresult); $cresult = split('\\r\\n', $cresult);"
},
{
"answer_id": 108214,
"author": "p4bl0",
"author_id": 12043,
"author_profile": "https://Stackoverflow.com/users/12043",
"pm_score": 1,
"selected": false,
"text": "$str = 'foo';\necho '$str'; // print “$str” to the screen\necho \"$str\"; // print “foo” to the screen\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1536217/"
] |
104,224
|
<p>I'm working on a WPF application that sometimes exhibits odd problems and appears to <em>hang</em> in the UI. It is inconsistent, it happens in different pages, but it happens often enough that it is a big problem. I should mention that it is not a true hang as described below.</p>
<p>My first thought was that the animations of some buttons was the problem since they are used on most pages, but after removing them the hangs still occur, although seemingly a bit less often. I have tried to break into the debugger when the hang occurs; however there is never any code to view. No code of mine is running. I have also noticed that the "hang" is not complete. I have code that lets me drag the form around (it has no border or title) which continues to work. I also have my won close button which functions when I click it. Clicking on buttons appears to actually work as my code runs, but the UI simply never updates to show a new page.</p>
<p>I'm looking for any advice, tools or techniques to track down this odd problem, so if you have any thoughts at all, I will greatly appreciate it.</p>
<p>EDIT: It just happened again, so this time when I tried to break into the debugger I chose to "show disassembly". It brings me to MS.Win32.UnsafeNativeMethods.GetMessageW. The stack trace follows:</p>
<pre><code>[Managed to Native Transition]
</code></pre>
<blockquote>
<p>WindowsBase.dll!MS.Win32.UnsafeNativeMethods.GetMessageW(ref System.Windows.Interop.MSG msg, System.Runtime.InteropServices.HandleRef hWnd, int uMsgFilterMin, int uMsgFilterMax) + 0x15 bytes<br>
WindowsBase.dll!System.Windows.Threading.Dispatcher.GetMessage(ref System.Windows.Interop.MSG msg, System.IntPtr hwnd, int minMessage, int maxMessage) + 0x48 bytes
WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame frame = {System.Windows.Threading.DispatcherFrame}) + 0x8b bytes
WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame frame) + 0x49 bytes<br>
WindowsBase.dll!System.Windows.Threading.Dispatcher.Run() + 0x4c bytes<br>
PresentationFramework.dll!System.Windows.Application.RunDispatcher(object ignore) + 0x1e bytes<br>
PresentationFramework.dll!System.Windows.Application.RunInternal(System.Windows.Window window) + 0x6f bytes
PresentationFramework.dll!System.Windows.Application.Run(System.Windows.Window window) + 0x26 bytes
PresentationFramework.dll!System.Windows.Application.Run() + 0x19 bytes
WinterGreen.exe!WinterGreen.App.Main() + 0x5e bytes C#
[Native to Managed Transition]<br>
[Managed to Native Transition]<br>
mscorlib.dll!System.AppDomain.nExecuteAssembly(System.Reflection.Assembly assembly, string[] args) + 0x19 bytes
mscorlib.dll!System.Runtime.Hosting.ManifestRunner.Run(bool checkAptModel) + 0x6e bytes
mscorlib.dll!System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly() + 0x84 bytes
mscorlib.dll!System.Runtime.Hosting.ApplicationActivator.CreateInstance(System.ActivationContext activationContext, string[] activationCustomData) + 0x65 bytes
mscorlib.dll!System.Runtime.Hosting.ApplicationActivator.CreateInstance(System.ActivationContext activationContext) + 0xa bytes
mscorlib.dll!System.Activator.CreateInstance(System.ActivationContext activationContext) + 0x3e bytes<br>
Microsoft.VisualStudio.HostingProcess.Utilities.dll!Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone() + 0x23 bytes<br>
mscorlib.dll!System.Threading.ThreadHelper.ThreadStart_Context(object state) + 0x66 bytes<br>
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) + 0x6f bytes<br>
mscorlib.dll!System.Threading.ThreadHelper.ThreadStart() + 0x44 bytes </p>
</blockquote>
|
[
{
"answer_id": 1908286,
"author": "EightyOne Unite",
"author_id": 5559,
"author_profile": "https://Stackoverflow.com/users/5559",
"pm_score": 1,
"selected": false,
"text": "AllowsTransparency"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/312/"
] |
104,225
|
<p>I have a co-worker that maintains that TRUE used to be defined as 0 and all other values were FALSE. I could swear that every language I've worked with, if you could even get a value for a boolean, that the value for FALSE is 0. Did TRUE used to be 0? If so, when did we switch?</p>
|
[
{
"answer_id": 104274,
"author": "GSerg",
"author_id": 11683,
"author_profile": "https://Stackoverflow.com/users/11683",
"pm_score": 0,
"selected": false,
"text": "TRUE 0 0 TRUE 1 -1"
},
{
"answer_id": 104280,
"author": "Dima",
"author_id": 13313,
"author_profile": "https://Stackoverflow.com/users/13313",
"pm_score": 0,
"selected": false,
"text": "if true false"
},
{
"answer_id": 104303,
"author": "David Nehme",
"author_id": 14167,
"author_profile": "https://Stackoverflow.com/users/14167",
"pm_score": 1,
"selected": false,
"text": "int x; \n....\nx = 0;\nif (x) // might be ambiguous\n{\n}\n if (0 != x)\n{\n}\n"
},
{
"answer_id": 104642,
"author": "Ray Hayes",
"author_id": 7093,
"author_profile": "https://Stackoverflow.com/users/7093",
"pm_score": 0,
"selected": false,
"text": "IF errorlevel 2 goto CRS\nIF errorlevel 1 goto DLR\nIF errorlevel 0 goto STR\n"
},
{
"answer_id": 104784,
"author": "neu242",
"author_id": 13365,
"author_profile": "https://Stackoverflow.com/users/13365",
"pm_score": 1,
"selected": false,
"text": "$ false; echo $?\n1\n$ true; echo $?\n0\n"
},
{
"answer_id": 105464,
"author": "DJClayworth",
"author_id": 19276,
"author_profile": "https://Stackoverflow.com/users/19276",
"pm_score": 1,
"selected": false,
"text": "if (2) {\n alwaysDoThis();\n} else {\n neverDothis();\n}\n"
},
{
"answer_id": 112689,
"author": "Sam Stokes",
"author_id": 20131,
"author_profile": "https://Stackoverflow.com/users/20131",
"pm_score": 4,
"selected": false,
"text": "/* like my constants better */\n#undef TRUE\n#define TRUE 1\n\n#undef FALSE\n#define FALSE 0\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10887/"
] |
104,230
|
<p>Situation: A PHP application with multiple installable modules creates a new table in database for each, in the style of mod_A, mod_B, mod_C etc. Each has the column section_id.</p>
<p>Now, I am looking for all entries for a specific section_id, and I'm hoping there's another way besides "Select * from mod_a, mod_b, mod_c ... mod_xyzzy where section_id=value"... or even worse, using a separate query for each module.</p>
|
[
{
"answer_id": 104257,
"author": "borjab",
"author_id": 16206,
"author_profile": "https://Stackoverflow.com/users/16206",
"pm_score": 1,
"selected": false,
"text": "SELECT * FROM mod_a WHERE section_id=value\nUNION ALL\nSELECT * FROM mod_b WHERE section_id=value\nUNION ALL\nSELECT * FROM mod_c WHERE section_id=value\n"
},
{
"answer_id": 104301,
"author": "µBio",
"author_id": 9796,
"author_profile": "https://Stackoverflow.com/users/9796",
"pm_score": 0,
"selected": false,
"text": "select a.some_field, b.some_field.... \nfrom mod_a a\ninner join mod_b b on a.section_id = b.section_id\n...\nwhere a.section_id = <parameter>\n"
},
{
"answer_id": 104515,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 2,
"selected": true,
"text": "SET @sql = ''\n\nDECLARE CURSOR FOR\nSELECT t.[name] AS TABLE_NAME\nFROM sys.tables t\nWHERE t.[name] LIKE 'SOME_PATTERN_TO_IDENTIFY_THE_TABLES'\n DECLARE CURSOR FOR\nSELECT t.[name] AS TABLE_NAME\nFROM TABLE_OF_TABLES_TO_SEACRH t\n\nSTART LOOP\n\nIF @sql <> '' SET @sql = @sql + 'UNION ALL '\nSET @sql = 'SELECT * FROM [' + @TABLE_NAME + '] WHERE section_id=value '\n\nEND LOOP\n\nEXEC(@sql)\n SET @sql = COALESCE(@sql + ' UNION ALL ', '')\n + 'SELECT * FROM [' + @TABLE_NAME + '] WHERE section_id=value '\n"
},
{
"answer_id": 105870,
"author": "dummy",
"author_id": 6297,
"author_profile": "https://Stackoverflow.com/users/6297",
"pm_score": 0,
"selected": false,
"text": "SELECT * FROM (\n SELECT * FROM table1\n UNION ALL\n SELECT * FROM table2\n UNION ALL\n SELECT * FROM table3\n) subQry\nWHERE field=value\n"
},
{
"answer_id": 105994,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 0,
"selected": false,
"text": "CREATE VIEW modules AS (\n SELECT * FROM mod_A\n UNION ALL \n SELECT * FROM mod_B\n UNION ALL \n SELECT * FROM mod_C\n);\n\nselect * from modules where section_id=value;\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4224/"
] |
104,235
|
<p>What is the syntax and which namespace/class needs to be imported? Give me sample code if possible. It would be of great help.</p>
|
[
{
"answer_id": 104262,
"author": "MagicKat",
"author_id": 8505,
"author_profile": "https://Stackoverflow.com/users/8505",
"pm_score": 5,
"selected": false,
"text": "System.Diagnostics.Debugger.Break();\n"
},
{
"answer_id": 104263,
"author": "Quintin Robinson",
"author_id": 12707,
"author_profile": "https://Stackoverflow.com/users/12707",
"pm_score": 2,
"selected": false,
"text": "System.Diagnostics.Debugger.Break()"
},
{
"answer_id": 104268,
"author": "John Hoven",
"author_id": 1907,
"author_profile": "https://Stackoverflow.com/users/1907",
"pm_score": 3,
"selected": false,
"text": "#if DEBUG\n System.Diagnostics.Debugger.Break();\n#endif\n"
},
{
"answer_id": 105599,
"author": "Philip Rieck",
"author_id": 12643,
"author_profile": "https://Stackoverflow.com/users/12643",
"pm_score": 5,
"selected": false,
"text": "using System.Diagnostics;\n\n//.... in the method:\n\nif( Debugger.IsAttached) //or if(!Debugger.IsAttached)\n{\n Debugger.Break();\n}\n"
},
{
"answer_id": 36127453,
"author": "CAD bloke",
"author_id": 492,
"author_profile": "https://Stackoverflow.com/users/492",
"pm_score": 2,
"selected": false,
"text": "#if DEBUG\n System.Diagnostics.Debugger.Break();\n#endif\n if( Debugger.IsAttached) //or if(!Debugger.IsAttached)\n{\n Debugger.Break();\n}\n SecurityException"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13432/"
] |
104,238
|
<p>I'm having an issue with my regex.</p>
<p>I want to capture <% some stuff %> and i need what's inside the <% and the %></p>
<p>This regex works quite well for that.</p>
<pre><code>$matches = preg_split("/<%[\s]*(.*?)[\s]*%>/i",$markup,-1,(PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE));
</code></pre>
<p>I also want to catch <code>&amp;% some stuff %&amp;gt;</code> so I need to capture <code><% or &amp;lt;% and %> or %&amp;gt;</code> respectively. </p>
<p>If I put in a second set of parens, it makes preg_split function differently (because as you can see from the flag, I'm trying to capture what's inside the parens.</p>
<p>Preferably, it would only match <code>&amp;lt; to &amp;gt; and < to ></code> as well, but that's not completely necessary</p>
<p>EDIT: The SUBJECT may contain multiple matches, and I need all of them</p>
|
[
{
"answer_id": 104295,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 4,
"selected": true,
"text": "preg_match(\"#((?:<|<)%)([\\s]*(?:[^ø]*)[\\s]*?)(%(?:>|>))#i\",$markup, $out);\nprint_r($out);\n\nArray\n(\n [0] => <% your stuff %>\n [1] => <%\n [2] => your stuff\n [3] => %>\n)\n #((?:<|<)%)([\\s]*(?:[^ø]*)[\\s]*?)(%(?:>|>))#i can be viewed as ((?:<|<)%) + ([\\s]*(?:[^ø]*)[\\s]*?) + (%(?:>|>)).\n\n((?:<|<)%) is capturing < or < then %\n(%(?:>|>)) is capturing % then < or > \n([\\s]*(?:[^ø]*)[\\s]*?) means 0 or more spaces, then 0 or more times anything that is not the ø symbol, the 0 or more spaces.\n"
},
{
"answer_id": 104315,
"author": "Issac Kelly",
"author_id": 144,
"author_profile": "https://Stackoverflow.com/users/144",
"pm_score": 0,
"selected": false,
"text": "$matches = preg_split(\"/(<|<)%[\\s]*(.*?)[\\s]*%(>|>)/i\",$markup,-1,(PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE));\n Hi my name is <h1>Issac</h1><% some stuff %>here<% more stuff %> \n Array(\n [0]=>Hi my name is <h1>Issac</h1>\n [1]=><\n [2]=>some stuff\n [3]=>>\n [4]=>here\n [5]=>&;lt;\n [6]=>more stuff\n [7]=>>\n)\n"
},
{
"answer_id": 104324,
"author": "Tegan Mulholland",
"author_id": 16431,
"author_profile": "https://Stackoverflow.com/users/16431",
"pm_score": 1,
"selected": false,
"text": "preg_split preg_match"
},
{
"answer_id": 104358,
"author": "Lasar",
"author_id": 9438,
"author_profile": "https://Stackoverflow.com/users/9438",
"pm_score": 2,
"selected": false,
"text": "<?php\n$code = 'Here is a <% test %> and <% another test %> for you';\npreg_match_all('/(<|<)%\\s*(.*?)\\s*%(>|>)/', $code, $matches);\nprint_r($matches[2]);\n?>\n Array\n(\n [0] => test\n [1] => another test\n)\n"
},
{
"answer_id": 104422,
"author": "user19087",
"author_id": 19087,
"author_profile": "https://Stackoverflow.com/users/19087",
"pm_score": 1,
"selected": false,
"text": "preg_match_all preg_match_all('/((\\<\\%)(\\s)(.*?)(\\s)(\\%\\>))/i', '<% wtf %> <% sadfdsafds %>', $result);\n Array\n(\n [0] => Array\n (\n [0] => <% wtf %>\n [1] => <% sadfdsafds %>\n )\n\n[1] => Array\n (\n [0] => <% wtf %>\n [1] => <% sadfdsafds %>\n )\n\n[2] => Array\n (\n [0] => <%\n [1] => <%\n )\n\n[3] => Array\n (\n [0] => \n [1] => \n )\n\n[4] => Array\n (\n [0] => wtf\n [1] => sadfdsafds\n )\n\n[5] => Array\n (\n [0] => \n [1] => \n )\n\n[6] => Array\n (\n [0] => %>\n [1] => %>\n )\n\n)\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/144/"
] |
104,254
|
<p>I use the Eclipse IDE to develop, compile, and run my Java projects. Today, I'm trying to use the <code>java.io.Console</code> class to manage output and, more importantly, user input.</p>
<p>The problem is that <code>System.console()</code> returns <code>null</code> when an application is run "through" Eclipse. Eclipse run the program on a background process, rather than a top-level process with the console window we're familiar with.</p>
<p>Is there a way to force Eclipse to run the program as a top level process, or at least create a Console that the JVM will recognize? Otherwise, I'm forced to jar the project up and run on a command-line environment external to Eclipse.</p>
|
[
{
"answer_id": 105403,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 7,
"selected": true,
"text": "java -cp workspace\\p1\\bin;workspace\\p2\\bin foo.Main\n workspace\\project\\\n \\.classpath\n \\.project\n \\debug.bat\n \\bin\\Main.class\n \\src\\Main.java\n @ECHO OFF\nSET A_PORT=8787\nSET A_DBG=-Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,address=%A_PORT%,server=y,suspend=y\njava.exe %A_DBG% -cp .\\bin Main\n"
},
{
"answer_id": 4491872,
"author": "Laplie Anderson",
"author_id": 14204,
"author_profile": "https://Stackoverflow.com/users/14204",
"pm_score": 5,
"selected": false,
"text": "String line = System.console().readLine();\n BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));\nString line = bufferedReader.readLine();\n"
},
{
"answer_id": 11998803,
"author": "binarycube",
"author_id": 765546,
"author_profile": "https://Stackoverflow.com/users/765546",
"pm_score": 2,
"selected": false,
"text": " private static String readLine(String prompt) {\n String line = null;\n Console c = System.console();\n if (c != null) {\n line = c.readLine(prompt);\n } else {\n System.out.print(prompt);\n BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));\n try {\n line = bufferedReader.readLine();\n } catch (IOException e) { \n //Ignore \n }\n }\n return line;\n }\n"
},
{
"answer_id": 15539444,
"author": "yztaoj",
"author_id": 2193610,
"author_profile": "https://Stackoverflow.com/users/2193610",
"pm_score": 3,
"selected": false,
"text": "public class Console {\n BufferedReader br;\n PrintStream ps;\n\n public Console(){\n br = new BufferedReader(new InputStreamReader(System.in));\n ps = System.out;\n }\n\n public String readLine(String out){\n ps.format(out);\n try{\n return br.readLine();\n }catch(IOException e)\n {\n return null;\n }\n }\n public PrintStream format(String format, Object...objects){\n return ps.format(format, objects);\n }\n}\n"
},
{
"answer_id": 42139447,
"author": "Paulo Merson",
"author_id": 317522,
"author_profile": "https://Stackoverflow.com/users/317522",
"pm_score": 0,
"selected": false,
"text": "System.console() java -cp C:\\MyWorkspace\\MyProject\\target\\classes com.mydomain.mypackage.MyClass\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19147/"
] |
104,267
|
<p>in short: <strong>is there any way to find the current directory full path of a xul application?</strong></p>
<p>long explanation:</p>
<p>I would like to open some html files in a xul browser application. The path to the html files should be set programmatically from the xul application. The html files reside outside the folder of my xul application, but at the same level. (users will checkout both folders from SVN, no installation available for the xul app)</p>
<p>It opened the files just fine if I set a full path like "file:///c:\temp\processing-sample\index.html"</p>
<p>what i want to do is to open the file relative to my xul application. </p>
<p>I found i can open the user's profile path:</p>
<pre><code>var DIR_SERVICE = new Components.Constructor("@mozilla.org/file/directory_service;1", "nsIProperties");
var path = (new DIR_SERVICE()).get("UChrm", Components.interfaces.nsIFile).path;
var appletPath;
// find directory separator type
if (path.search(/\\/) != -1)
{
appletPath = path + "\\myApp\\content\\applet.html"
}
else
{
appletPath = path + "/myApp/content/applet.html"
}
// Cargar el applet en el iframe
var appletFile = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
appletFile.initWithPath(appletPath);
var appletURL = Components.classes["@mozilla.org/network/protocol;1?name=file"].createInstance(Components.interfaces.nsIFileProtocolHandler).getURLSpecFromFile(appletFile);
var appletFrame = document.getElementById("appletFrame");
appletFrame.setAttribute("src", appletURL);
</code></pre>
<p><strong>is there any way to find the current directory full path of a xul application?</strong></p>
|
[
{
"answer_id": 104950,
"author": "rec",
"author_id": 14022,
"author_profile": "https://Stackoverflow.com/users/14022",
"pm_score": 3,
"selected": true,
"text": "var DIR_SERVICE = new Components.Constructor(\"@mozilla.org/file/directory_service;1\", \"nsIProperties\");\nvar path = (new DIR_SERVICE()).get(resource:app, Components.interfaces.nsIFile).path;\nvar appletPath;\n"
},
{
"answer_id": 107205,
"author": "pc1oad1etter",
"author_id": 525,
"author_profile": "https://Stackoverflow.com/users/525",
"pm_score": 0,
"selected": false,
"text": "<script src=\"chrome://includes/content/XSLTemplate.js\" type=\"application/x-javascript\"/>\n chrome://content/index.html \n"
},
{
"answer_id": 584662,
"author": "bizzy",
"author_id": 48797,
"author_profile": "https://Stackoverflow.com/users/48797",
"pm_score": 2,
"selected": false,
"text": "content.document.location.href = \"chrome://{appname}/content/logManager/index.html\"\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14022/"
] |
104,293
|
<p>I'm getting a 404 error when trying to run another web service on an IIS 6 server which is also running Sharepoint 2003. I'm pretty sure this is an issue with sharepoint taking over IIS configuration. Is there a way to make a certain web service or web site be ignored by whatever Sharepoint is doing?</p>
|
[
{
"answer_id": 104410,
"author": "Stimy",
"author_id": 8852,
"author_profile": "https://Stackoverflow.com/users/8852",
"pm_score": 3,
"selected": true,
"text": "STSADM.EXE -o addpath -url http://localhost/<your web service/app> -type exclusion\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8852/"
] |
104,313
|
<p>I'm implementing an Apache 2.0.x module in C, to interface with an existing product we have. I need to handle FORM data, most likely using POST but I want to handle the GET case as well.</p>
<p>Nick Kew's <A href="https://rads.stackoverflow.com/amzn/click/com/0132409674" rel="nofollow noreferrer" rel="nofollow noreferrer">Apache Modules</A> book has a section on handling form data. It provides code examples for POST and GET, which return an apr_hash_t of the key+value pairs in the form. parse_form_from_POST marshalls the bucket brigade and flattens it into a buffer, while parse_form_from_GET can simply reference the URL. Both routines rely on a parse_form_from_string routine to walk through each delimited field and extract the information into the hash table.</p>
<p>That would be fine, but it seems like there should be an easier way to do this than adding a couple hundred lines of code to my module. Is there an existing module or routines within apache, apr, or apr-util to extract the field names and associated data from a GET or POST FORM into a structure which C code can more easily access? I cannot find anything relevant, but this seems like a common need for which there should be a solution.</p>
|
[
{
"answer_id": 12989352,
"author": "mlibby",
"author_id": 13468,
"author_profile": "https://Stackoverflow.com/users/13468",
"pm_score": 0,
"selected": false,
"text": "ap_parse_form_data read_post mod_form"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4761/"
] |
104,322
|
<p>How do you install Boost on MacOS?
Right now I can't find bjam for the Mac.</p>
|
[
{
"answer_id": 104389,
"author": "dies",
"author_id": 19170,
"author_profile": "https://Stackoverflow.com/users/19170",
"pm_score": 8,
"selected": true,
"text": "sudo port install boost \n"
},
{
"answer_id": 104647,
"author": "dmckee --- ex-moderator kitten",
"author_id": 2509,
"author_profile": "https://Stackoverflow.com/users/2509",
"pm_score": 3,
"selected": false,
"text": "fink install boost1.35.nopython\n fink list boost\n"
},
{
"answer_id": 9196677,
"author": "jrwren",
"author_id": 16998,
"author_profile": "https://Stackoverflow.com/users/16998",
"pm_score": 8,
"selected": false,
"text": "brew install boost"
},
{
"answer_id": 11297605,
"author": "snies",
"author_id": 262822,
"author_profile": "https://Stackoverflow.com/users/262822",
"pm_score": 7,
"selected": false,
"text": "tar -xzf boost_1_50_0.tar.gz\ncd boost_1_50_0 bjam ./bootstrap.sh --prefix=/some/dir/you/would/like/to/prefix ./b2 ./b2 install"
},
{
"answer_id": 26300596,
"author": "user1823890",
"author_id": 1823890,
"author_profile": "https://Stackoverflow.com/users/1823890",
"pm_score": 2,
"selected": false,
"text": "sudo port install boost +universal\n"
},
{
"answer_id": 36657597,
"author": "Jacksonkr",
"author_id": 332578,
"author_profile": "https://Stackoverflow.com/users/332578",
"pm_score": 2,
"selected": false,
"text": "+universal python +universal python +universal $ brew reinstall python\n$ brew install boost\n $ sudo port -f uninstall python\n$ sudo port install python +universal\n$ sudo port install boost +universal\n"
},
{
"answer_id": 54735125,
"author": "UDAY JAIN",
"author_id": 11072474,
"author_profile": "https://Stackoverflow.com/users/11072474",
"pm_score": 3,
"selected": false,
"text": " /usr/bin/ruby -e \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)\"\n brew install boost\n <your macusername>/usr/local/Cellar/boost"
},
{
"answer_id": 65501748,
"author": "Neo li",
"author_id": 7000846,
"author_profile": "https://Stackoverflow.com/users/7000846",
"pm_score": 2,
"selected": false,
"text": "conda install -c conda-forge boost"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15124/"
] |
104,323
|
<p>I am quite new to JavaScript libraries. I wanted to replace my current code with jQuery. My current code looks like this:</p>
<pre><code>var req;
function createRequest() {
var key = document.getElementById("key");
var keypressed = document.getElementById("keypressed");
keypressed.value = key.value;
var url = "/My_Servlet/response?key=" + escape(key.value);
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
req.open("Get", url, true);
req.onreadystatechange = callback;
req.send(null);
}
function callback() {
if (req.readyState == 4) {
if (req.status == 200) {
var decimal = document.getElementById('decimal');
decimal.value = req.responseText;
}
}
clear();
}
</code></pre>
<p>I wanted to replace my code with something a little friendlier like jQuery's</p>
<pre><code>$.get(url, callback);
</code></pre>
<p>However it doesn't call my callback function.</p>
<p>Also I would like to call a function called <code>createRequest</code> continuously. Does jQuery have a nice way of doing that?
</p>
|
[
{
"answer_id": 104347,
"author": "ceejayoz",
"author_id": 1902010,
"author_profile": "https://Stackoverflow.com/users/1902010",
"pm_score": 2,
"selected": false,
"text": "url, data, callback url, callback"
},
{
"answer_id": 104408,
"author": "Lasar",
"author_id": 9438,
"author_profile": "https://Stackoverflow.com/users/9438",
"pm_score": 4,
"selected": false,
"text": "$.get(url, {}, callback);\n function callback(content){\n $('#decimal').val(content);\n}\n $.get(url, {}, function(content){\n $('#decimal').val(content);\n});\n function createRequest() {\n var keyValue = $('#key').val();\n $('#keypressed').val(keyValue);\n var url = \"/My_Servlet/response\";\n $.get(url, {key: keyValue}, function(content){\n $('#decimal').val(content);\n });\n}\n"
},
{
"answer_id": 104432,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 2,
"selected": false,
"text": "(data, textStatus) data req.responseText window.setTimeout() window.setInterval() var interval = 500; /* Milliseconds between requests. */\nwindow.setInterval(function() {\n var val = $(\"#key\").val();\n $(\"#keypressed\").val(val);\n $.get(\"/My_Servlet/response\", { \"key\": val }, function(data, textStatus) {\n $(\"#decimal\").val(data);\n });\n}), interval);\n"
},
{
"answer_id": 104452,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 2,
"selected": false,
"text": "var key = document.getElementById(\"key\");\n[...]\nvar url = \"/My_Servlet/response\";\n$.get (url, {'key': key}, function (responseText)\n{\n var decimal = document.getElementById ('decimal'); \n decimal.value = responseText;\n});\n"
},
{
"answer_id": 105635,
"author": "Bernie Perez",
"author_id": 1992,
"author_profile": "https://Stackoverflow.com/users/1992",
"pm_score": 0,
"selected": false,
"text": " function convertToDecimal(){ \n var key = document.getElementById(\"key\"); \n var keypressed = document.getElementById(\"keypressed\"); \n keypressed.value = key.value; \n var url = \"/My_Servlet/response?key=\"+ escape(key.value);\n jQuery.get(url, {}, function(data){\n callback(data);}\n , \"text\" );\n }\n\n function callback(data){\n var decimal = document.getElementById('decimal');\n decimal.value = data;\n clear();\n }\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
104,329
|
<p>What kind of performance implications are there to consider when using try-catch statements in php 5? </p>
<p>I've read some old and seemingly conflicting information on this subject on the web before. A lot of the framework I currently have to work with was created on php 4 and lacks many of the niceties of php 5. So, I don't have much experience myself in using try-catchs with php.</p>
|
[
{
"answer_id": 445094,
"author": "jmucchiello",
"author_id": 44065,
"author_profile": "https://Stackoverflow.com/users/44065",
"pm_score": 6,
"selected": false,
"text": "function no_except($a, $b) { \n $a += $b;\n return $a;\n}\nfunction except($a, $b) { \n try {\n $a += $b;\n } catch (Exception $e) {}\n return $a;\n}\n echo 'no except with no surrounding try';\nfor ($i = 0; $i < NUM_TESTS; ++$i) {\n no_except(5, 7);\n}\necho 'no except with surrounding try';\nfor ($i = 0; $i < NUM_TESTS; ++$i) {\n try {\n no_except(5, 7);\n } catch (Exception $e) {}\n}\necho 'except with no surrounding try';\nfor ($i = 0; $i < NUM_TESTS; ++$i) {\n except(5, 7);\n}\necho 'except with surrounding try';\nfor ($i = 0; $i < NUM_TESTS; ++$i) {\n try {\n except(5, 7);\n } catch (Exception $e) {}\n}\n no except with no surrounding try = 3.3296\nno except with surrounding try = 3.4246\nexcept with no surrounding try = 3.2548\nexcept with surrounding try = 3.2913\n"
},
{
"answer_id": 1839430,
"author": "Tom",
"author_id": 204155,
"author_profile": "https://Stackoverflow.com/users/204155",
"pm_score": 1,
"selected": false,
"text": "try {Controller::run();}catch(...)\n"
},
{
"answer_id": 12785677,
"author": "Fabrizio",
"author_id": 583230,
"author_profile": "https://Stackoverflow.com/users/583230",
"pm_score": 2,
"selected": false,
"text": "if(isset($var) && is_array($var)){\n foreach($var as $k=>$v){\n $var[$k] = $v+1;\n }\n}\n try{\n foreach($var as $k=>$v){\n $var[$k] = $v+1;\n }\n}catch(Exception($e)){\n}\n <?php\n//beginning code\ntry{\n //some more code\n foreach($var as $k=>$v){\n $var[$k] = $v+1;\n }\n //more code\n}catch(Exception($e)){\n}\n//output everything\n?>\n"
},
{
"answer_id": 17684984,
"author": "Brilliand",
"author_id": 638544,
"author_profile": "https://Stackoverflow.com/users/638544",
"pm_score": 5,
"selected": false,
"text": "function shuffle_assoc($array) { \n $keys = array_keys($array);\n shuffle($keys);\n return array_merge(array_flip($keys), $array);\n}\n\n$c_e = new Exception('n');\n\nfunction no_try($a, $b) { \n $a = new stdclass;\n return $a;\n}\nfunction no_except($a, $b) { \n try {\n $a = new Exception('k');\n } catch (Exception $e) {\n return $a + $b;\n }\n return $a;\n}\nfunction except($a, $b) { \n try {\n throw new Exception('k');\n } catch (Exception $e) {\n return $a + $b;\n }\n return $a;\n}\nfunction constant_except($a, $b) {\n global $c_e;\n try {\n throw $c_e;\n } catch (Exception $e) {\n return $a + $b;\n }\n return $a;\n}\n\n$tests = array(\n 'no try with no surrounding try'=>function() {\n no_try(5, 7);\n },\n 'no try with surrounding try'=>function() {\n try {\n no_try(5, 7);\n } catch (Exception $e) {}\n },\n 'no except with no surrounding try'=>function() {\n no_except(5, 7);\n },\n 'no except with surrounding try'=>function() {\n try {\n no_except(5, 7);\n } catch (Exception $e) {}\n },\n 'except with no surrounding try'=>function() {\n except(5, 7);\n },\n 'except with surrounding try'=>function() {\n try {\n except(5, 7);\n } catch (Exception $e) {}\n },\n 'constant except with no surrounding try'=>function() {\n constant_except(5, 7);\n },\n 'constant except with surrounding try'=>function() {\n try {\n constant_except(5, 7);\n } catch (Exception $e) {}\n },\n);\n$tests = shuffle_assoc($tests);\n\nforeach($tests as $k=>$f) {\n echo $k;\n $start = microtime(true);\n for ($i = 0; $i < 1000000; ++$i) {\n $f();\n }\n echo ' = '.number_format((microtime(true) - $start), 4).\"<br>\\n\";\n}\n no try with no surrounding try = 0.5130\nno try with surrounding try = 0.5665\nno except with no surrounding try = 3.6469\nno except with surrounding try = 3.6979\nexcept with no surrounding try = 3.8729\nexcept with surrounding try = 3.8978\nconstant except with no surrounding try = 0.5741\nconstant except with surrounding try = 0.6234\n"
},
{
"answer_id": 61130530,
"author": "Arkemlar",
"author_id": 4102223,
"author_profile": "https://Stackoverflow.com/users/4102223",
"pm_score": 2,
"selected": false,
"text": "<?php\n\nfunction shuffle_assoc($array) {\n $keys = array_keys($array);\n shuffle($keys);\n return array_merge(array_flip($keys), $array);\n}\n\n$c_e = new Exception('n');\n\nfunction do_nothing($a, $b) {\n return $a + $b;\n}\nfunction new_exception_but_not_throw($a, $b) {\n try {\n new Exception('k');\n } catch (Exception $e) {\n return $a + $b;\n }\n return $a + $b;\n}\nfunction new_exception_and_throw($a, $b) {\n try {\n throw new Exception('k');\n } catch (Exception $e) {\n return $a + $b;\n }\n return $a + $b;\n}\nfunction constant_exception_and_throw($a, $b) {\n global $c_e;\n try {\n throw $c_e;\n } catch (Exception $e) {\n return $a + $b;\n }\n return $a + $b;\n}\n\n$tests = array(\n 'do_nothing with no surrounding try'=>function() {\n do_nothing(5, 7);\n },\n 'do_nothing with surrounding try'=>function() {\n try {\n do_nothing(5, 7);\n } catch (Exception $e) {}\n },\n 'new_exception_but_not_throw with no surrounding try'=>function() {\n new_exception_but_not_throw(5, 7);\n },\n 'new_exception_but_not_throw with surrounding try'=>function() {\n try {\n new_exception_but_not_throw(5, 7);\n } catch (Exception $e) {}\n },\n 'new_exception_and_throw with no surrounding try'=>function() {\n new_exception_and_throw(5, 7);\n },\n 'new_exception_and_throw with surrounding try'=>function() {\n try {\n new_exception_and_throw(5, 7);\n } catch (Exception $e) {}\n },\n 'constant_exception_and_throw with no surrounding try'=>function() {\n constant_exception_and_throw(5, 7);\n },\n 'constant_exception_and_throw with surrounding try'=>function() {\n try {\n constant_exception_and_throw(5, 7);\n } catch (Exception $e) {}\n },\n);\n$results = array_fill_keys(array_keys($tests), 0);\n$testCount = 30;\nconst LINE_SEPARATOR = PHP_EOL; //\"<br>\";\n\nfor ($x = 0; $x < $testCount; ++$x) {\n if (($testCount-$x) % 5 === 0) {\n echo \"$x test cycles done so far\".LINE_SEPARATOR;\n }\n $tests = shuffle_assoc($tests);\n foreach ($tests as $k => $f) {\n $start = microtime(true);\n for ($i = 0; $i < 1000000; ++$i) {\n $f();\n }\n $results[$k] += microtime(true) - $start;\n }\n}\necho LINE_SEPARATOR;\nforeach ($results as $type => $result) {\n echo $type.' = '.number_format($result/$testCount, 4).LINE_SEPARATOR;\n}\n do_nothing with no surrounding try = 0.1873\ndo_nothing with surrounding try = 0.1990\nnew_exception_but_not_throw with no surrounding try = 1.1046\nnew_exception_but_not_throw with surrounding try = 1.1079\nnew_exception_and_throw with no surrounding try = 1.2114\nnew_exception_and_throw with surrounding try = 1.2208\nconstant_exception_and_throw with no surrounding try = 0.3214\nconstant_exception_and_throw with surrounding try = 0.3312\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14959/"
] |
104,330
|
<p>I have a table with a "Date" column, and I would like to do a query that does the following:</p>
<p>If the date is a <strong>Monday</strong>, <strong>Tuesday</strong>, <strong>Wednesday</strong>, or <strong>Thursday</strong>, the displayed date should be shifted up by 1 day, as in <pre>DATEADD(day, 1, [Date])</pre> On the other hand, if it is a <strong>Friday</strong>, the displayed date should be incremented by 3 days (i.e. so it becomes the following <em>Monday</em>).</p>
<p>How do I do this in my SELECT statement? As in,</p>
<pre>SELECT somewayofdoingthis([Date]) FROM myTable</pre>
<p>(This is SQL Server 2000.)</p>
|
[
{
"answer_id": 104362,
"author": "Dave Costa",
"author_id": 6568,
"author_profile": "https://Stackoverflow.com/users/6568",
"pm_score": 1,
"selected": false,
"text": "CASE\n WHEN [Date] is a Friday THEN DATEADD( day, 3, [Date] )\n ELSE DATEADD( day, 1, [Date] )\nEND\n"
},
{
"answer_id": 104384,
"author": "Rob Allen",
"author_id": 149,
"author_profile": "https://Stackoverflow.com/users/149",
"pm_score": 1,
"selected": false,
"text": "select case when DATENAME(dw, [date]) = 'Monday' then DATEADD(dw, 1, [Date])\n when DATENAME(dw, [date]) = 'Tuesday' then DATEADD(dw, 1, [Date])\n when DATENAME(dw, [date]) = 'Wednesday' then DATEADD(dw, 1, [Date])\n when DATENAME(dw, [date]) = 'Thursday' then DATEADD(dw, 1, [Date])\n when DATENAME(dw, [date]) = 'Friday' then DATEADD(dw, 3, [Date])\n end as nextDay\n ...\n"
},
{
"answer_id": 104385,
"author": "JustinD",
"author_id": 12063,
"author_profile": "https://Stackoverflow.com/users/12063",
"pm_score": 1,
"selected": false,
"text": "select dayname,newdayname =\n CASE dayname\n WHEN 'Monday' THEN 'Tuesday'\n WHEN 'Tuesday' THEN 'Wednesday'\n WHEN 'Wednesday' THEN 'Thursday'\n WHEN 'Thursday' THEN 'Friday'\n WHEN 'Friday' THEN 'Monday'\n WHEN 'Saturday' THEN 'Monday'\n WHEN 'Sunday' THEN 'Monday'\nEND\nFROM UDO_DAYS\n"
},
{
"answer_id": 104386,
"author": "K Richard",
"author_id": 16771,
"author_profile": "https://Stackoverflow.com/users/16771",
"pm_score": 4,
"selected": true,
"text": "CASE\nWHEN\n DATEPART(dw, [Date]) IN (2,3,4,5)\nTHEN\n DATEADD(d, 1, [Date])\nWHEN\n DATEPART(dw, [Date]) = 6\nTHEN\n DATEADD(d, 3, [Date])\nELSE\n [Date]\nEND AS [ConvertedDate]\n"
},
{
"answer_id": 104390,
"author": "Brian",
"author_id": 2831,
"author_profile": "https://Stackoverflow.com/users/2831",
"pm_score": 2,
"selected": false,
"text": "CREATE FUNCTION dbo.GetNextWDay(@Day datetime)\nRETURNS DATETIME\nAS\nBEGIN \n DECLARE @ReturnDate DateTime\n\n set @ReturnDate = dateadd(dd, 1, @Day)\n\n if (select datename(@ReturnDate))) = 'Saturday'\n set @ReturnDate = dateadd(dd, 2, @ReturnDate)\n\n if (select datename(@ReturnDate) = 'Sunday'\n set @ReturnDate = dateadd(dd, 1, @ReturnDate)\n\n RETURN @ReturnDate\nEND\n"
},
{
"answer_id": 104399,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 2,
"selected": false,
"text": "select case when datepart(dw,[Date]) between 2 and 5 then DATEADD(dd, 1, [Date])\nwhen datepart(dw,[Date]) = 6 then DATEADD(dd, 3, [Date]) else [Date] end as [Date] \n"
},
{
"answer_id": 104428,
"author": "LeppyR64",
"author_id": 16592,
"author_profile": "https://Stackoverflow.com/users/16592",
"pm_score": -1,
"selected": false,
"text": "create table #dates (dt datetime)\ninsert into #dates (dt) values ('1/1/2001')\ninsert into #dates (dt) values ('1/2/2001')\ninsert into #dates (dt) values ('1/3/2001')\ninsert into #dates (dt) values ('1/4/2001')\ninsert into #dates (dt) values ('1/5/2001')\n\n select\n dt, day(dt), dateadd(dd,1,dt)\n from\n #dates\n where\n day(dt) between 1 and 4\n\n union all\n\n select\n dt, day(dt), dateadd(dd,3,dt)\n from\n #dates\n where\n day(dt) = 5\n\n drop table #dates\n"
},
{
"answer_id": 104450,
"author": "user19164",
"author_id": 19164,
"author_profile": "https://Stackoverflow.com/users/19164",
"pm_score": 2,
"selected": false,
"text": "case\n --Sunday thru Thursday are shifted forward 1 day\n when datepart(weekday, [Date]) in (1,2,3,4,5) then dateadd(day, 1, [Date]) \n --Friday is shifted forward to Monday\n when datepart(weekday, [Date]) = 6 then dateadd(day, 3, [Date])\n --Saturday is shifted forward to Monday\n when datepart(weekday, [Date]) = 7 then dateadd(day, 2, [Date])\nend\n select dateadd(day, 1 + (datepart(weekday, [Date])/6) * (8-datepart(weekday, [Date])), [Date])\n"
},
{
"answer_id": 105029,
"author": "CindyH",
"author_id": 12897,
"author_profile": "https://Stackoverflow.com/users/12897",
"pm_score": 0,
"selected": false,
"text": "CREATE FUNCTION dbo.GetNextWDay(@Day datetime)\nRETURNS DATETIME\nAS\nBEGIN\n DECLARE @ReturnDate DateTime\n\n set @ReturnDate = dateadd(dd, 1, @Day)\n if datename(dw, @ReturnDate) = 'Saturday'\n set @ReturnDate = dateadd(dd, 2, @ReturnDate)\n if datename(dw, @ReturnDate) = 'Sunday'\n set @ReturnDate = dateadd(dd, 1, @ReturnDate)\n RETURN @ReturnDate\nEND\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10675/"
] |
104,339
|
<p>I'm doing some Objective-C programming that involves parsing an NSXmlDocument and populating an objects properties from the result.</p>
<p>First version looked like this:</p>
<pre><code>if([elementName compare:@"companyName"] == 0)
[character setCorporationName:currentElementText];
else if([elementName compare:@"corporationID"] == 0)
[character setCorporationID:currentElementText];
else if([elementName compare:@"name"] == 0)
...
</code></pre>
<p>But I don't like the <code>if-else-if-else</code> pattern this produces. Looking at the <code>switch</code> statement I see that i can only handle <code>ints</code>, <code>chars</code> etc and not objects... so is there a better implementation pattern I'm not aware of?</p>
<p>BTW I did actually come up with a better solution for setting the object's properties, but I want to know specifically about the <code>if</code>-<code>else</code> vs <code>switch</code> pattern in Objective-C</p>
|
[
{
"answer_id": 104610,
"author": "Palmin",
"author_id": 5949,
"author_profile": "https://Stackoverflow.com/users/5949",
"pm_score": 2,
"selected": false,
"text": "if-else switch if-else"
},
{
"answer_id": 109702,
"author": "Barry Wark",
"author_id": 2140,
"author_profile": "https://Stackoverflow.com/users/2140",
"pm_score": 1,
"selected": false,
"text": "elementNameCode typedef enum { \n companyName = 0,\n companyID, \n ...,\n Unknown\n } ElementCode;\n\n @interface NSString (ElementNameCodeAdditions)\n - (ElementCode)elementNameCode; \n @end\n\n @implementation NSString (ElementNameCodeAdditions)\n - (ElementCode)elementNameCode {\n if([self compare:@\"companyName\"]==0) {\n return companyName;\n } else if([self compare:@\"companyID\"]==0) {\n return companyID;\n } ... {\n\n }\n\n return Unknown;\n }\n @end\n [elementName elementNameCode]"
},
{
"answer_id": 110244,
"author": "Kendall Helmstetter Gelner",
"author_id": 6330,
"author_profile": "https://Stackoverflow.com/users/6330",
"pm_score": 2,
"selected": false,
"text": "if([elementName isEqualToString:@\"companyName\"] ) \n [character setCorporationName:currentElementText]; \nelse if([elementName isEqualToString:@\"corporationID\"] ) \n [character setCorporationID:currentElementText]; \nelse if([elementName isEqualToString:@\"name\"] ) \n"
},
{
"answer_id": 110254,
"author": "jmah",
"author_id": 3948,
"author_profile": "https://Stackoverflow.com/users/3948",
"pm_score": 4,
"selected": false,
"text": "[character setValue:currentElementText forKey:elementName];\n if (![validKeysCollection containsObject:elementName])\n // Exception or error\n"
},
{
"answer_id": 118361,
"author": "Brad Larson",
"author_id": 19679,
"author_profile": "https://Stackoverflow.com/users/19679",
"pm_score": 2,
"selected": false,
"text": "typedef enum { UNKNOWNRESIDUE, DEOXYADENINE, DEOXYCYTOSINE, DEOXYGUANINE, DEOXYTHYMINE } SLSResidueType;\n\nstatic NSDictionary *pdbResidueLookupTable;\n...\n\nif (pdbResidueLookupTable == nil)\n{\n pdbResidueLookupTable = [[NSDictionary alloc] initWithObjectsAndKeys:\n [NSNumber numberWithInteger:DEOXYADENINE], @\"DA\", \n [NSNumber numberWithInteger:DEOXYCYTOSINE], @\"DC\",\n [NSNumber numberWithInteger:DEOXYGUANINE], @\"DG\",\n [NSNumber numberWithInteger:DEOXYTHYMINE], @\"DT\",\n nil]; \n}\n\nSLSResidueType residueIdentifier = [[pdbResidueLookupTable objectForKey:residueType] intValue];\nswitch (residueIdentifier)\n{\n case DEOXYADENINE: do something; break;\n case DEOXYCYTOSINE: do something; break;\n case DEOXYGUANINE: do something; break;\n case DEOXYTHYMINE: do something; break;\n}\n"
},
{
"answer_id": 138452,
"author": "Michael Buckley",
"author_id": 22540,
"author_profile": "https://Stackoverflow.com/users/22540",
"pm_score": 5,
"selected": true,
"text": "<xmlroot>\n <corporationID>\n <stockSymbol>EXAM</stockSymbol>\n <uuid>31337</uuid>\n </corporationID>\n <companyName>Example Inc.</companyName>\n</xmlroot>\n NSXMLElement* root = [xmlDocument rootElement];\n\n// Assuming that we only have one of each element.\n[character setCorperationName:[[[root elementsForName:@\"companyName\"] objectAtIndex:0] stringValue]];\n\nNSXMLElement* corperationId = [root elementsForName:@\"corporationID\"];\n[character setCorperationStockSymbol:[[[corperationId elementsForName:@\"stockSymbol\"] objectAtIndex:0] stringValue]];\n[character setCorperationUUID:[[[corperationId elementsForName:@\"uuid\"] objectAtIndex:0] stringValue]];\n // The first line is the same as the last example, because NSXMLElement inherits from NSXMLNode\nNSXMLNode* aNode = [xmlDocument rootElement];\nwhile(aNode = [aNode nextNode]){\n if([[aNode name] isEqualToString:@\"companyName\"]){\n [character setCorperationName:[aNode stringValue]];\n }else if([[aNode name] isEqualToString:@\"corporationID\"]){\n NSXMLNode* correctParent = aNode;\n while((aNode = [aNode nextNode]) == nil && [aNode parent != correctParent){\n if([[aNode name] isEqualToString:@\"stockSymbol\"]){\n [character setCorperationStockSymbol:[aNode stringValue]];\n }else if([[aNode name] isEqualToString:@\"uuid\"]){\n [character setCorperationUUID:[aNode stringValue]];\n }\n }\n }\n}\n - (NSNode*)parse_companyName:(NSNode*)aNode\n{\n [character setCorperationName:[aNode stringValue]];\n return aNode;\n}\n\n- (NSNode*)parse_corporationID:(NSNode*)aNode\n{\n NSXMLNode* correctParent = aNode;\n while((aNode = [aNode nextNode]) == nil && [aNode parent != correctParent){\n [self invokeMethodForNode:aNode prefix:@\"parse_corporationID_\"];\n }\n return [aNode previousNode];\n}\n\n- (NSNode*)parse_corporationID_stockSymbol:(NSNode*)aNode\n{\n [character setCorperationStockSymbol:[aNode stringValue]];\n return aNode;\n}\n\n- (NSNode*)parse_corporationID_uuid:(NSNode*)aNode\n{\n [character setCorperationUUID:[aNode stringValue]];\n return aNode;\n}\n - (NSNode*)invokeMethodForNode:(NSNode*)aNode prefix:(NSString*)aPrefix\n{\n NSNode* ret = nil;\n NSString* methodName = [NSString stringWithFormat:@\"%@%@:\", prefix, [aNode name]];\n SEL selector = NSSelectorFromString(methodName);\n if([self respondsToSelector:selector])\n ret = [self performSelector:selector withObject:aNode];\n return ret;\n}\n NSXMLNode* aNode = [xmlDocument rootElement];\nwhile(aNode = [aNode nextNode]){\n aNode = [self invokeMethodForNode:aNode prefix:@\"parse_\"];\n}\n"
},
{
"answer_id": 141544,
"author": "epatel",
"author_id": 842,
"author_profile": "https://Stackoverflow.com/users/842",
"pm_score": 3,
"selected": false,
"text": "#define TEST( _name, _method ) \\\n if ([elementName isEqualToString:@ _name] ) \\\n [character _method:currentElementText]; else\n#define ENDTEST { /* empty */ }\n\nTEST( \"companyName\", setCorporationName )\nTEST( \"setCorporationID\", setCorporationID )\nTEST( \"name\", setName )\n:\n:\nENDTEST\n"
},
{
"answer_id": 142128,
"author": "Wevah",
"author_id": 14256,
"author_profile": "https://Stackoverflow.com/users/14256",
"pm_score": 3,
"selected": false,
"text": "SEL selector = NSSelectorFromString([NSString stringWithFormat:@\"set%@:\", [elementName capitalizedString]]);\n\n[character performSelector:selector withObject:currentElementText];\n [character setValue:currentElementText forKey:elementName]; // KVC-style\n"
},
{
"answer_id": 262687,
"author": "Mike Shields",
"author_id": 29030,
"author_profile": "https://Stackoverflow.com/users/29030",
"pm_score": 1,
"selected": false,
"text": "static CFDictionaryRef map = NULL;\nint count = 3;\nconst void *keys[count] = { @\"key1\", @\"key2\", @\"key3\" };\nconst void *values[count] = { (uintptr_t)1, (uintptr_t)2, (uintptr_t)3 };\n\nif (map == NULL)\n map = CFDictionaryCreate(NULL,keys,values,count,&kCFTypeDictionaryKeyCallBacks,NULL);\n\n\nswitch((uintptr_t)CFDictionaryGetValue(map,[node name]))\n{\n case 1:\n // do something\n break;\n case 2:\n // do something else\n break;\n case 3:\n // this other thing too\n break;\n}\n"
},
{
"answer_id": 1215783,
"author": "Dennis Munsie",
"author_id": 8728,
"author_profile": "https://Stackoverflow.com/users/8728",
"pm_score": 2,
"selected": false,
"text": "NSString *capName = [elementName stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:[[elementName substringToIndex:1] uppercaseString]];\nSEL selector = NSSelectorFromString([NSString stringWithFormat:@\"set%@:\", capName]);\n"
},
{
"answer_id": 10124375,
"author": "Lvsti",
"author_id": 1117912,
"author_profile": "https://Stackoverflow.com/users/1117912",
"pm_score": 2,
"selected": false,
"text": "BOOL switch_object(id aObject, ...)\n{\n va_list args;\n va_start(args, aObject);\n\n id value = nil;\n BOOL matchFound = NO;\n\n while ( (value = va_arg(args,id)) )\n {\n void (^block)(void) = va_arg(args,id);\n if ( [aObject isEqual:value] )\n {\n block();\n matchFound = YES;\n break;\n }\n }\n\n va_end(args);\n return matchFound;\n}\n while NSString* str = @\"stuff\";\nswitch_object(str,\n @\"blah\", ^{\n NSLog(@\"blah\");\n },\n @\"foobar\", ^{\n NSLog(@\"foobar\");\n },\n @\"stuff\", ^{\n NSLog(@\"stuff\");\n },\n @\"poing\", ^{\n NSLog(@\"poing\");\n },\n nil); // <-- sentinel\n\n// will print \"stuff\"\n"
},
{
"answer_id": 14789501,
"author": "vikingosegundo",
"author_id": 106435,
"author_profile": "https://Stackoverflow.com/users/106435",
"pm_score": 0,
"selected": false,
"text": "#import <Foundation/Foundation.h>\ntypedef id(^FilterBlock)(id element, NSUInteger idx, BOOL *stop);\n\n@interface NSObject (Functional)\n-(id)processByPerformingFilterBlocks:(NSArray *)filterBlocks;\n@end\n @implementation NSObject (Functional)\n-(id)processByPerformingFilterBlocks:(NSArray *)filterBlocks\n{\n __block id blockSelf = self;\n [filterBlocks enumerateObjectsUsingBlock:^( id (^block)(id,NSUInteger idx, BOOL*) , NSUInteger idx, BOOL *stop) {\n blockSelf = block(blockSelf, idx, stop);\n }];\n\n return blockSelf;\n}\n@end\n n FilterBlock caseYES = ^id(id element, NSUInteger idx, BOOL *breakAfter){ \n if ([element isEqualToString:@\"YES\"]) { \n NSLog(@\"You did it\"); \n *breakAfter = YES;\n } \n return element;\n};\n\nFilterBlock caseNO = ^id(id element, NSUInteger idx, BOOL *breakAfter){ \n if ([element isEqualToString:@\"NO\"] ) { \n NSLog(@\"Nope\");\n *breakAfter = YES;\n }\n return element;\n};\n NSArray *filters = @[caseYES, caseNO];\n id obj1 = @\"YES\";\nid obj2 = @\"NO\";\n[obj1 processByPerformingFilterBlocks:filters];\n[obj2 processByPerformingFilterBlocks:filters];\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18590/"
] |
104,363
|
<p>I'm trying to upgrade a package using yum on Fedora 8. The package is <code>elfutils</code>. Here's what I have installed locally:</p>
<pre><code>$ yum info elfutils
Installed Packages
Name : elfutils
Arch : x86_64
Version: 0.130
Release: 3.fc8
Size : 436 k
Repo : installed
Summary: A collection of utilities and DSOs to handle compiled objects
</code></pre>
<p>There's a bug in this version, and according to the <a href="https://bugzilla.redhat.com/show_bug.cgi?id=377241" rel="nofollow noreferrer">bug report</a>, a newer version has been pushed to the Fedora 8 stable repository. But, if I try to update:</p>
<pre><code>$ yum update elfutils
Setting up Update Process
Could not find update match for elfutils
No Packages marked for Update
</code></pre>
<p>Here are my repositories:</p>
<pre><code>$ yum repolist enabled
repo id repo name status
InstallMedia Fedora 8 enabled
fedora Fedora 8 - x86_64 enabled
updates Fedora 8 - x86_64 - Updates enabled
</code></pre>
<p>What am I missing?</p>
|
[
{
"answer_id": 104479,
"author": "ethyreal",
"author_id": 18159,
"author_profile": "https://Stackoverflow.com/users/18159",
"pm_score": 1,
"selected": false,
"text": "yum remove elfutils\n yum install elfutils\n yum update\n yum upgrade\n"
},
{
"answer_id": 104801,
"author": "Lorin Hochstein",
"author_id": 742,
"author_profile": "https://Stackoverflow.com/users/742",
"pm_score": 2,
"selected": false,
"text": "fedora-release"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/742/"
] |
104,373
|
<p>I wrote an application in Java and when it runs on one customer's computer running OS X The Save and Export buttons are disabled. (Everything else works in the application.)</p>
<p>Both of these buttons open up a standard save file dialog.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 104611,
"author": "Angelo van der Sijpt",
"author_id": 19144,
"author_profile": "https://Stackoverflow.com/users/19144",
"pm_score": 2,
"selected": false,
"text": "setEnabled false setEnabled false"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/363822/"
] |
104,383
|
<p>In Visual Basic 6, when I attempt to access <em>Project > References</em>, it throws an error:</p>
<blockquote>
<p>Error accessing system registry</p>
</blockquote>
<p>I am:</p>
<ul>
<li>Logged in as the local computer administrator </li>
<li>running Windows XP Professional and </li>
<li>I can execute <code>regedt32.exe</code> and access all the registry keys just fine. </li>
</ul>
<p>VB6 was installed as the local administrator. </p>
<p>Any idea why this happens? </p>
<hr>
<p>I'm running crystal reports 8.5 and it supposed to already have fixed that issue but apparently I still have the issue with 8.5 installed. I have also made the attempt of reinstalling crystal reports with no luck on the issue. </p>
|
[
{
"answer_id": 1884282,
"author": "Jim Lang",
"author_id": 194002,
"author_profile": "https://Stackoverflow.com/users/194002",
"pm_score": 3,
"selected": false,
"text": "HKCR\\TypeLib\\{00020905-0000-0000-C000-000000000046}\\8.5 ACCESS DENIED psexec -i -d -s c:\\windows\\regedit.exe psexec"
},
{
"answer_id": 48155500,
"author": "Zeus",
"author_id": 9187934,
"author_profile": "https://Stackoverflow.com/users/9187934",
"pm_score": 0,
"selected": false,
"text": "SYSTEM"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18853/"
] |
104,395
|
<p>I need some info on how to use margins and how exactly <em>padding</em> works.</p>
<p>For example: Should I put a line to occupy the whole width of the page (no matter what resolution is used to display the web page) letting just a small border on each side, how could I achieve this?</p>
|
[
{
"answer_id": 104536,
"author": "Thomas Koschel",
"author_id": 2012356,
"author_profile": "https://Stackoverflow.com/users/2012356",
"pm_score": 0,
"selected": false,
"text": "<table width=\"100%\" cellpadding=\"5\">\n <tr>\n <td>\nOne, two, three ... One, two, three ... One, two, three ... One, two, three ... One, two, three ... One, two, three ... One, two, three ... One, two, three ... One, two, three ... \n </td>\n </tr>\n</table>\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19159/"
] |
104,420
|
<p>How do I generate all the permutations of a list? For example:</p>
<pre><code>permutations([])
[]
permutations([1])
[1]
permutations([1, 2])
[1, 2]
[2, 1]
permutations([1, 2, 3])
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
</code></pre>
|
[
{
"answer_id": 104426,
"author": "Ricardo Reyes",
"author_id": 3399,
"author_profile": "https://Stackoverflow.com/users/3399",
"pm_score": 5,
"selected": false,
"text": "def permutations (orig_list):\n if not isinstance(orig_list, list):\n orig_list = list(orig_list)\n\n yield orig_list\n\n if len(orig_list) == 1:\n return\n\n for n in sorted(orig_list):\n new_list = orig_list[:]\n pos = new_list.index(n)\n del(new_list[pos])\n new_list.insert(0, n)\n for resto in permutations(new_list[1:]):\n if new_list[:1] + resto <> orig_list:\n yield new_list[:1] + resto\n"
},
{
"answer_id": 104436,
"author": "Eli Bendersky",
"author_id": 8206,
"author_profile": "https://Stackoverflow.com/users/8206",
"pm_score": 10,
"selected": true,
"text": "itertools.permutations import itertools\nlist(itertools.permutations([1, 2, 3]))\n itertools.permutations def permutations(elements):\n if len(elements) <= 1:\n yield elements\n return\n for perm in permutations(elements[1:]):\n for i in range(len(elements)):\n # nb elements[0:1] works in both string and list contexts\n yield perm[:i] + elements[0:1] + perm[i:]\n itertools.permutations def permutations(iterable, r=None):\n # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC\n # permutations(range(3)) --> 012 021 102 120 201 210\n pool = tuple(iterable)\n n = len(pool)\n r = n if r is None else r\n if r > n:\n return\n indices = range(n)\n cycles = range(n, n-r, -1)\n yield tuple(pool[i] for i in indices[:r])\n while n:\n for i in reversed(range(r)):\n cycles[i] -= 1\n if cycles[i] == 0:\n indices[i:] = indices[i+1:] + indices[i:i+1]\n cycles[i] = n - i\n else:\n j = cycles[i]\n indices[i], indices[-j] = indices[-j], indices[i]\n yield tuple(pool[i] for i in indices[:r])\n break\n else:\n return\n itertools.product def permutations(iterable, r=None):\n pool = tuple(iterable)\n n = len(pool)\n r = n if r is None else r\n for indices in product(range(n), repeat=r):\n if len(set(indices)) == r:\n yield tuple(pool[i] for i in indices)\n"
},
{
"answer_id": 104471,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 8,
"selected": false,
"text": "import itertools\nitertools.permutations([1, 2, 3])\n list(permutations(xs))"
},
{
"answer_id": 108651,
"author": "Ber",
"author_id": 11527,
"author_profile": "https://Stackoverflow.com/users/11527",
"pm_score": 4,
"selected": false,
"text": "def permute_in_place(a):\n a.sort()\n yield list(a)\n\n if len(a) <= 1:\n return\n\n first = 0\n last = len(a)\n while 1:\n i = last - 1\n\n while 1:\n i = i - 1\n if a[i] < a[i+1]:\n j = last - 1\n while not (a[i] < a[j]):\n j = j - 1\n a[i], a[j] = a[j], a[i] # swap the values\n r = a[i+1:last]\n r.reverse()\n a[i+1:last] = r\n yield list(a)\n break\n if i == first:\n a.reverse()\n return\n\nif __name__ == '__main__':\n for n in range(5):\n for a in permute_in_place(range(1, n+1)):\n print a\n print\n\n for a in permute_in_place([0, 0, 1, 1, 1]):\n print a\n print\n"
},
{
"answer_id": 170248,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 8,
"selected": false,
"text": "itertools import itertools\n print(list(itertools.permutations([1,2,3,4], 2)))\n\n[(1, 2), (1, 3), (1, 4),\n(2, 1), (2, 3), (2, 4),\n(3, 1), (3, 2), (3, 4),\n(4, 1), (4, 2), (4, 3)]\n print(list(itertools.combinations('123', 2)))\n\n[('1', '2'), ('1', '3'), ('2', '3')]\n print(list(itertools.product([1,2,3], [4,5,6])))\n\n[(1, 4), (1, 5), (1, 6),\n(2, 4), (2, 5), (2, 6),\n(3, 4), (3, 5), (3, 6)]\n print(list(itertools.product([1,2], repeat=3)))\n\n[(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2),\n(2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]\n"
},
{
"answer_id": 5501066,
"author": "tzwenn",
"author_id": 522943,
"author_profile": "https://Stackoverflow.com/users/522943",
"pm_score": 4,
"selected": false,
"text": "def permutList(l):\n if not l:\n return [[]]\n res = []\n for e in l:\n temp = l[:]\n temp.remove(e)\n res.extend([[e] + r for r in permutList(temp)])\n\n return res\n"
},
{
"answer_id": 7140205,
"author": "zmk",
"author_id": 891004,
"author_profile": "https://Stackoverflow.com/users/891004",
"pm_score": 4,
"selected": false,
"text": "list2Perm = [1, 2.0, 'three']\nlistPerm = [[a, b, c]\n for a in list2Perm\n for b in list2Perm\n for c in list2Perm\n if ( a != b and b != c and a != c )\n ]\nprint listPerm\n [\n [1, 2.0, 'three'], \n [1, 'three', 2.0], \n [2.0, 1, 'three'], \n [2.0, 'three', 1], \n ['three', 1, 2.0], \n ['three', 2.0, 1]\n]\n"
},
{
"answer_id": 7733966,
"author": "kx2k",
"author_id": 990523,
"author_profile": "https://Stackoverflow.com/users/990523",
"pm_score": 6,
"selected": false,
"text": "def permutations(head, tail=''):\n if len(head) == 0:\n print(tail)\n else:\n for i in range(len(head)):\n permutations(head[:i] + head[i+1:], tail + head[i])\n permutations('abc')\n"
},
{
"answer_id": 10799849,
"author": "Eric O Lebigot",
"author_id": 42973,
"author_profile": "https://Stackoverflow.com/users/42973",
"pm_score": 3,
"selected": false,
"text": "def all_perms(elements):\n if len(elements) <= 1:\n yield elements # Only permutation possible = no permutation\n else:\n # Iteration over the first element in the result permutation:\n for (index, first_elmt) in enumerate(elements):\n other_elmts = elements[:index]+elements[index+1:]\n for permutation in all_perms(other_elmts): \n yield [first_elmt] + permutation\n len(elements) <= 1 0 yield"
},
{
"answer_id": 11962517,
"author": "Silveira Neto",
"author_id": 914818,
"author_profile": "https://Stackoverflow.com/users/914818",
"pm_score": 5,
"selected": false,
"text": "#!/usr/bin/env python\n\ndef perm(a, k=0):\n if k == len(a):\n print a\n else:\n for i in xrange(k, len(a)):\n a[k], a[i] = a[i] ,a[k]\n perm(a, k+1)\n a[k], a[i] = a[i], a[k]\n\nperm([1,2,3])\n [1, 2, 3]\n[1, 3, 2]\n[2, 1, 3]\n[2, 3, 1]\n[3, 2, 1]\n[3, 1, 2]\n perm(list(\"ball\")) perm(\"ball\")"
},
{
"answer_id": 14470271,
"author": "Chen Xie",
"author_id": 1234376,
"author_profile": "https://Stackoverflow.com/users/1234376",
"pm_score": 3,
"selected": false,
"text": "n factorial n global result\nresult = [] \n\ndef permutation(li):\nif li == [] or li == None:\n return\n\nif len(li) == 1:\n result.append(li[0])\n print result\n result.pop()\n return\n\nfor i in range(0,len(li)):\n result.append(li[i])\n permutation(li[:i] + li[i+1:])\n result.pop() \n permutation([1,2,3])\n [1, 2, 3]\n[1, 3, 2]\n[2, 1, 3]\n[2, 3, 1]\n[3, 1, 2]\n[3, 2, 1]\n"
},
{
"answer_id": 16446022,
"author": "Adrian Statescu",
"author_id": 633040,
"author_profile": "https://Stackoverflow.com/users/633040",
"pm_score": 2,
"selected": false,
"text": "from __future__ import print_function\n\ndef perm(n):\n p = []\n for i in range(0,n+1):\n p.append(i)\n while True:\n for i in range(1,n+1):\n print(p[i], end=' ')\n print(\"\")\n i = n - 1\n found = 0\n while (not found and i>0):\n if p[i]<p[i+1]:\n found = 1\n else:\n i = i - 1\n k = n\n while p[i]>p[k]:\n k = k - 1\n aux = p[i]\n p[i] = p[k]\n p[k] = aux\n for j in range(1,(n-i)/2+1):\n aux = p[i+j]\n p[i+j] = p[n-j+1]\n p[n-j+1] = aux\n if not found:\n break\n\nperm(5)\n"
},
{
"answer_id": 17391851,
"author": "Paolo",
"author_id": 2536705,
"author_profile": "https://Stackoverflow.com/users/2536705",
"pm_score": 4,
"selected": false,
"text": "def addperm(x,l):\n return [ l[0:i] + [x] + l[i:] for i in range(len(l)+1) ]\n\ndef perm(l):\n if len(l) == 0:\n return [[]]\n return [x for y in perm(l[1:]) for x in addperm(l[0],y) ]\n\nprint perm([ i for i in range(3)])\n [[0, 1, 2], [1, 0, 2], [1, 2, 0], [0, 2, 1], [2, 0, 1], [2, 1, 0]]\n"
},
{
"answer_id": 17504089,
"author": "cdiggins",
"author_id": 184528,
"author_profile": "https://Stackoverflow.com/users/184528",
"pm_score": 2,
"selected": false,
"text": "def permute(xs, low=0):\n if low + 1 >= len(xs):\n yield xs\n else:\n for p in permute(xs, low + 1):\n yield p \n for i in range(low + 1, len(xs)): \n xs[low], xs[i] = xs[i], xs[low]\n for p in permute(xs, low + 1):\n yield p \n xs[low], xs[i] = xs[i], xs[low]\n\nfor p in permute([1, 2, 3, 4]):\n print p\n"
},
{
"answer_id": 18135428,
"author": "timeeeee",
"author_id": 1478340,
"author_profile": "https://Stackoverflow.com/users/1478340",
"pm_score": 4,
"selected": false,
"text": "from math import factorial\ndef permutations(l):\n permutations=[]\n length=len(l)\n for x in xrange(factorial(length)):\n available=list(l)\n newPermutation=[]\n for radix in xrange(length, 0, -1):\n placeValue=factorial(radix-1)\n index=x/placeValue\n newPermutation.append(available.pop(index))\n x-=index*placeValue\n permutations.append(newPermutation)\n return permutations\n\npermutations(range(3))\n [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]]\n"
},
{
"answer_id": 20014561,
"author": "piggybox",
"author_id": 2102764,
"author_profile": "https://Stackoverflow.com/users/2102764",
"pm_score": 3,
"selected": false,
"text": "def permutation(list):\n if len(list) == 0:\n return [[]]\n else:\n return [[x] + ys for x in list for ys in permutation(delete(list, x))]\n\ndef delete(list, item):\n lc = list[:]\n lc.remove(item)\n return lc\n"
},
{
"answer_id": 23732953,
"author": "darxtrix",
"author_id": 2679770,
"author_profile": "https://Stackoverflow.com/users/2679770",
"pm_score": 2,
"selected": false,
"text": ">>> import copy\n>>> def perm(prefix,rest):\n... for e in rest:\n... new_rest=copy.copy(rest)\n... new_prefix=copy.copy(prefix)\n... new_prefix.append(e)\n... new_rest.remove(e)\n... if len(new_rest) == 0:\n... print new_prefix + new_rest\n... continue\n... perm(new_prefix,new_rest)\n... \n>>> perm([],['a','b','c','d'])\n['a', 'b', 'c', 'd']\n['a', 'b', 'd', 'c']\n['a', 'c', 'b', 'd']\n['a', 'c', 'd', 'b']\n['a', 'd', 'b', 'c']\n['a', 'd', 'c', 'b']\n['b', 'a', 'c', 'd']\n['b', 'a', 'd', 'c']\n['b', 'c', 'a', 'd']\n['b', 'c', 'd', 'a']\n['b', 'd', 'a', 'c']\n['b', 'd', 'c', 'a']\n['c', 'a', 'b', 'd']\n['c', 'a', 'd', 'b']\n['c', 'b', 'a', 'd']\n['c', 'b', 'd', 'a']\n['c', 'd', 'a', 'b']\n['c', 'd', 'b', 'a']\n['d', 'a', 'b', 'c']\n['d', 'a', 'c', 'b']\n['d', 'b', 'a', 'c']\n['d', 'b', 'c', 'a']\n['d', 'c', 'a', 'b']\n['d', 'c', 'b', 'a']\n"
},
{
"answer_id": 28256360,
"author": "Cmyker",
"author_id": 1079659,
"author_profile": "https://Stackoverflow.com/users/1079659",
"pm_score": 2,
"selected": false,
"text": "def permute(items):\n length = len(items)\n def inner(ix=[]):\n do_yield = len(ix) == length - 1\n for i in range(0, length):\n if i in ix: #avoid duplicates\n continue\n if do_yield:\n yield tuple([items[y] for y in ix + [i]])\n else:\n for p in inner(ix + [i]):\n yield p\n return inner()\n for p in permute((1,2,3)):\n print(p)\n\n(1, 2, 3)\n(1, 3, 2)\n(2, 1, 3)\n(2, 3, 1)\n(3, 1, 2)\n(3, 2, 1)\n"
},
{
"answer_id": 30112080,
"author": "manish kumar",
"author_id": 4166033,
"author_profile": "https://Stackoverflow.com/users/4166033",
"pm_score": 2,
"selected": false,
"text": "def pzip(c, seq):\n result = []\n for item in seq:\n for i in range(len(item)+1):\n result.append(item[i:]+c+item[:i])\n return result\n\n\ndef perm(line):\n seq = [c for c in line]\n if len(seq) <=1 :\n return seq\n else:\n return pzip(seq[0], perm(seq[1:]))\n"
},
{
"answer_id": 30428753,
"author": "B. M.",
"author_id": 4016285,
"author_profile": "https://Stackoverflow.com/users/4016285",
"pm_score": 3,
"selected": false,
"text": "from numpy import empty, uint8\nfrom math import factorial\n\ndef perms(n):\n f = 1\n p = empty((2*n-1, factorial(n)), uint8)\n for i in range(n):\n p[i, :f] = i\n p[i+1:2*i+1, :f] = p[:i, :f] # constitution de blocs\n for j in range(i):\n p[:i+1, f*(j+1):f*(j+2)] = p[j+1:j+i+2, :f] # copie de blocs\n f = f*(i+1)\n return p[:n, :]\n list(itertools.permutations(range(n)) In [1]: %timeit -n10 list(permutations(range(10)))\n10 loops, best of 3: 815 ms per loop\n\nIn [2]: %timeit -n100 perms(10) \n100 loops, best of 3: 40 ms per loop\n"
},
{
"answer_id": 32448587,
"author": "Bharatwaja",
"author_id": 3944755,
"author_profile": "https://Stackoverflow.com/users/3944755",
"pm_score": -1,
"selected": false,
"text": "from itertools import product, permutations\nA = ([1,2,3])\nprint (list(permutations(sorted(A),2)))\n"
},
{
"answer_id": 36102351,
"author": "Miled Louis Rizk",
"author_id": 6023433,
"author_profile": "https://Stackoverflow.com/users/6023433",
"pm_score": 2,
"selected": false,
"text": "def calcperm(arr, size):\n result = set([()])\n for dummy_idx in range(size):\n temp = set()\n for dummy_lst in result:\n for dummy_outcome in arr:\n if dummy_outcome not in dummy_lst:\n new_seq = list(dummy_lst)\n new_seq.append(dummy_outcome)\n temp.add(tuple(new_seq))\n result = temp\n return result\n lst = [1, 2, 3, 4]\n#lst = [\"yellow\", \"magenta\", \"white\", \"blue\"]\nseq = 2\nfinal = calcperm(lst, seq)\nprint(len(final))\nprint(final)\n"
},
{
"answer_id": 38793421,
"author": "Karo Castro-Wunsch",
"author_id": 4725204,
"author_profile": "https://Stackoverflow.com/users/4725204",
"pm_score": 2,
"selected": false,
"text": "def all_insert(x, e, i=0):\n return [x[0:i]+[e]+x[i:]] + all_insert(x,e,i+1) if i<len(x)+1 else []\n\ndef for_each(X, e):\n return all_insert(X[0], e) + for_each(X[1:],e) if X else []\n\ndef permute(x):\n return [x] if len(x) < 2 else for_each( permute(x[1:]) , x[0])\n\n\nperms = permute([1,2,3])\n"
},
{
"answer_id": 43018229,
"author": "anhldbk",
"author_id": 197896,
"author_profile": "https://Stackoverflow.com/users/197896",
"pm_score": 1,
"selected": false,
"text": "def permutation(flag, k =1 ):\n N = len(flag)\n for i in xrange(0, N):\n if flag[i] != 0:\n continue\n flag[i] = k \n if k == N:\n print flag\n permutation(flag, k+1)\n flag[i] = 0\n\npermutation([0, 0, 0])\n"
},
{
"answer_id": 49072115,
"author": "abelenky",
"author_id": 34824,
"author_profile": "https://Stackoverflow.com/users/34824",
"pm_score": 0,
"selected": false,
"text": "def permutes(input,offset):\n if( len(input) == offset ):\n return [''.join(input)]\n\n result=[] \n for i in range( offset, len(input) ):\n input[offset], input[i] = input[i], input[offset]\n result = result + permutes(input,offset+1)\n input[offset], input[i] = input[i], input[offset]\n return result\n\n# input is a \"string\"\n# return value is a list of strings\ndef permutations(input):\n return permutes( list(input), 0 )\n\n# Main Program\nprint( permutations(\"wxyz\") )\n"
},
{
"answer_id": 50311529,
"author": "Ilgorbek Kuchkarov",
"author_id": 6283828,
"author_profile": "https://Stackoverflow.com/users/6283828",
"pm_score": 0,
"selected": false,
"text": "def permutation(word, first_char=None):\n if word == None or len(word) == 0: return []\n if len(word) == 1: return [word]\n\n result = []\n first_char = word[0]\n for sub_word in permutation(word[1:], first_char):\n result += insert(first_char, sub_word)\n return sorted(result)\n\ndef insert(ch, sub_word):\n arr = [ch + sub_word]\n for i in range(len(sub_word)):\n arr.append(sub_word[i:] + ch + sub_word[:i])\n return arr\n\n\nassert permutation(None) == []\nassert permutation('') == []\nassert permutation('1') == ['1']\nassert permutation('12') == ['12', '21']\n\nprint permutation('abc')\n"
},
{
"answer_id": 53785851,
"author": "Anatoly Alekseev",
"author_id": 4334120,
"author_profile": "https://Stackoverflow.com/users/4334120",
"pm_score": 2,
"selected": false,
"text": "@numba.njit()\ndef permutations(A, k):\n r = [[i for i in range(0)]]\n for i in range(k):\n r = [[a] + b for a in A for b in r if (a in b)==False]\n return r\npermutations([1,2,3],3)\n[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]\n %timeit permutations(np.arange(5),5)\n\n243 µs ± 11.1 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)\ntime: 406 ms\n\n%timeit list(itertools.permutations(np.arange(5),5))\n15.9 µs ± 8.61 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\ntime: 12.9 s\n"
},
{
"answer_id": 55070316,
"author": "Hello.World",
"author_id": 8850552,
"author_profile": "https://Stackoverflow.com/users/8850552",
"pm_score": 0,
"selected": false,
"text": "Counter from collections import Counter\n\ndef permutations(nums):\n ans = [[]]\n cache = Counter(nums)\n\n for idx, x in enumerate(nums):\n result = []\n for items in ans:\n cache1 = Counter(items)\n for id, n in enumerate(nums):\n if cache[n] != cache1[n] and items + [n] not in result:\n result.append(items + [n])\n\n ans = result\n return ans\npermutations([1, 2, 2])\n> [[1, 2, 2], [2, 1, 2], [2, 2, 1]]\n\n"
},
{
"answer_id": 55421084,
"author": "Tatsu",
"author_id": 5938224,
"author_profile": "https://Stackoverflow.com/users/5938224",
"pm_score": 2,
"selected": false,
"text": "def permutation(input):\n if len(input) == 1:\n return input if isinstance(input, list) else [input]\n\n result = []\n for i in range(len(input)):\n first = input[i]\n rest = input[:i] + input[i + 1:]\n rest_permutation = permutation(rest)\n for p in rest_permutation:\n result.append(first + p)\n return result\n print(permutation('abcd'))\nprint(permutation(['a', 'b', 'c', 'd']))\n"
},
{
"answer_id": 59433823,
"author": "Richard Ambler",
"author_id": 1340742,
"author_profile": "https://Stackoverflow.com/users/1340742",
"pm_score": 3,
"selected": false,
"text": "import trotter\n\nmy_permutations = trotter.Permutations(3, [1, 2, 3])\n\nprint(my_permutations)\n\nfor p in my_permutations:\n print(p)\n"
},
{
"answer_id": 59593816,
"author": "Maverick Meerkat",
"author_id": 6296435,
"author_profile": "https://Stackoverflow.com/users/6296435",
"pm_score": 4,
"selected": false,
"text": "def getPermutations(array):\n if len(array) == 1:\n return [array]\n permutations = []\n for i in range(len(array)): \n # get all perm's of subarray w/o current item\n perms = getPermutations(array[:i] + array[i+1:]) \n for p in perms:\n permutations.append([array[i], *p])\n return permutations\n def getPermutations(array):\n if len(array) == 1:\n yield array\n else:\n for i in range(len(array)):\n perms = getPermutations(array[:i] + array[i+1:])\n for p in perms:\n yield [array[i], *p]\n"
},
{
"answer_id": 62189160,
"author": "Dritte Saskaita",
"author_id": 12278470,
"author_profile": "https://Stackoverflow.com/users/12278470",
"pm_score": 0,
"selected": false,
"text": "def permuteArray (arr):\n\n arraySize = len(arr)\n\n permutedList = []\n\n if arraySize == 1:\n return [arr]\n\n i = 0\n\n for item in arr:\n\n for elem in permuteArray(arr[:i] + arr[i + 1:]):\n permutedList.append([item] + elem)\n\n i = i + 1 \n\n return permutedList\n"
},
{
"answer_id": 62770287,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "import sympy\nfrom sympy.utilities.iterables import multiset_permutations\nt = [1,2,3]\np = list(multiset_permutations(t))\nprint(p)\n\n# [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]\n"
},
{
"answer_id": 64471115,
"author": "Harvey Mao",
"author_id": 10665136,
"author_profile": "https://Stackoverflow.com/users/10665136",
"pm_score": 0,
"selected": false,
"text": "from typing import List\nimport time, random\n\ndef measure_time(func):\n def wrapper_time(*args, **kwargs):\n start_time = time.perf_counter()\n res = func(*args, **kwargs)\n end_time = time.perf_counter()\n return res, end_time - start_time\n\n return wrapper_time\n\n\nclass Solution:\n def permute(self, nums: List[int], method: int = 1) -> List[List[int]]:\n perms = []\n perm = []\n if method == 1:\n _, time_perm = self._permute_recur(nums, 0, len(nums) - 1, perms)\n elif method == 2:\n _, time_perm = self._permute_recur_agian(nums, perm, perms)\n print(perm)\n return perms, time_perm\n\n @measure_time\n def _permute_recur(self, nums: List[int], l: int, r: int, perms: List[List[int]]):\n # base case\n if l == r:\n perms.append(nums.copy())\n\n for i in range(l, r + 1):\n nums[l], nums[i] = nums[i], nums[l]\n self._permute_recur(nums, l + 1, r , perms)\n nums[l], nums[i] = nums[i], nums[l]\n\n @measure_time\n def _permute_recur_agian(self, nums: List[int], perm: List[int], perms_list: List[List[int]]):\n \"\"\"\n The idea is similar to nestedForLoops visualized as a recursion tree.\n \"\"\"\n if nums:\n for i in range(len(nums)):\n # perm.append(nums[i]) mistake, perm will be filled with all nums's elements.\n # Method1 perm_copy = copy.deepcopy(perm)\n # Method2 add in the parameter list using + (not in place)\n # caveat: list.append is in-place , which is useful for operating on global element perms_list\n # Note that:\n # perms_list pass by reference. shallow copy\n # perm + [nums[i]] pass by value instead of reference.\n self._permute_recur_agian(nums[:i] + nums[i+1:], perm + [nums[i]], perms_list)\n else:\n # Arrive at the last loop, i.e. leaf of the recursion tree.\n perms_list.append(perm)\n\n\n\nif __name__ == \"__main__\":\n array = [random.randint(-10, 10) for _ in range(3)]\n sol = Solution()\n # perms, time_perm = sol.permute(array, 1)\n perms2, time_perm2 = sol.permute(array, 2)\n print(perms2)\n # print(perms, perms2)\n # print(time_perm, time_perm2)\n```\n"
},
{
"answer_id": 65241289,
"author": "Michael Hodel",
"author_id": 12363750,
"author_profile": "https://Stackoverflow.com/users/12363750",
"pm_score": 0,
"selected": false,
"text": "def p(a):\n return a if len(a) == 1 else [[a[i], *j] for i in range(len(a)) for j in p(a[:i] + a[i + 1:])]\n"
},
{
"answer_id": 65542989,
"author": "Bhaskar13",
"author_id": 11930483,
"author_profile": "https://Stackoverflow.com/users/11930483",
"pm_score": 1,
"selected": false,
"text": "'''\nLexicographic permutation generation\n\nconsider example array state of [1,5,6,4,3,2] for sorted [1,2,3,4,5,6]\nafter 56432(treat as number) ->nothing larger than 6432(using 6,4,3,2) beginning with 5\nso 6 is next larger and 2345(least using numbers other than 6)\nso [1, 6,2,3,4,5]\n'''\ndef hasNextPermutation(array, len):\n ' Base Condition '\n if(len ==1):\n return False\n '''\n Set j = last-2 and find first j such that a[j] < a[j+1]\n If no such j(j==-1) then we have visited all permutations\n after this step a[j+1]>=..>=a[len-1] and a[j]<a[j+1]\n\n a[j]=5 or j=1, 6>5>4>3>2\n '''\n j = len -2\n while (j >= 0 and array[j] >= array[j + 1]):\n j= j-1\n if(j==-1):\n return False\n # print(f\"After step 2 for j {j} {array}\")\n '''\n decrease l (from n-1 to j) repeatedly until a[j]<a[l]\n Then swap a[j], a[l]\n a[l] is the smallest element > a[j] that can follow a[l]...a[j-1] in permutation\n before swap we have a[j+1]>=..>=a[l-1]>=a[l]>a[j]>=a[l+1]>=..>=a[len-1]\n after swap -> a[j+1]>=..>=a[l-1]>=a[j]>a[l]>=a[l+1]>=..>=a[len-1]\n\n a[l]=6 or l=2, j=1 just before swap [1, 5, 6, 4, 3, 2] \n after swap [1, 6, 5, 4, 3, 2] a[l]=5, a[j]=6\n '''\n l = len -1\n while(array[j] >= array[l]):\n l = l-1\n # print(f\"After step 3 for l={l}, j={j} before swap {array}\")\n array[j], array[l] = array[l], array[j]\n # print(f\"After step 3 for l={l} j={j} after swap {array}\")\n '''\n Reverse a[j+1...len-1](both inclusive)\n\n after reversing [1, 6, 2, 3, 4, 5]\n '''\n array[j+1:len] = reversed(array[j+1:len])\n # print(f\"After step 4 reversing {array}\")\n return True\n\narray = [1,2,4,4,5]\narray.sort()\nlen = len(array)\ncount =1\nprint(array)\n'''\nThe algorithm visits every permutation in lexicographic order\ngenerating one by one\n'''\nwhile(hasNextPermutation(array, len)):\n print(array)\n count = count +1\n# The number of permutations will be n! if no duplicates are present, else less than that\n# [1,4,3,3,2] -> 5!/2!=60\nprint(f\"Number of permutations: {count}\")\n\n\n"
},
{
"answer_id": 68712244,
"author": "Alon Barad",
"author_id": 8622976,
"author_profile": "https://Stackoverflow.com/users/8622976",
"pm_score": 3,
"selected": false,
"text": "import itertools\nlist(itertools.permutations([1, 2, 3]))\n from collections.abc import Iterable\n\n\ndef permute(iterable: Iterable[str]) -> set[str]:\n perms = set()\n\n if len(iterable) == 1:\n return {*iterable}\n\n for index, char in enumerate(iterable):\n perms.update([char + perm for perm in permute(iterable[:index] + iterable[index + 1:])])\n\n return perms\n\n\nif __name__ == '__main__':\n print(permute('abc'))\n # {'bca', 'abc', 'cab', 'acb', 'cba', 'bac'}\n print(permute(['1', '2', '3']))\n # {'123', '312', '132', '321', '213', '231'}\n"
},
{
"answer_id": 69397777,
"author": "0script0",
"author_id": 3615178,
"author_profile": "https://Stackoverflow.com/users/3615178",
"pm_score": 1,
"selected": false,
"text": "def permutate(l):\n for i, x in enumerate(l):\n for y in l[i + 1:]:\n yield x, y\n\n\nif __name__ == '__main__':\n print(list(permutate(list('abcd'))))\n print(list(permutate([1, 2, 3, 4])))\n\n#[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]\n#[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]\n"
},
{
"answer_id": 71197512,
"author": "Yilmaz",
"author_id": 10262805,
"author_profile": "https://Stackoverflow.com/users/10262805",
"pm_score": 0,
"selected": false,
"text": "class Solution:\n def permute(self,nums:List[int])->List[List[int]]:\n res=[]\n def dfs(nums,path):\n if len(nums)==0:\n res.append(path)\n for i in range(len(nums)):\n dfs(nums[:i]+nums[i+1:],path+[nums[i]])\n dfs(nums,[])\n return res\n"
},
{
"answer_id": 71726156,
"author": "Splendor",
"author_id": 2516816,
"author_profile": "https://Stackoverflow.com/users/2516816",
"pm_score": 0,
"selected": false,
"text": "def get_permutations(nums, p_list=[], temp_items=[]):\n if not nums:\n return\n elif len(nums) == 1:\n new_items = temp_items+[nums[0]]\n p_list.append(new_items)\n return\n else:\n for i in range(len(nums)):\n temp_nums = nums[:i]+nums[i+1:]\n new_temp_items = temp_items + [nums[i]]\n get_permutations(temp_nums, p_list, new_temp_items)\n\nnums = [1,2,3]\np_list = []\n\nget_permutations(nums, p_list)\n\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3399/"
] |
104,439
|
<p>The Eclipse projects are all stored in the Eclipse Foundation CVS servers. Using the source is a great way to debug your code and to figure out how to do new things. </p>
<p>Unfortunately in a large software project like BIRT, it can be difficult to know which projects and versions are required for a particular build. So what is the best way to get the source for a particular build?</p>
|
[
{
"answer_id": 104426,
"author": "Ricardo Reyes",
"author_id": 3399,
"author_profile": "https://Stackoverflow.com/users/3399",
"pm_score": 5,
"selected": false,
"text": "def permutations (orig_list):\n if not isinstance(orig_list, list):\n orig_list = list(orig_list)\n\n yield orig_list\n\n if len(orig_list) == 1:\n return\n\n for n in sorted(orig_list):\n new_list = orig_list[:]\n pos = new_list.index(n)\n del(new_list[pos])\n new_list.insert(0, n)\n for resto in permutations(new_list[1:]):\n if new_list[:1] + resto <> orig_list:\n yield new_list[:1] + resto\n"
},
{
"answer_id": 104436,
"author": "Eli Bendersky",
"author_id": 8206,
"author_profile": "https://Stackoverflow.com/users/8206",
"pm_score": 10,
"selected": true,
"text": "itertools.permutations import itertools\nlist(itertools.permutations([1, 2, 3]))\n itertools.permutations def permutations(elements):\n if len(elements) <= 1:\n yield elements\n return\n for perm in permutations(elements[1:]):\n for i in range(len(elements)):\n # nb elements[0:1] works in both string and list contexts\n yield perm[:i] + elements[0:1] + perm[i:]\n itertools.permutations def permutations(iterable, r=None):\n # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC\n # permutations(range(3)) --> 012 021 102 120 201 210\n pool = tuple(iterable)\n n = len(pool)\n r = n if r is None else r\n if r > n:\n return\n indices = range(n)\n cycles = range(n, n-r, -1)\n yield tuple(pool[i] for i in indices[:r])\n while n:\n for i in reversed(range(r)):\n cycles[i] -= 1\n if cycles[i] == 0:\n indices[i:] = indices[i+1:] + indices[i:i+1]\n cycles[i] = n - i\n else:\n j = cycles[i]\n indices[i], indices[-j] = indices[-j], indices[i]\n yield tuple(pool[i] for i in indices[:r])\n break\n else:\n return\n itertools.product def permutations(iterable, r=None):\n pool = tuple(iterable)\n n = len(pool)\n r = n if r is None else r\n for indices in product(range(n), repeat=r):\n if len(set(indices)) == r:\n yield tuple(pool[i] for i in indices)\n"
},
{
"answer_id": 104471,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 8,
"selected": false,
"text": "import itertools\nitertools.permutations([1, 2, 3])\n list(permutations(xs))"
},
{
"answer_id": 108651,
"author": "Ber",
"author_id": 11527,
"author_profile": "https://Stackoverflow.com/users/11527",
"pm_score": 4,
"selected": false,
"text": "def permute_in_place(a):\n a.sort()\n yield list(a)\n\n if len(a) <= 1:\n return\n\n first = 0\n last = len(a)\n while 1:\n i = last - 1\n\n while 1:\n i = i - 1\n if a[i] < a[i+1]:\n j = last - 1\n while not (a[i] < a[j]):\n j = j - 1\n a[i], a[j] = a[j], a[i] # swap the values\n r = a[i+1:last]\n r.reverse()\n a[i+1:last] = r\n yield list(a)\n break\n if i == first:\n a.reverse()\n return\n\nif __name__ == '__main__':\n for n in range(5):\n for a in permute_in_place(range(1, n+1)):\n print a\n print\n\n for a in permute_in_place([0, 0, 1, 1, 1]):\n print a\n print\n"
},
{
"answer_id": 170248,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 8,
"selected": false,
"text": "itertools import itertools\n print(list(itertools.permutations([1,2,3,4], 2)))\n\n[(1, 2), (1, 3), (1, 4),\n(2, 1), (2, 3), (2, 4),\n(3, 1), (3, 2), (3, 4),\n(4, 1), (4, 2), (4, 3)]\n print(list(itertools.combinations('123', 2)))\n\n[('1', '2'), ('1', '3'), ('2', '3')]\n print(list(itertools.product([1,2,3], [4,5,6])))\n\n[(1, 4), (1, 5), (1, 6),\n(2, 4), (2, 5), (2, 6),\n(3, 4), (3, 5), (3, 6)]\n print(list(itertools.product([1,2], repeat=3)))\n\n[(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2),\n(2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]\n"
},
{
"answer_id": 5501066,
"author": "tzwenn",
"author_id": 522943,
"author_profile": "https://Stackoverflow.com/users/522943",
"pm_score": 4,
"selected": false,
"text": "def permutList(l):\n if not l:\n return [[]]\n res = []\n for e in l:\n temp = l[:]\n temp.remove(e)\n res.extend([[e] + r for r in permutList(temp)])\n\n return res\n"
},
{
"answer_id": 7140205,
"author": "zmk",
"author_id": 891004,
"author_profile": "https://Stackoverflow.com/users/891004",
"pm_score": 4,
"selected": false,
"text": "list2Perm = [1, 2.0, 'three']\nlistPerm = [[a, b, c]\n for a in list2Perm\n for b in list2Perm\n for c in list2Perm\n if ( a != b and b != c and a != c )\n ]\nprint listPerm\n [\n [1, 2.0, 'three'], \n [1, 'three', 2.0], \n [2.0, 1, 'three'], \n [2.0, 'three', 1], \n ['three', 1, 2.0], \n ['three', 2.0, 1]\n]\n"
},
{
"answer_id": 7733966,
"author": "kx2k",
"author_id": 990523,
"author_profile": "https://Stackoverflow.com/users/990523",
"pm_score": 6,
"selected": false,
"text": "def permutations(head, tail=''):\n if len(head) == 0:\n print(tail)\n else:\n for i in range(len(head)):\n permutations(head[:i] + head[i+1:], tail + head[i])\n permutations('abc')\n"
},
{
"answer_id": 10799849,
"author": "Eric O Lebigot",
"author_id": 42973,
"author_profile": "https://Stackoverflow.com/users/42973",
"pm_score": 3,
"selected": false,
"text": "def all_perms(elements):\n if len(elements) <= 1:\n yield elements # Only permutation possible = no permutation\n else:\n # Iteration over the first element in the result permutation:\n for (index, first_elmt) in enumerate(elements):\n other_elmts = elements[:index]+elements[index+1:]\n for permutation in all_perms(other_elmts): \n yield [first_elmt] + permutation\n len(elements) <= 1 0 yield"
},
{
"answer_id": 11962517,
"author": "Silveira Neto",
"author_id": 914818,
"author_profile": "https://Stackoverflow.com/users/914818",
"pm_score": 5,
"selected": false,
"text": "#!/usr/bin/env python\n\ndef perm(a, k=0):\n if k == len(a):\n print a\n else:\n for i in xrange(k, len(a)):\n a[k], a[i] = a[i] ,a[k]\n perm(a, k+1)\n a[k], a[i] = a[i], a[k]\n\nperm([1,2,3])\n [1, 2, 3]\n[1, 3, 2]\n[2, 1, 3]\n[2, 3, 1]\n[3, 2, 1]\n[3, 1, 2]\n perm(list(\"ball\")) perm(\"ball\")"
},
{
"answer_id": 14470271,
"author": "Chen Xie",
"author_id": 1234376,
"author_profile": "https://Stackoverflow.com/users/1234376",
"pm_score": 3,
"selected": false,
"text": "n factorial n global result\nresult = [] \n\ndef permutation(li):\nif li == [] or li == None:\n return\n\nif len(li) == 1:\n result.append(li[0])\n print result\n result.pop()\n return\n\nfor i in range(0,len(li)):\n result.append(li[i])\n permutation(li[:i] + li[i+1:])\n result.pop() \n permutation([1,2,3])\n [1, 2, 3]\n[1, 3, 2]\n[2, 1, 3]\n[2, 3, 1]\n[3, 1, 2]\n[3, 2, 1]\n"
},
{
"answer_id": 16446022,
"author": "Adrian Statescu",
"author_id": 633040,
"author_profile": "https://Stackoverflow.com/users/633040",
"pm_score": 2,
"selected": false,
"text": "from __future__ import print_function\n\ndef perm(n):\n p = []\n for i in range(0,n+1):\n p.append(i)\n while True:\n for i in range(1,n+1):\n print(p[i], end=' ')\n print(\"\")\n i = n - 1\n found = 0\n while (not found and i>0):\n if p[i]<p[i+1]:\n found = 1\n else:\n i = i - 1\n k = n\n while p[i]>p[k]:\n k = k - 1\n aux = p[i]\n p[i] = p[k]\n p[k] = aux\n for j in range(1,(n-i)/2+1):\n aux = p[i+j]\n p[i+j] = p[n-j+1]\n p[n-j+1] = aux\n if not found:\n break\n\nperm(5)\n"
},
{
"answer_id": 17391851,
"author": "Paolo",
"author_id": 2536705,
"author_profile": "https://Stackoverflow.com/users/2536705",
"pm_score": 4,
"selected": false,
"text": "def addperm(x,l):\n return [ l[0:i] + [x] + l[i:] for i in range(len(l)+1) ]\n\ndef perm(l):\n if len(l) == 0:\n return [[]]\n return [x for y in perm(l[1:]) for x in addperm(l[0],y) ]\n\nprint perm([ i for i in range(3)])\n [[0, 1, 2], [1, 0, 2], [1, 2, 0], [0, 2, 1], [2, 0, 1], [2, 1, 0]]\n"
},
{
"answer_id": 17504089,
"author": "cdiggins",
"author_id": 184528,
"author_profile": "https://Stackoverflow.com/users/184528",
"pm_score": 2,
"selected": false,
"text": "def permute(xs, low=0):\n if low + 1 >= len(xs):\n yield xs\n else:\n for p in permute(xs, low + 1):\n yield p \n for i in range(low + 1, len(xs)): \n xs[low], xs[i] = xs[i], xs[low]\n for p in permute(xs, low + 1):\n yield p \n xs[low], xs[i] = xs[i], xs[low]\n\nfor p in permute([1, 2, 3, 4]):\n print p\n"
},
{
"answer_id": 18135428,
"author": "timeeeee",
"author_id": 1478340,
"author_profile": "https://Stackoverflow.com/users/1478340",
"pm_score": 4,
"selected": false,
"text": "from math import factorial\ndef permutations(l):\n permutations=[]\n length=len(l)\n for x in xrange(factorial(length)):\n available=list(l)\n newPermutation=[]\n for radix in xrange(length, 0, -1):\n placeValue=factorial(radix-1)\n index=x/placeValue\n newPermutation.append(available.pop(index))\n x-=index*placeValue\n permutations.append(newPermutation)\n return permutations\n\npermutations(range(3))\n [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]]\n"
},
{
"answer_id": 20014561,
"author": "piggybox",
"author_id": 2102764,
"author_profile": "https://Stackoverflow.com/users/2102764",
"pm_score": 3,
"selected": false,
"text": "def permutation(list):\n if len(list) == 0:\n return [[]]\n else:\n return [[x] + ys for x in list for ys in permutation(delete(list, x))]\n\ndef delete(list, item):\n lc = list[:]\n lc.remove(item)\n return lc\n"
},
{
"answer_id": 23732953,
"author": "darxtrix",
"author_id": 2679770,
"author_profile": "https://Stackoverflow.com/users/2679770",
"pm_score": 2,
"selected": false,
"text": ">>> import copy\n>>> def perm(prefix,rest):\n... for e in rest:\n... new_rest=copy.copy(rest)\n... new_prefix=copy.copy(prefix)\n... new_prefix.append(e)\n... new_rest.remove(e)\n... if len(new_rest) == 0:\n... print new_prefix + new_rest\n... continue\n... perm(new_prefix,new_rest)\n... \n>>> perm([],['a','b','c','d'])\n['a', 'b', 'c', 'd']\n['a', 'b', 'd', 'c']\n['a', 'c', 'b', 'd']\n['a', 'c', 'd', 'b']\n['a', 'd', 'b', 'c']\n['a', 'd', 'c', 'b']\n['b', 'a', 'c', 'd']\n['b', 'a', 'd', 'c']\n['b', 'c', 'a', 'd']\n['b', 'c', 'd', 'a']\n['b', 'd', 'a', 'c']\n['b', 'd', 'c', 'a']\n['c', 'a', 'b', 'd']\n['c', 'a', 'd', 'b']\n['c', 'b', 'a', 'd']\n['c', 'b', 'd', 'a']\n['c', 'd', 'a', 'b']\n['c', 'd', 'b', 'a']\n['d', 'a', 'b', 'c']\n['d', 'a', 'c', 'b']\n['d', 'b', 'a', 'c']\n['d', 'b', 'c', 'a']\n['d', 'c', 'a', 'b']\n['d', 'c', 'b', 'a']\n"
},
{
"answer_id": 28256360,
"author": "Cmyker",
"author_id": 1079659,
"author_profile": "https://Stackoverflow.com/users/1079659",
"pm_score": 2,
"selected": false,
"text": "def permute(items):\n length = len(items)\n def inner(ix=[]):\n do_yield = len(ix) == length - 1\n for i in range(0, length):\n if i in ix: #avoid duplicates\n continue\n if do_yield:\n yield tuple([items[y] for y in ix + [i]])\n else:\n for p in inner(ix + [i]):\n yield p\n return inner()\n for p in permute((1,2,3)):\n print(p)\n\n(1, 2, 3)\n(1, 3, 2)\n(2, 1, 3)\n(2, 3, 1)\n(3, 1, 2)\n(3, 2, 1)\n"
},
{
"answer_id": 30112080,
"author": "manish kumar",
"author_id": 4166033,
"author_profile": "https://Stackoverflow.com/users/4166033",
"pm_score": 2,
"selected": false,
"text": "def pzip(c, seq):\n result = []\n for item in seq:\n for i in range(len(item)+1):\n result.append(item[i:]+c+item[:i])\n return result\n\n\ndef perm(line):\n seq = [c for c in line]\n if len(seq) <=1 :\n return seq\n else:\n return pzip(seq[0], perm(seq[1:]))\n"
},
{
"answer_id": 30428753,
"author": "B. M.",
"author_id": 4016285,
"author_profile": "https://Stackoverflow.com/users/4016285",
"pm_score": 3,
"selected": false,
"text": "from numpy import empty, uint8\nfrom math import factorial\n\ndef perms(n):\n f = 1\n p = empty((2*n-1, factorial(n)), uint8)\n for i in range(n):\n p[i, :f] = i\n p[i+1:2*i+1, :f] = p[:i, :f] # constitution de blocs\n for j in range(i):\n p[:i+1, f*(j+1):f*(j+2)] = p[j+1:j+i+2, :f] # copie de blocs\n f = f*(i+1)\n return p[:n, :]\n list(itertools.permutations(range(n)) In [1]: %timeit -n10 list(permutations(range(10)))\n10 loops, best of 3: 815 ms per loop\n\nIn [2]: %timeit -n100 perms(10) \n100 loops, best of 3: 40 ms per loop\n"
},
{
"answer_id": 32448587,
"author": "Bharatwaja",
"author_id": 3944755,
"author_profile": "https://Stackoverflow.com/users/3944755",
"pm_score": -1,
"selected": false,
"text": "from itertools import product, permutations\nA = ([1,2,3])\nprint (list(permutations(sorted(A),2)))\n"
},
{
"answer_id": 36102351,
"author": "Miled Louis Rizk",
"author_id": 6023433,
"author_profile": "https://Stackoverflow.com/users/6023433",
"pm_score": 2,
"selected": false,
"text": "def calcperm(arr, size):\n result = set([()])\n for dummy_idx in range(size):\n temp = set()\n for dummy_lst in result:\n for dummy_outcome in arr:\n if dummy_outcome not in dummy_lst:\n new_seq = list(dummy_lst)\n new_seq.append(dummy_outcome)\n temp.add(tuple(new_seq))\n result = temp\n return result\n lst = [1, 2, 3, 4]\n#lst = [\"yellow\", \"magenta\", \"white\", \"blue\"]\nseq = 2\nfinal = calcperm(lst, seq)\nprint(len(final))\nprint(final)\n"
},
{
"answer_id": 38793421,
"author": "Karo Castro-Wunsch",
"author_id": 4725204,
"author_profile": "https://Stackoverflow.com/users/4725204",
"pm_score": 2,
"selected": false,
"text": "def all_insert(x, e, i=0):\n return [x[0:i]+[e]+x[i:]] + all_insert(x,e,i+1) if i<len(x)+1 else []\n\ndef for_each(X, e):\n return all_insert(X[0], e) + for_each(X[1:],e) if X else []\n\ndef permute(x):\n return [x] if len(x) < 2 else for_each( permute(x[1:]) , x[0])\n\n\nperms = permute([1,2,3])\n"
},
{
"answer_id": 43018229,
"author": "anhldbk",
"author_id": 197896,
"author_profile": "https://Stackoverflow.com/users/197896",
"pm_score": 1,
"selected": false,
"text": "def permutation(flag, k =1 ):\n N = len(flag)\n for i in xrange(0, N):\n if flag[i] != 0:\n continue\n flag[i] = k \n if k == N:\n print flag\n permutation(flag, k+1)\n flag[i] = 0\n\npermutation([0, 0, 0])\n"
},
{
"answer_id": 49072115,
"author": "abelenky",
"author_id": 34824,
"author_profile": "https://Stackoverflow.com/users/34824",
"pm_score": 0,
"selected": false,
"text": "def permutes(input,offset):\n if( len(input) == offset ):\n return [''.join(input)]\n\n result=[] \n for i in range( offset, len(input) ):\n input[offset], input[i] = input[i], input[offset]\n result = result + permutes(input,offset+1)\n input[offset], input[i] = input[i], input[offset]\n return result\n\n# input is a \"string\"\n# return value is a list of strings\ndef permutations(input):\n return permutes( list(input), 0 )\n\n# Main Program\nprint( permutations(\"wxyz\") )\n"
},
{
"answer_id": 50311529,
"author": "Ilgorbek Kuchkarov",
"author_id": 6283828,
"author_profile": "https://Stackoverflow.com/users/6283828",
"pm_score": 0,
"selected": false,
"text": "def permutation(word, first_char=None):\n if word == None or len(word) == 0: return []\n if len(word) == 1: return [word]\n\n result = []\n first_char = word[0]\n for sub_word in permutation(word[1:], first_char):\n result += insert(first_char, sub_word)\n return sorted(result)\n\ndef insert(ch, sub_word):\n arr = [ch + sub_word]\n for i in range(len(sub_word)):\n arr.append(sub_word[i:] + ch + sub_word[:i])\n return arr\n\n\nassert permutation(None) == []\nassert permutation('') == []\nassert permutation('1') == ['1']\nassert permutation('12') == ['12', '21']\n\nprint permutation('abc')\n"
},
{
"answer_id": 53785851,
"author": "Anatoly Alekseev",
"author_id": 4334120,
"author_profile": "https://Stackoverflow.com/users/4334120",
"pm_score": 2,
"selected": false,
"text": "@numba.njit()\ndef permutations(A, k):\n r = [[i for i in range(0)]]\n for i in range(k):\n r = [[a] + b for a in A for b in r if (a in b)==False]\n return r\npermutations([1,2,3],3)\n[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]\n %timeit permutations(np.arange(5),5)\n\n243 µs ± 11.1 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)\ntime: 406 ms\n\n%timeit list(itertools.permutations(np.arange(5),5))\n15.9 µs ± 8.61 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\ntime: 12.9 s\n"
},
{
"answer_id": 55070316,
"author": "Hello.World",
"author_id": 8850552,
"author_profile": "https://Stackoverflow.com/users/8850552",
"pm_score": 0,
"selected": false,
"text": "Counter from collections import Counter\n\ndef permutations(nums):\n ans = [[]]\n cache = Counter(nums)\n\n for idx, x in enumerate(nums):\n result = []\n for items in ans:\n cache1 = Counter(items)\n for id, n in enumerate(nums):\n if cache[n] != cache1[n] and items + [n] not in result:\n result.append(items + [n])\n\n ans = result\n return ans\npermutations([1, 2, 2])\n> [[1, 2, 2], [2, 1, 2], [2, 2, 1]]\n\n"
},
{
"answer_id": 55421084,
"author": "Tatsu",
"author_id": 5938224,
"author_profile": "https://Stackoverflow.com/users/5938224",
"pm_score": 2,
"selected": false,
"text": "def permutation(input):\n if len(input) == 1:\n return input if isinstance(input, list) else [input]\n\n result = []\n for i in range(len(input)):\n first = input[i]\n rest = input[:i] + input[i + 1:]\n rest_permutation = permutation(rest)\n for p in rest_permutation:\n result.append(first + p)\n return result\n print(permutation('abcd'))\nprint(permutation(['a', 'b', 'c', 'd']))\n"
},
{
"answer_id": 59433823,
"author": "Richard Ambler",
"author_id": 1340742,
"author_profile": "https://Stackoverflow.com/users/1340742",
"pm_score": 3,
"selected": false,
"text": "import trotter\n\nmy_permutations = trotter.Permutations(3, [1, 2, 3])\n\nprint(my_permutations)\n\nfor p in my_permutations:\n print(p)\n"
},
{
"answer_id": 59593816,
"author": "Maverick Meerkat",
"author_id": 6296435,
"author_profile": "https://Stackoverflow.com/users/6296435",
"pm_score": 4,
"selected": false,
"text": "def getPermutations(array):\n if len(array) == 1:\n return [array]\n permutations = []\n for i in range(len(array)): \n # get all perm's of subarray w/o current item\n perms = getPermutations(array[:i] + array[i+1:]) \n for p in perms:\n permutations.append([array[i], *p])\n return permutations\n def getPermutations(array):\n if len(array) == 1:\n yield array\n else:\n for i in range(len(array)):\n perms = getPermutations(array[:i] + array[i+1:])\n for p in perms:\n yield [array[i], *p]\n"
},
{
"answer_id": 62189160,
"author": "Dritte Saskaita",
"author_id": 12278470,
"author_profile": "https://Stackoverflow.com/users/12278470",
"pm_score": 0,
"selected": false,
"text": "def permuteArray (arr):\n\n arraySize = len(arr)\n\n permutedList = []\n\n if arraySize == 1:\n return [arr]\n\n i = 0\n\n for item in arr:\n\n for elem in permuteArray(arr[:i] + arr[i + 1:]):\n permutedList.append([item] + elem)\n\n i = i + 1 \n\n return permutedList\n"
},
{
"answer_id": 62770287,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "import sympy\nfrom sympy.utilities.iterables import multiset_permutations\nt = [1,2,3]\np = list(multiset_permutations(t))\nprint(p)\n\n# [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]\n"
},
{
"answer_id": 64471115,
"author": "Harvey Mao",
"author_id": 10665136,
"author_profile": "https://Stackoverflow.com/users/10665136",
"pm_score": 0,
"selected": false,
"text": "from typing import List\nimport time, random\n\ndef measure_time(func):\n def wrapper_time(*args, **kwargs):\n start_time = time.perf_counter()\n res = func(*args, **kwargs)\n end_time = time.perf_counter()\n return res, end_time - start_time\n\n return wrapper_time\n\n\nclass Solution:\n def permute(self, nums: List[int], method: int = 1) -> List[List[int]]:\n perms = []\n perm = []\n if method == 1:\n _, time_perm = self._permute_recur(nums, 0, len(nums) - 1, perms)\n elif method == 2:\n _, time_perm = self._permute_recur_agian(nums, perm, perms)\n print(perm)\n return perms, time_perm\n\n @measure_time\n def _permute_recur(self, nums: List[int], l: int, r: int, perms: List[List[int]]):\n # base case\n if l == r:\n perms.append(nums.copy())\n\n for i in range(l, r + 1):\n nums[l], nums[i] = nums[i], nums[l]\n self._permute_recur(nums, l + 1, r , perms)\n nums[l], nums[i] = nums[i], nums[l]\n\n @measure_time\n def _permute_recur_agian(self, nums: List[int], perm: List[int], perms_list: List[List[int]]):\n \"\"\"\n The idea is similar to nestedForLoops visualized as a recursion tree.\n \"\"\"\n if nums:\n for i in range(len(nums)):\n # perm.append(nums[i]) mistake, perm will be filled with all nums's elements.\n # Method1 perm_copy = copy.deepcopy(perm)\n # Method2 add in the parameter list using + (not in place)\n # caveat: list.append is in-place , which is useful for operating on global element perms_list\n # Note that:\n # perms_list pass by reference. shallow copy\n # perm + [nums[i]] pass by value instead of reference.\n self._permute_recur_agian(nums[:i] + nums[i+1:], perm + [nums[i]], perms_list)\n else:\n # Arrive at the last loop, i.e. leaf of the recursion tree.\n perms_list.append(perm)\n\n\n\nif __name__ == \"__main__\":\n array = [random.randint(-10, 10) for _ in range(3)]\n sol = Solution()\n # perms, time_perm = sol.permute(array, 1)\n perms2, time_perm2 = sol.permute(array, 2)\n print(perms2)\n # print(perms, perms2)\n # print(time_perm, time_perm2)\n```\n"
},
{
"answer_id": 65241289,
"author": "Michael Hodel",
"author_id": 12363750,
"author_profile": "https://Stackoverflow.com/users/12363750",
"pm_score": 0,
"selected": false,
"text": "def p(a):\n return a if len(a) == 1 else [[a[i], *j] for i in range(len(a)) for j in p(a[:i] + a[i + 1:])]\n"
},
{
"answer_id": 65542989,
"author": "Bhaskar13",
"author_id": 11930483,
"author_profile": "https://Stackoverflow.com/users/11930483",
"pm_score": 1,
"selected": false,
"text": "'''\nLexicographic permutation generation\n\nconsider example array state of [1,5,6,4,3,2] for sorted [1,2,3,4,5,6]\nafter 56432(treat as number) ->nothing larger than 6432(using 6,4,3,2) beginning with 5\nso 6 is next larger and 2345(least using numbers other than 6)\nso [1, 6,2,3,4,5]\n'''\ndef hasNextPermutation(array, len):\n ' Base Condition '\n if(len ==1):\n return False\n '''\n Set j = last-2 and find first j such that a[j] < a[j+1]\n If no such j(j==-1) then we have visited all permutations\n after this step a[j+1]>=..>=a[len-1] and a[j]<a[j+1]\n\n a[j]=5 or j=1, 6>5>4>3>2\n '''\n j = len -2\n while (j >= 0 and array[j] >= array[j + 1]):\n j= j-1\n if(j==-1):\n return False\n # print(f\"After step 2 for j {j} {array}\")\n '''\n decrease l (from n-1 to j) repeatedly until a[j]<a[l]\n Then swap a[j], a[l]\n a[l] is the smallest element > a[j] that can follow a[l]...a[j-1] in permutation\n before swap we have a[j+1]>=..>=a[l-1]>=a[l]>a[j]>=a[l+1]>=..>=a[len-1]\n after swap -> a[j+1]>=..>=a[l-1]>=a[j]>a[l]>=a[l+1]>=..>=a[len-1]\n\n a[l]=6 or l=2, j=1 just before swap [1, 5, 6, 4, 3, 2] \n after swap [1, 6, 5, 4, 3, 2] a[l]=5, a[j]=6\n '''\n l = len -1\n while(array[j] >= array[l]):\n l = l-1\n # print(f\"After step 3 for l={l}, j={j} before swap {array}\")\n array[j], array[l] = array[l], array[j]\n # print(f\"After step 3 for l={l} j={j} after swap {array}\")\n '''\n Reverse a[j+1...len-1](both inclusive)\n\n after reversing [1, 6, 2, 3, 4, 5]\n '''\n array[j+1:len] = reversed(array[j+1:len])\n # print(f\"After step 4 reversing {array}\")\n return True\n\narray = [1,2,4,4,5]\narray.sort()\nlen = len(array)\ncount =1\nprint(array)\n'''\nThe algorithm visits every permutation in lexicographic order\ngenerating one by one\n'''\nwhile(hasNextPermutation(array, len)):\n print(array)\n count = count +1\n# The number of permutations will be n! if no duplicates are present, else less than that\n# [1,4,3,3,2] -> 5!/2!=60\nprint(f\"Number of permutations: {count}\")\n\n\n"
},
{
"answer_id": 68712244,
"author": "Alon Barad",
"author_id": 8622976,
"author_profile": "https://Stackoverflow.com/users/8622976",
"pm_score": 3,
"selected": false,
"text": "import itertools\nlist(itertools.permutations([1, 2, 3]))\n from collections.abc import Iterable\n\n\ndef permute(iterable: Iterable[str]) -> set[str]:\n perms = set()\n\n if len(iterable) == 1:\n return {*iterable}\n\n for index, char in enumerate(iterable):\n perms.update([char + perm for perm in permute(iterable[:index] + iterable[index + 1:])])\n\n return perms\n\n\nif __name__ == '__main__':\n print(permute('abc'))\n # {'bca', 'abc', 'cab', 'acb', 'cba', 'bac'}\n print(permute(['1', '2', '3']))\n # {'123', '312', '132', '321', '213', '231'}\n"
},
{
"answer_id": 69397777,
"author": "0script0",
"author_id": 3615178,
"author_profile": "https://Stackoverflow.com/users/3615178",
"pm_score": 1,
"selected": false,
"text": "def permutate(l):\n for i, x in enumerate(l):\n for y in l[i + 1:]:\n yield x, y\n\n\nif __name__ == '__main__':\n print(list(permutate(list('abcd'))))\n print(list(permutate([1, 2, 3, 4])))\n\n#[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]\n#[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]\n"
},
{
"answer_id": 71197512,
"author": "Yilmaz",
"author_id": 10262805,
"author_profile": "https://Stackoverflow.com/users/10262805",
"pm_score": 0,
"selected": false,
"text": "class Solution:\n def permute(self,nums:List[int])->List[List[int]]:\n res=[]\n def dfs(nums,path):\n if len(nums)==0:\n res.append(path)\n for i in range(len(nums)):\n dfs(nums[:i]+nums[i+1:],path+[nums[i]])\n dfs(nums,[])\n return res\n"
},
{
"answer_id": 71726156,
"author": "Splendor",
"author_id": 2516816,
"author_profile": "https://Stackoverflow.com/users/2516816",
"pm_score": 0,
"selected": false,
"text": "def get_permutations(nums, p_list=[], temp_items=[]):\n if not nums:\n return\n elif len(nums) == 1:\n new_items = temp_items+[nums[0]]\n p_list.append(new_items)\n return\n else:\n for i in range(len(nums)):\n temp_nums = nums[:i]+nums[i+1:]\n new_temp_items = temp_items + [nums[i]]\n get_permutations(temp_nums, p_list, new_temp_items)\n\nnums = [1,2,3]\np_list = []\n\nget_permutations(nums, p_list)\n\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5412/"
] |
104,448
|
<p>I'm trying to create a map application similar to <a href="http://flashden.net/item/zoom-pan-controls-with-dynamic-image-settings/15713" rel="nofollow noreferrer">this</a>. Click the SWF Preview tab on the left of the image. Specifically, noticed how you can pan around, and the clickable buttons on the map move with it. Basically, how do they do that?</p>
<p>My application has a map that you can click and pan around using a startDrag() function. I have a separate layer with other, clickable movie clips that I'd like to follow the pans of the map layer. Unfortunately, Flash limits you to dragging only <a href="http://www.adobe.com/support/flash/action_scripts/actionscript_dictionary/actionscript_dictionary681.html" rel="nofollow noreferrer">one movie clip at a time</a>. Somebody proposed a solution using a <a href="http://proto.layer51.com/d.aspx?f=845" rel="nofollow noreferrer">prototype</a>, but I can't get that working correctly, and I'm not sure if it's because I'm using ActionScript 3.0 or not.</p>
<p>Can anybody outline a better way for me to accomplish what I'm trying to do, or a better way to do what I'm currently doing? Appreciate it.</p>
|
[
{
"answer_id": 104855,
"author": "hasseg",
"author_id": 4111,
"author_profile": "https://Stackoverflow.com/users/4111",
"pm_score": 2,
"selected": false,
"text": "_siblings private var _dragStartCoordinates:Point = null;\nprivate var _siblingsDragStartCoordinates:Dictionary = null;\n\nprivate function mouseDownHandler(event:MouseEvent):void\n{\n this.startDrag();\n _dragStartCoordinates = new Point(this.x, this.y);\n\n _siblingsDragStartCoordinates = new Dictionary(true);\n for (var sibling:DisplayObject in _siblings)\n {\n _siblingsDragStartCoordinates[sibling] = new Point(sibling.x, sibling.y);\n }\n\n stage.addEventListener(MouseEvent.MOUSE_UP, dragMouseUpHandler, false, 0, true);\n stage.addEventListener(MouseEvent.MOUSE_MOVE, dragMouseMoveHandler, false, 0, true);\n}\n\nprivate function dragMouseUpHandler(event:MouseEvent):void\n{\n stage.removeEventListener(MouseEvent.MOUSE_UP, dragMouseUpHandler, false);\n stage.removeEventListener(MouseEvent.MOUSE_MOVE, dragMouseMoveHandler, false);\n this.stopDrag();\n moveSiblings();\n _dragStartCoordinates = null;\n _siblingsDragStartCoordinates = null;\n}\n\nprivate function dragMouseMoveHandler(event:MouseEvent):void\n{\n moveSiblings();\n}\n\n// expects _dragStartCoordinates and _siblingsDragStartCoordinates\n// to be set\nprivate function moveSiblings():void\n{\n var xDiff:Number = this.x - _dragStartCoordinates.x;\n var yDiff:Number = this.y - _dragStartCoordinates.y;\n\n for (var sibling:DisplayObject in _siblings)\n {\n sibling.x = _siblingsDragStartCoordinates[sibling].x + xDiff;\n sibling.y = _siblingsDragStartCoordinates[sibling].y + yDiff;\n }\n}\n"
},
{
"answer_id": 608092,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": " package Tools\n{\n import flash.display.MovieClip; \n import flash.events.*; \n import flash.geom.Rectangle; \n import flash.utils.setInterval; \n import flash.utils.clearInterval; \n import flash.display.MovieClip;\n import flash.display.DisplayObject;\n import flash.display.Sprite;\n import flash.geom.Point;\n import flash.utils.Dictionary;\n\n public class DragSync { \n private var _dragStartCoordinates:Point = null;\n private var _siblingsDragStartCoordinates:Dictionary = null;\n private var _primaryItem:Object = null;\n private var _dragWithPrimary:Array = null;\n\n public function DragSync(primaryItem:Object,dragWithPrimary:Array)\n {\n _primaryItem = primaryItem;\n _dragWithPrimary = dragWithPrimary;\n\n _primaryItem.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);\n _primaryItem.addEventListener(MouseEvent.MOUSE_UP, dragMouseUpHandler);\n _primaryItem.addEventListener(MouseEvent.MOUSE_MOVE, dragMouseMoveHandler);\n }\n\n private function mouseDownHandler(event:MouseEvent):void\n {\n _dragStartCoordinates = new Point(_primaryItem.x, _primaryItem.y);\n _siblingsDragStartCoordinates = new Dictionary(true);\n\n for each (var sibling:DisplayObject in _dragWithPrimary)\n {\n _siblingsDragStartCoordinates[sibling] = new Point(sibling.x, sibling.y)\n }\n }\n\n private function dragMouseUpHandler(event:MouseEvent):void\n {\n moveSiblings();\n _dragStartCoordinates = null;\n _siblingsDragStartCoordinates = null;\n }\n\n private function dragMouseMoveHandler(event:MouseEvent):void\n {\n moveSiblings();\n }\n\n // expects _dragStartCoordinates and _siblingsDragStartCoordinates\n // to be set\n private function moveSiblings():void\n {\n if (!_dragStartCoordinates || !_siblingsDragStartCoordinates) return;\n\n var xDiff:Number = _primaryItem.x - _dragStartCoordinates.x;\n var yDiff:Number = _primaryItem.y - _dragStartCoordinates.y;\n\n for each (var sibling:DisplayObject in _dragWithPrimary)\n {\n sibling.x = _siblingsDragStartCoordinates[sibling].x + xDiff;\n sibling.y = _siblingsDragStartCoordinates[sibling].y + yDiff;\n }\n }\n\n\n } \n}\n"
},
{
"answer_id": 2376363,
"author": "Ratha",
"author_id": 285906,
"author_profile": "https://Stackoverflow.com/users/285906",
"pm_score": 1,
"selected": false,
"text": "public class DragSync { \n private var _dragStartCoordinates:Point = null;\n private var _siblingsDragStartCoordinates:Dictionary = null;\n private var _primaryItem:Object = null;\n public function DragSync(primaryItem:Object,workSpace:Object, dragWithPrimary:Array)\n {\n _primaryItem = primaryItem;\n _dragWithPrimary = dragWithPrimary;\n_workSpace = workSpace;\n\n _workSpace.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);\n _workSpace.addEventListener(MouseEvent.MOUSE_UP, dragMouseUpHandler);\n _workSpace.addEventListener(MouseEvent.MOUSE_MOVE, dragMouseMoveHandler);\n_workSpace.addEventListener(MouseEvent.MOUSE_OUT, dragOut);\n }\n\n private function mouseDownHandler(event:MouseEvent):void\n {\n trace(\"event mouse down\");\n_primaryItem.startDrag();\n_dragStartCoordinates = new Point(_primaryItem.x, _primaryItem.y);\n _siblingsDragStartCoordinates = new Dictionary(true);\n\n for each (var sibling:DisplayObject in _dragWithPrimary)\n {\n _siblingsDragStartCoordinates[sibling] = new Point(sibling.x, sibling.y)\n }\n }\n\n private function dragMouseUpHandler(event:MouseEvent):void\n {\n moveSiblings();\n_primaryItem.stopDrag();\n _dragStartCoordinates = null;\n _siblingsDragStartCoordinates = null;\n }\n\n private function dragMouseMoveHandler(event:MouseEvent):void\n {\n trace(\"event mouse MOVE MOVE\");\nmoveSiblings();\n }\n // expects _dragStartCoordinates and _siblingsDragStartCoordinates\n // to be set\n private function moveSiblings():void\n {\n if (!_dragStartCoordinates || !_siblingsDragStartCoordinates) return;\n\n var xDiff:Number = _primaryItem.x - _dragStartCoordinates.x;\n var yDiff:Number = _primaryItem.y - _dragStartCoordinates.y;\n\n for each (var sibling:DisplayObject in _dragWithPrimary)\n {\n sibling.x = _siblingsDragStartCoordinates[sibling].x + xDiff;\n sibling.y = _siblingsDragStartCoordinates[sibling].y + yDiff;\n }\n\n }\n\n\n} \n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/557/"
] |
104,458
|
<p>How can styles be applied to CheckBoxList ListItems. Unlike other controls, such as the Repeater where you can specify <code><ItemStyle></code>, you can't seem to specify a style for each individual control.</p>
<p>Is there some sort of work around?</p>
|
[
{
"answer_id": 104502,
"author": "Andrew Burgess",
"author_id": 12096,
"author_profile": "https://Stackoverflow.com/users/12096",
"pm_score": 4,
"selected": false,
"text": ".chkboxlist td \n{\n font-size:x-large;\n}\n <asp:CheckBoxList ID=\"chkboxlist1\" runat=\"server\" CssClass=\"chkboxlist\" />\n"
},
{
"answer_id": 104589,
"author": "Cyberherbalist",
"author_id": 16964,
"author_profile": "https://Stackoverflow.com/users/16964",
"pm_score": 6,
"selected": true,
"text": "ListItem li = new ListItem(\"Richard Byrd\", \"11\");\nli.Selected = false;\nli.Attributes.Add(\"Style\", \"color: red;\");\nCheckBoxList1.Items.Add(li);\n"
},
{
"answer_id": 118373,
"author": "CMPalmer",
"author_id": 14894,
"author_profile": "https://Stackoverflow.com/users/14894",
"pm_score": 3,
"selected": false,
"text": "CheckBoxList RadioButtonList RepeatLayout=\"Flow\""
},
{
"answer_id": 9632437,
"author": "Jon White",
"author_id": 1259067,
"author_profile": "https://Stackoverflow.com/users/1259067",
"pm_score": 3,
"selected": false,
"text": "<asp:ListItem Text=\"Good\" Value=\"True\" style=\"background-color:green;color:white\" />\n<br />\n<asp:ListItem Text=\"Bad\" Value=\"False\" style=\"background-color:red;color:white\" />\n"
},
{
"answer_id": 11250136,
"author": "John",
"author_id": 1489376,
"author_profile": "https://Stackoverflow.com/users/1489376",
"pm_score": 1,
"selected": false,
"text": "public bool Repeater_Bind()\n{\n RadioButtonList objRadioButton = (RadioButtonList)eventArgs.Item.FindControl(\"rbList\");\n if (curQuestionInfo.CorrectAnswer != -1) {\n objRadioButton.Items[curQuestionInfo.CorrectAnswer].Attributes.Add(\"Style\", \"color: #b4fbb1;\");\n }\n}\n"
},
{
"answer_id": 19596627,
"author": "SubhoM",
"author_id": 2547399,
"author_profile": "https://Stackoverflow.com/users/2547399",
"pm_score": 2,
"selected": false,
"text": "<asp:ListItem Text=\"Other (<span style=font-weight:bold;>please </span><span>style=color:Red;font-weight:bold;>specify</span>):\" Value=\"10\"></asp:ListItem>\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12096/"
] |
104,485
|
<p>I'm trying to skin HTML output which I don't have control over. One of the elements is a <code>div</code> with a <code>style="overflow: auto"</code> attribute.<br>
Is there a way in CSS to force that <code>div</code> to use <code>overflow: hidden;</code>?</p>
|
[
{
"answer_id": 104499,
"author": "Magnar",
"author_id": 1123,
"author_profile": "https://Stackoverflow.com/users/1123",
"pm_score": 7,
"selected": true,
"text": "!important element {\n overflow: hidden !important;\n}\n"
},
{
"answer_id": 104501,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 4,
"selected": false,
"text": "!important #mydiv { overflow: hidden !important; }\n"
},
{
"answer_id": 104507,
"author": "DanWoolston",
"author_id": 19133,
"author_profile": "https://Stackoverflow.com/users/19133",
"pm_score": 3,
"selected": false,
"text": "overflow overflow:hidden !important\n"
},
{
"answer_id": 104683,
"author": "TheZenker",
"author_id": 10552,
"author_profile": "https://Stackoverflow.com/users/10552",
"pm_score": 2,
"selected": false,
"text": "However, for balance, an \"!important\" declaration (the keywords\n Note. This is a semantic change since CSS1. In CSS1, author\n Declaring a shorthand property (e.g., 'background') to be\n Example(s):\n\nThe first rule in the user's style sheet in the following example\n /* From the user's style sheet */\nP { text-indent: 1em ! important }\nP { font-style: italic ! important }\nP { font-size: 18pt }\n\n/* From the author's style sheet */\nP { text-indent: 1.5em !important }\nP { font: 12pt sans-serif !important }\nP { font-size: 24pt }\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4898/"
] |
104,487
|
<p>Right now I'm doing something like this:</p>
<pre><code>RewriteRule ^/?logout(/)?$ logout.php
RewriteRule ^/?config(/)?$ config.php
</code></pre>
<p>I would much rather have one rules that would do the same thing for each url, so I don't have to keep adding them every time I add a new file.</p>
<p>Also, I like to match things like '/config/new' to 'config_new.php' if that is possible. I am guessing some regexp would let me accomplish this?</p>
|
[
{
"answer_id": 104596,
"author": "Jason Terk",
"author_id": 12582,
"author_profile": "https://Stackoverflow.com/users/12582",
"pm_score": 1,
"selected": false,
"text": "RewriteEngine on\nRewriteMap quux-map prg:/path/to/map.quux.pl\nRewriteRule ^/~quux/(.*)$ /~quux/${quux-map:$1}\n\n#!/path/to/perl\n\n# disable buffered I/O which would lead\n# to deadloops for the Apache server\n$| = 1;\n\n# read URLs one per line from stdin and\n# generate substitution URL on stdout\nwhile (<>) {\n s|^foo/|bar/|;\n print $_;\n}\n"
},
{
"answer_id": 104614,
"author": "Aeon",
"author_id": 13289,
"author_profile": "https://Stackoverflow.com/users/13289",
"pm_score": 2,
"selected": false,
"text": "RewriteRule ^/?(logout|config|foo)/?$ $1.php\nRewriteRule ^/?(logout|config|foo)/(new|edit|delete)$ $1_$2.php\n book/new movie/new user/new logout/new"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15000/"
] |
104,516
|
<p>In PHP, the HEREDOC string declarations are really useful for outputting a block of html. You can have it parse in variables just by prefixing them with $, but for more complicated syntax (like $var[2][3]), you have to put your expression inside {} braces.</p>
<p>In PHP 5, it <em>is</em> possible to actually make function calls within {} braces inside a HEREDOC string, but you have to go through a bit of work. The function name itself has to be stored in a variable, and you have to call it like it is a dynamically-named function. For example:</p>
<pre><code>$fn = 'testfunction';
function testfunction() { return 'ok'; }
$string = <<< heredoc
plain text and now a function: {$fn()}
heredoc;
</code></pre>
<p>As you can see, this is a bit more messy than just:</p>
<pre><code>$string = <<< heredoc
plain text and now a function: {testfunction()}
heredoc;
</code></pre>
<p>There are other ways besides the first code example, such as breaking out of the HEREDOC to call the function, or reversing the issue and doing something like:</p>
<pre><code>?>
<!-- directly output html and only breaking into php for the function -->
plain text and now a function: <?PHP print testfunction(); ?>
</code></pre>
<p>The latter has the disadvantage that the output is directly put into the output stream (unless I'm using output buffering), which might not be what I want.</p>
<p>So, the essence of my question is: is there a more elegant way to approach this?</p>
<p><b>Edit based on responses:</b> It certainly does seem like some kind of template engine would make my life much easier, but it would require me basically invert my usual PHP style. Not that that's a bad thing, but it explains my inertia.. I'm up for figuring out ways to make life easier though, so I'm looking into templates now.</p>
|
[
{
"answer_id": 104556,
"author": "boxxar",
"author_id": 15732,
"author_profile": "https://Stackoverflow.com/users/15732",
"pm_score": 6,
"selected": false,
"text": "$string = <<< heredoc\nplain text and now a function: %s\nheredoc;\n$string = sprintf($string, testfunction());\n"
},
{
"answer_id": 104645,
"author": "Peter Bailey",
"author_id": 8815,
"author_profile": "https://Stackoverflow.com/users/8815",
"pm_score": 7,
"selected": true,
"text": "<?php ?> <html>\n<head>\n <title><?php echo $page_title; ?></title>\n</head>\n<body>\n <?php echo getPageContent(); ?>\n</body>\n <?php\n\n$page_title = \"This is a simple demo\";\n\nfunction getPageContent() {\n return '<p>Hello World!</p>';\n}\n\ninclude('template_file.php');\n"
},
{
"answer_id": 1386692,
"author": "BraedenP",
"author_id": 95764,
"author_profile": "https://Stackoverflow.com/users/95764",
"pm_score": 3,
"selected": false,
"text": "<?php echo \"plain text and now a function: \" . testfunction(); ?>\n <?php\nob_start();\ninclude \"template_file.php\";\n$output_string = ob_get_contents();\nob_end_clean();\necho $output_string;\n?>\n"
},
{
"answer_id": 1948173,
"author": "Isofarro",
"author_id": 237069,
"author_profile": "https://Stackoverflow.com/users/237069",
"pm_score": 4,
"selected": false,
"text": "<?php\n class Fn {\n public function __call($name, $args) {\n if (function_exists($name)) {\n return call_user_func_array($name, $args);\n }\n }\n }\n\n $fn = new Fn();\n?>\n $fn testfunction() {$fn->testfunction()} __call magic"
},
{
"answer_id": 4387729,
"author": "Michael McMillan",
"author_id": 510652,
"author_profile": "https://Stackoverflow.com/users/510652",
"pm_score": 3,
"selected": false,
"text": "function add ($int) { return $int + 1; }\n$f=get_defined_functions();foreach($f[user]as$v){$$v=$v;}\n\n$string = <<< heredoc\nplain text and now a function: {$add(1)}\nheredoc;\n"
},
{
"answer_id": 6384711,
"author": "MLU",
"author_id": 803058,
"author_profile": "https://Stackoverflow.com/users/803058",
"pm_score": 3,
"selected": false,
"text": "<html>\n<head>\n <title><?php echo $page_title; ?></title>\n</head>\n<body>\n <?php echo getPageContent(); ?>\n</body>\n $page_content = getPageContent();\n\nprint <<<END\n<html>\n<head>\n <title>$page_title</title>\n</head>\n<body>\n$page_content\n</body>\nEND;\n"
},
{
"answer_id": 10713298,
"author": "CJ Dennis",
"author_id": 1166898,
"author_profile": "https://Stackoverflow.com/users/1166898",
"pm_score": 6,
"selected": false,
"text": "function fn($data) {\n return $data;\n}\n$fn = 'fn';\n\n$my_string = <<<EOT\nNumber of seconds since the Unix Epoch: {$fn(time())}\nEOT;\n"
},
{
"answer_id": 14392377,
"author": "Paulo Buchsbaum",
"author_id": 1062727,
"author_profile": "https://Stackoverflow.com/users/1062727",
"pm_score": 2,
"selected": false,
"text": "function double($i)\n{ return $i*2; }\n\nfunction triple($i)\n{ return $i*3;}\n\n$tab = 'double';\necho \"{$tab(5)} is $tab 5<br>\";\n\n$tab = 'triple';\necho \"{$tab(5)} is $tab 5<br>\";\n"
},
{
"answer_id": 18955399,
"author": "Ismael Miguel",
"author_id": 2729937,
"author_profile": "https://Stackoverflow.com/users/2729937",
"pm_score": 2,
"selected": false,
"text": "$or=function($c,$t,$f){return$c?$t:$f;};\necho <<<TRUEFALSE\n The best color ever is {$or(rand(0,1),'green','black')}\nTRUEFALSE;\n"
},
{
"answer_id": 27049352,
"author": "p.voinov",
"author_id": 2121460,
"author_profile": "https://Stackoverflow.com/users/2121460",
"pm_score": 3,
"selected": false,
"text": "function heredoc($param) {\n // just return whatever has been passed to us\n return $param;\n}\n\n$heredoc = 'heredoc';\n\n$string = <<<HEREDOC\n\\$heredoc is now a generic function that can be used in all sorts of ways:\nOutput the result of a function: {$heredoc(date('r'))}\nOutput the value of a constant: {$heredoc(__FILE__)}\nStatic methods work just as well: {$heredoc(MyClass::getSomething())}\n2 + 2 equals {$heredoc(2+2)}\nHEREDOC;\n\n// The same works not only with HEREDOC strings,\n// but with double-quoted strings as well:\n$string = \"{$heredoc(2+2)}\";\n"
},
{
"answer_id": 36202673,
"author": "bishop",
"author_id": 2908724,
"author_profile": "https://Stackoverflow.com/users/2908724",
"pm_score": 5,
"selected": false,
"text": "!${''} echo <<<EOT\nOne month ago was ${!${''} = date('Y-m-d H:i:s', strtotime('-1 month'))}.\nEOT;\n"
},
{
"answer_id": 39303612,
"author": "Rubel Hossain",
"author_id": 4305693,
"author_profile": "https://Stackoverflow.com/users/4305693",
"pm_score": 0,
"selected": false,
"text": "<?php\necho <<<ETO\n<h1>Hellow ETO</h1>\nETO;\n"
},
{
"answer_id": 39542266,
"author": "Ken",
"author_id": 638510,
"author_profile": "https://Stackoverflow.com/users/638510",
"pm_score": 1,
"selected": false,
"text": "<div><?=<<<heredoc\nUse heredoc and functions in ONE statement.\nShow lower case ABC=\"\nheredoc\n. strtolower('ABC') . <<<heredoc\n\". And that is it!\nheredoc\n?></div>\n"
},
{
"answer_id": 58964820,
"author": "codeasaurus",
"author_id": 5914739,
"author_profile": "https://Stackoverflow.com/users/5914739",
"pm_score": 2,
"selected": false,
"text": "<?php\n\n$test = function(){\n return 'it works!';\n};\n\n\necho <<<HEREDOC\nthis is a test: {$test()}\nHEREDOC;\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9330/"
] |
104,520
|
<p>I have been seriously disappointed with WPF validation system. Anyway! How can I validate the complete form by clicking the "button"? </p>
<p>For some reason everything in WPF is soo complicated! I can do the validation in 1 line of code in ASP.NET which requires like 10-20 lines of code in WPF!!</p>
<p>I can do this using my own ValidationEngine framework: </p>
<pre><code>Customer customer = new Customer();
customer.FirstName = "John";
customer.LastName = String.Empty;
ValidationEngine.Validate(customer);
if (customer.BrokenRules.Count > 0)
{
// do something display the broken rules!
}
</code></pre>
|
[
{
"answer_id": 157665,
"author": "Christopher Bennage",
"author_id": 6855,
"author_profile": "https://Stackoverflow.com/users/6855",
"pm_score": 0,
"selected": false,
"text": " <StackPanel> \n <TextBox Text=\"{Binding CurrentCustomer.FirstName}\" />\n <TextBox Text=\"{Binding CurrentCustomer.LastName}\" />\n <Button Content=\"Validate\" \n Command=\"{Binding ValidateCommand}\"\n CommandParameter=\"{Binding CurrentCustomer}\" />\n <ItemsControl ItemsSource=\"{Binding CurrentCustomer.BrokenRules}\" />\n </StackPanel>\n"
},
{
"answer_id": 182330,
"author": "David Schmitt",
"author_id": 4918,
"author_profile": "https://Stackoverflow.com/users/4918",
"pm_score": 6,
"selected": true,
"text": "ValidatesOnDataErrors =true Validation.ErrorTemplate <Window x:Class=\"Example.CustomerWindow\" ...>\n <Window.CommandBindings>\n <CommandBinding Command=\"ApplicationCommands.Save\"\n CanExecute=\"SaveCanExecute\"\n Executed=\"SaveExecuted\" />\n </Window.CommandBindings>\n <StackPanel>\n <TextBox Text=\"{Binding FirstName, ValidatesOnDataErrors=true, UpdateSourceTrigger=PropertyChanged}\" />\n <TextBox Text=\"{Binding LastName, ValidatesOnDataErrors=true, UpdateSourceTrigger=PropertyChanged}\" />\n <Button Command=\"ApplicationCommands.Save\" IsDefault=\"True\">Save</Button>\n <TextBlock Text=\"{Binding Error}\"/>\n </StackPanel>\n</Window>\n Window TextBox TextBlock ErrorTemplate // The CustomerWindow class receives the Customer to display\n// and manages the Save command\npublic class CustomerWindow : Window\n{\n private Customer CurrentCustomer;\n public CustomerWindow(Customer c) \n {\n // store the customer for the bindings\n DataContext = CurrentCustomer = c;\n InitializeComponent();\n }\n\n private void SaveCanExecute(object sender, CanExecuteRoutedEventArgs e)\n {\n e.CanExecute = ValidationEngine.Validate(CurrentCustomer);\n }\n\n private void SaveExecuted(object sender, ExecutedRoutedEventArgs e) \n {\n CurrentCustomer.Save();\n }\n}\n\npublic class Customer : IDataErrorInfo, INotifyPropertyChanged\n{\n // holds the actual value of FirstName\n private string FirstNameBackingStore;\n // the accessor for FirstName. Only accepts valid values.\n public string FirstName {\n get { return FirstNameBackingStore; }\n set {\n FirstNameBackingStore = value;\n ValidationEngine.Validate(this);\n OnPropertyChanged(\"FirstName\");\n }\n }\n // similar for LastName \n\n string IDataErrorInfo.Error {\n get { return String.Join(\"\\n\", BrokenRules.Values); }\n }\n\n string IDataErrorInfo.this[string columnName]\n {\n get { return BrokenRules[columnName]; }\n }\n}\n IDataErrorInfo ValidationEngine"
},
{
"answer_id": 4263768,
"author": "skjagini",
"author_id": 185907,
"author_profile": "https://Stackoverflow.com/users/185907",
"pm_score": 1,
"selected": false,
"text": "<TextBox Text=\"{Binding Age, ValidatesOnDataErrors=true, UpdateSourceTrigger=PropertyChanged}\" />\n <TextBox Text=\"{Binding Age, ValidatesOnDataErrors=true, ValidatesOnExceptions=\"True\", UpdateSourceTrigger=PropertyChanged}\" />\n <TextBox>\n <TextBox.Text>\n <Binding Path=\"Age\" UpdateSourceTrigger=\"PropertyChanged\" ValidatesOnDataErrors=\"True\">\n <Binding.ValidationRules>\n <ExceptionValidationRule />\n </Binding.ValidationRules>\n </Binding>\n </TextBox.Text>\n</TextBox>\n <TextBox.Text>\n <Binding Path=\"Age\" ValidatesOnDataErrors=\"True\">\n <Binding.ValidationRules>\n <rules:NumericRule />\n </Binding.ValidationRules>\n </Binding>\n </TextBox.Text>\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3797/"
] |
104,525
|
<p>We have a warm sql backup. full backup nightly, txn logs shipped every so often during the day and restored. I need to move the data files to another disk. These DB's are in a "warm backup" state (such that I can't unmark them as read-only - "Error 5063: Database '<dbname>' is in warm standby. A warm-standby database is read-only.
") and am worried about detaching and re-attaching. </p>
<p>How do we obtain the "warm backup" status after detach/attach operations are complete?</p>
|
[
{
"answer_id": 104762,
"author": "boes",
"author_id": 17746,
"author_profile": "https://Stackoverflow.com/users/17746",
"pm_score": 3,
"selected": true,
"text": "backup database activedb to disk='somefile'\n restore database warmbackup from disk='somefile'\n with norecovery, replace ....\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10235/"
] |
104,550
|
<p>Are <code>.css</code> files always needed? Or may I have a <code>.css</code> "basic" file and define other style items inside the HTML page?</p>
<p>Does <code>padding</code>, <code>borders</code> and so on always have to be defined in a <code>.css</code> file that is stored separately, or may I embed then into an HTML page?</p>
|
[
{
"answer_id": 104595,
"author": "Michael",
"author_id": 13379,
"author_profile": "https://Stackoverflow.com/users/13379",
"pm_score": 3,
"selected": false,
"text": "<style> <head> <head>\n <style type=\"text/css\">\n body{ background-color: blue; }\n </style>\n</head>\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19159/"
] |
104,568
|
<p>Is there any way that my script can retrieve metadata values that are declared in its own header? I don't see anything promising in the API, except perhaps <code>GM_getValue()</code>. That would of course involve a special name syntax. I have tried, for example: <code>GM_getValue("@name")</code>.</p>
<p>The motivation here is to avoid redundant specification.</p>
<p>If GM metadata is not directly accessible, perhaps there's a way to read the body of the script itself. It's certainly in memory somewhere, and it wouldn't be too awfully hard to parse for <code>"// @"</code>. (That may be necessary in my case any way, since the value I'm really interested in is <code>@version</code>, which is an extended value read by <a href="http://userscripts.org/" rel="noreferrer">userscripts.org</a>.)</p>
|
[
{
"answer_id": 104814,
"author": "Athena",
"author_id": 17846,
"author_profile": "https://Stackoverflow.com/users/17846",
"pm_score": 4,
"selected": true,
"text": "GM_info var metadata=<> \n// ==UserScript==\n// @name Reading metadata\n// @namespace http://www.afunamatata.com/greasemonkey/\n// @description Read in metadata from the header\n// @version 0.9\n// @include https://stackoverflow.com/questions/104568/accessing-greasemonkey-metadata-from-within-your-script\n// ==/UserScript==\n</>.toString();\n\nGM_log(metadata); \n"
},
{
"answer_id": 10475344,
"author": "Brock Adams",
"author_id": 331508,
"author_profile": "https://Stackoverflow.com/users/331508",
"pm_score": 3,
"selected": false,
"text": "GM_info // ==UserScript==\n// @name _GM_info demo\n// @namespace Stack Overflow\n// @description Tell me more about me, me, ME!\n// @include http://stackoverflow.com/questions/*\n// @version 8.8\n// ==/UserScript==\n\nunsafeWindow.console.clear ();\nunsafeWindow.console.log (GM_info);\n {\n version: (new String(\"0.9.18\")),\n scriptWillUpdate: false,\n script: {\n description: \"Tell me more about me, me, ME!\",\n excludes: [],\n includes: [\"http://stackoverflow.com/questions/*\"],\n matches: [],\n name: \"_GM_info demo\",\n namespace: \"Stack Overflow\",\n 'run-at': \"document-end\",\n unwrap: false,\n version: \"8.8\"\n },\n scriptMetaStr: \"// @name _GM_info demo\\r\\n// @namespace Stack Overflow\\r\\n// @description Tell me more about me, me, ME!\\r\\n// @include http://stackoverflow.com/questions/*\\r\\n// @version 8.8\\r\\n\"\n}\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14749/"
] |
104,587
|
<p>Everywhere I look always the same explanation pop ups.<br/>
Configure the view resolver.</p>
<pre><code><bean id="viewMappings"
class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="basename" value="views" />
</bean>
</code></pre>
<p>And then put a file in the classpath named view.properties with some key-value pairs (don't mind the names).<br/></p>
<pre><code>logout.class=org.springframework.web.servlet.view.JstlView
logout.url=WEB-INF/jsp/logout.jsp
</code></pre>
<p>What does <code>logout.class</code> and <code>logout.url</code> mean?<br/>
How does <code>ResourceBundleViewResolver</code> uses the key-value pairs in the file?<br/>
My goal is that when someone enters the URI <code>myserver/myapp/logout.htm</code> the file <code>logout.jsp</code> gets served.</p>
|
[
{
"answer_id": 105554,
"author": "Brian Matthews",
"author_id": 1969,
"author_profile": "https://Stackoverflow.com/users/1969",
"pm_score": 0,
"selected": false,
"text": "logout *.htm web.xml *.jsp"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2024/"
] |
104,599
|
<p>I need to write a Java Comparator class that compares Strings, however with one twist. If the two strings it is comparing are the same at the beginning and end of the string are the same, and the middle part that differs is an integer, then compare based on the numeric values of those integers. For example, I want the following strings to end up in order they're shown:</p>
<ul>
<li>aaa</li>
<li>bbb 3 ccc</li>
<li>bbb 12 ccc</li>
<li>ccc 11</li>
<li>ddd</li>
<li>eee 3 ddd jpeg2000 eee</li>
<li>eee 12 ddd jpeg2000 eee</li>
</ul>
<p>As you can see, there might be other integers in the string, so I can't just use regular expressions to break out any integer. I'm thinking of just walking the strings from the beginning until I find a bit that doesn't match, then walking in from the end until I find a bit that doesn't match, and then comparing the bit in the middle to the regular expression "[0-9]+", and if it compares, then doing a numeric comparison, otherwise doing a lexical comparison.</p>
<p>Is there a better way?</p>
<p><strong>Update</strong> I don't think I can guarantee that the other numbers in the string, the ones that may match, don't have spaces around them, or that the ones that differ do have spaces.</p>
|
[
{
"answer_id": 104693,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 0,
"selected": false,
"text": "int"
},
{
"answer_id": 104926,
"author": "Paul Brinkley",
"author_id": 18160,
"author_profile": "https://Stackoverflow.com/users/18160",
"pm_score": 0,
"selected": false,
"text": " aa 0 aa\n aa 23aa\n aa 2a3aa\n aa 113aa\n aa 113 aa\n a 1-2 a\n a 13 a\n a 12 a\n a 2-3 a\n a 21 a\n a 2.3 a\n"
},
{
"answer_id": 105665,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 4,
"selected": false,
"text": "String[] strs =\n{\n \"eee 5 ddd jpeg2001 eee\",\n \"eee 123 ddd jpeg2000 eee\",\n \"ddd\",\n \"aaa 5 yy 6\",\n \"ccc 555\",\n \"bbb 3 ccc\",\n \"bbb 9 a\",\n \"\",\n \"eee 4 ddd jpeg2001 eee\",\n \"ccc 11\",\n \"bbb 12 ccc\",\n \"aaa 5 yy 22\",\n \"aaa\",\n \"eee 3 ddd jpeg2000 eee\",\n \"ccc 5\",\n};\n\nPattern splitter = Pattern.compile(\"(\\\\d+|\\\\D+)\");\n\npublic class InternalNumberComparator implements Comparator\n{\n public int compare(Object o1, Object o2)\n {\n // I deliberately use the Java 1.4 syntax, \n // all this can be improved with 1.5's generics\n String s1 = (String)o1, s2 = (String)o2;\n // We split each string as runs of number/non-number strings\n ArrayList sa1 = split(s1);\n ArrayList sa2 = split(s2);\n // Nothing or different structure\n if (sa1.size() == 0 || sa1.size() != sa2.size())\n {\n // Just compare the original strings\n return s1.compareTo(s2);\n }\n int i = 0;\n String si1 = \"\";\n String si2 = \"\";\n // Compare beginning of string\n for (; i < sa1.size(); i++)\n {\n si1 = (String)sa1.get(i);\n si2 = (String)sa2.get(i);\n if (!si1.equals(si2))\n break; // Until we find a difference\n }\n // No difference found?\n if (i == sa1.size())\n return 0; // Same strings!\n\n // Try to convert the different run of characters to number\n int val1, val2;\n try\n {\n val1 = Integer.parseInt(si1);\n val2 = Integer.parseInt(si2);\n }\n catch (NumberFormatException e)\n {\n return s1.compareTo(s2); // Strings differ on a non-number\n }\n\n // Compare remainder of string\n for (i++; i < sa1.size(); i++)\n {\n si1 = (String)sa1.get(i);\n si2 = (String)sa2.get(i);\n if (!si1.equals(si2))\n {\n return s1.compareTo(s2); // Strings differ\n }\n }\n\n // Here, the strings differ only on a number\n return val1 < val2 ? -1 : 1;\n }\n\n ArrayList split(String s)\n {\n ArrayList r = new ArrayList();\n Matcher matcher = splitter.matcher(s);\n while (matcher.find())\n {\n String m = matcher.group(1);\n r.add(m);\n }\n return r;\n }\n}\n\nArrays.sort(strs, new InternalNumberComparator());\n"
},
{
"answer_id": 6066138,
"author": "JustinKSU",
"author_id": 724835,
"author_profile": "https://Stackoverflow.com/users/724835",
"pm_score": 2,
"selected": false,
"text": "public class StringAsNumberComparator implements Comparator<String> {\n\n public static final Pattern NUMBER_PATTERN = Pattern.compile(\"(\\\\-?\\\\d+\\\\.\\\\d+)|(\\\\-?\\\\.\\\\d+)|(\\\\-?\\\\d+)\");\n\n /**\n * Splits strings into parts sorting each instance of a number as a number if there is\n * a matching number in the other String.\n * \n * For example A1B, A2B, A11B, A11B1, A11B2, A11B11 will be sorted in that order instead\n * of alphabetically which will sort A1B and A11B together.\n */\n public int compare(String str1, String str2) {\n if(str1 == str2) return 0;\n else if(str1 == null) return 1;\n else if(str2 == null) return -1;\n\n List<String> split1 = split(str1);\n List<String> split2 = split(str2);\n int diff = 0;\n\n for(int i = 0; diff == 0 && i < split1.size() && i < split2.size(); i++) {\n String token1 = split1.get(i);\n String token2 = split2.get(i);\n\n if((NUMBER_PATTERN.matcher(token1).matches() && NUMBER_PATTERN.matcher(token2).matches()) {\n diff = (int) Math.signum(Double.parseDouble(token1) - Double.parseDouble(token2));\n } else {\n diff = token1.compareToIgnoreCase(token2);\n }\n }\n if(diff != 0) {\n return diff;\n } else {\n return split1.size() - split2.size();\n }\n }\n\n /**\n * Splits a string into strings and number tokens.\n */\n private List<String> split(String s) {\n List<String> list = new ArrayList<String>();\n try (Scanner scanner = new Scanner(s)) {\n int index = 0;\n String num = null;\n while ((num = scanner.findInLine(NUMBER_PATTERN)) != null) {\n int indexOfNumber = s.indexOf(num, index);\n if (indexOfNumber > index) {\n list.add(s.substring(index, indexOfNumber));\n }\n list.add(num);\n index = indexOfNumber + num.length();\n }\n if (index < s.length()) {\n list.add(s.substring(index));\n }\n }\n return list;\n }\n}\n"
},
{
"answer_id": 11596232,
"author": "Giuseppe Scrivano",
"author_id": 1542527,
"author_profile": "https://Stackoverflow.com/users/1542527",
"pm_score": 1,
"selected": false,
"text": "import java.util.Collections;\nimport java.util.Vector;\n\npublic class CompareToken implements Comparable<CompareToken>\n{\n int valN;\n String valS;\n String repr;\n\n public String toString() {\n return repr;\n }\n\n public CompareToken(String s) {\n int l = 0;\n char data[] = new char[s.length()];\n repr = s;\n valN = 0;\n for (char c : s.toCharArray()) {\n if(Character.isDigit(c))\n valN = valN * 10 + (c - '0');\n else\n data[l++] = c;\n }\n\n valS = new String(data, 0, l);\n }\n\n public int compareTo(CompareToken b) {\n int r = valS.compareTo(b.valS);\n if (r != 0)\n return r;\n\n return valN - b.valN;\n }\n\n\n public static void main(String [] args) {\n String [] strings = {\n \"aaa\",\n \"bbb3ccc\",\n \"bbb12ccc\",\n \"ccc 11\",\n \"ddd\",\n \"eee3dddjpeg2000eee\",\n \"eee12dddjpeg2000eee\"\n };\n\n Vector<CompareToken> data = new Vector<CompareToken>();\n for(String s : strings)\n data.add(new CompareToken(s));\n Collections.shuffle(data);\n\n Collections.sort(data);\n for (CompareToken c : data)\n System.out.println (\"\" + c);\n }\n\n}\n"
},
{
"answer_id": 24948978,
"author": "cdaringe",
"author_id": 1438908,
"author_profile": "https://Stackoverflow.com/users/1438908",
"pm_score": 1,
"selected": false,
"text": "...\nvar regex = /(\\d+)/g,\n str1Components = str1.split(regex),\n str2Components = str2.split(regex),\n...\n"
},
{
"answer_id": 27530654,
"author": "Olivier OUDOT",
"author_id": 4370518,
"author_profile": "https://Stackoverflow.com/users/4370518",
"pm_score": 3,
"selected": false,
"text": "public static final int compareNatural (String s1, String s2)\n{\n // Skip all identical characters\n int len1 = s1.length();\n int len2 = s2.length();\n int i;\n char c1, c2;\n for (i = 0, c1 = 0, c2 = 0; (i < len1) && (i < len2) && (c1 = s1.charAt(i)) == (c2 = s2.charAt(i)); i++);\n \n // Check end of string\n if (c1 == c2)\n return(len1 - len2);\n\n // Check digit in first string\n if (Character.isDigit(c1))\n {\n // Check digit only in first string \n if (!Character.isDigit(c2))\n return(1);\n \n // Scan all integer digits\n int x1, x2;\n for (x1 = i + 1; (x1 < len1) && Character.isDigit(s1.charAt(x1)); x1++);\n for (x2 = i + 1; (x2 < len2) && Character.isDigit(s2.charAt(x2)); x2++);\n \n // Longer integer wins, first digit otherwise\n return(x2 == x1 ? c1 - c2 : x1 - x2);\n }\n \n // Check digit only in second string\n if (Character.isDigit(c2))\n return(-1);\n \n // No digits\n return(c1 - c2);\n}\n"
},
{
"answer_id": 30694914,
"author": "specialscope",
"author_id": 1161876,
"author_profile": "https://Stackoverflow.com/users/1161876",
"pm_score": 1,
"selected": false,
"text": " private final boolean isDigit(char ch)\n {\n return ch >= 48 && ch <= 57;\n }\n\n\n private int compareNumericalString(String s1,String s2){\n\n int s1Counter=0;\n int s2Counter=0;\n while(true){\n if(s1Counter>=s1.length()){\n break;\n }\n if(s2Counter>=s2.length()){\n break;\n }\n char currentChar1=s1.charAt(s1Counter++);\n char currentChar2=s2.charAt(s2Counter++);\n if(isDigit(currentChar1) &&isDigit(currentChar2)){\n String digitString1=\"\"+currentChar1;\n String digitString2=\"\"+currentChar2;\n while(true){\n if(s1Counter>=s1.length()){\n break;\n }\n if(s2Counter>=s2.length()){\n break;\n }\n\n if(isDigit(s1.charAt(s1Counter))){\n digitString1+=s1.charAt(s1Counter);\n s1Counter++;\n }\n\n if(isDigit(s2.charAt(s2Counter))){\n digitString2+=s2.charAt(s2Counter);\n s2Counter++;\n }\n\n if((!isDigit(s1.charAt(s1Counter))) && (!isDigit(s2.charAt(s2Counter)))){\n currentChar1=s1.charAt(s1Counter);\n currentChar2=s2.charAt(s2Counter);\n break;\n }\n }\n if(!digitString1.equals(digitString2)){\n return Integer.parseInt(digitString1)-Integer.parseInt(digitString2);\n }\n }\n\n if(currentChar1!=currentChar2){\n return currentChar1-currentChar2;\n }\n\n }\n return s1.compareTo(s2);\n }\n"
},
{
"answer_id": 37003792,
"author": "Bennie Krijger",
"author_id": 5197240,
"author_profile": "https://Stackoverflow.com/users/5197240",
"pm_score": 0,
"selected": false,
"text": "object Alphanum {\n\n private[this] val regex = \"((?<=[0-9])(?=[^0-9]))|((?<=[^0-9])(?=[0-9]))\"\n\n private[this] val alphaNum: Ordering[String] = Ordering.fromLessThan((ss1: String, ss2: String) => (ss1, ss2) match {\n case (sss1, sss2) if sss1.matches(\"[0-9]+\") && sss2.matches(\"[0-9]+\") => sss1.toLong < sss2.toLong\n case (sss1, sss2) => sss1 < sss2\n })\n\n def ordering: Ordering[String] = Ordering.fromLessThan((s1: String, s2: String) => {\n import Ordering.Implicits.infixOrderingOps\n implicit val ord: Ordering[List[String]] = Ordering.Implicits.seqDerivedOrdering(alphaNum)\n\n s1.split(regex).toList < s2.split(regex).toList\n })\n\n}\n"
},
{
"answer_id": 45189067,
"author": "Helder Pereira",
"author_id": 5180989,
"author_profile": "https://Stackoverflow.com/users/5180989",
"pm_score": 3,
"selected": false,
"text": "public static Comparator<String> naturalOrdering() {\n final Pattern compile = Pattern.compile(\"(\\\\d+)|(\\\\D+)\");\n return (s1, s2) -> {\n final Matcher matcher1 = compile.matcher(s1);\n final Matcher matcher2 = compile.matcher(s2);\n while (true) {\n final boolean found1 = matcher1.find();\n final boolean found2 = matcher2.find();\n if (!found1 || !found2) {\n return Boolean.compare(found1, found2);\n } else if (!matcher1.group().equals(matcher2.group())) {\n if (matcher1.group(1) == null || matcher2.group(1) == null) {\n return matcher1.group().compareTo(matcher2.group());\n } else {\n return Integer.valueOf(matcher1.group(1)).compareTo(Integer.valueOf(matcher2.group(1)));\n }\n }\n }\n };\n}\n final List<String> strings = Arrays.asList(\"x15\", \"xa\", \"y16\", \"x2a\", \"y11\", \"z\", \"z5\", \"x2b\", \"z\");\nstrings.sort(naturalOrdering());\nSystem.out.println(strings);\n"
},
{
"answer_id": 53228819,
"author": "mavisto",
"author_id": 5790258,
"author_profile": "https://Stackoverflow.com/users/5790258",
"pm_score": 0,
"selected": false,
"text": "SortedSet<Code> codeSet;\ncodeSet = new TreeSet<Code>(new Comparator<Code>() {\n\nprivate boolean isThereAnyNumber(String a, String b) {\n return isNumber(a) || isNumber(b);\n}\n\nprivate boolean isNumber(String s) {\n return s.matches(\"[-+]?\\\\d*\\\\.?\\\\d+\");\n}\n\nprivate String extractChars(String s) {\n String chars = s.replaceAll(\"\\\\d\", \"\");\n return chars;\n}\n\nprivate int extractInt(String s) {\n String num = s.replaceAll(\"\\\\D\", \"\");\n return num.isEmpty() ? 0 : Integer.parseInt(num);\n}\n\nprivate int compareStrings(String o1, String o2) {\n\n if (!extractChars(o1).equals(extractChars(o2))) {\n return o1.compareTo(o2);\n } else\n return extractInt(o1) - extractInt(o2);\n}\n\n@Override\npublic int compare(Code a, Code b) {\n\n return isThereAnyNumber(a.getPrimaryCode(), b.getPrimaryCode()) \n ? isNumber(a.getPrimaryCode()) ? 1 : -1 \n : compareStrings(a.getPrimaryCode(), b.getPrimaryCode());\n }\n });\n"
},
{
"answer_id": 56795450,
"author": "Saša",
"author_id": 897373,
"author_profile": "https://Stackoverflow.com/users/897373",
"pm_score": 0,
"selected": false,
"text": "public class StringWithNumberComparator implements Comparator<MyClass> {\n\n@Override\npublic int compare(MyClass o1, MyClass o2) {\n if (o1.getStringToCompare().equals(o2.getStringToCompare())) {\n return 0;\n }\n String[] first = o1.getStringToCompare().split(\" \");\n String[] second = o2.getStringToCompare().split(\" \");\n if (first.length == second.length) {\n for (int i = 0; i < first.length; i++) {\n\n int segmentCompare = StringUtils.compare(first[i], second[i]);\n if (StringUtils.isNumeric(first[i]) && StringUtils.isNumeric(second[i])) {\n\n segmentCompare = NumberUtils.compare(Integer.valueOf(first[i]), Integer.valueOf(second[i]));\n if (0 != segmentCompare) {\n // return only if uneven numbers in case there are more segments to be checked\n return segmentCompare;\n }\n }\n if (0 != segmentCompare) {\n return segmentCompare;\n }\n }\n } else {\n return StringUtils.compare(o1.getDenominazione(), o2.getDenominazione());\n }\n\n return 0;\n}\n"
},
{
"answer_id": 58249974,
"author": "Stanislav",
"author_id": 2556378,
"author_profile": "https://Stackoverflow.com/users/2556378",
"pm_score": 2,
"selected": false,
"text": "\"0001\" \"1\" \"01234\" \"4567\" public class NumberAwareComparator implements Comparator<String>\n{\n @Override\n public int compare(String s1, String s2)\n {\n int len1 = s1.length();\n int len2 = s2.length();\n int i1 = 0;\n int i2 = 0;\n while (true)\n {\n // handle the case when one string is longer than another\n if (i1 == len1)\n return i2 == len2 ? 0 : -1;\n if (i2 == len2)\n return 1;\n\n char ch1 = s1.charAt(i1);\n char ch2 = s2.charAt(i2);\n if (Character.isDigit(ch1) && Character.isDigit(ch2))\n {\n // skip leading zeros\n while (i1 < len1 && s1.charAt(i1) == '0')\n i1++;\n while (i2 < len2 && s2.charAt(i2) == '0')\n i2++;\n\n // find the ends of the numbers\n int end1 = i1;\n int end2 = i2;\n while (end1 < len1 && Character.isDigit(s1.charAt(end1)))\n end1++;\n while (end2 < len2 && Character.isDigit(s2.charAt(end2)))\n end2++;\n\n int diglen1 = end1 - i1;\n int diglen2 = end2 - i2;\n\n // if the lengths are different, then the longer number is bigger\n if (diglen1 != diglen2)\n return diglen1 - diglen2;\n\n // compare numbers digit by digit\n while (i1 < end1)\n {\n if (s1.charAt(i1) != s2.charAt(i2))\n return s1.charAt(i1) - s2.charAt(i2);\n i1++;\n i2++;\n }\n }\n else\n {\n // plain characters comparison\n if (ch1 != ch2)\n return ch1 - ch2;\n i1++;\n i2++;\n }\n }\n }\n}\n"
},
{
"answer_id": 60588742,
"author": "Devan K S",
"author_id": 13027997,
"author_profile": "https://Stackoverflow.com/users/13027997",
"pm_score": 1,
"selected": false,
"text": "\npublic class NaturalSortingComparator implements Comparator<String> {\n\n @Override\n public int compare(String string1, String string2) {\n int lengthOfString1 = string1.length();\n int lengthOfString2 = string2.length();\n int iteratorOfString1 = 0;\n int iteratorOfString2 = 0;\n int differentCaseCompared = 0;\n while (true) {\n if (iteratorOfString1 == lengthOfString1) {\n if (iteratorOfString2 == lengthOfString2) {\n if (lengthOfString1 == lengthOfString2) {\n // If both strings are the same except for the different cases, the differentCaseCompared will be returned\n return differentCaseCompared;\n }\n //If the characters are the same at the point, returns the difference between length of the strings\n else {\n return lengthOfString1 - lengthOfString2;\n }\n }\n //If String2 is bigger than String1\n else\n return -1;\n }\n //Check if String1 is bigger than string2\n if (iteratorOfString2 == lengthOfString2) {\n return 1;\n }\n\n char ch1 = string1.charAt(iteratorOfString1);\n char ch2 = string2.charAt(iteratorOfString2);\n\n if (Character.isDigit(ch1) && Character.isDigit(ch2)) {\n // skip leading zeros\n iteratorOfString1 = skipLeadingZeroes(string1, lengthOfString1, iteratorOfString1);\n iteratorOfString2 = skipLeadingZeroes(string2, lengthOfString2, iteratorOfString2);\n\n // find the ends of the numbers\n int endPositionOfNumbersInString1 = findEndPositionOfNumber(string1, lengthOfString1, iteratorOfString1);\n int endPositionOfNumbersInString2 = findEndPositionOfNumber(string2, lengthOfString2, iteratorOfString2);\n\n int lengthOfDigitsInString1 = endPositionOfNumbersInString1 - iteratorOfString1;\n int lengthOfDigitsInString2 = endPositionOfNumbersInString2 - iteratorOfString2;\n\n // if the lengths are different, then the longer number is bigger\n if (lengthOfDigitsInString1 != lengthOfDigitsInString2)\n return lengthOfDigitsInString1 - lengthOfDigitsInString2;\n\n // compare numbers digit by digit\n while (iteratorOfString1 < endPositionOfNumbersInString1) {\n\n if (string1.charAt(iteratorOfString1) != string2.charAt(iteratorOfString2))\n return string1.charAt(iteratorOfString1) - string2.charAt(iteratorOfString2);\n\n iteratorOfString1++;\n iteratorOfString2++;\n }\n } else {\n // plain characters comparison\n if (ch1 != ch2) {\n if (!ignoreCharacterCaseEquals(ch1, ch2))\n return Character.toLowerCase(ch1) - Character.toLowerCase(ch2);\n\n // Set a differentCaseCompared if the characters being compared are different case.\n // Should be done only once, hence the check with 0\n if (differentCaseCompared == 0) {\n differentCaseCompared = ch1 - ch2;\n }\n }\n\n iteratorOfString1++;\n iteratorOfString2++;\n }\n }\n }\n\n private boolean ignoreCharacterCaseEquals(char character1, char character2) {\n\n return Character.toLowerCase(character1) == Character.toLowerCase(character2);\n }\n\n private int findEndPositionOfNumber(String string, int lengthOfString, int end) {\n\n while (end < lengthOfString && Character.isDigit(string.charAt(end)))\n end++;\n\n return end;\n }\n\n private int skipLeadingZeroes(String string, int lengthOfString, int iteratorOfString) {\n\n while (iteratorOfString < lengthOfString && string.charAt(iteratorOfString) == '0')\n iteratorOfString++;\n\n return iteratorOfString;\n }\n}\n \npublic class NaturalSortingComparatorTest {\n\n private int NUMBER_OF_TEST_CASES = 100000;\n\n @Test\n public void compare() {\n\n NaturalSortingComparator naturalSortingComparator = new NaturalSortingComparator();\n\n List<String> expectedStringList = getCorrectStringList();\n List<String> testListOfStrings = createTestListOfStrings();\n runTestCases(expectedStringList, testListOfStrings, NUMBER_OF_TEST_CASES, naturalSortingComparator);\n\n }\n\n private void runTestCases(List<String> expectedStringList, List<String> testListOfStrings,\n int numberOfTestCases, Comparator<String> comparator) {\n\n for (int testCase = 0; testCase < numberOfTestCases; testCase++) {\n Collections.shuffle(testListOfStrings);\n testListOfStrings.sort(comparator);\n Assert.assertEquals(expectedStringList, testListOfStrings);\n }\n }\n\n private List<String> getCorrectStringList() {\n return Arrays.asList(\n \"1\", \"01\", \"001\", \"2\", \"02\", \"10\", \"10\", \"010\",\n \"20\", \"100\", \"_1\", \"_01\", \"_2\", \"_200\", \"A 02\",\n \"A01\", \"a2\", \"A20\", \"t1A\", \"t1a\", \"t1AB\", \"t1Ab\",\n \"t1aB\", \"t1ab\", \"T010T01\", \"T0010T01\");\n }\n\n private List<String> createTestListOfStrings() {\n return Arrays.asList(\n \"10\", \"20\", \"A20\", \"2\", \"t1ab\", \"01\", \"T010T01\", \"t1aB\",\n \"_2\", \"001\", \"_200\", \"1\", \"A 02\", \"t1Ab\", \"a2\", \"_1\", \"t1A\", \"_01\",\n \"100\", \"02\", \"T0010T01\", \"t1AB\", \"10\", \"A01\", \"010\", \"t1a\");\n }\n\n}\n"
},
{
"answer_id": 64880158,
"author": "izogfif",
"author_id": 156973,
"author_profile": "https://Stackoverflow.com/users/156973",
"pm_score": 2,
"selected": false,
"text": "import com.ibm.icu.text.Collator;\nimport com.ibm.icu.text.RuleBasedCollator;\n\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Locale;\n\npublic class CollatorExample {\n public static void main(String[] args) {\n // Make sure to choose correct locale: in Turkish uppercase of \"i\" is \"İ\", not \"I\"\n RuleBasedCollator collator = (RuleBasedCollator) Collator.getInstance(Locale.US);\n collator.setNumericCollation(true); // Place \"10\" after \"2\"\n collator.setStrength(Collator.PRIMARY); // Case-insensitive\n List<String> strings = Arrays.asList(\"10\", \"20\", \"A20\", \"2\", \"t1ab\", \"01\", \"T010T01\", \"t1aB\",\n \"_2\", \"001\", \"_200\", \"1\", \"A 02\", \"t1Ab\", \"a2\", \"_1\", \"t1A\", \"_01\",\n \"100\", \"02\", \"T0010T01\", \"t1AB\", \"10\", \"A01\", \"010\", \"t1a\"\n );\n strings.sort(collator);\n System.out.println(String.join(\", \", strings));\n // Output: _1, _01, _2, _200, 01, 001, 1,\n // 2, 02, 10, 10, 010, 20, 100, A 02, A01, \n // a2, A20, t1A, t1a, t1ab, t1aB, t1Ab, t1AB,\n // T010T01, T0010T01\n }\n}\n"
},
{
"answer_id": 66701024,
"author": "Mike",
"author_id": 448078,
"author_profile": "https://Stackoverflow.com/users/448078",
"pm_score": 1,
"selected": false,
"text": "import static java.lang.Math.pow;\n\nimport java.util.Comparator;\n\npublic class AlphanumComparator implements Comparator<String> {\n \n public static final AlphanumComparator ALPHANUM_COMPARATOR = new AlphanumComparator();\n private static char[] upperCaseCache = new char[(int) pow(2, 16)];\n private boolean nullIsLess;\n \n public AlphanumComparator() {\n }\n \n public AlphanumComparator(boolean nullIsLess) {\n this.nullIsLess = nullIsLess;\n }\n \n @Override\n public int compare(String s1, String s2) {\n if (s1 == s2)\n return 0;\n if (s1 == null)\n return nullIsLess ? -1 : 1;\n if (s2 == null)\n return nullIsLess ? 1 : -1;\n \n int i1 = 0;\n int i2 = 0;\n int len1 = s1.length();\n int len2 = s2.length();\n while (true) {\n // handle the case when one string is longer than another\n if (i1 == len1)\n return i2 == len2 ? 0 : -1;\n if (i2 == len2)\n return 1;\n \n char ch1 = s1.charAt(i1);\n char ch2 = s2.charAt(i2);\n if (isDigit(ch1) && isDigit(ch2)) {\n // skip leading zeros\n while (i1 < len1 && s1.charAt(i1) == '0')\n i1++;\n while (i2 < len2 && s2.charAt(i2) == '0')\n i2++;\n \n // find the ends of the numbers\n int end1 = i1;\n int end2 = i2;\n while (end1 < len1 && isDigit(s1.charAt(end1)))\n end1++;\n while (end2 != len2 && isDigit(s2.charAt(end2)))\n end2++;\n \n // if the lengths are different, then the longer number is bigger\n int diglen1 = end1 - i1;\n int diglen2 = end2 - i2;\n if (diglen1 != diglen2)\n return diglen1 - diglen2;\n \n // compare numbers digit by digit\n while (i1 < end1) {\n ch1 = s1.charAt(i1);\n ch2 = s2.charAt(i2);\n if (ch1 != ch2)\n return ch1 - ch2;\n i1++;\n i2++;\n }\n } else {\n ch1 = toUpperCase(ch1);\n ch2 = toUpperCase(ch2);\n if (ch1 != ch2)\n return ch1 - ch2;\n i1++;\n i2++;\n }\n }\n }\n \n private boolean isDigit(char ch) {\n return ch >= 48 && ch <= 57;\n }\n \n private char toUpperCase(char ch) {\n char cached = upperCaseCache[ch];\n if (cached == 0) {\n cached = Character.toUpperCase(ch);\n upperCaseCache[ch] = cached;\n }\n return cached;\n }\n}\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3333/"
] |
104,601
|
<p>I want to do a <code>Response.Redirect("MyPage.aspx")</code> but have it open in a new browser window. I've done this before without using the JavaScript register script method. I just can't remember how?</p>
|
[
{
"answer_id": 104660,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 5,
"selected": false,
"text": "response.write(\"<script>\");\nresponse.write(\"window.open('page.html','_blank')\");\nresponse.write(\"</script>\");\n"
},
{
"answer_id": 104881,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": false,
"text": "OnClientClick=\"aspnetForm.target ='_blank';\"\n <asp:LinkButton ID=\"myButton\" runat=\"server\" Text=\"Click Me!\" \n OnClick=\"myButton_Click\" \n OnClientClick=\"aspnetForm.target ='_blank';\"/>\n Response.Redirect(\"MyPage.aspx\"); <script type=\"text/javascript\">\n function fixform() {\n if (opener.document.getElementById(\"aspnetForm\").target != \"_blank\") return;\n opener.document.getElementById(\"aspnetForm\").target = \"\";\n opener.document.getElementById(\"aspnetForm\").action = opener.location.href;\n }\n</script>\n <body onload=\"fixform()\">\n"
},
{
"answer_id": 829034,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "ClientScript.RegisterStartupScript(this.Page.GetType(), \"\",\n \"window.open('page.aspx','Graph','height=400,width=500');\", true);\n"
},
{
"answer_id": 2829992,
"author": "tom",
"author_id": 340651,
"author_profile": "https://Stackoverflow.com/users/340651",
"pm_score": 4,
"selected": false,
"text": "OnClientClick=\"aspnetForm.target ='_blank';setTimeout('fixform()', 500);\"\n function fixform() {\n document.getElementById(\"aspnetForm\").target = '';\n}\n"
},
{
"answer_id": 3578157,
"author": "Abhishek Shrivastava",
"author_id": 328116,
"author_profile": "https://Stackoverflow.com/users/328116",
"pm_score": 2,
"selected": false,
"text": "String clientScriptName = \"ButtonClickScript\";\nType clientScriptType = this.GetType ();\n\n// Get a ClientScriptManager reference from the Page class.\nClientScriptManager clientScript = Page.ClientScript;\n\n// Check to see if the client script is already registered.\nif (!clientScript.IsClientScriptBlockRegistered (clientScriptType, clientScriptName))\n {\n StringBuilder sb = new StringBuilder ();\n sb.Append (\"<script type='text/javascript'>\");\n sb.Append (\"window.open(' \" + url + \"')\"); //URL = where you want to redirect.\n sb.Append (\"</script>\");\n clientScript.RegisterClientScriptBlock (clientScriptType, clientScriptName, sb.ToString ());\n }\n"
},
{
"answer_id": 3883008,
"author": "Yaplex",
"author_id": 199027,
"author_profile": "https://Stackoverflow.com/users/199027",
"pm_score": 0,
"selected": false,
"text": "protected void Page_Load(object sender, EventArgs e)\n{\n Calendar1.SelectionChanged += CalendarSelectionChanged;\n}\n\nprivate void CalendarSelectionChanged(object sender, EventArgs e)\n{\n DateTime selectedDate = ((Calendar) sender).SelectedDate;\n string url = \"HistoryRates.aspx?date=\"\n+ HttpUtility.UrlEncode(selectedDate.ToShortDateString());\n ScriptManager.RegisterClientScriptBlock(this, GetType(),\n\"rates\" + selectedDate, \"openWindow('\" + url + \"');\", true);\n}\n"
},
{
"answer_id": 4961312,
"author": "Sasa Tancev",
"author_id": 611904,
"author_profile": "https://Stackoverflow.com/users/611904",
"pm_score": 6,
"selected": false,
"text": "public static class ResponseHelper\n{ \n public static void Redirect(this HttpResponse response, string url, string target, string windowFeatures) \n { \n\n if ((String.IsNullOrEmpty(target) || target.Equals(\"_self\", StringComparison.OrdinalIgnoreCase)) && String.IsNullOrEmpty(windowFeatures)) \n { \n response.Redirect(url); \n } \n else \n { \n Page page = (Page)HttpContext.Current.Handler; \n\n if (page == null) \n { \n throw new InvalidOperationException(\"Cannot redirect to new window outside Page context.\"); \n } \n url = page.ResolveClientUrl(url); \n\n string script; \n if (!String.IsNullOrEmpty(windowFeatures)) \n { \n script = @\"window.open(\"\"{0}\"\", \"\"{1}\"\", \"\"{2}\"\");\"; \n } \n else \n { \n script = @\"window.open(\"\"{0}\"\", \"\"{1}\"\");\"; \n }\n script = String.Format(script, url, target, windowFeatures); \n ScriptManager.RegisterStartupScript(page, typeof(Page), \"Redirect\", script, true); \n } \n }\n}\n Response.Redirect(redirectURL, \"_blank\", \"menubar=0,scrollbars=1,width=780,height=900,top=10\");\n"
},
{
"answer_id": 6222358,
"author": "kazinix",
"author_id": 724689,
"author_profile": "https://Stackoverflow.com/users/724689",
"pm_score": 3,
"selected": false,
"text": "<asp:Button ID=\"btnNewEntry\" runat=\"Server\" CssClass=\"button\" Text=\"New Entry\"\n\nOnClick=\"btnNewEntry_Click\" OnClientClick=\"aspnetForm.target ='_blank';\"/>\n\nprotected void btnNewEntry_Click(object sender, EventArgs e)\n{\n Response.Redirect(\"New.aspx\");\n}\n"
},
{
"answer_id": 6816642,
"author": "humbads",
"author_id": 553396,
"author_profile": "https://Stackoverflow.com/users/553396",
"pm_score": 2,
"selected": false,
"text": "protected void MyButton_OnPreRender(object sender, EventArgs e)\n{\n string URL = \"~/MyPage.aspx\";\n URL = Page.ResolveClientUrl(URL);\n MyButton.OnClientClick = \"window.open('\" + URL + \"'); return false;\";\n}\n"
},
{
"answer_id": 7071967,
"author": "steve",
"author_id": 374480,
"author_profile": "https://Stackoverflow.com/users/374480",
"pm_score": 5,
"selected": false,
"text": "string strUrl = \"/some/url/path\" + myvar;\n ScriptManager.RegisterStartupScript(Page, Page.GetType(), \"popup\", \"window.open('\" + strUrl + \"','_blank')\", true);\n"
},
{
"answer_id": 10451855,
"author": "Ben Barreth",
"author_id": 603670,
"author_profile": "https://Stackoverflow.com/users/603670",
"pm_score": 1,
"selected": false,
"text": "<asp:Button ID=\"btnSubmit\" OnClientClick=\"openNewWin();\" Text=\"Submit\" OnClick=\"btn_OnClick\" runat=\"server\"/>\n function openNewWin () {\n $('form').attr('target','_blank');\n setTimeout('resetFormTarget()', 500);\n}\n\nfunction resetFormTarget(){\n $('form').attr('target','');\n}\n"
},
{
"answer_id": 12860475,
"author": "bokkie",
"author_id": 1071439,
"author_profile": "https://Stackoverflow.com/users/1071439",
"pm_score": 1,
"selected": false,
"text": "<asp:HyperLink CssClass=\"hlk11\" ID=\"hlkLink\" runat=\"server\" Text='<%# Eval(\"LinkText\") %>' Visible='<%# !(bool)Eval(\"IsDocument\") %>' Target=\"_blank\" NavigateUrl='<%# Eval(\"WebAddress\") %>'></asp:HyperLink>\n"
},
{
"answer_id": 17902865,
"author": "Zohaib",
"author_id": 2221450,
"author_profile": "https://Stackoverflow.com/users/2221450",
"pm_score": 2,
"selected": false,
"text": "<asp:Button ID=\"Button1\" runat=\"server\" Text=\"Go\" \n OnClientClick=\"window.open('yourPage.aspx');return false;\" \n onclick=\"Button3_Click\" />\n"
},
{
"answer_id": 19864862,
"author": "crh225",
"author_id": 1879992,
"author_profile": "https://Stackoverflow.com/users/1879992",
"pm_score": 0,
"selected": false,
"text": "Dim URL As String = \"http://www.google/?Search=\" + txtExample.Text.ToString\nURL = Page.ResolveClientUrl(URL)\nbtnSearch.OnClientClick = \"window.open('\" + URL + \"'); return false;\"\n"
},
{
"answer_id": 21834600,
"author": "Ricketts",
"author_id": 754830,
"author_profile": "https://Stackoverflow.com/users/754830",
"pm_score": 0,
"selected": false,
"text": "$(function () {\n //--- setup click event for elements that use a response.redirect in code behind but should open in a new window\n $(\".new-window\").on(\"click\", function () {\n\n //--- change the form's target\n $(\"#aspnetForm\").prop(\"target\", \"_blank\");\n\n //--- change the target back after the window has opened\n setTimeout(function () {\n $(\"#aspnetForm\").prop(\"target\", \"\");\n }, 1);\n });\n});\n"
},
{
"answer_id": 25188941,
"author": "Zen Of Kursat",
"author_id": 2036103,
"author_profile": "https://Stackoverflow.com/users/2036103",
"pm_score": 3,
"selected": false,
"text": "<script type=\"text/javascript\">\n function targetMeBlank() {\n document.forms[0].target = \"_blank\";\n }\n</script>\n <asp:linkbutton runat=\"server\" ID=\"lnkbtn1\" Text=\"target me to blank dude\" OnClick=\"lnkbtn1_Click\" OnClientClick=\"targetMeBlank();\"/>\n"
},
{
"answer_id": 30050188,
"author": "Hevski",
"author_id": 2373058,
"author_profile": "https://Stackoverflow.com/users/2373058",
"pm_score": 0,
"selected": false,
"text": "<asp:LinkButton ID=\"btn\" runat=\"server\" CausesValidation=\"false\" Text=\"Print\" Visible=\"false\" target=\"_blank\" />\n btn.Attributes(\"href\") = String.Format(ResolveUrl(\"~/\") + \"test/TestForm.aspx?formId={0}\", formId)\n"
},
{
"answer_id": 48512798,
"author": "Tran Anh Hien",
"author_id": 6537098,
"author_profile": "https://Stackoverflow.com/users/6537098",
"pm_score": 0,
"selected": false,
"text": "<asp:Button ID=\"Button1\" runat=\"server\" Text=\"Button\" onclick=\"Button1_Click\" OnClientClick = \"SetTarget();\" />\n function SetTarget() {\n document.forms[0].target = \"_blank\";}\n Response.Redirect(URL); \n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
104,603
|
<p>Is there a way to iterate (through foreach preferably) over a collection using reflection? I'm iterating over the properties in an object using reflection, and when the program gets to a type that is a collection, I'd like it to iterate over the contents of the collection and be able to access the objects in the collection.</p>
<p>At the moment I have an attribute set on all of my properties, with an IsCollection flag set to true on the properties that are collections. My code checks for this flag and if it's true, it gets the Type using reflection. Is there a way to invoke GetEnumerator or Items somehow on a collection to be able to iterate over the items?</p>
|
[
{
"answer_id": 104664,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 6,
"selected": true,
"text": "if (item is IEnumerable)\n{\n foreach (object o in (item as IEnumerable))\n {\n\n }\n} else {\n // reflect over item\n}\n"
},
{
"answer_id": 104757,
"author": "jop",
"author_id": 11830,
"author_profile": "https://Stackoverflow.com/users/11830",
"pm_score": 3,
"selected": false,
"text": "ClassWithListProperty obj = new ClassWithListProperty();\nobj.List.Add(1);\nobj.List.Add(2);\nobj.List.Add(3);\n\nType type = obj.GetType();\nPropertyInfo listProperty = type.GetProperty(\"List\", BindingFlags.Public);\nIEnumerable listObject = (IEnumerable) listProperty.GetValue(obj, null);\n\nforeach (int i in listObject)\n Console.Write(i); // should print out 123\n"
},
{
"answer_id": 549212,
"author": "Nagyman",
"author_id": 45715,
"author_profile": "https://Stackoverflow.com/users/45715",
"pm_score": 5,
"selected": false,
"text": "string public bool isCollection(object o)\n {\n return typeof(ICollection).IsAssignableFrom(o.GetType())\n || typeof(ICollection<>).IsAssignableFrom(o.GetType());\n }\n"
},
{
"answer_id": 3012496,
"author": "Abdo",
"author_id": 226255,
"author_profile": "https://Stackoverflow.com/users/226255",
"pm_score": 0,
"selected": false,
"text": "// type is IEnumerable\nif (type.GetInterface(\"IEnumerable\") != null)\n{\n}\n"
},
{
"answer_id": 10726432,
"author": "Sugar Bowl",
"author_id": 757992,
"author_profile": "https://Stackoverflow.com/users/757992",
"pm_score": 2,
"selected": false,
"text": " public void LogObject(object obj, int indent)\n {\n if (obj == null) return;\n string indentString = new string(' ', indent);\n Type objType = obj.GetType();\n PropertyInfo[] properties = objType.GetProperties();\n\n foreach (PropertyInfo property in properties)\n {\n Type tColl = typeof(ICollection<>);\n Type t = property.PropertyType;\n string name = property.Name;\n\n\n object propValue = property.GetValue(obj, null); \n //check for nested classes as properties\n if (property.PropertyType.Assembly == objType.Assembly)\n {\n string _result = string.Format(\"{0}{1}:\", indentString, property.Name);\n log.Info(_result);\n LogObject(propValue, indent + 2);\n }\n else\n {\n string _result = string.Format(\"{0}{1}: {2}\", indentString, property.Name, propValue);\n log.Info(_result);\n }\n\n //check for collection\n if (t.IsGenericType && tColl.IsAssignableFrom(t.GetGenericTypeDefinition()) ||\n t.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == tColl))\n {\n //var get = property.GetGetMethod();\n IEnumerable listObject = (IEnumerable)property.GetValue(obj, null);\n if (listObject != null)\n {\n foreach (object o in listObject)\n {\n LogObject(o, indent + 2);\n }\n }\n }\n }\n }\n LogObject(obj, 0);\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12999/"
] |
104,612
|
<p>I want to copy a live production database into my local development database. Is there a way to do this without locking the production database?</p>
<p>I'm currently using:</p>
<pre class="lang-none prettyprint-override"><code>mysqldump -u root --password=xxx -h xxx my_db1 | mysql -u root --password=xxx -h localhost my_db1
</code></pre>
<p>But it's locking each table as it runs.</p>
|
[
{
"answer_id": 104628,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 10,
"selected": true,
"text": "--lock-tables=false --single-transaction --lock-tables, -l\n\nLock all tables before dumping them. The tables are locked with READ\nLOCAL to allow concurrent inserts in the case of MyISAM tables. For\ntransactional tables such as InnoDB and BDB, --single-transaction is\na much better option, because it does not need to lock the tables at\nall.\n mysqldump --single-transaction=TRUE -u username -p DB\n"
},
{
"answer_id": 105207,
"author": "dvorak",
"author_id": 19235,
"author_profile": "https://Stackoverflow.com/users/19235",
"pm_score": 6,
"selected": false,
"text": "--single-transaction"
},
{
"answer_id": 1263296,
"author": "Warren Krewenki",
"author_id": 98028,
"author_profile": "https://Stackoverflow.com/users/98028",
"pm_score": 8,
"selected": false,
"text": "--lock-tables=false\n"
},
{
"answer_id": 4460408,
"author": "Azamat Tokhtaev",
"author_id": 544701,
"author_profile": "https://Stackoverflow.com/users/544701",
"pm_score": 6,
"selected": false,
"text": "--skip-add-locks"
},
{
"answer_id": 10395650,
"author": "naveen_sfx",
"author_id": 1099905,
"author_profile": "https://Stackoverflow.com/users/1099905",
"pm_score": 3,
"selected": false,
"text": " mysqldump -uuid -ppwd --skip-opt --single-transaction --max_allowed_packet=1G -q db | mysql -u root --password=xxx -h localhost db\n"
},
{
"answer_id": 10726820,
"author": "dtbarne",
"author_id": 477628,
"author_profile": "https://Stackoverflow.com/users/477628",
"pm_score": 4,
"selected": false,
"text": "--skip-lock-tables\n"
},
{
"answer_id": 14252179,
"author": "Lex",
"author_id": 615397,
"author_profile": "https://Stackoverflow.com/users/615397",
"pm_score": 4,
"selected": false,
"text": "--single-transaction"
},
{
"answer_id": 40113862,
"author": "augustomen",
"author_id": 317971,
"author_profile": "https://Stackoverflow.com/users/317971",
"pm_score": -1,
"selected": false,
"text": "mysqldump [...] | grep -v \"LOCK TABLE\" | mysql [...]\n LOCK TABLE <x> UNLOCK TABLES"
},
{
"answer_id": 45650415,
"author": "Andrés Morales",
"author_id": 422765,
"author_profile": "https://Stackoverflow.com/users/422765",
"pm_score": 0,
"selected": false,
"text": "mysqlhotcopy LOCK TABLES"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13009/"
] |
104,618
|
<p>I've been trying to get into F# on and off for a while but I keep getting put off. Why?</p>
<p>Because no matter which 'beginners' resource I try to look at I see very simple examples that start using the operator <code>-></code>.</p>
<p>However, nowhere have I found as yet that provides a clear simple explanation of what this operator means. It's as though it must be so obvious that it doesn't need explanation even to complete newbies.</p>
<p>I must therefore be really dense or perhaps it's nearly 3 decades of previous experience holding me back.</p>
<p>Can someone please, explain it or point to a truly accessible resource that explains it?</p>
|
[
{
"answer_id": 104744,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 4,
"selected": false,
"text": "> List.map (fun x -> x % 2 = 0) [1 .. 10];;\nval it : bool list\n= [false; true; false; true; false; true; false; true; false; true]\n"
},
{
"answer_id": 104779,
"author": "Apocalisp",
"author_id": 3434,
"author_profile": "https://Stackoverflow.com/users/3434",
"pm_score": 2,
"selected": false,
"text": "val f : (int -> int) = fun n -> n * 2\n"
},
{
"answer_id": 104924,
"author": "Mikael Jansson",
"author_id": 18753,
"author_profile": "https://Stackoverflow.com/users/18753",
"pm_score": 0,
"selected": false,
"text": "adder n x y = n + x + y\n adder 1 2 3\n adder :: Int -> Int -> Int -> Int\n five :: Int\nfive = 5\n add5 = adder 5\n add5 :: Int -> Int -> Int\n addder :: Int -> (Int -> (Int -> Int))\n add5andtwomore :: Int -> (Int -> Int)\nadd5andtwomore = adder 5\n add5and7andonemore :: Int -> Int\nadd5and7andonemore = adder 5 7\n > add5and7andonemore 9\n => ((add5andtwomore) 7) 9\n => ((adder 5) 7) 9)\n<=> adder 5 7 9\n > adder 5 7 9 = 5 + 7 + 9\n => 5 + 7 + 9\n => 21\n > 5 + 7 + 9\n => (+ 5 (+ 7 9))\n => (+ 5 16)\n => 21\n"
},
{
"answer_id": 105157,
"author": "Michiel Borkent",
"author_id": 6264,
"author_profile": "https://Stackoverflow.com/users/6264",
"pm_score": 1,
"selected": false,
"text": "=> F#: let f = fun x -> x*x\nC#: Func<int, int> f = x => x * x;\n -> | -> -> let isOne x = match x with\n | 1 -> true\n | _ -> false\n"
},
{
"answer_id": 105318,
"author": "Benjol",
"author_id": 11410,
"author_profile": "https://Stackoverflow.com/users/11410",
"pm_score": 3,
"selected": false,
"text": "match x with\n| 1 -> dosomething\n| _ -> dosomethingelse\n > let add a b = a + b\nval add: int -> int -> int\n > let inc = add 1\nval inc: int -> int\n"
},
{
"answer_id": 105559,
"author": "Brian",
"author_id": 19299,
"author_profile": "https://Stackoverflow.com/users/19299",
"pm_score": 7,
"selected": true,
"text": "let f : int -> int = ...\n fun x y -> x + y + 1\n match someList with\n| [] -> 0\n| h::t -> 1\n"
},
{
"answer_id": 109426,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 1,
"selected": false,
"text": "fun x y -> x + y + 1\n (x, y) => x + y + 1;\n Int -> Int -> Int\n Int -> (Int -> Int)\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17516/"
] |
104,640
|
<p>By default when using a webapp server in Eclipse Web Tools, the server startup will fail after a timeout of 45 seconds. I can increase this timeout in the server instance properties, but I don't see a way to disable the timeout entirely (useful when debugging application startup). Is there a way to do this?</p>
|
[
{
"answer_id": 65708767,
"author": "Jason Pyeron",
"author_id": 58794,
"author_profile": "https://Stackoverflow.com/users/58794",
"pm_score": 0,
"selected": false,
"text": ".metadata/.plugins/org.eclipse.wst.server.core/servers.xml start-timeout -1"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5586/"
] |
104,674
|
<p>It's known that you should declare events that take as parameters <code>(object sender, EventArgs args)</code>. Why?</p>
|
[
{
"answer_id": 105519,
"author": "fryguybob",
"author_id": 4592,
"author_profile": "https://Stackoverflow.com/users/4592",
"pm_score": 2,
"selected": false,
"text": "(sender, e)"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11236/"
] |
104,725
|
<p>Joel Spolsky <a href="http://www.joelonsoftware.com/articles/PleaseLinker.html" rel="noreferrer">praised</a> native-code versions of programs that have no dependencies on runtimes. </p>
<p>What native-code compilers are available for functional languages?</p>
|
[
{
"answer_id": 104956,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 3,
"selected": false,
"text": "ocamlc ocamlopt GCL"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17569/"
] |
104,747
|
<p>I have a members table in MySQL</p>
<pre><code>CREATE TABLE `members` (
`id` int(10) unsigned NOT NULL auto_increment,
`name` varchar(65) collate utf8_unicode_ci NOT NULL,
`order` tinyint(3) unsigned NOT NULL default '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
</code></pre>
<p>And I would like to let users order the members how they like.
I'm storing the order in <code>order</code> column.</p>
<p>I'm wondering how to insert new user to be added to the bottom of the list.
This is what I have today:</p>
<pre><code>$db->query('insert into members VALUES (0, "new member", 0)');
$lastId = $db->lastInsertId();
$maxOrder = $db->fetchAll('select MAX(`order`) max_order FROM members');
$db->query('update members
SET
`order` = ?
WHERE
id = ?',
array(
$maxOrder[0]['max_order'] + 1,
$lastId
));
</code></pre>
<p>But that's not really precise while when there are several users adding new members at the same time, it might happen the <code>MAX(order)</code> will return the same values.</p>
<p>How do you handle such cases?</p>
|
[
{
"answer_id": 104961,
"author": "Harrison Fisk",
"author_id": 16111,
"author_profile": "https://Stackoverflow.com/users/16111",
"pm_score": 3,
"selected": true,
"text": "order"
},
{
"answer_id": 105217,
"author": "user10340",
"author_id": 10340,
"author_profile": "https://Stackoverflow.com/users/10340",
"pm_score": 0,
"selected": false,
"text": "+-----------+--------------+\n| member_id | name |\n+-----------+--------------+\n| 1 | John Smith |\n| 2 | John Doe |\n| 3 | John Johnson |\n| 4 | Sue Someone |\n+-----------+--------------+\n +---------------+----------+-----------------+\n| member_id_key | position | member_id_value |\n+---------------+----------+-----------------+\n| 1 | 1 | 4 |\n| 1 | 2 | 1 |\n| 1 | 3 | 3 |\n| 1 | 4 | 2 |\n| 2 | 2 | 1 |\n| 2 | 3 | 2 |\n+---------------+----------+-----------------+\n SELECT name\nFROM members inner join orderings \n ON members.member_id = orderings.member_id_value\nWHERE orderings.member_id_key = <ID for member you want to lookup>\nORDER BY position;\n +--------------+\n| name |\n+--------------+\n| Sue Someone |\n| John Smith |\n| John Johnson |\n| John Doe |\n+--------------+\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19217/"
] |
104,764
|
<p>Are there any prebuilt modules for this? Is there an event thats called everytime a page is loaded? I'm just trying to secure one of my more important admin sections.</p>
|
[
{
"answer_id": 104839,
"author": "AaronS",
"author_id": 26932,
"author_profile": "https://Stackoverflow.com/users/26932",
"pm_score": 0,
"selected": false,
"text": " Request.ServerVariables[\"REMOTE_ADDR\"]\n"
},
{
"answer_id": 105373,
"author": "Chris Cudmore",
"author_id": 18907,
"author_profile": "https://Stackoverflow.com/users/18907",
"pm_score": 0,
"selected": false,
"text": "Page_Load .Net .Net WebForms"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8456/"
] |
104,791
|
<p>The SQL-LDR documentation states that you need to do a convetional Path Load:</p>
<blockquote>
<p>When you want to apply SQL functions
to data fields. SQL functions are not
available during a direct path load</p>
</blockquote>
<p>I have TimeStamp data stored in a CSV file that I'm loading with SQL-LDR by describing the fields as such:</p>
<pre><code>STARTTIME "To_TimeStamp(:STARTTIME,'YYYY-MM-DD HH24:MI:SS.FF6')",
COMPLETIONTIME "To_TimeStamp(:COMPLETIONTIME,'YYYY-MM-DD HH24:MI:SS.FF6')"
</code></pre>
<p>So my question is: Can you load timestamp data without a function, or is it the case that you can not do a Direct Path Load when Loading TimeStamp data?</p>
|
[
{
"answer_id": 104839,
"author": "AaronS",
"author_id": 26932,
"author_profile": "https://Stackoverflow.com/users/26932",
"pm_score": 0,
"selected": false,
"text": " Request.ServerVariables[\"REMOTE_ADDR\"]\n"
},
{
"answer_id": 105373,
"author": "Chris Cudmore",
"author_id": 18907,
"author_profile": "https://Stackoverflow.com/users/18907",
"pm_score": 0,
"selected": false,
"text": "Page_Load .Net .Net WebForms"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9940/"
] |
104,797
|
<p>What is the best way to create a webservice for accepting an image.
The image might be quite big and I do not want to change the default receive size for the web application.
I have written one that accepts a binary image but that I feel that there has to be a better alternative.</p>
|
[
{
"answer_id": 104902,
"author": "core",
"author_id": 11574,
"author_profile": "https://Stackoverflow.com/users/11574",
"pm_score": 3,
"selected": true,
"text": "using System.Drawing;\nusing System.IO;\nusing System.Net;\nusing System.Net.Sockets;\n\n[OperationContract]\npublic void FetchImage(Uri url)\n{\n // Validate url\n\n if (url == null)\n {\n throw new ArgumentNullException(url);\n }\n\n // If the service doesn't know how to resolve relative URI paths\n\n /*if (!uri.IsAbsoluteUri)\n {\n throw new ArgumentException(\"Must be absolute.\", url);\n }*/\n\n // Download and load the image\n\n Image image = new Func<Bitmap>(() =>\n {\n try\n {\n using (WebClient downloader = new WebClient())\n {\n return new Bitmap(downloader.OpenRead(url));\n }\n }\n catch (ArgumentException exception)\n {\n throw new ResourceNotImageException(url, exception);\n }\n catch (WebException exception)\n {\n throw new ImageDownloadFailedException(url, exception);\n }\n\n // IOException and SocketException are not wrapped by WebException :( \n\n catch (IOException exception)\n {\n throw new ImageDownloadFailedException(url, exception);\n }\n catch (SocketException exception)\n {\n throw new ImageDownloadFailedException(url, exception);\n }\n })();\n\n // Do something with image\n\n}\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/403/"
] |
104,799
|
<p>Why isn't <a href="http://java.sun.com/javase/6/docs/api/java/util/Collection.html#remove(java.lang.Object)" rel="noreferrer">Collection.remove(Object o)</a> generic? </p>
<p>Seems like <code>Collection<E></code> could have <code>boolean remove(E o);</code> </p>
<p>Then, when you accidentally try to remove (for example) <code>Set<String></code> instead of each individual String from a <code>Collection<String></code>, it would be a compile time error instead of a debugging problem later.</p>
|
[
{
"answer_id": 104943,
"author": "noah",
"author_id": 12034,
"author_profile": "https://Stackoverflow.com/users/12034",
"pm_score": -1,
"selected": false,
"text": "Set stringSet = new HashSet();\n// do some stuff...\nObject o = \"foobar\";\nstringSet.remove(o);\n"
},
{
"answer_id": 105812,
"author": "dmeister",
"author_id": 4194,
"author_profile": "https://Stackoverflow.com/users/4194",
"pm_score": 7,
"selected": true,
"text": "List Number List Long"
},
{
"answer_id": 483016,
"author": "Hosam Aly",
"author_id": 41283,
"author_profile": "https://Stackoverflow.com/users/41283",
"pm_score": 3,
"selected": false,
"text": "Object class Person {\n public String name;\n // override equals()\n}\nclass Employee extends Person {\n public String company;\n // override equals()\n}\nclass Developer extends Employee {\n public int yearsOfExperience;\n // override equals()\n}\n\nclass Test {\n public static void main(String[] args) {\n Collection<? extends Person> people = new ArrayList<Employee>();\n // ...\n\n // to remove the first employee with a specific name:\n people.remove(new Person(someName1));\n\n // to remove the first developer that matches some criteria:\n people.remove(new Developer(someName2, someCompany, 10));\n\n // to remove the first employee who is either\n // a developer or an employee of someCompany:\n people.remove(new Object() {\n public boolean equals(Object employee) {\n return employee instanceof Developer\n || ((Employee) employee).company.equals(someCompany);\n }});\n }\n}\n remove equals"
},
{
"answer_id": 815470,
"author": "newacct",
"author_id": 86989,
"author_profile": "https://Stackoverflow.com/users/86989",
"pm_score": 6,
"selected": false,
"text": "remove() Map Collection remove() remove() remove() remove(o) e (o==null ? e==null : o.equals(e)) true o e equals() Object equals() List.equals() List Map<ArrayList, Something> remove() LinkedList remove()"
},
{
"answer_id": 10790275,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 3,
"selected": false,
"text": "Cat Animal Cat SiameseCat Dog Cat SiameseCat Animal Cat Cat"
},
{
"answer_id": 33939894,
"author": "Patrick",
"author_id": 2485599,
"author_profile": "https://Stackoverflow.com/users/2485599",
"pm_score": -1,
"selected": false,
"text": "public interface A {}\n\npublic interface B {}\n\npublic class MyClass implements A, B {}\n\npublic static void main(String[] args) {\n Collection<A> collection = new ArrayList<>();\n MyClass item = new MyClass();\n collection.add(item); // works fine\n B b = item; // valid\n collection.remove(b); /* It works because the remove method accepts an Object. If it was generic, this would not work */\n}\n"
},
{
"answer_id": 57178370,
"author": "Stefan Feuerhahn",
"author_id": 1235217,
"author_profile": "https://Stackoverflow.com/users/1235217",
"pm_score": 1,
"selected": false,
"text": "remove(Object o) remove(E e)"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104799",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15816/"
] |
104,803
|
<p>I've got a (mostly) working plugin developed, but since its function is directly related to the project it processes, how do you develop unit and integration tests for the plugin. The best idea I've had is to create an integration test project for the plugin that uses the plugin during its lifecycle and has tests that report on the plugins success or failure in processing the data.</p>
<p>Anyone with better ideas?</p>
|
[
{
"answer_id": 105259,
"author": "Brian Matthews",
"author_id": 1969,
"author_profile": "https://Stackoverflow.com/users/1969",
"pm_score": 4,
"selected": true,
"text": "src/test/resources"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17008/"
] |
104,837
|
<p>I'd like to have some rails apps over different servers sharing the same session. I can do it within the same server but don't know if it is possible to share over different servers. Anyone already did or knows how to do it?</p>
<p>Thanks</p>
|
[
{
"answer_id": 105001,
"author": "webmat",
"author_id": 6349,
"author_profile": "https://Stackoverflow.com/users/6349",
"pm_score": 3,
"selected": false,
"text": "rake db:sessions:create\n config.action_controller.session_store = :active_record_store\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19224/"
] |
104,844
|
<p>I'm looking for a way to find the name of the Windows default printer using unmanaged C++ (found plenty of .NET examples, but no success unmanaged). Thanks.</p>
|
[
{
"answer_id": 104882,
"author": "Doug T.",
"author_id": 8123,
"author_profile": "https://Stackoverflow.com/users/8123",
"pm_score": 3,
"selected": true,
"text": "char szPrinterName[255];\nunsigned long lPrinterNameLength;\nGetDefaultPrinter( szPrinterName, &lPrinterNameLength );\nHDC hPrinterDC;\nhPrinterDC = CreateDC(\"WINSPOOL\\0\", szPrinterName, NULL, NULL);\n"
},
{
"answer_id": 104910,
"author": "KPexEA",
"author_id": 13676,
"author_profile": "https://Stackoverflow.com/users/13676",
"pm_score": 2,
"selected": false,
"text": "DWORD numprinters;\nDWORD defprinter=0;\nDWORD dwSizeNeeded=0;\nDWORD dwItem;\nLPPRINTER_INFO_2 printerinfo = NULL;\n\n// Get buffer size\n\nEnumPrinters ( PRINTER_ENUM_LOCAL | PRINTER_ENUM_CONNECTIONS , NULL, 2, NULL, 0, &dwSizeNeeded, &numprinters );\n\n// allocate memory\n//printerinfo = (LPPRINTER_INFO_2)HeapAlloc ( GetProcessHeap (), HEAP_ZERO_MEMORY, dwSizeNeeded );\nprinterinfo = (LPPRINTER_INFO_2)new char[dwSizeNeeded];\n\nif ( EnumPrinters ( PRINTER_ENUM_LOCAL | PRINTER_ENUM_CONNECTIONS, // what to enumerate\n NULL, // printer name (NULL for all)\n 2, // level\n (LPBYTE)printerinfo, // buffer\n dwSizeNeeded, // size of buffer\n &dwSizeNeeded, // returns size\n &numprinters // return num. items\n ) == 0 )\n{\n numprinters=0;\n}\n\n{\n DWORD size=0; \n\n // Get the size of the default printer name.\n GetDefaultPrinter(NULL, &size);\n if(size)\n {\n // Allocate a buffer large enough to hold the printer name.\n TCHAR* buffer = new TCHAR[size];\n\n // Get the printer name.\n GetDefaultPrinter(buffer, &size);\n\n for ( dwItem = 0; dwItem < numprinters; dwItem++ )\n {\n if(!strcmp(buffer,printerinfo[dwItem].pPrinterName))\n defprinter=dwItem;\n }\n delete buffer;\n }\n}\n"
},
{
"answer_id": 104930,
"author": "jeffm",
"author_id": 1544,
"author_profile": "https://Stackoverflow.com/users/1544",
"pm_score": 2,
"selected": false,
"text": "// You are explicitly linking to GetDefaultPrinter because linking \n// implicitly on Windows 95/98 or NT4 results in a runtime error.\n// This block specifies which text version you explicitly link to.\n#ifdef UNICODE\n #define GETDEFAULTPRINTER \"GetDefaultPrinterW\"\n#else\n #define GETDEFAULTPRINTER \"GetDefaultPrinterA\"\n#endif\n\n// Size of internal buffer used to hold \"printername,drivername,portname\"\n// string. You may have to increase this for huge strings.\n#define MAXBUFFERSIZE 250\n\n/*----------------------------------------------------------------*/ \n/* DPGetDefaultPrinter */ \n/* */ \n/* Parameters: */ \n/* pPrinterName: Buffer alloc'd by caller to hold printer name. */ \n/* pdwBufferSize: On input, ptr to size of pPrinterName. */ \n/* On output, min required size of pPrinterName. */ \n/* */ \n/* NOTE: You must include enough space for the NULL terminator! */ \n/* */ \n/* Returns: TRUE for success, FALSE for failure. */ \n/*----------------------------------------------------------------*/ \nBOOL DPGetDefaultPrinter(LPTSTR pPrinterName, LPDWORD pdwBufferSize)\n{\n BOOL bFlag;\n OSVERSIONINFO osv;\n TCHAR cBuffer[MAXBUFFERSIZE];\n PRINTER_INFO_2 *ppi2 = NULL;\n DWORD dwNeeded = 0;\n DWORD dwReturned = 0;\n HMODULE hWinSpool = NULL;\n PROC fnGetDefaultPrinter = NULL;\n\n // What version of Windows are you running?\n osv.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);\n GetVersionEx(&osv);\n\n // If Windows 95 or 98, use EnumPrinters.\n if (osv.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)\n {\n // The first EnumPrinters() tells you how big our buffer must\n // be to hold ALL of PRINTER_INFO_2. Note that this will\n // typically return FALSE. This only means that the buffer (the 4th\n // parameter) was not filled in. You do not want it filled in here.\n SetLastError(0);\n bFlag = EnumPrinters(PRINTER_ENUM_DEFAULT, NULL, 2, NULL, 0, &dwNeeded, &dwReturned);\n {\n if ((GetLastError() != ERROR_INSUFFICIENT_BUFFER) || (dwNeeded == 0))\n return FALSE;\n }\n\n // Allocate enough space for PRINTER_INFO_2.\n ppi2 = (PRINTER_INFO_2 *)GlobalAlloc(GPTR, dwNeeded);\n if (!ppi2)\n return FALSE;\n\n // The second EnumPrinters() will fill in all the current information.\n bFlag = EnumPrinters(PRINTER_ENUM_DEFAULT, NULL, 2, (LPBYTE)ppi2, dwNeeded, &dwNeeded, &dwReturned);\n if (!bFlag)\n {\n GlobalFree(ppi2);\n return FALSE;\n }\n\n // If specified buffer is too small, set required size and fail.\n if ((DWORD)lstrlen(ppi2->pPrinterName) >= *pdwBufferSize)\n {\n *pdwBufferSize = (DWORD)lstrlen(ppi2->pPrinterName) + 1;\n GlobalFree(ppi2);\n return FALSE;\n }\n\n // Copy printer name into passed-in buffer.\n lstrcpy(pPrinterName, ppi2->pPrinterName);\n\n // Set buffer size parameter to minimum required buffer size.\n *pdwBufferSize = (DWORD)lstrlen(ppi2->pPrinterName) + 1;\n }\n\n // If Windows NT, use the GetDefaultPrinter API for Windows 2000,\n // or GetProfileString for version 4.0 and earlier.\n else if (osv.dwPlatformId == VER_PLATFORM_WIN32_NT)\n {\n if (osv.dwMajorVersion >= 5) // Windows 2000 or later (use explicit call)\n {\n hWinSpool = LoadLibrary(\"winspool.drv\");\n if (!hWinSpool)\n return FALSE;\n fnGetDefaultPrinter = GetProcAddress(hWinSpool, GETDEFAULTPRINTER);\n if (!fnGetDefaultPrinter)\n {\n FreeLibrary(hWinSpool);\n return FALSE;\n }\n\n bFlag = fnGetDefaultPrinter(pPrinterName, pdwBufferSize);\n FreeLibrary(hWinSpool);\n if (!bFlag)\n return FALSE;\n }\n\n else // NT4.0 or earlier\n {\n // Retrieve the default string from Win.ini (the registry).\n // String will be in form \"printername,drivername,portname\".\n if (GetProfileString(\"windows\", \"device\", \",,,\", cBuffer, MAXBUFFERSIZE) <= 0)\n return FALSE;\n\n // Printer name precedes first \",\" character.\n strtok(cBuffer, \",\");\n\n // If specified buffer is too small, set required size and fail.\n if ((DWORD)lstrlen(cBuffer) >= *pdwBufferSize)\n {\n *pdwBufferSize = (DWORD)lstrlen(cBuffer) + 1;\n return FALSE;\n }\n\n // Copy printer name into passed-in buffer.\n lstrcpy(pPrinterName, cBuffer);\n\n // Set buffer size parameter to minimum required buffer size.\n *pdwBufferSize = (DWORD)lstrlen(cBuffer) + 1;\n }\n }\n\n // Clean up.\n if (ppi2)\n GlobalFree(ppi2);\n\n return TRUE;\n}\n#undef MAXBUFFERSIZE\n#undef GETDEFAULTPRINTER\n\n\n// You are explicitly linking to SetDefaultPrinter because implicitly\n// linking on Windows 95/98 or NT4 results in a runtime error.\n// This block specifies which text version you explicitly link to.\n#ifdef UNICODE\n #define SETDEFAULTPRINTER \"SetDefaultPrinterW\"\n#else\n #define SETDEFAULTPRINTER \"SetDefaultPrinterA\"\n#endif\n\n/*-----------------------------------------------------------------*/ \n/* DPSetDefaultPrinter */ \n/* */ \n/* Parameters: */ \n/* pPrinterName: Valid name of existing printer to make default. */ \n/* */ \n/* Returns: TRUE for success, FALSE for failure. */ \n/*-----------------------------------------------------------------*/ \nBOOL DPSetDefaultPrinter(LPTSTR pPrinterName)\n\n{\n BOOL bFlag;\n OSVERSIONINFO osv;\n DWORD dwNeeded = 0;\n HANDLE hPrinter = NULL;\n PRINTER_INFO_2 *ppi2 = NULL;\n LPTSTR pBuffer = NULL;\n LONG lResult;\n HMODULE hWinSpool = NULL;\n PROC fnSetDefaultPrinter = NULL;\n\n // What version of Windows are you running?\n osv.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);\n GetVersionEx(&osv);\n\n if (!pPrinterName)\n return FALSE;\n\n // If Windows 95 or 98, use SetPrinter.\n if (osv.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)\n {\n // Open this printer so you can get information about it.\n bFlag = OpenPrinter(pPrinterName, &hPrinter, NULL);\n if (!bFlag || !hPrinter)\n return FALSE;\n\n // The first GetPrinter() tells you how big our buffer must\n // be to hold ALL of PRINTER_INFO_2. Note that this will\n // typically return FALSE. This only means that the buffer (the 3rd\n // parameter) was not filled in. You do not want it filled in here.\n SetLastError(0);\n bFlag = GetPrinter(hPrinter, 2, 0, 0, &dwNeeded);\n if (!bFlag)\n {\n if ((GetLastError() != ERROR_INSUFFICIENT_BUFFER) || (dwNeeded == 0))\n {\n ClosePrinter(hPrinter);\n return FALSE;\n }\n }\n\n // Allocate enough space for PRINTER_INFO_2.\n ppi2 = (PRINTER_INFO_2 *)GlobalAlloc(GPTR, dwNeeded);\n if (!ppi2)\n {\n ClosePrinter(hPrinter);\n return FALSE;\n }\n\n // The second GetPrinter() will fill in all the current information\n // so that all you have to do is modify what you are interested in.\n bFlag = GetPrinter(hPrinter, 2, (LPBYTE)ppi2, dwNeeded, &dwNeeded);\n if (!bFlag)\n {\n ClosePrinter(hPrinter);\n GlobalFree(ppi2);\n return FALSE;\n }\n\n // Set default printer attribute for this printer.\n ppi2->Attributes |= PRINTER_ATTRIBUTE_DEFAULT;\n bFlag = SetPrinter(hPrinter, 2, (LPBYTE)ppi2, 0);\n if (!bFlag)\n {\n ClosePrinter(hPrinter);\n GlobalFree(ppi2);\n return FALSE;\n }\n\n // Tell all open programs that this change occurred. \n // Allow each program 1 second to handle this message.\n lResult = SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0L,\n (LPARAM)(LPCTSTR)\"windows\", SMTO_NORMAL, 1000, NULL);\n }\n\n // If Windows NT, use the SetDefaultPrinter API for Windows 2000,\n // or WriteProfileString for version 4.0 and earlier.\n else if (osv.dwPlatformId == VER_PLATFORM_WIN32_NT)\n {\n if (osv.dwMajorVersion >= 5) // Windows 2000 or later (use explicit call)\n {\n hWinSpool = LoadLibrary(\"winspool.drv\");\n if (!hWinSpool)\n return FALSE;\n fnSetDefaultPrinter = GetProcAddress(hWinSpool, SETDEFAULTPRINTER);\n if (!fnSetDefaultPrinter)\n {\n FreeLibrary(hWinSpool);\n return FALSE;\n }\n\n bFlag = fnSetDefaultPrinter(pPrinterName);\n FreeLibrary(hWinSpool);\n if (!bFlag)\n return FALSE;\n }\n\n else // NT4.0 or earlier\n {\n // Open this printer so you can get information about it.\n bFlag = OpenPrinter(pPrinterName, &hPrinter, NULL);\n if (!bFlag || !hPrinter)\n return FALSE;\n\n // The first GetPrinter() tells you how big our buffer must\n // be to hold ALL of PRINTER_INFO_2. Note that this will\n // typically return FALSE. This only means that the buffer (the 3rd\n // parameter) was not filled in. You do not want it filled in here.\n SetLastError(0);\n bFlag = GetPrinter(hPrinter, 2, 0, 0, &dwNeeded);\n if (!bFlag)\n {\n if ((GetLastError() != ERROR_INSUFFICIENT_BUFFER) || (dwNeeded == 0))\n {\n ClosePrinter(hPrinter);\n return FALSE;\n }\n }\n\n // Allocate enough space for PRINTER_INFO_2.\n ppi2 = (PRINTER_INFO_2 *)GlobalAlloc(GPTR, dwNeeded);\n if (!ppi2)\n {\n ClosePrinter(hPrinter);\n return FALSE;\n }\n\n // The second GetPrinter() fills in all the current<BR/>\n // information.\n bFlag = GetPrinter(hPrinter, 2, (LPBYTE)ppi2, dwNeeded, &dwNeeded);\n if ((!bFlag) || (!ppi2->pDriverName) || (!ppi2->pPortName))\n {\n ClosePrinter(hPrinter);\n GlobalFree(ppi2);\n return FALSE;\n }\n\n // Allocate buffer big enough for concatenated string.\n // String will be in form \"printername,drivername,portname\".\n pBuffer = (LPTSTR)GlobalAlloc(GPTR,\n lstrlen(pPrinterName) +\n lstrlen(ppi2->pDriverName) +\n lstrlen(ppi2->pPortName) + 3);\n if (!pBuffer)\n {\n ClosePrinter(hPrinter);\n GlobalFree(ppi2);\n return FALSE;\n }\n\n // Build string in form \"printername,drivername,portname\".\n lstrcpy(pBuffer, pPrinterName); lstrcat(pBuffer, \",\");\n lstrcat(pBuffer, ppi2->pDriverName); lstrcat(pBuffer, \",\");\n lstrcat(pBuffer, ppi2->pPortName);\n\n // Set the default printer in Win.ini and registry.\n bFlag = WriteProfileString(\"windows\", \"device\", pBuffer);\n if (!bFlag)\n {\n ClosePrinter(hPrinter);\n GlobalFree(ppi2);\n GlobalFree(pBuffer);\n return FALSE;\n }\n }\n\n // Tell all open programs that this change occurred. \n // Allow each app 1 second to handle this message.\n lResult = SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0L, 0L,\n SMTO_NORMAL, 1000, NULL);\n }\n\n // Clean up.\n if (hPrinter)\n ClosePrinter(hPrinter);\n if (ppi2)\n GlobalFree(ppi2);\n if (pBuffer)\n GlobalFree(pBuffer);\n\n return TRUE;\n}\n#undef SETDEFAULTPRINTER\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8117/"
] |
104,850
|
<p>I want to try to convert a string to a Guid, but I don't want to rely on catching exceptions (</p>
<ul>
<li>for performance reasons - exceptions are expensive</li>
<li>for usability reasons - the debugger pops up </li>
<li>for design reasons - the expected is not exceptional</li>
</ul>
<p>In other words the code:</p>
<pre><code>public static Boolean TryStrToGuid(String s, out Guid value)
{
try
{
value = new Guid(s);
return true;
}
catch (FormatException)
{
value = Guid.Empty;
return false;
}
}
</code></pre>
<p>is not suitable.</p>
<p>I would try using RegEx, but since the guid can be parenthesis wrapped, brace wrapped, none wrapped, makes it hard. </p>
<p>Additionally, I thought certain Guid values are invalid(?)</p>
<hr>
<p><strong>Update 1</strong></p>
<p><a href="https://stackoverflow.com/questions/104850/c-test-if-string-is-a-guid-without-throwing-exceptions#137829">ChristianK</a> had a good idea to catch only <code>FormatException</code>, rather than all. Changed the question's code sample to include suggestion.</p>
<hr>
<p><strong>Update 2</strong></p>
<p>Why worry about thrown exceptions? Am I really expecting invalid GUIDs all that often? </p>
<p>The answer is <em>yes</em>. That is why I am using TryStrToGuid - I <strong>am</strong> expecting bad data.</p>
<p><strong>Example 1</strong> <a href="http://msdn.microsoft.com/en-us/library/cc144096(VS.85).aspx" rel="noreferrer">Namespace extensions can be specified by appending a GUID to a folder name</a>. I might be parsing folder names, checking to see if the text after the final <strong>.</strong> is a GUID.</p>
<pre><code>c:\Program Files
c:\Program Files.old
c:\Users
c:\Users.old
c:\UserManager.{CE7F5AA5-6832-43FE-BAE1-80D14CD8F666}
c:\Windows
c:\Windows.old
</code></pre>
<p><strong>Example 2</strong> I might be running a heavily used web-server wants to check the validity of some posted back data. I don't want invalid data tying up resources 2-3 orders of magnitude higher than it needs to be.</p>
<p><strong>Example 3</strong> I might be parsing a search expression entered by a user. </p>
<p><img src="https://i.stack.imgur.com/Ghb12.png" alt="enter image description here"></p>
<p>If they enter GUID's I want to process them specially (such as specifically searching for that object, or highlight and format that specific search term in the response text.)</p>
<hr>
<p><strong>Update 3 - Performance benchmarks</strong></p>
<p>Test converting 10,000 good Guids, and 10,000 bad Guids.</p>
<pre><code>Catch FormatException:
10,000 good: 63,668 ticks
10,000 bad: 6,435,609 ticks
Regex Pre-Screen with try-catch:
10,000 good: 637,633 ticks
10,000 bad: 717,894 ticks
COM Interop CLSIDFromString
10,000 good: 126,120 ticks
10,000 bad: 23,134 ticks
</code></pre>
<p><em>p.s. I shouldn't have to justify a question.</em></p>
|
[
{
"answer_id": 104932,
"author": "pdavis",
"author_id": 7819,
"author_profile": "https://Stackoverflow.com/users/7819",
"pm_score": 3,
"selected": false,
"text": "^[A-Fa-f0-9]{32}$|^({|\\\\()?[A-Fa-f0-9]{8}-([A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}(}|\\\\))?$|^({)?[0xA-Fa-f0-9]{3,10}(, {0,1}[0xA-Fa-f0-9]{3,6}){2}, {0,1}({)([0xA-Fa-f0-9]{3,4}, {0,1}){7}[0xA-Fa-f0-9]{3,4}(}})$\n"
},
{
"answer_id": 104962,
"author": "rupello",
"author_id": 635,
"author_profile": "https://Stackoverflow.com/users/635",
"pm_score": 1,
"selected": false,
"text": " bool IsProbablyGuid(string s)\n {\n int hexchars = 0;\n foreach(character c in string s)\n {\n if(IsValidHexChar(c)) \n hexchars++; \n }\n return hexchars==32;\n }\n"
},
{
"answer_id": 104972,
"author": "Josef",
"author_id": 5581,
"author_profile": "https://Stackoverflow.com/users/5581",
"pm_score": 3,
"selected": false,
"text": "TRY-CATCH CATCH using System.Text.RegularExpressions;\n\n\n /// <summary>\n /// Validate that a string is a valid GUID\n /// </summary>\n /// <param name=\"GUIDCheck\"></param>\n /// <returns></returns>\n private bool IsValidGUID(string GUIDCheck)\n {\n if (!string.IsNullOrEmpty(GUIDCheck))\n {\n return new Regex(@\"^(\\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\\}{0,1})$\").IsMatch(GUIDCheck);\n }\n return false;\n }\n"
},
{
"answer_id": 137829,
"author": "Christian.K",
"author_id": 21567,
"author_profile": "https://Stackoverflow.com/users/21567",
"pm_score": 5,
"selected": false,
"text": "try\n{\n value = new Guid(s);\n return true;\n}\ncatch (FormatException)\n{\n value = Guid.Empty;\n return false;\n}\n Guid.TryParse Guid.TryParseExact"
},
{
"answer_id": 287877,
"author": "Ian Boyd",
"author_id": 12597,
"author_profile": "https://Stackoverflow.com/users/12597",
"pm_score": 8,
"selected": true,
"text": "Catch exception:\n 10,000 good: 63,668 ticks\n 10,000 bad: 6,435,609 ticks\n\nRegex Pre-Screen:\n 10,000 good: 637,633 ticks\n 10,000 bad: 717,894 ticks\n\nCOM Interop CLSIDFromString\n 10,000 good: 126,120 ticks\n 10,000 bad: 23,134 ticks\n /// <summary>\n/// Attempts to convert a string to a guid.\n/// </summary>\n/// <param name=\"s\">The string to try to convert</param>\n/// <param name=\"value\">Upon return will contain the Guid</param>\n/// <returns>Returns true if successful, otherwise false</returns>\npublic static Boolean TryStrToGuid(String s, out Guid value)\n{\n //ClsidFromString returns the empty guid for null strings \n if ((s == null) || (s == \"\")) \n { \n value = Guid.Empty; \n return false; \n }\n\n int hresult = PInvoke.ObjBase.CLSIDFromString(s, out value);\n if (hresult >= 0)\n {\n return true;\n }\n else\n {\n value = Guid.Empty;\n return false;\n }\n}\n\n\nnamespace PInvoke\n{\n class ObjBase\n {\n /// <summary>\n /// This function converts a string generated by the StringFromCLSID function back into the original class identifier.\n /// </summary>\n /// <param name=\"sz\">String that represents the class identifier</param>\n /// <param name=\"clsid\">On return will contain the class identifier</param>\n /// <returns>\n /// Positive or zero if class identifier was obtained successfully\n /// Negative if the call failed\n /// </returns>\n [DllImport(\"ole32.dll\", CharSet = CharSet.Unicode, ExactSpelling = true, PreserveSig = true)]\n public static extern int CLSIDFromString(string sz, out Guid clsid);\n }\n}\n new Guid(someString);\n"
},
{
"answer_id": 290730,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 4,
"selected": false,
"text": "Exception: 26ms\nInterop: 1,201ms\n Exception: 1,150ms\n Interop: 1,201ms\n"
},
{
"answer_id": 1185400,
"author": "JBrooks",
"author_id": 136059,
"author_profile": "https://Stackoverflow.com/users/136059",
"pm_score": 3,
"selected": false,
"text": "public static Boolean TryStrToGuid(String s, out Guid value)\n{\n\n // this is before the overhead of setting up the try/catch block.\n if(value == null || value.Length != 36)\n { \n value = Guid.Empty;\n return false;\n }\n\n try\n {\n value = new Guid(s);\n return true;\n }\n catch (FormatException)\n {\n value = Guid.Empty;\n return false;\n }\n}\n"
},
{
"answer_id": 1305659,
"author": "Stefan Steiger",
"author_id": 155077,
"author_profile": "https://Stackoverflow.com/users/155077",
"pm_score": 0,
"selected": false,
"text": "Private Function IsGuidWithOptionalBraces(ByRef strValue As String) As Boolean\n If String.IsNullOrEmpty(strValue) Then\n Return False\n End If\n\n Return System.Text.RegularExpressions.Regex.IsMatch(strValue, \"^[\\{]?[0-9a-fA-F]{8}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{12}[\\}]?$\", System.Text.RegularExpressions.RegexOptions.IgnoreCase)\nEnd Function\n\n\nPrivate Function IsGuidWithoutBraces(ByRef strValue As String) As Boolean\n If String.IsNullOrEmpty(strValue) Then\n Return False\n End If\n\n Return System.Text.RegularExpressions.Regex.IsMatch(strValue, \"^[0-9a-fA-F]{8}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{12}$\", System.Text.RegularExpressions.RegexOptions.IgnoreCase)\nEnd Function\n\n\nPrivate Function IsGuidWithBraces(ByRef strValue As String) As Boolean\n If String.IsNullOrEmpty(strValue) Then\n Return False\n End If\n\n Return System.Text.RegularExpressions.Regex.IsMatch(strValue, \"^\\{[0-9a-fA-F]{8}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{12}\\}$\", System.Text.RegularExpressions.RegexOptions.IgnoreCase)\nEnd Function\n"
},
{
"answer_id": 1983992,
"author": "No Refunds No Returns",
"author_id": 210754,
"author_profile": "https://Stackoverflow.com/users/210754",
"pm_score": 7,
"selected": false,
"text": "Guid.TryParse()"
},
{
"answer_id": 6533282,
"author": "zhilia",
"author_id": 822813,
"author_profile": "https://Stackoverflow.com/users/822813",
"pm_score": 6,
"selected": false,
"text": "public static bool IsValidGuid(string str)\n{\n Guid guid;\n return Guid.TryParse(str, out guid);\n}\n"
},
{
"answer_id": 45224630,
"author": "Mike",
"author_id": 649766,
"author_profile": "https://Stackoverflow.com/users/649766",
"pm_score": 0,
"selected": false,
"text": "public static bool IsGUID(this string text)\n{\n return Guid.TryParse(text, out Guid guid);\n}\n"
},
{
"answer_id": 69887837,
"author": "rajquest",
"author_id": 1834631,
"author_profile": "https://Stackoverflow.com/users/1834631",
"pm_score": 0,
"selected": false,
"text": " /// <summary>\n /// Gets the GUID from string.\n /// </summary>\n /// <param name=\"guid\">The GUID.</param>\n /// <returns></returns>\n public static Guid GetGuidFromString(string guid)\n {\n try\n {\n if (Guid.TryParse(guid, out Guid value))\n {\n return value;\n }\n else\n {\n return Guid.Empty;\n }\n }\n catch (Exception)\n {\n return Guid.Empty;\n }\n }\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12597/"
] |
104,854
|
<p>When I start Tomcat (6.0.18) from Eclipse (3.4), I receive this message (first in the log):</p>
<blockquote>
<p>WARNING:
[SetPropertiesRule]{Server/Service/Engine/Host/Context}
Setting property 'source' to
'org.eclipse.jst.jee.server: (project name)'
did not find a matching property.</p>
</blockquote>
<p>Seems this message does not have any severe impact, however, does anyone know how to get rid of it?</p>
|
[
{
"answer_id": 355378,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<wb-resource deploy-path=\"/WEB-INF/classes\" source-path=\"/src/main/resources\"/>\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17585/"
] |
104,866
|
<p>Looking for C# class which wraps calls to do the following:</p>
<p>read and write a key value
read & write a key entry</p>
<p>enumerate the entries in a key. This is important. For example, need to list all entries in:
HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI\ODBC Data Sources</p>
<p>(I scanned through some codeproject.com registry classes and they didn't enumerate)</p>
|
[
{
"answer_id": 104912,
"author": "Clinton Pierce",
"author_id": 8173,
"author_profile": "https://Stackoverflow.com/users/8173",
"pm_score": 2,
"selected": false,
"text": " Registry.CurrentUser.OpenSubKey()\n Registry.CurrentUser.CreateSubKey()\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5232/"
] |
104,872
|
<p>I'm working on a <code>PHP</code> application that links into the <code>Protx VSP Direct payment gateway</code>. To handle "3D Secure" requests from the credit card processing company, I need to forward the user to a different website, mimicking a form that has been posted. I'm trying to use the <code>cURL</code> libraries, but seem to have hit a problem. My code is the following: </p>
<pre><code><?php
$ch = curl_init();
// Set the URL
curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/');
// Perform a POST
curl_setopt($ch, CURLOPT_POST, 1);
// If not set, curl prints output to the browser
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
// Set the "form fields"
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$output = curl_exec($ch);
curl_close($ch);
?>
</code></pre>
<p>All this does is grab the content of the URL passed through, and doesn't forward the user anywhere. I've tried Googling and reading up as much as I can, but can't figure out what i'm missing. Any ideas? I don't want to have to create a HTML form that auto-submits itself if I can avoid it.</p>
<p>Thanks for any help :-)</p>
|
[
{
"answer_id": 104887,
"author": "neu242",
"author_id": 13365,
"author_profile": "https://Stackoverflow.com/users/13365",
"pm_score": 3,
"selected": true,
"text": "<html> \n <head> \n <title>Processing your request...</title> \n </head> \n <body OnLoad=\"OnLoadEvent();\"> \n <form name=\"downloadForm\" action=\"<%=RedirURL%>\" method=\"POST\"> \n <noscript> \n <br> \n <br> \n <div align=\"center\"> \n <h1>Processing your 3-D Secure Transaction</h1> \n <h2>JavaScript is currently disabled or is not supported by your browser.</h2><BR> \n <h3>Please click Submit to continue the processing of your 3-D Secure transaction.</h3><BR> \n <input type=\"submit\" value=\"Submit\"> \n </div> \n </noscript> \n <input type=\"hidden\" name=\"PaReq\" value=\"<%=PAREQ%>\"> \n <input type=\"hidden\" name=\"MD\" value=\"<%=TransactionID%>\"> \n <input type=\"hidden\" name=\"TermUrl\" value=\"<%=TermUrl%>\"> \n </form> \n <SCRIPT LANGUAGE=\"Javascript\"> \n <!-- \n function OnLoadEvent() { \n document.downloadForm.submit(); \n } \n //--> \n </SCRIPT> \n </body> \n</html>\n"
},
{
"answer_id": 104909,
"author": "Jeremy",
"author_id": 1114,
"author_profile": "https://Stackoverflow.com/users/1114",
"pm_score": 0,
"selected": false,
"text": "header(\"Location: http://example.com/newpage\");"
},
{
"answer_id": 104927,
"author": "Michael Ridley",
"author_id": 4838,
"author_profile": "https://Stackoverflow.com/users/4838",
"pm_score": 0,
"selected": false,
"text": "function sendToHost($host,$method,$path,$data,$useragent=0)\n{\n // Supply a default method of GET if the one passed was empty\n if (empty($method)) {\n $method = 'GET';\n }\n $method = strtoupper($method);\n $fp = fsockopen($host, 80);\n if ($method == 'GET') {\n $path .= '?' . $data;\n }\n fputs($fp, \"$method $path HTTP/1.1\\r\\n\");\n fputs($fp, \"Host: $host\\r\\n\");\n fputs($fp,\"Content-type: application/x-www-form- urlencoded\\r\\n\");\n fputs($fp, \"Content-length: \" . strlen($data) . \"\\r\\n\");\n if ($useragent) {\n fputs($fp, \"User-Agent: MSIE\\r\\n\");\n }\n fputs($fp, \"Connection: close\\r\\n\\r\\n\");\n if ($method == 'POST') {\n fputs($fp, $data);\n }\n\n while (!feof($fp)) {\n $buf .= fgets($fp,128);\n }\n fclose($fp);\n return $buf;\n}\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19232/"
] |
104,918
|
<p>My question is related to the command pattern, where we have the following abstraction (C# code) :</p>
<pre><code>public interface ICommand
{
void Execute();
}
</code></pre>
<p>Let's take a simple concrete command, which aims to delete an entity from our application. A <code>Person</code> instance, for example.</p>
<p>I'll have a <code>DeletePersonCommand</code>, which implements <code>ICommand</code>. This command needs the <code>Person</code> to delete as a parameter, in order to delete it when <code>Execute</code> method is called.</p>
<p>What is the best way to manage parametrized commands ? How to pass parameters to commands, before executing them ?</p>
|
[
{
"answer_id": 104940,
"author": "Matt Dillard",
"author_id": 863,
"author_profile": "https://Stackoverflow.com/users/863",
"pm_score": 0,
"selected": false,
"text": "DeletePersonCommand Execute()"
},
{
"answer_id": 104946,
"author": "Joel Martinez",
"author_id": 5416,
"author_profile": "https://Stackoverflow.com/users/5416",
"pm_score": -1,
"selected": false,
"text": "public class DeleteCommand : ICommand\n{\n public void Execute(Entity entity)\n {\n IDeletable del = entity as IDeletable;\n if (del != null) del.Delete();\n }\n}\n"
},
{
"answer_id": 104948,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 7,
"selected": true,
"text": "public class DeletePersonCommand: ICommand\n{\n private Person personToDelete;\n public DeletePersonCommand(Person personToDelete)\n {\n this.personToDelete = personToDelete;\n }\n\n public void Execute()\n {\n doSomethingWith(personToDelete);\n }\n}\n"
},
{
"answer_id": 104949,
"author": "Juanma",
"author_id": 3730,
"author_profile": "https://Stackoverflow.com/users/3730",
"pm_score": 4,
"selected": false,
"text": "interface ICommand<T>\n{\n void Execute(T args);\n}\n"
},
{
"answer_id": 104985,
"author": "jop",
"author_id": 11830,
"author_profile": "https://Stackoverflow.com/users/11830",
"pm_score": 3,
"selected": false,
"text": "ICommand command = new DeletePersonCommand(person);\n class DeletePersonCommand : ICommand\n{\n private Person person;\n public DeletePersonCommand(Person person)\n {\n this.person = person;\n }\n\n public void Execute()\n {\n RealDelete(person);\n }\n}\n"
},
{
"answer_id": 104995,
"author": "user12786",
"author_id": 12786,
"author_profile": "https://Stackoverflow.com/users/12786",
"pm_score": 3,
"selected": false,
"text": "void execute(Context ctx);\n"
},
{
"answer_id": 105050,
"author": "TheZenker",
"author_id": 10552,
"author_profile": "https://Stackoverflow.com/users/10552",
"pm_score": 2,
"selected": false,
"text": "interface ICommand\n {\n bool CanExecute(object parameter);\n void Execute(object parameter);\n }\n public static ICommand DeleteCommand = new DeleteCommandInstance();\n public void Execute(object parameter)\n {\n person target = (person)parameter;\n target.Delete();\n } \n"
},
{
"answer_id": 136565,
"author": "Scott Stanchfield",
"author_id": 12541,
"author_profile": "https://Stackoverflow.com/users/12541",
"pm_score": 5,
"selected": false,
"text": "User Interface (GUI controls, CLI, etc)\n |\n[syncs with/gets data]\n V\nController / Presentation Model\n | ^\n[executes] |\n V |\nCommands --------> [gets data by name]\n |\n[updates]\n V\nDomain Model\n"
},
{
"answer_id": 2486070,
"author": "bloparod",
"author_id": 134559,
"author_profile": "https://Stackoverflow.com/users/134559",
"pm_score": 3,
"selected": false,
"text": "public class DeletePersonCommand: ICommand<Person>\n{\n public DeletePersonCommand(IPersonService personService)\n { \n this.personService = personService;\n }\n\n public void Execute(Person person)\n {\n this.personService.DeletePerson(person);\n }\n}\n"
},
{
"answer_id": 60908173,
"author": "Kostas Thanasis",
"author_id": 7296110,
"author_profile": "https://Stackoverflow.com/users/7296110",
"pm_score": 2,
"selected": false,
"text": " class DeletePersonCommand implements ICommand\n{\n private Supplier<Person> personSupplier;\n\n public DeletePersonCommand(Supplier<Person> personSupplier)\n {\n this.personSupplier = personSupplier;\n }\n\n public void Execute()\n {\n personSupplier.get().delete();\n }\n}\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4687/"
] |
104,952
|
<p>I am using VS2005 VC++ for unmanaged C++. I have VSTS and am trying to use the code coverage tool to accomplish two things with regards to unit tests:</p>
<ol>
<li>See how much of my referenced code under test is getting executed</li>
<li>See how many methods of my code under test (if any) are not unit tested at all</li>
</ol>
<p>Setting up the VSTS code coverage tool (see the <a href="https://blogs.msdn.com/ms_joc/articles/406608.aspx" rel="nofollow noreferrer" title="MSDN Code Coverage Blog">link text</a>) and accomplishing task #1 was straightforward. However #2 has been a surprising challenge for me. Here is my test code. </p>
<pre><code>class CodeCoverageTarget
{
public:
std::string ThisMethodRuns() {
return "Running";
}
std::string ThisMethodDoesNotRun() {
return "Not Running";
}
};
#include <iostream>
#include "CodeCoverageTarget.h"
using namespace std;
int main()
{
CodeCoverageTarget cct;
cout<<cct.ThisMethodRuns()<<endl;
}
</code></pre>
<p>When both methods are defined within the class as above the compiler automatically eliminates the ThisMethodDoesNotRun() from the obj file. If I move it's definition outside the class then it is included in the obj file and the code coverage tool shows it has not been exercised at all. Under most circumstances I want the compiler to do this elimination for me but for the code coverage tool it defeats a significant portion of the value (e.g. finding untested methods). I have tried a number of things to tell the compiler to stop being smart for me and compile everything but I am stumped. It would be nice if the code coverage tool compensated for this (I suppose by scanning the source and matching it up with the linker output) but I didn't find anything to suggest it has a special mode to be turned on. Am I totally missing something simple here or is this not possible with the VC++ compiler + VSTS code coverage tool? </p>
<p>Thanks in advance,
KGB</p>
|
[
{
"answer_id": 105238,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 1,
"selected": false,
"text": "\nint main(int argc, char **argv)\n{\n if(argv == NULL) // C runtime says this won't happen\n someMethodWhichIsntReallyEverCalled();\n}\n"
},
{
"answer_id": 105458,
"author": "Don Neufeld",
"author_id": 13097,
"author_profile": "https://Stackoverflow.com/users/13097",
"pm_score": 0,
"selected": false,
"text": "inline std::string Foo::ThisMethodDoesNotRun()\n{\n return \"Not Running\";\n}\n #if !COVERAGE_BUILD\n#include \"foo.inl\"\n#endif\n #if COVERAGE_BUILD\n#define inline\n#include \"foo.inl\"\n#endif\n"
},
{
"answer_id": 107444,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 1,
"selected": false,
"text": "__declspec(dllexport) .DEF __declspec(noinline) a.obj b.obj b.obj a.obj a.obj"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
104,953
|
<p>I'm trying to create a horizontal 100% stacked bar graph using HTML and CSS. I'd like to create the bars using <code>DIVs</code> with background colors and percentage widths depending on the values I want to graph. I also want to have a grid lines to mark an arbitrary position along the graph.</p>
<p>In my experimentation, I've already gotten the bars to stack horizontally by assigning the CSS property <code>float: left</code>. However, I'd like to avoid that, as it really seems to mess with the layout in confusing ways. Also, the grid lines don't seem to work very well when the bars are floated.</p>
<p>I think that CSS positioning should be able to handle this, but I don't yet know how to do it. I want to be able to specify the position of several elements relative to the top-left corner of their container. I run into this sort of issue regularly (even outside of this particular graph project), so I'd like a method that's:</p>
<ol>
<li>Cross-browser (ideally without too many browser hacks)</li>
<li>Runs in Quirks mode</li>
<li>As clear/clean as possible, to facilitate customizations</li>
<li>Done without JavaScript if possible.</li>
</ol>
|
[
{
"answer_id": 104965,
"author": "Stephen Deken",
"author_id": 7154,
"author_profile": "https://Stackoverflow.com/users/7154",
"pm_score": 4,
"selected": false,
"text": "div.parent{\n position: relative;\n left: 0px; /* stick it wherever it was positioned by default */\n top: 0px;\n}\n\ndiv.child{\n position: absolute;\n left: 10px;\n top: 10px;\n}\n"
},
{
"answer_id": 104981,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 2,
"selected": false,
"text": "position: relative top left position: absolute"
},
{
"answer_id": 105035,
"author": "Bryan M.",
"author_id": 4636,
"author_profile": "https://Stackoverflow.com/users/4636",
"pm_score": 10,
"selected": true,
"text": "position: relative position: absolute position: relative position: absolute #container {\n position: relative;\n border: 1px solid red;\n height: 100px;\n}\n\n#box {\n position: absolute;\n top: 50px;\n left: 20px;\n} <div id=\"container\">\n <div id=\"box\">absolute</div>\n</div> #box #container #container position: relative #box"
},
{
"answer_id": 44819597,
"author": "yusufshakeel",
"author_id": 4441708,
"author_profile": "https://Stackoverflow.com/users/4441708",
"pm_score": 4,
"selected": false,
"text": "#myelem {\n position : static;\n}\n #myelem {\n position : fixed;\n bottom : 30px;\n right : 30px;\n}\n #myelem {\n position : relative;\n left : 30px;\n top : 30px;\n}\n #myelem {\n position : absolute;\n top : 30px;\n left : 300px;\n}\n #container {\n position : relative;\n}\n\n#div-2 {\n position : absolute;\n top : 0;\n right : 0;\n}\n"
},
{
"answer_id": 50373390,
"author": "Nesha Zoric",
"author_id": 1660318,
"author_profile": "https://Stackoverflow.com/users/1660318",
"pm_score": 1,
"selected": false,
"text": "position: relative position: absolute .parent {\n position: relative;\n} \n\n.child {\n position: absolute;\n top: 0;\n left: 0; \n}\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3488/"
] |
104,959
|
<p>If I have a <code>std::vector</code> or <code>std::map</code> variable, and I want to see the contents, it's a big pain to see the nth element while debugging. Is there a plugin, or some trick to making it easier to watch STL container variables while debugging <code>(VS2003/2005/2008)</code>?</p>
|
[
{
"answer_id": 105563,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 4,
"selected": false,
"text": "(v._Myfirst)[startIndex], count"
},
{
"answer_id": 29318546,
"author": "1''",
"author_id": 1397061,
"author_profile": "https://Stackoverflow.com/users/1397061",
"pm_score": 3,
"selected": false,
"text": "container.operator[](n)\n"
},
{
"answer_id": 37693972,
"author": "Manohar Reddy Poreddy",
"author_id": 984471,
"author_profile": "https://Stackoverflow.com/users/984471",
"pm_score": 0,
"selected": false,
"text": "std::vector<std::string> vs(M_coins + 1);\nfor (unsigned long long i = 0; i <= M_coins; i++) {\n std::for_each(memo[i].begin(), memo[i].end(), [i, &vs](long long &n) {\n vs[i].append(std::to_string(n));\n });\n}\n// now vs is ready for use as vs[0], vs[1].. so on, for your debugger\n std::vector<std::string> s;\nstd::for_each(v1.begin(), v1.end(), [&s](long long &n) {\n s.append(std::to_string(n));\n });\n// now s is ready for use, for your debugger\n"
},
{
"answer_id": 40335848,
"author": "24k.wakahana",
"author_id": 7093406,
"author_profile": "https://Stackoverflow.com/users/7093406",
"pm_score": 2,
"selected": false,
"text": "vector<int> a = { 0,1,2,3,4,5 };\nint* ptr = &a[0]; // watch this ptr in VisualStudio Watch window like this \"ptr,6\".\n <?xml version=\"1.0\" encoding=\"utf-8\"?> \n<AutoVisualizer xmlns=\"http://schemas.microsoft.com/vstudio/debugger/natvis/2010\">\n <Type Name=\"std::vector<*>\">\n <DisplayString>{{ size={_Mypair._Myval2._Mylast - _Mypair._Myval2._Myfirst} }}</DisplayString>\n <Expand>\n <Item Name=\"[size]\" ExcludeView=\"simple\">_Mypair._Myval2._Mylast - _Mypair._Myval2._Myfirst</Item>\n <Item Name=\"[capacity]\" ExcludeView=\"simple\">_Mypair._Myval2._Myend - _Mypair._Myval2._Myfirst</Item>\n <ArrayItems>\n <Size>_Mypair._Myval2._Mylast - _Mypair._Myval2._Myfirst</Size>\n <ValuePointer>_Mypair._Myval2._Myfirst</ValuePointer>\n </ArrayItems>\n </Expand>\n </Type>\n</AutoVisualizer>\n"
},
{
"answer_id": 70935106,
"author": "Scylardor",
"author_id": 1987466,
"author_profile": "https://Stackoverflow.com/users/1987466",
"pm_score": 0,
"selected": false,
"text": "vectorName.data()\n vectorName.data(),N\n (float*)vectorName.data(),4\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10705/"
] |
104,960
|
<p>What is the best way to interact with a database using Haskell? I'm accustomed to using some sort of ORM (Django's ORM, hibernate, etc.) and something similar would be nice when creating apps with <a href="http://www.happs.org/" rel="noreferrer">HAppS</a>.</p>
<p><strong>Edit:</strong> I'd like to be free to choose from Postgresql MySql and SQLite as far as the actual databases go. </p>
|
[
{
"answer_id": 16802511,
"author": "John Wiegley",
"author_id": 370902,
"author_profile": "https://Stackoverflow.com/users/370902",
"pm_score": 3,
"selected": false,
"text": "User\n name Text\n age Int\n\nLogin\n user UserId\n login Text\n passwd Text\n Just (Entity uid _) <- selectFirst [ UserName ==. \"exampleUser\" ] []\nJust (Entity lid Login {..}) <- selectFirst [ LoginUser ==. uid ] []\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3446/"
] |
104,967
|
<p>As a pet-project, I'd like to attempt to implement a basic language of my own design that can be used as a web-scripting language. It's trivial to run a C++ program as an Apache CGI, so the real work lies in how to parse an input file containing non-code (HTML/CSS markup) and server-side code.</p>
<p>In my undergrad compiler course, we used <a href="http://www.gnu.org/software/flex/" rel="nofollow noreferrer">Flex</a> and <a href="http://www.gnu.org/software/bison/" rel="nofollow noreferrer">Bison</a> to generate a scanner and a parser for a simple language. We were given a copy of the grammar and wrote a parser that translated the simple language to a simple assembly for a virtual machine. The flex scanner tokenizes the input, and passes the tokens to the Bison parser.</p>
<p>The difference between that and what I'd like to do is that like PHP, this language could have plain HTML markup and the scripting language interspersed like the following:</p>
<pre><code><p>Hello,
<? echo "World ?>
</p>
</code></pre>
<p>Am I incorrect in assuming that it would be efficient to parse the input file as follows:</p>
<ol>
<li>Scan input until a script start tag is found ('
<li>Second scanner tokenizes the server-side script section of the input file (from the open tag: '') and passes the token to the parser, which has no need to know about the markup in the file.</li>
<li>Control is returned to the first scanner that continues this general pattern.</li>
</ol>
<p>Basically, the first scanner only differentiates between Markup (which is returned directly to the browser unmodified) and code, which is passed to the second scanner, which in turn tokenizes the code and passes the tokens to the parser. </p>
<p>If this is <em>not</em> a solid design pattern, how do languages such as PHP handle scanning input and parsing code efficiently?</p>
|
[
{
"answer_id": 105082,
"author": "Kris Erickson",
"author_id": 3798,
"author_profile": "https://Stackoverflow.com/users/3798",
"pm_score": 2,
"selected": false,
"text": "zend_language_scanner.l"
},
{
"answer_id": 111218,
"author": "eduffy",
"author_id": 7536,
"author_profile": "https://Stackoverflow.com/users/7536",
"pm_score": 4,
"selected": true,
"text": "\"<?\" { BEGIN (PHP); }\n<PHP>[a-zA-Z]* { return PHP_TOKEN; }\n<PHP>\">?\" { BEGIN (0); }\n[a-zA-Z]* { return HTML_TOKEN; }\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8636/"
] |
104,971
|
<p>I have a table with a "Date" column. Each Date may appear multiple times. How do I select only the dates that appear < k number of times?</p>
|
[
{
"answer_id": 104984,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": false,
"text": "SELECT * FROM [MyTable] WHERE [Date] IN\n(\n SELECT [Date] \n FROM [MyTable] \n GROUP By [Date] \n HAVING COUNT(*) < @Max\n)\n"
},
{
"answer_id": 104991,
"author": "Ihar Bury",
"author_id": 18001,
"author_profile": "https://Stackoverflow.com/users/18001",
"pm_score": 2,
"selected": false,
"text": "SELECT Date\nFROM SomeTable\nGROUP BY Date\nHAVING COUNT(*) < @k\n"
},
{
"answer_id": 104992,
"author": "Das",
"author_id": 17585,
"author_profile": "https://Stackoverflow.com/users/17585",
"pm_score": 2,
"selected": false,
"text": "SELECT Date FROM table GROUP BY Date HAVING COUNT(*)<k\n SELECT * FROM Table WHERE Date IN (\nSELECT Date FROM table GROUP BY Date HAVING COUNT(*)<k)\n"
},
{
"answer_id": 104994,
"author": "Forgotten Semicolon",
"author_id": 1960,
"author_profile": "https://Stackoverflow.com/users/1960",
"pm_score": 1,
"selected": false,
"text": "SELECT date, COUNT(date)\nFROM table\nGROUP BY date\nHAVING COUNT(date) < k\n SELECT table.*\nFROM table\nINNER JOIN (\n SELECT date, COUNT(date) \n FROM table\n GROUP BY date\n HAVING COUNT(date) < k) dates ON table.date = dates.date\n"
},
{
"answer_id": 104997,
"author": "Mike McAllister",
"author_id": 16247,
"author_profile": "https://Stackoverflow.com/users/16247",
"pm_score": 1,
"selected": false,
"text": "select date_col,count(*)\nfrom your_table\ngroup by date_col\nhaving count(*) < 5;\n select trunc(date_col) as date_col,count(*)\nfrom your_table\ngroup by trunc(date_col)\nhaving count(*) < 5;\n"
},
{
"answer_id": 104999,
"author": "Zsolt Botykai",
"author_id": 11621,
"author_profile": "https://Stackoverflow.com/users/11621",
"pm_score": 4,
"selected": true,
"text": "select dates \n from table t \n group by dates having count(dates) < k ;\n"
},
{
"answer_id": 105006,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 2,
"selected": false,
"text": "DECLARE @Max int\nSELECT @Max = 5\n\nSELECT t1.* \nFROM [MyTable] t1 \nJOIN(\n SELECT [Date] \n FROM [MyTable] \n GROUP By [Date] \n HAVING COUNT(*) < @Max\n) t2 on t1.[Date] = t2.[Date] \n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10675/"
] |
104,983
|
<p>In Python specifically, how do variables get shared between threads?</p>
<p>Although I have used <code>threading.Thread</code> before I never really understood or saw examples of how variables got shared. Are they shared between the main thread and the children or only among the children? When would I need to use thread local storage to avoid this sharing?</p>
<p>I have seen many warnings about synchronizing access to shared data among threads by using locks but I have yet to see a really good example of the problem. </p>
<p>Thanks in advance!</p>
|
[
{
"answer_id": 105025,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 8,
"selected": true,
"text": "Thread Thread Thread threading.local threading.local"
},
{
"answer_id": 106560,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 5,
"selected": false,
"text": "threading.local() >>> tls = threading.local()\n>>> tls.x = 4 \n>>> tls.x\n4\n"
},
{
"answer_id": 1894371,
"author": "ahatchkins",
"author_id": 230394,
"author_profile": "https://Stackoverflow.com/users/230394",
"pm_score": 7,
"selected": false,
"text": "#/usr/bin/env python\n\nfrom time import sleep\nfrom random import random\nfrom threading import Thread, local\n\ndata = local()\n\ndef bar():\n print(\"I'm called from\", data.v)\n\ndef foo():\n bar()\n\nclass T(Thread):\n def run(self):\n sleep(random())\n data.v = self.getName() # Thread-1 and Thread-2 accordingly\n sleep(1)\n foo()\n #/usr/bin/env python\n\nfrom time import sleep\nfrom random import random\nfrom threading import Thread\n\ndef bar():\n global v\n print(\"I'm called from\", v)\n\ndef foo():\n bar()\n\nclass T(Thread):\n def run(self):\n global v\n sleep(random())\n v = self.getName() # Thread-1 and Thread-2 accordingly\n sleep(1)\n foo()\n from threading import Thread\n\ndef bar(v):\n print(\"I'm called from\", v)\n\ndef foo(v):\n bar(v)\n\nclass T(Thread):\n def run(self):\n foo(self.getName())\n"
},
{
"answer_id": 70450414,
"author": "Sławomir Lenart",
"author_id": 1416144,
"author_profile": "https://Stackoverflow.com/users/1416144",
"pm_score": 0,
"selected": false,
"text": "threading.local()"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/104983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19215/"
] |
105,007
|
<p>I have read <a href="https://stackoverflow.com/questions/34571/whats-the-best-way-of-unit-testing-private-methods">this post</a> about how to test private methods. I usually do not test them, because I always thought it's faster to test only public methods that will be called from outside the object. Do you test private methods? Should I always test them?</p>
|
[
{
"answer_id": 7239814,
"author": "eddy147",
"author_id": 30759,
"author_profile": "https://Stackoverflow.com/users/30759",
"pm_score": 6,
"selected": false,
"text": "class Detective {\n public function investigate() {}\n private function sleepWithSuspect($suspect) {}\n}\nAltered version:\nclass Detective {\n public function investigate() {}\n final protected function sleepWithSuspect($suspect) {}\n}\nIn Test class:\nclass Mock_Detective extends Detective {\n\n public test_sleepWithSuspect($suspect) \n {\n //this is now accessible, but still not overridable!\n $this->sleepWithSuspect($suspect);\n }\n}\n"
},
{
"answer_id": 42230581,
"author": "unflores",
"author_id": 188870,
"author_profile": "https://Stackoverflow.com/users/188870",
"pm_score": 0,
"selected": false,
"text": "class Thing\n def some_string\n one + two\n end\n\n private \n\n def one\n 'aaaa'\n end\n\n def two\n 'bbbb'\n end\n\nend\n\n\nclass RefactoredThing\ndef some_string\n one + one_a + two + two_b\n end\n\n private \n\n def one\n 'aa'\n end\n\n def one_a\n 'aa'\n end\n\n def two\n 'bb'\n end\n\n def two_b\n 'bb'\n end\nend\n RefactoredThing def some_string_positioner\n if some case\n elsif other case\n elsif other case\n elsif other case\n else one more case\n end\nend\n"
},
{
"answer_id": 47401015,
"author": "Matt Messersmith",
"author_id": 3691783,
"author_profile": "https://Stackoverflow.com/users/3691783",
"pm_score": 6,
"selected": false,
"text": "GetNextToken() TEST_THAT(RuleEvaluator, canParseSpaceDelimtedTokens)\n{\n input_string = \"1 2 test bar\"\n re = RuleEvaluator(input_string);\n\n ASSERT re.GetNextToken() IS \"1\";\n ASSERT re.GetNextToken() IS \"2\";\n ASSERT re.GetNextToken() IS \"test\";\n ASSERT re.GetNextToken() IS \"bar\";\n ASSERT re.HasMoreTokens() IS FALSE;\n}\n GetNextToken() RuleEvaluator Tokenizer HasMoreTokens() GetNextTokens() RuleEvaluator Tokenizer Tokenizer RuleEvaluator GetNextToken() Tokenizer TEST_THAT(Tokenizer, canParseSpaceDelimtedTokens)\n{\n input_string = \"1 2 test bar\"\n tokenizer = Tokenizer(input_string);\n\n ASSERT tokenizer.GetNextToken() IS \"1\";\n ASSERT tokenizer.GetNextToken() IS \"2\";\n ASSERT tokenizer.GetNextToken() IS \"test\";\n ASSERT tokenizer.GetNextToken() IS \"bar\";\n ASSERT tokenizer.HasMoreTokens() IS FALSE;\n}\n FRIEND_TEST FRIEND_TEST Tokenizer SplitUpByDelimiter() GetNextToken() TEST_THAT(Tokenizer, canParseSpaceDelimtedTokens)\n{\n input_string = \"1 2 test bar\"\n tokenizer = Tokenizer(input_string);\n\n ASSERT tokenizer.GetNextToken() IS \"1\";\n ASSERT tokenizer.GetNextToken() IS \"2\";\n ASSERT tokenizer.GetNextToken() IS \"test\";\n ASSERT tokenizer.GetNextToken() IS \"bar\";\n ASSERT tokenizer.HasMoreTokens() IS false;\n}\n FRIEND_TEST TEST_THAT(TokenizerTest, canGenerateSpaceDelimtedTokens)\n{\n input_string = \"1 2 test bar\"\n tokenizer = Tokenizer(input_string);\n result_array = tokenizer.SplitUpByDelimiter(\" \");\n\n ASSERT result.size() IS 4;\n ASSERT result[0] IS \"1\";\n ASSERT result[1] IS \"2\";\n ASSERT result[2] IS \"test\";\n ASSERT result[3] IS \"bar\";\n}\n Delimiter"
},
{
"answer_id": 55548038,
"author": "Colm Bhandal",
"author_id": 5134722,
"author_profile": "https://Stackoverflow.com/users/5134722",
"pm_score": 2,
"selected": false,
"text": "public bool allPrime(int a, int b, int c)\n{\n return andAll(isPrime(a), isPrime(b), isPrime(c))\n}\n\nprivate bool andAll(bool... boolArray)\n{\n foreach (bool b in boolArray)\n {\n if(b == false) return false;\n }\n return true;\n}\n\nprivate bool isPrime(int x){\n //Implementation to go here. Sorry if you were expecting a prime sieve.\n}\n allPrime isPrime andAll < 0 = 0 = 1 prime > 1 not prime > 1 5*5*5 isPrime andAll allPrime"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/105007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13913/"
] |
105,014
|
<p>A while ago I came across some code that marked a member variable of a class with the <code>mutable</code> keyword. As far as I can see it simply allows you to modify a variable in a <code>const</code> method:</p>
<pre><code>class Foo
{
private:
mutable bool done_;
public:
void doSomething() const { ...; done_ = true; }
};
</code></pre>
<p>Is this the only use of this keyword or is there more to it than meets the eye? I have since used this technique in a class, marking a <code>boost::mutex</code> as mutable allowing <code>const</code> functions to lock it for thread-safety reasons, but, to be honest, it feels like a bit of a hack.</p>
|
[
{
"answer_id": 105052,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 5,
"selected": false,
"text": "const mutable"
},
{
"answer_id": 105056,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 5,
"selected": false,
"text": "const HashTable lookup()"
},
{
"answer_id": 105061,
"author": "KeithB",
"author_id": 2298,
"author_profile": "https://Stackoverflow.com/users/2298",
"pm_score": 10,
"selected": true,
"text": "mutable int x = 0;\nauto f1 = [=]() mutable {x = 42;}; // OK\nauto f2 = [=]() {x = 42;}; // Error: a by-value capture cannot be modified in a non-mutable lambda\n"
},
{
"answer_id": 105086,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 3,
"selected": false,
"text": "class CIniWrapper\n{\npublic:\n CIniWrapper(LPCTSTR szIniFile);\n\n // non-const: logically modifies the state of the object\n void SetValue(LPCTSTR szName, LPCTSTR szValue);\n\n // const: does not logically change the object\n LPCTSTR GetValue(LPCTSTR szName, LPCTSTR szDefaultValue) const;\n\n // ...\n\nprivate:\n // cache, avoids going to disk when a named value is retrieved multiple times\n // does not logically change the public interface, so declared mutable\n // so that it can be used by the const GetValue() method\n mutable std::map<string, string> m_mapNameToValue;\n};\n const mutable"
},
{
"answer_id": 105276,
"author": "Lloyd",
"author_id": 9952,
"author_profile": "https://Stackoverflow.com/users/9952",
"pm_score": 4,
"selected": false,
"text": "mutable const mutable mutable boost::mutex"
},
{
"answer_id": 2384201,
"author": "Dan L",
"author_id": 286776,
"author_profile": "https://Stackoverflow.com/users/286776",
"pm_score": 7,
"selected": false,
"text": "mutable const mutable const const mutable mutable const mutable mutable const mutable const const const mutable const_cast const_cast mutable const const const_cast mutable const const"
},
{
"answer_id": 6017425,
"author": "Daniel Hershcovich",
"author_id": 223267,
"author_profile": "https://Stackoverflow.com/users/223267",
"pm_score": 1,
"selected": false,
"text": "mutable Get mutable const_cast"
},
{
"answer_id": 21949205,
"author": "Rajdeep Rathore",
"author_id": 3339634,
"author_profile": "https://Stackoverflow.com/users/3339634",
"pm_score": -1,
"selected": false,
"text": "//Prototype \nclass tag_name{\n :\n :\n mutable var_name;\n :\n :\n }; \n"
},
{
"answer_id": 24942741,
"author": "Kevin Cox",
"author_id": 1166181,
"author_profile": "https://Stackoverflow.com/users/1166181",
"pm_score": 2,
"selected": false,
"text": "const const const_cast class Logical {\n mutable int var;\n\npublic:\n Logical(): var(0) {}\n void set(int x) const { var = x; }\n};\n\nclass Bitwise {\n int var;\n\npublic:\n Bitwise(): var(0) {}\n void set(int x) const {\n const_cast<Bitwise*>(this)->var = x;\n }\n};\n\nconst Logical logical; // Not put in read-only.\nconst Bitwise bitwise; // Likely put in read-only.\n\nint main(void)\n{\n logical.set(5); // Well defined.\n bitwise.set(5); // Undefined.\n}\n"
},
{
"answer_id": 28139786,
"author": "Venkatakrishna Kalepalli",
"author_id": 4184683,
"author_profile": "https://Stackoverflow.com/users/4184683",
"pm_score": 0,
"selected": false,
"text": "const &obj mutable mutable class Test\n{\npublic:\n Test(): x(1), y(1) {};\n mutable int x;\n int y;\n};\n\nint main()\n{\n const Test object;\n object.x = 123;\n //object.y = 123;\n /* \n * The above line if uncommented, will create compilation error.\n */ \n\n cout<< \"X:\"<< object.x << \", Y:\" << object.y;\n return 0;\n}\n\nOutput:-\nX:123, Y:1\n x x y"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/105014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
] |
105,031
|
<p>Using C#, I want to get the total amount of RAM that my computer has.
With the PerformanceCounter I can get the amount of Available ram, by setting:</p>
<pre><code>counter.CategoryName = "Memory";
counter.Countername = "Available MBytes";
</code></pre>
<p>But I can't seem to find a way to get the total amount of memory. How would I go about doing this?</p>
<p><strong>Update:</strong></p>
<p>MagicKat: I saw that when I was searching, but it doesn't work - "Are you missing an assembly or reference?". I've looked to add that to the References, but I don't see it there.</p>
|
[
{
"answer_id": 105084,
"author": "MagicKat",
"author_id": 8505,
"author_profile": "https://Stackoverflow.com/users/8505",
"pm_score": 8,
"selected": false,
"text": "Microsoft.VisualBasic using Microsoft.VisualBasic.Devices; ComputerInfo"
},
{
"answer_id": 105099,
"author": "CodeRot",
"author_id": 14134,
"author_profile": "https://Stackoverflow.com/users/14134",
"pm_score": 3,
"selected": false,
"text": "Set objWMIService = GetObject(\"winmgmts:\" _\n& \"{impersonationLevel=impersonate}!\\\\\" _ \n& strComputer & \"\\root\\cimv2\") \nSet colComputer = objWMIService.ExecQuery _\n(\"Select * from Win32_ComputerSystem\")\n\nFor Each objComputer in colComputer \n strMemory = objComputer.TotalPhysicalMemory\nNext\n"
},
{
"answer_id": 105109,
"author": "Philip Rieck",
"author_id": 12643,
"author_profile": "https://Stackoverflow.com/users/12643",
"pm_score": 7,
"selected": true,
"text": "GlobalMemoryStatusEx [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]\n private class MEMORYSTATUSEX\n {\n public uint dwLength;\n public uint dwMemoryLoad;\n public ulong ullTotalPhys;\n public ulong ullAvailPhys;\n public ulong ullTotalPageFile;\n public ulong ullAvailPageFile;\n public ulong ullTotalVirtual;\n public ulong ullAvailVirtual;\n public ulong ullAvailExtendedVirtual;\n public MEMORYSTATUSEX()\n {\n this.dwLength = (uint)Marshal.SizeOf(typeof(NativeMethods.MEMORYSTATUSEX));\n }\n }\n\n\n [return: MarshalAs(UnmanagedType.Bool)]\n [DllImport(\"kernel32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n static extern bool GlobalMemoryStatusEx([In, Out] MEMORYSTATUSEX lpBuffer);\n ulong installedMemory;\nMEMORYSTATUSEX memStatus = new MEMORYSTATUSEX();\nif( GlobalMemoryStatusEx( memStatus))\n{ \n installedMemory = memStatus.ullTotalPhys;\n}\n TotalPhysicalMemory Win32_ComputerSystem"
},
{
"answer_id": 105890,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 6,
"selected": false,
"text": "static ulong GetTotalMemoryInBytes()\n{\n return new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory;\n}\n"
},
{
"answer_id": 2655015,
"author": "grendel",
"author_id": 171396,
"author_profile": "https://Stackoverflow.com/users/171396",
"pm_score": 5,
"selected": false,
"text": "using System;\nusing System.Diagnostics;\n\nclass app\n{\n static void Main ()\n {\n var pc = new PerformanceCounter (\"Mono Memory\", \"Total Physical Memory\");\n Console.WriteLine (\"Physical RAM (bytes): {0}\", pc.RawValue);\n }\n}\n"
},
{
"answer_id": 10462545,
"author": "SuMeeT ShaHaPeTi",
"author_id": 1376882,
"author_profile": "https://Stackoverflow.com/users/1376882",
"pm_score": -1,
"selected": false,
"text": "/*The simplest way to get/display total physical memory in VB.net (Tested)\n\npublic sub get_total_physical_mem()\n\n dim total_physical_memory as integer\n\n total_physical_memory=CInt((My.Computer.Info.TotalPhysicalMemory) / (1024 * 1024))\n MsgBox(\"Total Physical Memory\" + CInt((My.Computer.Info.TotalPhysicalMemory) / (1024 * 1024)).ToString + \"Mb\" )\nend sub\n*/\n\n\n//The simplest way to get/display total physical memory in C# (converted Form http://www.developerfusion.com/tools/convert/vb-to-csharp)\n\npublic void get_total_physical_mem()\n{\n int total_physical_memory = 0;\n\n total_physical_memory = Convert.ToInt32((My.Computer.Info.TotalPhysicalMemory) / (1024 * 1024));\n Interaction.MsgBox(\"Total Physical Memory\" + Convert.ToInt32((My.Computer.Info.TotalPhysicalMemory) / (1024 * 1024)).ToString() + \"Mb\");\n}\n"
},
{
"answer_id": 22753830,
"author": "Nilan Niyomal",
"author_id": 2219885,
"author_profile": "https://Stackoverflow.com/users/2219885",
"pm_score": 3,
"selected": false,
"text": "using Microsoft.VisualBasic.Devices;\n private void button1_Click(object sender, EventArgs e)\n {\n getAvailableRAM();\n }\n\n public void getAvailableRAM()\n {\n ComputerInfo CI = new ComputerInfo();\n ulong mem = ulong.Parse(CI.TotalPhysicalMemory.ToString());\n richTextBox1.Text = (mem / (1024*1024) + \" MB\").ToString();\n }\n"
},
{
"answer_id": 24395572,
"author": "zgerd",
"author_id": 2496267,
"author_profile": "https://Stackoverflow.com/users/2496267",
"pm_score": 4,
"selected": false,
"text": "string Query = \"SELECT Capacity FROM Win32_PhysicalMemory\";\nManagementObjectSearcher searcher = new ManagementObjectSearcher(Query);\n\nUInt64 Capacity = 0;\nforeach (ManagementObject WniPART in searcher.Get())\n{\n Capacity += Convert.ToUInt64(WniPART.Properties[\"Capacity\"].Value);\n}\n\nreturn Capacity;\n"
},
{
"answer_id": 26514915,
"author": "Roman Starkov",
"author_id": 33080,
"author_profile": "https://Stackoverflow.com/users/33080",
"pm_score": 0,
"selected": false,
"text": "PhysicalTotal PageSize"
},
{
"answer_id": 33413251,
"author": "Lance",
"author_id": 4767537,
"author_profile": "https://Stackoverflow.com/users/4767537",
"pm_score": 2,
"selected": false,
"text": "ManagementQuery private static string ManagementQuery(string query, string parameter, string scope = null) {\n string result = string.Empty;\n var searcher = string.IsNullOrEmpty(scope) ? new ManagementObjectSearcher(query) : new ManagementObjectSearcher(scope, query);\n foreach (var os in searcher.Get()) {\n try {\n result = os[parameter].ToString();\n }\n catch {\n //ignore\n }\n\n if (!string.IsNullOrEmpty(result)) {\n break;\n }\n }\n\n return result;\n}\n Console.WriteLine(BytesToMb(Convert.ToInt64(ManagementQuery(\"SELECT TotalPhysicalMemory FROM Win32_ComputerSystem\", \"TotalPhysicalMemory\", \"root\\\\CIMV2\"))));\n"
},
{
"answer_id": 34100935,
"author": "sstan",
"author_id": 4955425,
"author_profile": "https://Stackoverflow.com/users/4955425",
"pm_score": 5,
"selected": false,
"text": "[DllImport(\"kernel32.dll\")]\n[return: MarshalAs(UnmanagedType.Bool)]\nstatic extern bool GetPhysicallyInstalledSystemMemory(out long TotalMemoryInKilobytes);\n\nstatic void Main()\n{\n long memKb;\n GetPhysicallyInstalledSystemMemory(out memKb);\n Console.WriteLine((memKb / 1024 / 1024) + \" GB of RAM installed.\");\n}\n"
},
{
"answer_id": 34900103,
"author": "Mehul Sant",
"author_id": 5815839,
"author_profile": "https://Stackoverflow.com/users/5815839",
"pm_score": 3,
"selected": false,
"text": "// use `/ 1048576` to get ram in MB\n// and `/ (1048576 * 1024)` or `/ 1048576 / 1024` to get ram in GB\nprivate static String getRAMsize()\n{\n ManagementClass mc = new ManagementClass(\"Win32_ComputerSystem\");\n ManagementObjectCollection moc = mc.GetInstances();\n foreach (ManagementObject item in moc)\n {\n return Convert.ToString(Math.Round(Convert.ToDouble(item.Properties[\"TotalPhysicalMemory\"].Value) / 1048576, 0)) + \" MB\";\n }\n\n return \"RAMsize\";\n}\n"
},
{
"answer_id": 53017759,
"author": "Soroush Falahati",
"author_id": 1913051,
"author_profile": "https://Stackoverflow.com/users/1913051",
"pm_score": 1,
"selected": false,
"text": "ComputerInfo PerformanceCounter using System;\nusing System.Diagnostics;\nusing System.Runtime.InteropServices;\nusing System.Security;\n\npublic class SystemMemoryInfo\n{\n private readonly PerformanceCounter _monoAvailableMemoryCounter;\n private readonly PerformanceCounter _monoTotalMemoryCounter;\n private readonly PerformanceCounter _netAvailableMemoryCounter;\n\n private ulong _availablePhysicalMemory;\n private ulong _totalPhysicalMemory;\n\n public SystemMemoryInfo()\n {\n try\n {\n if (PerformanceCounterCategory.Exists(\"Mono Memory\"))\n {\n _monoAvailableMemoryCounter = new PerformanceCounter(\"Mono Memory\", \"Available Physical Memory\");\n _monoTotalMemoryCounter = new PerformanceCounter(\"Mono Memory\", \"Total Physical Memory\");\n }\n else if (PerformanceCounterCategory.Exists(\"Memory\"))\n {\n _netAvailableMemoryCounter = new PerformanceCounter(\"Memory\", \"Available Bytes\");\n }\n }\n catch\n {\n // ignored\n }\n }\n\n public ulong AvailablePhysicalMemory\n {\n [SecurityCritical]\n get\n {\n Refresh();\n\n return _availablePhysicalMemory;\n }\n }\n\n public ulong TotalPhysicalMemory\n {\n [SecurityCritical]\n get\n {\n Refresh();\n\n return _totalPhysicalMemory;\n }\n }\n\n [SecurityCritical]\n [DllImport(\"Kernel32\", CharSet = CharSet.Auto, SetLastError = true)]\n private static extern void GlobalMemoryStatus(ref MEMORYSTATUS lpBuffer);\n\n [SecurityCritical]\n [DllImport(\"Kernel32\", CharSet = CharSet.Auto, SetLastError = true)]\n [return: MarshalAs(UnmanagedType.Bool)]\n private static extern bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX lpBuffer);\n\n [SecurityCritical]\n private void Refresh()\n {\n try\n {\n if (_monoTotalMemoryCounter != null && _monoAvailableMemoryCounter != null)\n {\n _totalPhysicalMemory = (ulong) _monoTotalMemoryCounter.NextValue();\n _availablePhysicalMemory = (ulong) _monoAvailableMemoryCounter.NextValue();\n }\n else if (Environment.OSVersion.Version.Major < 5)\n {\n var memoryStatus = MEMORYSTATUS.Init();\n GlobalMemoryStatus(ref memoryStatus);\n\n if (memoryStatus.dwTotalPhys > 0)\n {\n _availablePhysicalMemory = memoryStatus.dwAvailPhys;\n _totalPhysicalMemory = memoryStatus.dwTotalPhys;\n }\n else if (_netAvailableMemoryCounter != null)\n {\n _availablePhysicalMemory = (ulong) _netAvailableMemoryCounter.NextValue();\n }\n }\n else\n {\n var memoryStatusEx = MEMORYSTATUSEX.Init();\n\n if (GlobalMemoryStatusEx(ref memoryStatusEx))\n {\n _availablePhysicalMemory = memoryStatusEx.ullAvailPhys;\n _totalPhysicalMemory = memoryStatusEx.ullTotalPhys;\n }\n else if (_netAvailableMemoryCounter != null)\n {\n _availablePhysicalMemory = (ulong) _netAvailableMemoryCounter.NextValue();\n }\n }\n }\n catch\n {\n // ignored\n }\n }\n\n private struct MEMORYSTATUS\n {\n private uint dwLength;\n internal uint dwMemoryLoad;\n internal uint dwTotalPhys;\n internal uint dwAvailPhys;\n internal uint dwTotalPageFile;\n internal uint dwAvailPageFile;\n internal uint dwTotalVirtual;\n internal uint dwAvailVirtual;\n\n public static MEMORYSTATUS Init()\n {\n return new MEMORYSTATUS\n {\n dwLength = checked((uint) Marshal.SizeOf(typeof(MEMORYSTATUS)))\n };\n }\n }\n\n private struct MEMORYSTATUSEX\n {\n private uint dwLength;\n internal uint dwMemoryLoad;\n internal ulong ullTotalPhys;\n internal ulong ullAvailPhys;\n internal ulong ullTotalPageFile;\n internal ulong ullAvailPageFile;\n internal ulong ullTotalVirtual;\n internal ulong ullAvailVirtual;\n internal ulong ullAvailExtendedVirtual;\n\n public static MEMORYSTATUSEX Init()\n {\n return new MEMORYSTATUSEX\n {\n dwLength = checked((uint) Marshal.SizeOf(typeof(MEMORYSTATUSEX)))\n };\n }\n }\n}\n"
},
{
"answer_id": 59073095,
"author": "BRAHIM Kamel",
"author_id": 2597372,
"author_profile": "https://Stackoverflow.com/users/2597372",
"pm_score": 5,
"selected": false,
"text": ".net Core 3.0 PInvoke GC GC.GetGCMemoryInfo GCMemoryInfo Struct TotalAvailableMemoryBytes var gcMemoryInfo = GC.GetGCMemoryInfo();\ninstalledMemory = gcMemoryInfo.TotalAvailableMemoryBytes;\n// it will give the size of memory in MB\nvar physicalMemory = (double) installedMemory / 1048576.0;\n"
},
{
"answer_id": 66804236,
"author": "Alberico Francesco",
"author_id": 15469158,
"author_profile": "https://Stackoverflow.com/users/15469158",
"pm_score": -1,
"selected": false,
"text": "var ram = new ManagementObjectSearcher(\"select * from Win32_PhysicalMemory\") .Get().Cast<ManagementObject>().First(); var a = Convert.ToInt64(ram[\"Capacity\"]) / 1024 / 1024 / 1024; ulong memory() { return new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory; } var b = Convert.ToDecimal(memory()) / 1024 / 1024 / 1024;"
},
{
"answer_id": 74258606,
"author": "Rob",
"author_id": 18735,
"author_profile": "https://Stackoverflow.com/users/18735",
"pm_score": 0,
"selected": false,
"text": "// total memory\nlong totalPhysicalMemory = My.Computer.Info.TotalPhysicalMemory;\n\n// unused memory\nlong availablePhysicalMemory = My.Computer.Info.AvailablePhysicalMemory;\n\n// used memory\nlong usedMemory = totalPhysicalMemory - availablePhysicalMemory;\n"
},
{
"answer_id": 74472605,
"author": "frakon",
"author_id": 2094687,
"author_profile": "https://Stackoverflow.com/users/2094687",
"pm_score": 0,
"selected": false,
"text": "private static readonly object _linuxMemoryLock = new();\nprivate static readonly char[] _arrayForMemInfoRead = new char[200];\n\npublic static void GetBytesCountOnLinux(out ulong availableBytes, out ulong totalBytes)\n{\n lock (_linuxMemoryLock) // lock because of reusing static fields due to optimization\n {\n totalBytes = GetBytesCountFromLinuxMemInfo(token: \"MemTotal:\", refreshFromFile: true);\n availableBytes = GetBytesCountFromLinuxMemInfo(token: \"MemAvailable:\", refreshFromFile: false);\n }\n}\n\nprivate static ulong GetBytesCountFromLinuxMemInfo(string token, bool refreshFromFile)\n{\n // NOTE: Using the linux file /proc/meminfo which is refreshed frequently and starts with:\n //MemTotal: 7837208 kB\n //MemFree: 190612 kB\n //MemAvailable: 5657580 kB\n\n var readSpan = _arrayForMemInfoRead.AsSpan();\n\n if (refreshFromFile)\n {\n using var fileStream = new FileStream(\"/proc/meminfo\", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);\n\n using var reader = new StreamReader(fileStream, Encoding.UTF8, leaveOpen: true);\n\n reader.ReadBlock(readSpan);\n }\n\n var tokenIndex = readSpan.IndexOf(token);\n\n var fromTokenSpan = readSpan.Slice(tokenIndex + token.Length);\n\n var kbIndex = fromTokenSpan.IndexOf(\"kB\");\n\n var notTrimmedSpan = fromTokenSpan.Slice(0, kbIndex);\n\n var trimmedSpan = notTrimmedSpan.Trim(' ');\n\n var kBytesCount = ulong.Parse(trimmedSpan);\n\n var bytesCount = kBytesCount * 1024;\n\n return bytesCount;\n}\n public static void GetRamBytes(out ulong availableBytes, out ulong totalBytes)\n{\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))\n {\n GetBytesCountOnLinux(out availableBytes, out totalBytes);\n }\n else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n GetBytesCountOnWindows(out availableBytes, out totalBytes);\n }\n else\n {\n throw new NotImplementedException(\"Not implemented for OS: \" + Environment.OSVersion);\n }\n}\n\nprivate static readonly object _winMemoryLock = new();\nprivate static readonly MEMORYSTATUSEX _memStatus = new();\n\nprivate static void GetBytesCountOnWindows(out ulong availableBytes, out ulong totalBytes)\n{\n lock (_winMemoryLock) // lock because of reusing the static class _memStatus\n {\n GlobalMemoryStatusEx(_memStatus);\n\n availableBytes = _memStatus.ullAvailPhys;\n totalBytes = _memStatus.ullTotalPhys;\n }\n}\n\n[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]\nprivate class MEMORYSTATUSEX\n{\n public uint dwLength;\n public uint dwMemoryLoad;\n public ulong ullTotalPhys;\n public ulong ullAvailPhys;\n public ulong ullTotalPageFile;\n public ulong ullAvailPageFile;\n public ulong ullTotalVirtual;\n public ulong ullAvailVirtual;\n public ulong ullAvailExtendedVirtual;\n\n public MEMORYSTATUSEX()\n {\n this.dwLength = (uint)Marshal.SizeOf(typeof(MEMORYSTATUSEX));\n }\n}\n\n[return: MarshalAs(UnmanagedType.Bool)]\n[DllImport(\"kernel32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\nprivate static extern bool GlobalMemoryStatusEx([In] [Out] MEMORYSTATUSEX lpBuffer);\n"
}
] |
2008/09/19
|
[
"https://Stackoverflow.com/questions/105031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13713/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.