qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
---|---|---|---|---|
75,145 |
<p>How to you find the URL that represents the documentation of a .NET framework method on the MSDN website?</p>
<p>For example, I want to embed the URL for the .NET framework method into some comments in some code. The normal "mangled" URL that one gets searching MSDN isn't very friendly looking: <a href="http://msdn.microsoft.com/library/xd12z8ts.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/library/xd12z8ts.aspx</a>. Using a Google search URL isn't all that pretty looking either.</p>
<p>What I really want a URL that can be embedded in comments that is plain and easy to read. For example,</p>
<p>// blah blah blah. See http://<....>/System.Byte.ToString for more information</p>
|
[
{
"answer_id": 75167,
"author": "user7116",
"author_id": 7116,
"author_profile": "https://Stackoverflow.com/users/7116",
"pm_score": 3,
"selected": false,
"text": "http://msdn.microsoft.com/en-us/library/system.windows.application_events.aspx\n http://msdn.microsoft.com/en-us/library/system.windows.forms.button(VS.80).aspx\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2459/"
] |
75,156 |
<p>This is a shared hosting environment. I control the server, but not necessarily the content. I've got a client with a Perl script that seems to run out of control every now and then and suck down 50% of the processor until the process is killed.</p>
<p>With ASP scripts, I'm able to restrict the amount of time the script can run, and IIS will simply shut it down after, say, 90 seconds. This doesn't work for Perl scripts, since it's running as a cgi process (and actually launches an external process to execute the script). </p>
<p>Similarly, techniques that look for excess resource consumption in a worker process will likely not see this, since the resource that's being consumed (the processor) is being chewed up by a child process rather than the WP itself.</p>
<p>Is there a way to make IIS abort a Perl script (or other cgi-type process) that's running too long? How??</p>
|
[
{
"answer_id": 75875,
"author": "arclight",
"author_id": 13366,
"author_profile": "https://Stackoverflow.com/users/13366",
"pm_score": 1,
"selected": false,
"text": "eval {\n # Create signal handler and make it local so it falls out of scope\n # outside the eval block\n local $SIG{ALRM} = sub {\n print \"Print this if we time out, then die.\\n\";\n die \"alarm\\n\";\n };\n\n # Set the alarm, take your chance running the routine, and turn off\n # the alarm if it completes.\n alarm(90);\n routine_that_might_take_a_while();\n alarm(0);\n};\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75156",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13282/"
] |
75,159 |
<p>I need to provide statistics on how many lines of code <code>(LOC)</code> associated with a system. The application part is easy but I need to also include any code residing within the SQL Server database. This would apply to stored procedures, functions, triggers, etc. </p>
<p>How can I easily get that info? Can it be done (accurately) with <strong>TSQL</strong> by querying the system <code>tables\sprocs</code>, etc?</p>
|
[
{
"answer_id": 75412,
"author": "Chris Bilson",
"author_id": 12934,
"author_profile": "https://Stackoverflow.com/users/12934",
"pm_score": 2,
"selected": false,
"text": "$conn = new-object System.Data.SqlClient.SqlConnection(\"Server=server;Database=database;Integrated Security=SSPI\")\n$cmd = new-object System.Data.SqlClient.SqlCommand(\"select text from syscomments\", $conn)\n$conn.Open()\n$reader = $cmd.ExecuteReader()\n\n$reader.Read() | out-null\n$reader.GetString(0) | clip\n$reader.Close()\n$conn.Close()\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] |
75,175 |
<p>Is it possible to create an instance of a generic type in Java? I'm thinking based on what I've seen that the answer is <code>no</code> (<em>due to type erasure</em>), but I'd be interested if anyone can see something I'm missing:</p>
<pre><code>class SomeContainer<E>
{
E createContents()
{
return what???
}
}
</code></pre>
<p>EDIT: It turns out that <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=208860" rel="noreferrer">Super Type Tokens</a> could be used to resolve my issue, but it requires a lot of reflection-based code, as some of the answers below have indicated.</p>
<p>I'll leave this open for a little while to see if anyone comes up with anything dramatically different than Ian Robertson's <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=208860" rel="noreferrer">Artima Article</a>.</p>
|
[
{
"answer_id": 75254,
"author": "Justin Rudd",
"author_id": 12968,
"author_profile": "https://Stackoverflow.com/users/12968",
"pm_score": 9,
"selected": false,
"text": "new E() private static class SomeContainer<E> {\n E createContents(Class<E> clazz) {\n return clazz.newInstance();\n }\n}\n"
},
{
"answer_id": 75313,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 3,
"selected": false,
"text": "public static class Container<E> {\n private Class<E> clazz;\n\n public Container(Class<E> clazz) {\n this.clazz = clazz;\n }\n\n public E createContents() throws Exception {\n return clazz.newInstance();\n }\n}\n @SuppressWarnings(\"unchecked\")\npublic Container(E instance) {\n this.clazz = (Class<E>) instance.getClass();\n}\n"
},
{
"answer_id": 75345,
"author": "noah",
"author_id": 12034,
"author_profile": "https://Stackoverflow.com/users/12034",
"pm_score": 7,
"selected": false,
"text": "public abstract class Foo<E> {\n\n public E instance; \n\n public Foo() throws Exception {\n instance = ((Class)((ParameterizedType)this.getClass().\n getGenericSuperclass()).getActualTypeArguments()[0]).newInstance();\n ...\n }\n\n}\n // notice that this in anonymous subclass of Foo\nassert( new Foo<Bar>() {}.instance instanceof Bar );\n"
},
{
"answer_id": 75528,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 6,
"selected": false,
"text": "interface Factory<E> {\n E create();\n}\n\nclass SomeContainer<E> {\n private final Factory<E> factory;\n SomeContainer(Factory<E> factory) {\n this.factory = factory;\n }\n E createContents() {\n return factory.create();\n }\n}\n"
},
{
"answer_id": 75595,
"author": "Pavel Feldman",
"author_id": 5507,
"author_profile": "https://Stackoverflow.com/users/5507",
"pm_score": 0,
"selected": false,
"text": "new E() Class<E> interface Factory<E>{\n E create();\n} \n\nclass IntegerFactory implements Factory<Integer>{ \n private static int i = 0; \n Integer create() { \n return i++; \n }\n}\n"
},
{
"answer_id": 87187,
"author": "jb.",
"author_id": 7918,
"author_profile": "https://Stackoverflow.com/users/7918",
"pm_score": 3,
"selected": false,
"text": "new SomeContainer<SomeType>(SomeType.class);\n <E> SomeContainer<E> createContainer(Class<E> class); \n public class Container<E> {\n\n public static <E> Container<E> create(Class<E> c) {\n return new Container<E>(c);\n }\n\n Class<E> c;\n\n public Container(Class<E> c) {\n super();\n this.c = c;\n }\n\n public E createInstance()\n throws InstantiationException,\n IllegalAccessException {\n return c.newInstance();\n }\n\n}\n"
},
{
"answer_id": 376216,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "Class.forName(String).getConstructor(arguments types).newInstance(arguments)\n java.io.FileInputStream"
},
{
"answer_id": 3635805,
"author": "Lars Bohl",
"author_id": 438960,
"author_profile": "https://Stackoverflow.com/users/438960",
"pm_score": 5,
"selected": false,
"text": "package org.foo.com;\n\nimport java.lang.reflect.ParameterizedType;\nimport java.lang.reflect.Type;\n\n/**\n * Basically the same answer as noah's.\n */\npublic class Home<E>\n{\n\n @SuppressWarnings (\"unchecked\")\n public Class<E> getTypeParameterClass()\n {\n Type type = getClass().getGenericSuperclass();\n ParameterizedType paramType = (ParameterizedType) type;\n return (Class<E>) paramType.getActualTypeArguments()[0];\n }\n\n private static class StringHome extends Home<String>\n {\n }\n\n private static class StringBuilderHome extends Home<StringBuilder>\n {\n }\n\n private static class StringBufferHome extends Home<StringBuffer>\n {\n } \n\n /**\n * This prints \"String\", \"StringBuilder\" and \"StringBuffer\"\n */\n public static void main(String[] args) throws InstantiationException, IllegalAccessException\n {\n Object object0 = new StringHome().getTypeParameterClass().newInstance();\n Object object1 = new StringBuilderHome().getTypeParameterClass().newInstance();\n Object object2 = new StringBufferHome().getTypeParameterClass().newInstance();\n System.out.println(object0.getClass().getSimpleName());\n System.out.println(object1.getClass().getSimpleName());\n System.out.println(object2.getClass().getSimpleName());\n }\n\n}\n"
},
{
"answer_id": 5389482,
"author": "Rachid",
"author_id": 670960,
"author_profile": "https://Stackoverflow.com/users/670960",
"pm_score": 0,
"selected": false,
"text": "return (E)((Class)((ParameterizedType)this.getClass().getGenericSuperclass()).getActualTypeArguments()[0]).newInstance();\n"
},
{
"answer_id": 10042797,
"author": "Bogdan Veliscu",
"author_id": 818753,
"author_profile": "https://Stackoverflow.com/users/818753",
"pm_score": 0,
"selected": false,
"text": "import java.lang.reflect.ParameterizedType;\n\npublic class SomeContainer<E> {\n E createContents() throws InstantiationException, IllegalAccessException {\n ParameterizedType genericSuperclass = (ParameterizedType)\n getClass().getGenericSuperclass();\n @SuppressWarnings(\"unchecked\")\n Class<E> clazz = (Class<E>)\n genericSuperclass.getActualTypeArguments()[0];\n return clazz.newInstance();\n }\n public static void main( String[] args ) throws Throwable {\n SomeContainer< Long > scl = new SomeContainer<>();\n Long l = scl.createContents();\n System.out.println( l );\n }\n}\n"
},
{
"answer_id": 12407106,
"author": "Sergiy Sokolenko",
"author_id": 131337,
"author_profile": "https://Stackoverflow.com/users/131337",
"pm_score": 4,
"selected": false,
"text": "public static <E> void append(List<E> list) {\n E elem = new E(); // compile-time error\n list.add(elem);\n}\n public static <E> void append(List<E> list, Class<E> cls) throws Exception {\n E elem = cls.getDeclaredConstructor().newInstance(); // OK\n list.add(elem);\n}\n List<String> ls = new ArrayList<>();\nappend(ls, String.class);\n"
},
{
"answer_id": 14146479,
"author": "Luigi R. Viggiano",
"author_id": 258289,
"author_profile": "https://Stackoverflow.com/users/258289",
"pm_score": 2,
"selected": false,
"text": "import java.lang.reflect.InvocationHandler;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Proxy;\n\ninterface SomeContainer<E> {\n E createContents();\n}\n\npublic class Main {\n\n @SuppressWarnings(\"unchecked\")\n public static <E> SomeContainer<E> createSomeContainer() {\n return (SomeContainer<E>) Proxy.newProxyInstance(Main.class.getClassLoader(),\n new Class[]{ SomeContainer.class }, new InvocationHandler() {\n @Override\n public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {\n Class<?> returnType = method.getReturnType();\n return returnType.newInstance();\n }\n });\n }\n\n public static void main(String[] args) {\n SomeContainer<String> container = createSomeContainer();\n\n [*] System.out.println(\"String created: [\" +container.createContents()+\"]\");\n\n }\n}\n Exception in thread \"main\" java.lang.ClassCastException: java.lang.Object cannot be cast to java.lang.String\n at Main.main(Main.java:26)\n at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)\n at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n at java.lang.reflect.Method.invoke(Method.java:601)\n at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)\n [*]"
},
{
"answer_id": 14191442,
"author": "R2D2M2",
"author_id": 1949703,
"author_profile": "https://Stackoverflow.com/users/1949703",
"pm_score": 5,
"selected": false,
"text": "public final class Foo<T> {\n\n private Class<T> typeArgumentClass;\n\n public Foo(Class<T> typeArgumentClass) {\n\n this.typeArgumentClass = typeArgumentClass;\n }\n\n public void doSomethingThatRequiresNewT() throws Exception {\n\n T myNewT = typeArgumentClass.newInstance();\n ...\n }\n}\n Foo<Bar> barFoo = new Foo<Bar>(Bar.class);\nFoo<Etc> etcFoo = new Foo<Etc>(Etc.class);\n Foo<L> newInstance()"
},
{
"answer_id": 21553287,
"author": "Roald",
"author_id": 2344378,
"author_profile": "https://Stackoverflow.com/users/2344378",
"pm_score": -1,
"selected": false,
"text": "final ClassLoader classLoader = ...\nfinal Class<?> aClass = classLoader.loadClass(\"java.lang.Integer\");\nfinal Constructor<?> constructor = aClass.getConstructor(int.class);\nfinal Object o = constructor.newInstance(123);\nSystem.out.println(\"o = \" + o);\n"
},
{
"answer_id": 21716855,
"author": "Ira",
"author_id": 3299647,
"author_profile": "https://Stackoverflow.com/users/3299647",
"pm_score": 3,
"selected": false,
"text": "abstract class SomeContainer<E>\n{\n abstract protected E createContents();\n public void doWork(){\n E obj = createContents();\n // Do the work with E \n }\n}\n\nclass BlackContainer extends SomeContainer<Black>{\n protected Black createContents() {\n return new Black();\n }\n}\n"
},
{
"answer_id": 25195050,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "import com.google.common.reflect.TypeToken;\n\npublic class Q26289147\n{\n public static void main(final String[] args) throws IllegalAccessException, InstantiationException\n {\n final StrawManParameterizedClass<String> smpc = new StrawManParameterizedClass<String>() {};\n final String string = (String) smpc.type.getRawType().newInstance();\n System.out.format(\"string = \\\"%s\\\"\",string);\n }\n\n static abstract class StrawManParameterizedClass<T>\n {\n final TypeToken<T> type = new TypeToken<T>(getClass()) {};\n }\n}\n"
},
{
"answer_id": 26796874,
"author": "Amio.io",
"author_id": 1075289,
"author_profile": "https://Stackoverflow.com/users/1075289",
"pm_score": 2,
"selected": false,
"text": "public abstract class Clazz<P extends Params, M extends Model> {\n\n protected M model;\n\n protected void createModel() {\n Type[] typeArguments = ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments();\n for (Type type : typeArguments) {\n if ((type instanceof Class) && (Model.class.isAssignableFrom((Class) type))) {\n try {\n model = ((Class<M>) type).newInstance();\n } catch (InstantiationException | IllegalAccessException e) {\n throw new RuntimeException(e);\n }\n }\n }\n}\n model = ((Class<M>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1]).newInstance();\n"
},
{
"answer_id": 29680588,
"author": "Ingo",
"author_id": 86604,
"author_profile": "https://Stackoverflow.com/users/86604",
"pm_score": 4,
"selected": false,
"text": "E createContents(Callable<E> makeone) {\n return makeone.call(); // most simple case clearly not that useful\n}\n"
},
{
"answer_id": 35315432,
"author": "Neepsnikeep",
"author_id": 5507619,
"author_profile": "https://Stackoverflow.com/users/5507619",
"pm_score": 3,
"selected": false,
"text": "public static <E> void append(List<E> list) {\n E elem = new E(); // compile-time error\n list.add(elem);\n}\n public static <E> void append(List<E> list, Class<E> cls) throws Exception {\n E elem = cls.newInstance(); // OK\n list.add(elem);\n}\n List<String> ls = new ArrayList<>();\nappend(ls, String.class);\n"
},
{
"answer_id": 36315051,
"author": "Daniel Pryden",
"author_id": 128397,
"author_profile": "https://Stackoverflow.com/users/128397",
"pm_score": 7,
"selected": false,
"text": "Supplier class SomeContainer<E> {\n private Supplier<E> supplier;\n\n SomeContainer(Supplier<E> supplier) {\n this.supplier = supplier;\n }\n\n E createContents() {\n return supplier.get();\n }\n}\n SomeContainer<String> stringContainer = new SomeContainer<>(String::new);\n String::new SomeContainer<BigInteger> bigIntegerContainer\n = new SomeContainer<>(() -> new BigInteger(1));\n"
},
{
"answer_id": 53955316,
"author": "Alexandr",
"author_id": 511804,
"author_profile": "https://Stackoverflow.com/users/511804",
"pm_score": 0,
"selected": false,
"text": "ParameterizedType.getActualTypeArguments Class.newInstance() public class TypeReference<T> {\n public Class<T> type(){\n try {\n ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();\n if (pt.getActualTypeArguments() == null || pt.getActualTypeArguments().length == 0){\n throw new IllegalStateException(\"Could not define type\");\n }\n if (pt.getActualTypeArguments().length != 1){\n throw new IllegalStateException(\"More than one type has been found\");\n }\n Type type = pt.getActualTypeArguments()[0];\n String typeAsString = type.getTypeName();\n return (Class<T>) Class.forName(typeAsString);\n\n } catch (Exception e){\n throw new IllegalStateException(\"Could not identify type\", e);\n }\n\n }\n}\n {} import java.lang.reflect.Constructor;\n\npublic class TypeReferenceTest {\n\n private static final String NAME = \"Peter\";\n\n private static class Person{\n final String name;\n\n Person(String name) {\n this.name = name;\n }\n }\n\n @Test\n public void erased() {\n TypeReference<Person> p = new TypeReference<>();\n Assert.assertNotNull(p);\n try {\n p.type();\n Assert.fail();\n } catch (Exception e){\n Assert.assertEquals(\"Could not identify type\", e.getMessage());\n }\n }\n\n @Test\n public void reified() throws Exception {\n TypeReference<Person> p = new TypeReference<Person>(){};\n Assert.assertNotNull(p);\n Assert.assertEquals(Person.class.getName(), p.type().getName());\n Constructor ctor = p.type().getDeclaredConstructor(NAME.getClass());\n Assert.assertNotNull(ctor);\n Person person = (Person) ctor.newInstance(NAME);\n Assert.assertEquals(NAME, person.name);\n }\n\n static class TypeReferencePerson extends TypeReference<Person>{}\n\n @Test\n public void reifiedExtenension() throws Exception {\n TypeReference<Person> p = new TypeReferencePerson();\n Assert.assertNotNull(p);\n Assert.assertEquals(Person.class.getName(), p.type().getName());\n Constructor ctor = p.type().getDeclaredConstructor(NAME.getClass());\n Assert.assertNotNull(ctor);\n Person person = (Person) ctor.newInstance(NAME);\n Assert.assertEquals(NAME, person.name);\n }\n}\n TypeReference {} public abstract class TypeReference<T>"
},
{
"answer_id": 54213575,
"author": "Se Song",
"author_id": 3458608,
"author_profile": "https://Stackoverflow.com/users/3458608",
"pm_score": 3,
"selected": false,
"text": "createContents private static class SomeContainer<E extends Object> {\n E e;\n E createContents() throws Exception{\n return (E) e.getClass().getDeclaredConstructor().newInstance();\n }\n}\n public class SomeContainer<E extends Object> {\n E object;\n\n void resetObject throws Exception{\n object = (E) object.getClass().getDeclaredConstructor().newInstance();\n }\n}\n"
},
{
"answer_id": 57112253,
"author": "Sudhanshu Jain",
"author_id": 6685277,
"author_profile": "https://Stackoverflow.com/users/6685277",
"pm_score": 2,
"selected": false,
"text": "private Class<E> entity; public xyzservice(Class<E> entity) {\n this.entity = entity;\n }\n\n\n\npublic E getEntity(Class<E> entity) throws InstantiationException, IllegalAccessException {\n return entity.newInstance();\n }\n"
},
{
"answer_id": 57125467,
"author": "cacheoff",
"author_id": 2549901,
"author_profile": "https://Stackoverflow.com/users/2549901",
"pm_score": 2,
"selected": false,
"text": "TypeToken<T> public class MyClass<T> {\n public T doSomething() {\n return (T) new TypeToken<T>(){}.getRawType().newInstance();\n }\n}\n"
},
{
"answer_id": 67363847,
"author": "Braian Coronel",
"author_id": 5279996,
"author_profile": "https://Stackoverflow.com/users/5279996",
"pm_score": 0,
"selected": false,
"text": " implementation(\"org.objenesis\",\"objenesis\", \"3.2\")\n val fooType = Foo::class.java\n var instance: T = try {\n fooType.newInstance()\n } catch (e: InstantiationException) {\n// Use Objenesis because the fooType class has not a default constructor\n val objenesis: Objenesis = ObjenesisStd()\n objenesis.newInstance(fooType)\n }\n"
},
{
"answer_id": 68001457,
"author": "michal.jakubeczy",
"author_id": 2470765,
"author_profile": "https://Stackoverflow.com/users/2470765",
"pm_score": 0,
"selected": false,
"text": "abstract class SomeContainer<E>\n{\n protected E createContents() {\n throw new NotImplementedException();\n }\n\n public void doWork(){\n E obj = createContents();\n // Do the work with E \n }\n}\n\nclass BlackContainer extends SomeContainer<Black>{\n // this method is optional to implement in case you need it\n protected Black createContents() {\n return new Black();\n }\n}\n E createContents"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5309/"
] |
75,180 |
<p>If you have a statically allocated array, the Visual Studio debugger can easily display all of the array elements. However, if you have an array allocated dynamically and pointed to by a pointer, it will only display the first element of the array when you click the + to expand it. Is there an easy way to tell the debugger, show me this data as an array of type Foo and size X?</p>
|
[
{
"answer_id": 75202,
"author": "shoosh",
"author_id": 9611,
"author_profile": "https://Stackoverflow.com/users/9611",
"pm_score": 9,
"selected": true,
"text": "char *a = new char[10];\n a,10\n"
},
{
"answer_id": 12477304,
"author": "wog",
"author_id": 1022328,
"author_profile": "https://Stackoverflow.com/users/1022328",
"pm_score": 0,
"selected": false,
"text": "((*((*current).Attribs)).Attrib)[26]\n ((*((*current).Attribs)).Attrib)+25\n"
},
{
"answer_id": 21000009,
"author": "dabinsi",
"author_id": 3173933,
"author_profile": "https://Stackoverflow.com/users/3173933",
"pm_score": 1,
"selected": false,
"text": " pArray.m_pData,5 \n pArray.m_pData[x].m_pData,y\n"
},
{
"answer_id": 22239703,
"author": "gpliu",
"author_id": 337863,
"author_profile": "https://Stackoverflow.com/users/337863",
"pm_score": 3,
"selected": false,
"text": "double ** a; // assume 5*10\n (double(*)[10]) a[0],5\n double[5][10] a;\n"
},
{
"answer_id": 25690207,
"author": "Riaz Rizvi",
"author_id": 213307,
"author_profile": "https://Stackoverflow.com/users/213307",
"pm_score": 5,
"selected": false,
"text": "float m4x4[16]={\n 1.f,0.f,0.f,0.f,\n 0.f,2.f,0.f,0.f,\n 0.f,0.f,3.f,0.f,\n 0.f,0.f,0.f,4.f\n};\n m4x4,16\n m4x4\n"
},
{
"answer_id": 28973224,
"author": "Taylor Price",
"author_id": 3805,
"author_profile": "https://Stackoverflow.com/users/3805",
"pm_score": 2,
"selected": false,
"text": "char *a = new char[10];\n a,su\n"
},
{
"answer_id": 31872247,
"author": "Legolas",
"author_id": 109787,
"author_profile": "https://Stackoverflow.com/users/109787",
"pm_score": 2,
"selected": false,
"text": "a,10 \na,su \n a,en (shows an enum value by name instead of the number)\na,mb (to show 1 line of 'memory' view right there in the watch window)\n"
},
{
"answer_id": 31900913,
"author": "vicky",
"author_id": 3922508,
"author_profile": "https://Stackoverflow.com/users/3922508",
"pm_score": 3,
"selected": false,
"text": "int **a; //row x col\n (int(**)[col])a,row\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9530/"
] |
75,182 |
<p>How can one detect being in a chroot jail without root privileges? Assume a standard BSD or Linux system. The best I came up with was to look at the inode value for "/" and to consider whether it is reasonably low, but I would like a more accurate method for detection.</p>
<p><code>[edit 20080916 142430 EST]</code> Simply looking around the filesystem isn't sufficient, as it's not difficult to duplicate things like /boot and /dev to fool the jailed user.</p>
<p><code>[edit 20080916 142950 EST]</code> For Linux systems, checking for unexpected values within /proc is reasonable, but what about systems that don't support /proc in the first place?</p>
|
[
{
"answer_id": 8070267,
"author": "Gilles 'SO- stop being evil'",
"author_id": 387076,
"author_profile": "https://Stackoverflow.com/users/387076",
"pm_score": 3,
"selected": false,
"text": "/proc/1/root / /proc [ \"$(stat -c %d:%i /)\" != \"$(stat -c %d:%i /proc/1/root/.)\" ]\n# With ash/bash/ksh/zsh\n! [ -x /proc/1/root/. ] || [ /proc/1/root/. -ef / ]\n /proc/1/exe init init /proc/1/mountinfo /proc/$$/mountinfo filesystems/proc.txt /proc/1/mountinfo / /proc/1/mountinfo /proc/1/mountinfo / /proc/1/mountinfo $4 [ \"$(awk '$5==\"/\" {print $1}' </proc/1/mountinfo)\" != \"$(awk '$5==\"/\" {print $1}' </proc/$$/mountinfo)\" ]\n"
},
{
"answer_id": 24245912,
"author": "Jérôme Pouiller",
"author_id": 301717,
"author_profile": "https://Stackoverflow.com/users/301717",
"pm_score": 3,
"selected": false,
"text": "stat -c %i /\n ls -id /\n stat stat -c %04D /\n mknode /tmp/root_dev b 8 1\n ls -id / sudo debugfs /tmp/root_dev -R 'ls <923960>'\n 923960 (12) . 915821 (32) .. 5636100 (12) var \n5636319 (12) lib 5636322 (12) usr 5636345 (12) tmp \n5636346 (12) sys 5636347 (12) sbin 5636348 (12) run \n5636349 (12) root 5636350 (12) proc 5636351 (12) mnt \n5636352 (12) home 5636353 (12) dev 5636354 (12) boot \n5636355 (12) bin 5636356 (12) etc 5638152 (16) selinux \n5769366 (12) srv 5769367 (12) opt 5769375 (3832) media \n .. sudo debugfs /tmp/root_dev -R 'ls <915821>'\n915821 (12) . 2 (12) .. 923960 (20) debian-jail \n923961 (4052) other-jail \n debian-jail debian-jail sudo debugfs /tmp/root_dev -R 'ls <2>'\n 2 (12) . 2 (12) .. 11 (20) lost+found 1046529 (12) home \n 130817 (12) etc 784897 (16) media 3603 (20) initrd.img \n 261633 (12) var 654081 (12) usr 392449 (12) sys 392450 (12) lib \n 784898 (12) root 915715 (12) sbin 1046530 (12) tmp \n1046531 (12) bin 784899 (12) dev 392451 (12) mnt \n 915716 (12) run 12 (12) proc 1046532 (12) boot 13 (16) lib64 \n 784945 (12) srv 915821 (12) opt 3604 (3796) vmlinuz \n opt /opt/debian-jail /dev/sda1 /proc"
},
{
"answer_id": 48844758,
"author": "Samuel Harmer",
"author_id": 594137,
"author_profile": "https://Stackoverflow.com/users/594137",
"pm_score": 2,
"selected": false,
"text": "/proc / / [root@host ~]# procstat 0\n PID PPID PGID SID TSID THR LOGIN WCHAN EMUL COMM \n 0 0 0 0 0 1234 - swapin - kernel \n[root@host ~]# echo $?\n0\n[root@host ~]# jexec guest tcsh\nroot@guest:/ # procstat 0\nprocstat: sysctl(kern.proc): No such process\nprocstat: procstat_getprocs()\nroot@guest:/ # echo $?\n1\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13277/"
] |
75,191 |
<p>In C/C++, what an <code>unsigned char</code> is used for? How is it different from a regular <code>char</code>?</p>
|
[
{
"answer_id": 75238,
"author": "Todd Gamblin",
"author_id": 9122,
"author_profile": "https://Stackoverflow.com/users/9122",
"pm_score": 7,
"selected": false,
"text": "char signed unsigned signed char unsigned char char signed char unsigned char signed char -128 127 unsigned char 0 255 char sizeof(char) 1 CHAR_BIT limits.h 8 int8_t uint8_t"
},
{
"answer_id": 75279,
"author": "James Hopkin",
"author_id": 11828,
"author_profile": "https://Stackoverflow.com/users/11828",
"pm_score": 4,
"selected": false,
"text": "signed char unsigned char char char"
},
{
"answer_id": 75327,
"author": "Zac Gochenour",
"author_id": 1812999,
"author_profile": "https://Stackoverflow.com/users/1812999",
"pm_score": 3,
"selected": false,
"text": "unsigned char char char"
},
{
"answer_id": 75334,
"author": "Julienne Walker",
"author_id": 13259,
"author_profile": "https://Stackoverflow.com/users/13259",
"pm_score": 3,
"selected": false,
"text": "CHAR_MIN CHAR_MAX CHAR_BIT char unsigned char signed char"
},
{
"answer_id": 75348,
"author": "Dark Shikari",
"author_id": 11206,
"author_profile": "https://Stackoverflow.com/users/11206",
"pm_score": 3,
"selected": false,
"text": "uint8_t int8_t uint16_t"
},
{
"answer_id": 75883,
"author": "ugasoft",
"author_id": 10120,
"author_profile": "https://Stackoverflow.com/users/10120",
"pm_score": 3,
"selected": false,
"text": "unsigned char unsigned char char char signed char unsigned char"
},
{
"answer_id": 79405,
"author": "Zachary Garrett",
"author_id": 14692,
"author_profile": "https://Stackoverflow.com/users/14692",
"pm_score": 5,
"selected": false,
"text": "unsigned char unsigned char unsigned char signed char signed char unsigned char signed char unsigned char"
},
{
"answer_id": 80376,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 3,
"selected": false,
"text": "char unsigned char"
},
{
"answer_id": 87648,
"author": "Fruny",
"author_id": 16815,
"author_profile": "https://Stackoverflow.com/users/16815",
"pm_score": 10,
"selected": true,
"text": "char signed char unsigned char char 'a' '0' int \"abcde\" signed char unsigned char sizeof (char) sizeof 1 sizeof (char) == sizeof (long) == 1"
},
{
"answer_id": 442647,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 5,
"selected": false,
"text": "unsigned char unsigned char -1 unsigned char unsigned char 6.3.1.3p2 -1 unsigned char CHAR_BIT UCHAR_MAX+1 -1 UCHAR_MAX unsigned char unsigned char c = (unsigned char)-1;\n"
},
{
"answer_id": 14456663,
"author": "munna",
"author_id": 1865289,
"author_profile": "https://Stackoverflow.com/users/1865289",
"pm_score": 3,
"selected": false,
"text": "unsigned char signed char"
},
{
"answer_id": 45228423,
"author": "ZhaoGang",
"author_id": 2830167,
"author_profile": "https://Stackoverflow.com/users/2830167",
"pm_score": 2,
"selected": false,
"text": "signed unsigned"
},
{
"answer_id": 47480841,
"author": "NL628",
"author_id": 8925851,
"author_profile": "https://Stackoverflow.com/users/8925851",
"pm_score": 2,
"selected": false,
"text": "unsigned char signed char"
},
{
"answer_id": 59587899,
"author": "Kalana",
"author_id": 11383441,
"author_profile": "https://Stackoverflow.com/users/11383441",
"pm_score": 2,
"selected": false,
"text": "signed char unsigned char Type | range\n-------------------------------\nsigned char | -128 to +127\nunsigned char | 0 to 255\n signed char char letter = 'A' ASCII/Unicode ASCII/Unicode #include <stdio.h>\n\nint main()\n{\n signed char char1 = 255;\n signed char char2 = -128;\n unsigned char char3 = 255;\n unsigned char char4 = -128;\n\n printf(\"Signed char(255) : %d\\n\",char1);\n printf(\"Unsigned char(255) : %d\\n\",char3);\n\n printf(\"\\nSigned char(-128) : %d\\n\",char2);\n printf(\"Unsigned char(-128) : %d\\n\",char4);\n\n return 0;\n}\n Signed char(255) : -1\nUnsigned char(255) : 255\n\nSigned char(-128) : -128\nUnsigned char(-128) : 128\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1785/"
] |
75,213 |
<p>In C++, what is the purpose of the scope resolution operator when used without a scope? For instance:</p>
<pre><code>::foo();
</code></pre>
|
[
{
"answer_id": 75262,
"author": "Mark",
"author_id": 4405,
"author_profile": "https://Stackoverflow.com/users/4405",
"pm_score": 7,
"selected": true,
"text": "void bar(); // this is a global function\n\nclass foo {\n void some_func() { ::bar(); } // this function is calling the global bar() and not the class version\n void bar(); // this is a class member\n};\n"
},
{
"answer_id": 75309,
"author": "Matt Price",
"author_id": 852,
"author_profile": "https://Stackoverflow.com/users/852",
"pm_score": 3,
"selected": false,
"text": "void bar() {};\nclass foo {\n void bar(int) {};\n void foobar() { bar(); } // won't compile needs ::bar()\n void foobar(int i) { bar(i); } // ok\n}\n"
},
{
"answer_id": 22085788,
"author": "Shafik Yaghmour",
"author_id": 1708801,
"author_profile": "https://Stackoverflow.com/users/1708801",
"pm_score": 4,
"selected": false,
"text": ":: 3.4.3 int count = 0;\n\nint main(void) {\n int count = 0;\n ::count = 1; // set global count to 1\n count = 2; // set local count to 2\n return 0;\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1785/"
] |
75,218 |
<p>How can I detect when an Exception has been thrown anywhere in my application?</p>
<p>I'm try to auto-magically send myself an email whenever an exception is thrown anywhere in my Java Desktop Application. I figure this way I can be more proactive.</p>
<p>I know I could just explicitly log and notify myself whenever an exception occurs, but I'd have to do it everywhere and I might(more likely will) miss a couple.</p>
<p>Any suggestions?</p>
|
[
{
"answer_id": 75298,
"author": "Mat Mannion",
"author_id": 6282,
"author_profile": "https://Stackoverflow.com/users/6282",
"pm_score": 1,
"selected": false,
"text": "<error-page>\n <error-code>500</error-code>\n <location>/error/500.htm</location>\n</error-page>\n Exception exception = (Exception) request.getAttribute(\"javax.servlet.error.exception\");\n"
},
{
"answer_id": 75302,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 0,
"selected": false,
"text": "try-catch"
},
{
"answer_id": 75439,
"author": "shemnon",
"author_id": 8020,
"author_profile": "https://Stackoverflow.com/users/8020",
"pm_score": 6,
"selected": true,
"text": "java.util.Thread.UncaughtExceptionHandler java.util.Thread.setDefaultUncaughtExceptionHandler 'sun.awt.exception.handler' Throwable class ExceptionHandler implements Thread.UncaughtExceptionHandler {\n public void uncaughtException(Thread t, Throwable e) {\n handle(e);\n }\n\n public void handle(Throwable throwable) {\n try {\n // insert your e-mail code here\n } catch (Throwable t) {\n // don't let the exception get thrown out, will cause infinite looping!\n }\n }\n\n public static void registerExceptionHandler() {\n Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());\n System.setProperty(\"sun.awt.exception.handler\", ExceptionHandler.class.getName());\n }\n}\n registerExceptionHandler"
},
{
"answer_id": 8152499,
"author": "Alex Fedulov",
"author_id": 336152,
"author_profile": "https://Stackoverflow.com/users/336152",
"pm_score": 1,
"selected": false,
"text": "log.error(\"Error's description goes here\", e); import org.apache.log4j.AppenderSkeleton;\nimport org.apache.log4j.spi.LoggingEvent;\n\npublic class ErrorsDetectingAppender extends AppenderSkeleton {\n\n private static boolean errorsOccured = false;\n\n public static boolean errorsOccured() {\n return errorsOccured;\n }\n\n public ErrorsDetectingAppender() {\n super();\n }\n\n @Override\n public void close() {\n // TODO Auto-generated method stub\n }\n\n @Override\n public boolean requiresLayout() {\n return false;\n }\n\n @Override\n protected void append(LoggingEvent event) {\n if (event.getLevel().toString().toLowerCase().equals(\"error\")) {\n System.out.println(\"-----------------Errors detected\");\n this.errorsOccured = true;\n }\n }\n}\n log4j.rootLogger = OTHER_APPENDERS, ED\nlog4j.appender.ED=com.your.package.ErrorsDetectingAppender\n"
},
{
"answer_id": 57960747,
"author": "Raedwald",
"author_id": 545127,
"author_profile": "https://Stackoverflow.com/users/545127",
"pm_score": 0,
"selected": false,
"text": "try catch"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2443/"
] |
75,230 |
<p>How do you quickly find the URL for a Win32 API on MSDN? It's easy for .NET methods -- just add the method name (for example, System.Byte.ToString) to <a href="http://msdn.microsoft.com/library/" rel="nofollow noreferrer">http://msdn.microsoft.com/library/</a>.</p>
<p>However, for Win32 APIs (say GetLongPathName), this doesn't work: <a href="http://msdn.microsoft.com/en-us/library/GetLongPathName" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/GetLongPathName</a>.</p>
<p>I want to be able to use the URL in code comments or documentation. So the URL one gets with an MSDN or Google search (for example, <a href="http://msdn.microsoft.com/library/aa364980.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/library/aa364980.aspx</a>) isn't really what I'm looking for. I'd really like my code comments to look something like:</p>
<p>// blah blah blah. See <a href="http://msdn.microsoft.com/en-us/library/GetLongPathName" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/GetLongPathName</a> for more information.</p>
<p>What's the magic pixie dust for Win32 APIs? Or does it only work for .NET methods?</p>
|
[
{
"answer_id": 1138828,
"author": "peterchen",
"author_id": 31317,
"author_profile": "https://Stackoverflow.com/users/31317",
"pm_score": 0,
"selected": false,
"text": "// see msdn:GetLongPathName\n"
},
{
"answer_id": 1138850,
"author": "Kirill V. Lyadvinsky",
"author_id": 123111,
"author_profile": "https://Stackoverflow.com/users/123111",
"pm_score": 0,
"selected": false,
"text": "Refinement=86"
},
{
"answer_id": 72611509,
"author": "Mr. Doge",
"author_id": 12772224,
"author_profile": "https://Stackoverflow.com/users/12772224",
"pm_score": 0,
"selected": false,
"text": "(I don't know how new this is) \"https://learn.microsoft.com/api/search?locale=en-us&scoringprofile=semantic-captions&%24top=1&search=\" functionName\n {\n \"results\": [\n {\n \"title\": \"KeClearEvent function (wdm.h) - Windows drivers\",\n \"url\": \"https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-keclearevent\",\n \"displayUrl\": {\n \"content\": \"/windows-hardware/drivers/ddi/wdm/nf-wdm-keclearevent\",\n \"hitHighlights\": [\n {\n \"start\": 41,\n \"length\": 12\n }\n ]\n },\n \"description\": \"The KeClearEvent routine sets an event to a not-signaled state.\",\n \"descriptions\": [\n {\n \"content\": \"KeClearEvent function (wdm.h) Article 04/18/2022 2 minutes to read In this article The KeClearEvent routine sets an event to a not-signaled state.\",\n \"hitHighlights\": [\n {\n \"start\": 0,\n \"length\": 12\n },\n {\n \"start\": 87,\n \"length\": 12\n }\n ]\n },\n {\n \"content\": \"For better performance, use KeClearEvent unless the caller uses the value returned by KeResetEvent to determine what to do next.\",\n \"hitHighlights\": [\n {\n \"start\": 28,\n \"length\": 12\n }\n ]\n }\n ],\n \"lastUpdatedDate\": \"2022-04-18T04:31:00+00:00\",\n \"breadcrumbs\": []\n }\n ],\n \"spellingCorrection\": [],\n \"scopeRemoved\": false,\n \"count\": 18,\n \"nextLink\": \"https://learn.microsoft.com/api/Search?locale=en-us\\u0026search=KeClearEvent\\u0026$skip=1\\u0026$top=1\",\n \"srcheng\": \"02\"\n}\n #SingleInstance force\nListLines 0\nKeyHistory 0\nSendMode \"Input\" ; Recommended for new scripts due to its superior speed and reliability.\nSetWorkingDir A_ScriptDir ; Ensures a consistent starting directory.\n\nlinkFromName(functionName) {\n json:=downloadToVar(\"https://learn.microsoft.com/api/search?locale=en-us&scoringprofile=semantic-captions&%24top=1&search=\" functionName)\n obj:=JSON_parse(json)\n if (obj.results.Length) {\n RegExMatch(obj.results[1].title, \".*?(?=\\s|$)\", &OutputVar)\n if (OutputVar.0 = functionName) {\n validUrl:=obj.results[1].url\n } else if (OutputVar.0 = functionName \"W\" || OutputVar.0 = functionName \"A\") {\n validUrl:=SubStr(obj.results[1].url, 1, -1) \"w\"\n }\n ; A_Clipboard:=validUrl\n Run validUrl\n }\n}\n\n; linkFromName(\"GetLongPathNameW\") ;works\n; linkFromName(\"GetLongPathName\") ;works\nlinkFromName(A_Clipboard)\n\nExitapp\n\nf3::Exitapp\n\ndownloadToVar(url) {\n whr := ComObject(\"WinHttp.WinHttpRequest.5.1\")\n whr.Open(\"GET\", url, true)\n whr.SetRequestHeader(\"User-Agent\", \"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)\")\n whr.Send()\n ; Using 'true' above and the call below allows the script to remain responsive.\n whr.WaitForResponse()\n return whr.ResponseText\n}\n\nJSON_parse(str) {\n\n c_:=1\n\n return JSON_value()\n\n JSON_value() {\n\n char_:=SubStr(str, c_, 1)\n Switch char_ {\n case \"{\":\n obj_:=Map()\n ;object\n c_++\n loop {\n skip_s()\n if (SubStr(str, c_, 1) == \"}\") {\n c_++\n return obj_\n }\n\n ; key_:=JSON_objKey()\n ; a or \"a\"\n if (SubStr(str, c_, 1) == \"`\"\") {\n RegExMatch(str, \"(?:\\\\.|.)*?(?=`\")\", &OutputVar, c_ + 1)\n key_:=RegExReplace(OutputVar.0, \"\\\\(.)\", \"$1\")\n c_+=OutputVar.Len\n } else {\n RegExMatch(str, \".*?(?=[\\s:])\", &OutputVar, c_)\n key_:=OutputVar.0\n c_+=OutputVar.Len\n }\n\n c_:=InStr(str, \":\", true, c_) + 1\n skip_s()\n\n value_:=JSON_value()\n obj_[key_]:=value_\n obj_.DefineProp(key_, {Value: value_})\n\n skip_s()\n if (SubStr(str, c_, 1) == \",\") {\n c_++, skip_s()\n }\n }\n case \"[\":\n arr_:=[]\n ;array\n c_++\n loop {\n skip_s()\n if (SubStr(str, c_, 1) == \"]\") {\n c_++\n return arr_\n }\n\n value_:=JSON_value()\n arr_.Push(value_)\n\n skip_s()\n char_:=SubStr(str, c_, 1)\n if (char_ == \",\") {\n c_++, skip_s()\n }\n }\n case \"`\"\":\n RegExMatch(str, \"(?:\\\\.|.)*?(?=`\")\", &OutputVar, c_ + 1)\n unquoted:=RegExReplace(OutputVar.0, \"\\\\(.)\", \"$1\")\n c_+=OutputVar.Len + 2\n return unquoted\n case \"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\":\n RegExMatch(str, \"[0-9.]*\", &OutputVar, c_)\n c_+=OutputVar.Len\n return Number(OutputVar.0)\n case \"t\":\n ;\"true\"\n c_+=4\n return {a:1}\n case \"f\":\n ;\"false\"\n c_+=5\n return {a:0}\n case \"n\":\n ;\"null\"\n c_+=4\n return {a:-1}\n\n\n }\n }\n\n skip_s() {\n RegExMatch(str, \"\\s*\", &OutputVar, c_)\n c_+=OutputVar.Len\n }\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2459/"
] |
75,245 |
<p>Is it possible to reach the individual columns of table2 using HQL with a configuration like this?</p>
<pre><code><hibernate-mapping>
<class table="table1">
<set name="table2" table="table2" lazy="true" cascade="all">
<key column="result_id"/>
<many-to-many column="group_id"/>
</set>
</class>
</hibernate-mapping>
</code></pre>
|
[
{
"answer_id": 75272,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 1,
"selected": false,
"text": "select t1.table2.property1, t1.table2.property2, ... from table1 as t1\n select t2.property1, t2.property2, ... \n from table1 as t1\n inner join t1.table2 as t2\n"
},
{
"answer_id": 75402,
"author": "Mike Desjardins",
"author_id": 10466,
"author_profile": "https://Stackoverflow.com/users/10466",
"pm_score": 1,
"selected": false,
"text": "select t1.table2.x from table1 as t1\n select t1 from table1 as t1 where t1.table2.x = foo\n"
},
{
"answer_id": 76181,
"author": "Michael",
"author_id": 13379,
"author_profile": "https://Stackoverflow.com/users/13379",
"pm_score": 0,
"selected": false,
"text": "color varchar(128) from table1 where table2.color = 'red'\n table1 table2 color set"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
75,255 |
<p>When you're doing a usual gdb session on an executable file on the same computer, you can give the run command and it will start the program over again.</p>
<p>When you're running gdb on an embedded system, as with the command <code>target localhost:3210</code>, how do you start the program over again without quitting and restarting your gdb session?</p>
|
[
{
"answer_id": 76727,
"author": "Drew Frezell",
"author_id": 10954,
"author_profile": "https://Stackoverflow.com/users/10954",
"pm_score": 3,
"selected": false,
"text": "jump function set $pc=address main"
},
{
"answer_id": 5200638,
"author": "pdileepa",
"author_id": 55376,
"author_profile": "https://Stackoverflow.com/users/55376",
"pm_score": 5,
"selected": true,
"text": "set remote exec-file filename"
},
{
"answer_id": 42813624,
"author": "hermannk",
"author_id": 3186936,
"author_profile": "https://Stackoverflow.com/users/3186936",
"pm_score": 2,
"selected": false,
"text": "monitor reset halt c load"
},
{
"answer_id": 44161527,
"author": "Ciro Santilli OurBigBook.com",
"author_id": 895245,
"author_profile": "https://Stackoverflow.com/users/895245",
"pm_score": 2,
"selected": false,
"text": "# pwd contains cross-compiled ./myexec\ngdbserver --multi :1234\n # pwd also contains the same cross-compiled ./myexec\ngdb -ex 'target extended-remote 192.168.0.1:1234' \\\n -ex 'set remote exec-file ./myexec' \\\n --args ./myexec arg1 arg2\n(gdb) r\n[Inferior 1 (process 1234) exited normally]\n(gdb) r\n[Inferior 1 (process 1235) exited normally]\n(gdb) monitor exit\n gdbserver --multi :1234 ./myexec arg1 arg2\n ./myexec set remote exec-file ./myexec show args"
},
{
"answer_id": 44786145,
"author": "Steven Eckhoff",
"author_id": 2511892,
"author_profile": "https://Stackoverflow.com/users/2511892",
"pm_score": 0,
"selected": false,
"text": "(gdb) mon reset 0\n(gdb) continue\n(gdb) continue\n"
},
{
"answer_id": 67924905,
"author": "abhiarora",
"author_id": 5735010,
"author_profile": "https://Stackoverflow.com/users/5735010",
"pm_score": 1,
"selected": false,
"text": "jump startup startup script .section .text.Reset_Handler\n .weak Reset_Handler\n .type Reset_Handler, %function\nReset_Handler: \n ldr r0, =_estack\n mov sp, r0 /* set stack pointer */\n jump Reset_Handler\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11138/"
] |
75,261 |
<p>I got this output when running <code>sudo cpan Scalar::Util::Numeric</code></p>
<pre>
jmm@freekbox:~/bfwsandbox/sa/angel/astroportal/dtu8e/resources$ sudo cpan Scalar::Util::Numeric
[sudo] password for jmm:
CPAN: Storable loaded ok
Going to read /home/jmm/.cpan/Metadata
Database was generated on Tue, 09 Sep 2008 16:02:51 GMT
CPAN: LWP::UserAgent loaded ok
Fetching with LWP:
ftp://ftp.perl.org/pub/CPAN/authors/01mailrc.txt.gz
Going to read /home/jmm/.cpan/sources/authors/01mailrc.txt.gz
Fetching with LWP:
ftp://ftp.perl.org/pub/CPAN/modules/02packages.details.txt.gz
Going to read /home/jmm/.cpan/sources/modules/02packages.details.txt.gz
Database was generated on Tue, 16 Sep 2008 16:02:50 GMT
There's a new CPAN.pm version (v1.9205) available!
[Current version is v1.7602]
You might want to try
install Bundle::CPAN
reload cpan
without quitting the current session. It should be a seamless upgrade
while we are running...
Fetching with LWP:
ftp://ftp.perl.org/pub/CPAN/modules/03modlist.data.gz
Going to read /home/jmm/.cpan/sources/modules/03modlist.data.gz
Going to write /home/jmm/.cpan/Metadata
Running install for module Scalar::Util::Numeric
Running make for C/CH/CHOCOLATE/Scalar-Util-Numeric-0.02.tar.gz
CPAN: Digest::MD5 loaded ok
Checksum for /home/jmm/.cpan/sources/authors/id/C/CH/CHOCOLATE/Scalar-Util-Numeric-0.02.tar.gz ok
Scanning cache /home/jmm/.cpan/build for sizes
Scalar-Util-Numeric-0.02/
Scalar-Util-Numeric-0.02/Changes
Scalar-Util-Numeric-0.02/lib/
Scalar-Util-Numeric-0.02/lib/Scalar/
Scalar-Util-Numeric-0.02/lib/Scalar/Util/
Scalar-Util-Numeric-0.02/lib/Scalar/Util/Numeric.pm
Scalar-Util-Numeric-0.02/Makefile.PL
Scalar-Util-Numeric-0.02/MANIFEST
Scalar-Util-Numeric-0.02/META.yml
Scalar-Util-Numeric-0.02/Numeric.xs
Scalar-Util-Numeric-0.02/ppport.h
Scalar-Util-Numeric-0.02/README
Scalar-Util-Numeric-0.02/t/
Scalar-Util-Numeric-0.02/t/pod.t
Scalar-Util-Numeric-0.02/t/Scalar-Util-Numeric.t
Removing previously used /home/jmm/.cpan/build/Scalar-Util-Numeric-0.02
CPAN.pm: Going to build C/CH/CHOCOLATE/Scalar-Util-Numeric-0.02.tar.gz
Checking if your kit is complete...
Looks good
Writing Makefile for Scalar::Util::Numeric
cp lib/Scalar/Util/Numeric.pm blib/lib/Scalar/Util/Numeric.pm
AutoSplitting blib/lib/Scalar/Util/Numeric.pm (blib/lib/auto/Scalar/Util/Numeric)
/usr/bin/perl /usr/share/perl/5.8/ExtUtils/xsubpp -typemap /usr/share/perl/5.8/ExtUtils/typemap Numeric.xs > Numeric.xsc && mv Numeric.xsc Numeric.c
cc -c -D_REENTRANT -D_GNU_SOURCE -DTHREADS_HAVE_PIDS -DDEBIAN -fno-strict-aliasing -pipe -I/usr/local/include -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -O3 -DVERSION=\"0.02\" -DXS_VERSION=\"0.02\" -fPIC "-I/usr/lib/perl/5.8/CORE" Numeric.c
In file included from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/perl.h:420:24: error: sys/types.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:451:19: error: ctype.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:463:23: error: locale.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:480:20: error: setjmp.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:486:26: error: sys/param.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:491:23: error: stdlib.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:496:23: error: unistd.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:776:23: error: string.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:925:27: error: netinet/in.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:929:26: error: arpa/inet.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:939:25: error: sys/stat.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:961:21: error: time.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:968:25: error: sys/time.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:975:27: error: sys/times.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:982:19: error: errno.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:997:25: error: sys/socket.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:1024:21: error: netdb.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:1127:24: error: sys/ioctl.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:1156:23: error: dirent.h: No such file or directory
In file included from /usr/lib/gcc/i486-linux-gnu/4.2.3/include/syslimits.h:7,
from /usr/lib/gcc/i486-linux-gnu/4.2.3/include/limits.h:11,
from /usr/lib/perl/5.8/CORE/perl.h:1510,
from Numeric.xs:2:
/usr/lib/gcc/i486-linux-gnu/4.2.3/include/limits.h:122:61: error: limits.h: No such file or directory
In file included from /usr/lib/perl/5.8/CORE/perl.h:2120,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/handy.h:136:25: error: inttypes.h: No such file or directory
In file included from /usr/lib/perl/5.8/CORE/perl.h:2284,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/unixish.h:106:21: error: signal.h: No such file or directory
In file included from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/perl.h:2421:33: error: pthread.h: No such file or directory
In file included from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/perl.h:2423: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘perl_os_thread’
/usr/lib/perl/5.8/CORE/perl.h:2424: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘perl_mutex’
/usr/lib/perl/5.8/CORE/perl.h:2425: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘perl_cond’
/usr/lib/perl/5.8/CORE/perl.h:2426: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘perl_key’
In file included from /usr/lib/perl/5.8/CORE/iperlsys.h:51,
from /usr/lib/perl/5.8/CORE/perl.h:2733,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/perlio.h:65:19: error: stdio.h: No such file or directory
In file included from /usr/lib/perl/5.8/CORE/iperlsys.h:51,
from /usr/lib/perl/5.8/CORE/perl.h:2733,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/perlio.h:259: error: expected ‘)’ before ‘*’ token
/usr/lib/perl/5.8/CORE/perlio.h:262: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
/usr/lib/perl/5.8/CORE/perlio.h:265: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
/usr/lib/perl/5.8/CORE/perlio.h:268: error: expected declaration specifiers or ‘...’ before ‘FILE’
In file included from /usr/lib/perl/5.8/CORE/perl.h:2747,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/sv.h:389: error: expected specifier-qualifier-list before ‘DIR’
In file included from /usr/lib/perl/5.8/CORE/op.h:497,
from /usr/lib/perl/5.8/CORE/perl.h:2754,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/reentr.h:72:20: error: pwd.h: No such file or directory
/usr/lib/perl/5.8/CORE/reentr.h:75:20: error: grp.h: No such file or directory
/usr/lib/perl/5.8/CORE/reentr.h:85:26: error: crypt.h: No such file or directory
/usr/lib/perl/5.8/CORE/reentr.h:90:27: error: shadow.h: No such file or directory
In file included from /usr/lib/perl/5.8/CORE/op.h:497,
from /usr/lib/perl/5.8/CORE/perl.h:2754,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/reentr.h:612: error: field ‘_crypt_struct’ has incomplete type
/usr/lib/perl/5.8/CORE/reentr.h:620: error: field ‘_drand48_struct’ has incomplete type
/usr/lib/perl/5.8/CORE/reentr.h:624: error: field ‘_grent_struct’ has incomplete type
/usr/lib/perl/5.8/CORE/reentr.h:635: error: field ‘_hostent_struct’ has incomplete type
/usr/lib/perl/5.8/CORE/reentr.h:654: error: field ‘_netent_struct’ has incomplete type
/usr/lib/perl/5.8/CORE/reentr.h:669: error: field ‘_protoent_struct’ has incomplete type
/usr/lib/perl/5.8/CORE/reentr.h:684: error: field ‘_pwent_struct’ has incomplete type
/usr/lib/perl/5.8/CORE/reentr.h:695: error: field ‘_servent_struct’ has incomplete type
/usr/lib/perl/5.8/CORE/reentr.h:710: error: field ‘_spent_struct’ has incomplete type
/usr/lib/perl/5.8/CORE/reentr.h:721: error: field ‘_gmtime_struct’ has incomplete type
/usr/lib/perl/5.8/CORE/reentr.h:724: error: field ‘_localtime_struct’ has incomplete type
/usr/lib/perl/5.8/CORE/reentr.h:771: error: field ‘_random_struct’ has incomplete type
/usr/lib/perl/5.8/CORE/reentr.h:772: error: expected specifier-qualifier-list before ‘int32_t’
In file included from /usr/lib/perl/5.8/CORE/perl.h:2756,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/av.h:13: error: expected specifier-qualifier-list before ‘ssize_t’
In file included from /usr/lib/perl/5.8/CORE/perl.h:2759,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/scope.h:232: error: expected specifier-qualifier-list before ‘sigjmp_buf’
In file included from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/perl.h:2931: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘getuid’
/usr/lib/perl/5.8/CORE/perl.h:2932: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘geteuid’
/usr/lib/perl/5.8/CORE/perl.h:2933: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘getgid’
/usr/lib/perl/5.8/CORE/perl.h:2934: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘getegid’
In file included from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/perl.h:3238:22: error: math.h: No such file or directory
In file included from /usr/lib/perl/5.8/CORE/perl.h:3881,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/thrdvar.h:85: error: field ‘Tstatbuf’ has incomplete type
/usr/lib/perl/5.8/CORE/thrdvar.h:86: error: field ‘Tstatcache’ has incomplete type
/usr/lib/perl/5.8/CORE/thrdvar.h:91: error: field ‘Ttimesbuf’ has incomplete type
In file included from /usr/lib/perl/5.8/CORE/perl.h:3883,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/intrpvar.h:66: error: expected specifier-qualifier-list before ‘time_t’
In file included from /usr/lib/perl/5.8/CORE/perl.h:3950,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/proto.h:128: error: expected declaration specifiers or ‘...’ before ‘mode_t’
/usr/lib/perl/5.8/CORE/proto.h:128: error: expected declaration specifiers or ‘...’ before ‘uid_t’
/usr/lib/perl/5.8/CORE/proto.h:297: error: expected declaration specifiers or ‘...’ before ‘off64_t’
/usr/lib/perl/5.8/CORE/proto.h:299: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_do_sysseek’
/usr/lib/perl/5.8/CORE/proto.h:300: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_do_tell’
/usr/lib/perl/5.8/CORE/proto.h:411: error: expected declaration specifiers or ‘...’ before ‘gid_t’
/usr/lib/perl/5.8/CORE/proto.h:411: error: expected declaration specifiers or ‘...’ before ‘uid_t’
/usr/lib/perl/5.8/CORE/proto.h:736: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_my_fork’
/usr/lib/perl/5.8/CORE/proto.h:1020: error: expected declaration specifiers or ‘...’ before ‘pid_t’
/usr/lib/perl/5.8/CORE/proto.h:1300: error: expected declaration specifiers or ‘...’ before ‘pid_t’
/usr/lib/perl/5.8/CORE/proto.h:1456: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
/usr/lib/perl/5.8/CORE/proto.h:2001: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_PerlIO_read’
/usr/lib/perl/5.8/CORE/proto.h:2002: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_PerlIO_write’
/usr/lib/perl/5.8/CORE/proto.h:2003: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_PerlIO_unread’
/usr/lib/perl/5.8/CORE/proto.h:2004: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_PerlIO_tell’
/usr/lib/perl/5.8/CORE/proto.h:2005: error: expected declaration specifiers or ‘...’ before ‘off64_t’
In file included from /usr/lib/perl/5.8/CORE/perl.h:3988,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/perlvars.h:31: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘PL_thr_key’
/usr/lib/perl/5.8/CORE/perlvars.h:48: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘PL_op_mutex’
/usr/lib/perl/5.8/CORE/perlvars.h:52: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘PL_dollarzero_mutex’
/usr/lib/perl/5.8/CORE/perl.h:4485:24: error: sys/ipc.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:4486:24: error: sys/sem.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:4611:24: error: sys/file.h: No such file or directory
In file included from /usr/lib/perl/5.8/CORE/perlapi.h:38,
from /usr/lib/perl/5.8/CORE/XSUB.h:349,
from Numeric.xs:3:
/usr/lib/perl/5.8/CORE/intrpvar.h:66: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
/usr/lib/perl/5.8/CORE/intrpvar.h:237: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
/usr/lib/perl/5.8/CORE/intrpvar.h:238: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
/usr/lib/perl/5.8/CORE/intrpvar.h:239: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
/usr/lib/perl/5.8/CORE/intrpvar.h:240: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
In file included from /usr/lib/perl/5.8/CORE/perlapi.h:39,
from /usr/lib/perl/5.8/CORE/XSUB.h:349,
from Numeric.xs:3:
/usr/lib/perl/5.8/CORE/perlvars.h:31: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
/usr/lib/perl/5.8/CORE/perlvars.h:48: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
/usr/lib/perl/5.8/CORE/perlvars.h:52: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
In file included from Numeric.xs:4:
ppport.h:3042:1: warning: "PERL_UNUSED_DECL" redefined
In file included from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/perl.h:163:1: warning: this is the location of the previous definition
Numeric.c: In function ‘XS_Scalar__Util__Numeric_is_num’:
Numeric.c:20: error: invalid type argument of ‘unary *’
Numeric.c:20: error: invalid type argument of ‘unary *’
Numeric.c:20: error: invalid type argument of ‘unary *’
Numeric.c:22: error: invalid type argument of ‘unary *’
Numeric.c:24: error: invalid type argument of ‘unary *’
Numeric.xs:16: error: invalid type argument of ‘unary *’
Numeric.xs:17: error: invalid type argument of ‘unary *’
Numeric.xs:20: error: invalid type argument of ‘unary *’
Numeric.xs:20: error: invalid type argument of ‘unary *’
Numeric.xs:20: error: invalid type argument of ‘unary *’
Numeric.xs:20: error: invalid type argument of ‘unary *’
Numeric.xs:20: error: invalid type argument of ‘unary *’
Numeric.c:36: error: invalid type argument of ‘unary *’
Numeric.c:36: error: invalid type argument of ‘unary *’
Numeric.c: In function ‘XS_Scalar__Util__Numeric_uvmax’:
Numeric.c:43: error: invalid type argument of ‘unary *’
Numeric.c:43: error: invalid type argument of ‘unary *’
Numeric.c:43: error: invalid type argument of ‘unary *’
Numeric.c:45: error: invalid type argument of ‘unary *’
Numeric.xs:26: error: invalid type argument of ‘unary *’
Numeric.xs:26: error: invalid type argument of ‘unary *’
Numeric.xs:26: error: invalid type argument of ‘unary *’
Numeric.xs:26: error: invalid type argument of ‘unary *’
Numeric.xs:26: error: invalid type argument of ‘unary *’
Numeric.c:51: error: invalid type argument of ‘unary *’
Numeric.c:51: error: invalid type argument of ‘unary *’
Numeric.c: In function ‘boot_Scalar__Util__Numeric’:
Numeric.c:60: error: invalid type argument of ‘unary *’
Numeric.c:60: error: invalid type argument of ‘unary *’
Numeric.c:60: error: invalid type argument of ‘unary *’
Numeric.c:63: error: invalid type argument of ‘unary *’
Numeric.c:63: error: invalid type argument of ‘unary *’
Numeric.c:63: error: invalid type argument of ‘unary *’
Numeric.c:63: error: invalid type argument of ‘unary *’
Numeric.c:63: error: invalid type argument of ‘unary *’
Numeric.c:63: error: invalid type argument of ‘unary *’
Numeric.c:63: error: invalid type argument of ‘unary *’
Numeric.c:63: error: invalid type argument of ‘unary *’
Numeric.c:63: error: invalid type argument of ‘unary *’
Numeric.c:63: error: invalid type argument of ‘unary *’
Numeric.c:63: error: invalid type argument of ‘unary *’
Numeric.c:65: error: invalid type argument of ‘unary *’
Numeric.c:65: error: invalid type argument of ‘unary *’
Numeric.c:66: error: invalid type argument of ‘unary *’
Numeric.c:66: error: invalid type argument of ‘unary *’
Numeric.c:67: error: invalid type argument of ‘unary *’
Numeric.c:67: error: invalid type argument of ‘unary *’
Numeric.c:67: error: invalid type argument of ‘unary *’
Numeric.c:67: error: invalid type argument of ‘unary *’
make: *** [Numeric.o] Error 1
/usr/bin/make -- NOT OK
Running make test
Can't test without successful make
Running make install
make had returned bad status, install seems impossible
jmm@freekbox:~/bfwsandbox/sa/angel/astroportal/dtu8e/resources$
</pre>
|
[
{
"answer_id": 75399,
"author": "Mark Grimes",
"author_id": 13233,
"author_profile": "https://Stackoverflow.com/users/13233",
"pm_score": 2,
"selected": false,
"text": "sys/types.h"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
75,267 |
<p>In how many languages is Null not equal to anything not even Null?</p>
|
[
{
"answer_id": 75278,
"author": "Josh Bush",
"author_id": 1672,
"author_profile": "https://Stackoverflow.com/users/1672",
"pm_score": 2,
"selected": false,
"text": "SELECT * FROM dual WHERE NULL=null; --no rows returned\n"
},
{
"answer_id": 75472,
"author": "AShelly",
"author_id": 10396,
"author_profile": "https://Stackoverflow.com/users/10396",
"pm_score": 2,
"selected": false,
"text": "class Null\n def self.==(other);false;end\nend\nn=Null\nprint \"Null equals nothing\" if n!=Null\n"
},
{
"answer_id": 137965,
"author": "Hugh Allen",
"author_id": 15069,
"author_profile": "https://Stackoverflow.com/users/15069",
"pm_score": 2,
"selected": false,
"text": "Null = Null Null True If ... Then False Null <> Null Null Null IsNull() Nothing Nothing = Nothing is Missing Missing = Missing IsMissing(foo) Empty IsEmpty()"
},
{
"answer_id": 1805207,
"author": "Stephane Grenier",
"author_id": 39371,
"author_profile": "https://Stackoverflow.com/users/39371",
"pm_score": 0,
"selected": false,
"text": "WHERE column is NULL\n WHERE column = NULL\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6178/"
] |
75,270 |
<p>Does anyone know of a good open source plugin for database querying and exploring within Eclipse? </p>
<p>The active Database Exploring plugin within Eclipse is really geared around being associated with a Java project. While I am just trying to run ad-hoc queries and explore the schema. I am effectively looking for a just a common, quick querying tool without the overhead of having to create a code project. I have found a couple open source database plugins for Eclipse but these have not seen active development in over a year.</p>
<p>Any suggestions?</p>
|
[
{
"answer_id": 75278,
"author": "Josh Bush",
"author_id": 1672,
"author_profile": "https://Stackoverflow.com/users/1672",
"pm_score": 2,
"selected": false,
"text": "SELECT * FROM dual WHERE NULL=null; --no rows returned\n"
},
{
"answer_id": 75472,
"author": "AShelly",
"author_id": 10396,
"author_profile": "https://Stackoverflow.com/users/10396",
"pm_score": 2,
"selected": false,
"text": "class Null\n def self.==(other);false;end\nend\nn=Null\nprint \"Null equals nothing\" if n!=Null\n"
},
{
"answer_id": 137965,
"author": "Hugh Allen",
"author_id": 15069,
"author_profile": "https://Stackoverflow.com/users/15069",
"pm_score": 2,
"selected": false,
"text": "Null = Null Null True If ... Then False Null <> Null Null Null IsNull() Nothing Nothing = Nothing is Missing Missing = Missing IsMissing(foo) Empty IsEmpty()"
},
{
"answer_id": 1805207,
"author": "Stephane Grenier",
"author_id": 39371,
"author_profile": "https://Stackoverflow.com/users/39371",
"pm_score": 0,
"selected": false,
"text": "WHERE column is NULL\n WHERE column = NULL\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12600/"
] |
75,273 |
<p>I'm in an <strong>ASP.NET UserControl</strong>. When I type Control-K, Control-D to reformat all the markup, I get a series of messages from VS 2008:</p>
<p>"Could not reformat the document. The original format was restored."</p>
<p>"Could not complete the action."</p>
<p>"The operation could not be completed. The parameter is incorrect."</p>
<p>Anybody know what causes this?</p>
<p><strong>Edit</strong>: OK, that is just...weird.</p>
<p>The problem is here:</p>
<pre><code><asp:TableCell>
<asp:Button Text="Cancel" runat="server" ID="lnkCancel" CssClass="CellSingleItem" />
</asp:TableCell>
</code></pre>
<p>Somehow that asp:Button line is causing the problem. But if I delete any individual attribute, the formatting works. Or if I add a new attribute, the formatting works. Or if I change the tag to be non-self-closing, it works. But if I undo and leave it as-is, it doesn't work.</p>
<p>All I can figure is that this is some sort of really obscure, bizarre bug.</p>
|
[
{
"answer_id": 75308,
"author": "palehorse",
"author_id": 312,
"author_profile": "https://Stackoverflow.com/users/312",
"pm_score": 2,
"selected": false,
"text": "<div><h1>My Title</div></h1\n"
},
{
"answer_id": 41345298,
"author": "ViVi",
"author_id": 5621607,
"author_profile": "https://Stackoverflow.com/users/5621607",
"pm_score": 0,
"selected": false,
"text": "html , \""
},
{
"answer_id": 48592288,
"author": "Sterling Diaz",
"author_id": 1228807,
"author_profile": "https://Stackoverflow.com/users/1228807",
"pm_score": 2,
"selected": false,
"text": "\""
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5486/"
] |
75,282 |
<p>I'm handling the <code>onSelectIndexChanged</code> event. An event is raised when the DropDownList selection changes. the problem is that the DropDownList still returns the old values for <code>SelectedValue</code> and <code>SelectedIndex</code>. What am I doing wrong?</p>
<p>Here is the DropDownList definition from the aspx file:</p>
<pre><code><div style="margin: 0px; padding: 0px 1em 0px 0px;">
<span style="margin: 0px; padding: 0px; vertical-align: top;">Route:</span>
<asp:DropDownList id="Select1" runat="server" onselectedindexchanged="index_changed" AutoPostBack="true">
</asp:DropDownList>
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
</div>
</code></pre>
<p>Here is the DropDownList <code>OnSelectedIndexChanged</code> event handler:</p>
<pre><code>protected void index_changed(object sender, EventArgs e)
{
decimal d = Convert.ToDecimal( Select1.SelectedValue );
Literal1.Text = d.ToString();
}
</code></pre>
|
[
{
"answer_id": 75437,
"author": "axk",
"author_id": 578,
"author_profile": "https://Stackoverflow.com/users/578",
"pm_score": 2,
"selected": false,
"text": "if(!IsPostback) d.SelectedValue = \"Default\"\n"
},
{
"answer_id": 75827,
"author": "Jason Stevenson",
"author_id": 13368,
"author_profile": "https://Stackoverflow.com/users/13368",
"pm_score": 2,
"selected": false,
"text": " if (!IsCallback && !IsPostBack)\n {\n // Do your page setup here\n }\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4491/"
] |
75,322 |
<p>I have an ASP.Net/AJAX control kit project that i am working on. 80% of the time there is no problem. The page runs as it should. If you refresh the page it will sometimes show a javascript error "Sys is undefined".</p>
<p>It doesn't happen all the time, but it is reproducible. When it happens, the user has to shut down their browser and reopen the page.</p>
<p>This leads me to believe that it could be an IIS setting.</p>
<p>Another note. I looked at the page source both when I get the error, and when not. When the page throws errors the following code is missing:</p>
<pre><code><script src="/ScriptResource.axd?d=EAvfjPfYejDh0Z2Zq5zTR_TXqL0DgVcj_h1wz8cst6uXazNiprV1LnAGq3uL8N2vRbpXu46VsAMFGSgpfovx9_cO8tpy2so6Qm_0HXVGg_Y1&amp;t=baeb8cc" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
if (typeof(Sys) === 'undefined') throw new Error('ASP.NET Ajax client-side framework failed to load.');
//]]>
</script>
</code></pre>
|
[
{
"answer_id": 75460,
"author": "Compulsion",
"author_id": 3675,
"author_profile": "https://Stackoverflow.com/users/3675",
"pm_score": 3,
"selected": false,
"text": "<asp:ScriptManager ID=\"ScriptManager1\" runat=\"server\" EnablePartialRendering=\"true\" /> \n"
},
{
"answer_id": 200316,
"author": "Tom Carter",
"author_id": 2839,
"author_profile": "https://Stackoverflow.com/users/2839",
"pm_score": 2,
"selected": false,
"text": "if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();\n"
},
{
"answer_id": 538200,
"author": "MadMax1138",
"author_id": 65187,
"author_profile": "https://Stackoverflow.com/users/65187",
"pm_score": 2,
"selected": false,
"text": "<compilation debug=\"true\"> <compilation debug=\"false\"> <xhtmlConformance mode=\"Legacy\"/>"
},
{
"answer_id": 1718513,
"author": "Dean L",
"author_id": 127887,
"author_profile": "https://Stackoverflow.com/users/127887",
"pm_score": 6,
"selected": false,
"text": "<script type=\"text/javascript\"></script> <asp:Content/> <asp:Content/>"
},
{
"answer_id": 2563888,
"author": "Ray",
"author_id": 4872,
"author_profile": "https://Stackoverflow.com/users/4872",
"pm_score": 4,
"selected": false,
"text": "<system.web> <httpHandlers>\n <remove verb=\"*\" path=\"*.asmx\"/>\n <add verb=\"*\" path=\"*.asmx\" validate=\"false\" type=\"System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n <add verb=\"GET\" path=\"ScriptResource.axd\" type=\"System.Web.Handlers.ScriptResourceHandler\" validate=\"false\"/>\n</httpHandlers>\n"
},
{
"answer_id": 3757770,
"author": "Anish",
"author_id": 453539,
"author_profile": "https://Stackoverflow.com/users/453539",
"pm_score": -1,
"selected": false,
"text": " <!--<add verb=\"*\" path=\"*.asmx\" validate=\"false\" type=\"Microsoft.Web.Script.Services.ScriptHandlerFactory, Microsoft.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" />\n <add verb=\"GET\" path=\"ScriptResource.axd\" type=\"Microsoft.Web.Handlers.ScriptResourceHandler\" validate=\"false\" />-->\n <add verb=\"*\" path=\"*.asmx\" validate=\"false\" type=\"System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n <add verb=\"GET\" path=\"ScriptResource.axd\" type=\"System.Web.Handlers.ScriptResourceHandler\" validate=\"false\"/>\n"
},
{
"answer_id": 4260550,
"author": "Alcides Martínez",
"author_id": 518003,
"author_profile": "https://Stackoverflow.com/users/518003",
"pm_score": 3,
"selected": false,
"text": "<httpHandlers>\n <remove verb=\"*\" path=\"*.asmx\"/>\n <add verb=\"*\" path=\"*.asmx\" validate=\"false\" type=\"System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n <add verb=\"*\" path=\"*_AppService.axd\" validate=\"false\" type=\"System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n <add verb=\"GET,HEAD\" path=\"ScriptResource.axd\" type=\"System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" validate=\"false\"/>\n</httpHandlers>\n<httpModules>\n <add name=\"ScriptModule\" type=\"System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n</httpModules>\n</system.web>\n"
},
{
"answer_id": 6020313,
"author": "JonK",
"author_id": 755955,
"author_profile": "https://Stackoverflow.com/users/755955",
"pm_score": 0,
"selected": false,
"text": "<rewrite> <outboundRules> <preConditions>\n <preCondition name=\"IsHTML\">\n <add input=\"{RESPONSE_CONTENT_TYPE}\" pattern=\"^text/html\"/>\n </preCondition>\n</preConditions>\n <rule preCondition=\"IsHTML\" name=\"MyOutboundRule\">\n"
},
{
"answer_id": 6291807,
"author": "Zara_me",
"author_id": 121336,
"author_profile": "https://Stackoverflow.com/users/121336",
"pm_score": 1,
"selected": false,
"text": " <configuration>\n<configSections>\n <sectionGroup name=\"system.web.extensions\" type=\"System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\">\n <sectionGroup name=\"scripting\" type=\"System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\">\n <section name=\"scriptResourceHandler\" type=\"System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" requirePermission=\"false\" allowDefinition=\"MachineToApplication\"/>\n</sectionGroup>\n\n </sectionGroup>\n</configSections>\n <assemblies>\n\n <add assembly=\"System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n\n </assemblies>\n </compilation>\n <httpHandlers>\n <remove verb=\"*\" path=\"*.asmx\"/>\n <add verb=\"*\" path=\"*.asmx\" validate=\"false\" type=\"System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n <add verb=\"*\" path=\"*_AppService.axd\" validate=\"false\" type=\"System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n <add verb=\"GET,HEAD\" path=\"ScriptResource.axd\" type=\"System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" validate=\"false\"/>\n </httpHandlers>\n <httpModules>\n <add name=\"ScriptModule\" type=\"System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n </httpModules>\n</system.web>\n <system.webServer>\n <validation validateIntegratedModeConfiguration=\"false\"/>\n <modules>\n <add name=\"ScriptModule\" preCondition=\"integratedMode\" type=\"System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n </modules>\n <handlers>\n <remove name=\"WebServiceHandlerFactory-Integrated\"/>\n <add name=\"ScriptHandlerFactory\" verb=\"*\" path=\"*.asmx\" preCondition=\"integratedMode\" type=\"System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n <add name=\"ScriptHandlerFactoryAppServices\" verb=\"*\" path=\"*_AppService.axd\" preCondition=\"integratedMode\" type=\"System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n <add name=\"ScriptResource\" preCondition=\"integratedMode\" verb=\"GET,HEAD\" path=\"ScriptResource.axd\" type=\"System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n </handlers>\n</system.webServer>\n"
},
{
"answer_id": 9350258,
"author": "Zviadi",
"author_id": 299203,
"author_profile": "https://Stackoverflow.com/users/299203",
"pm_score": 3,
"selected": false,
"text": "<location path=\"Telerik.Web.UI.WebResource.axd\"> \n <system.web> \n <authorization> \n <allow users=\"*\"/> \n </authorization> \n </system.web> \n</location>\n"
},
{
"answer_id": 9442728,
"author": "v s",
"author_id": 1023156,
"author_profile": "https://Stackoverflow.com/users/1023156",
"pm_score": 0,
"selected": false,
"text": "<compilation debug=\"true\">\n <httpHandlers>\n <remove verb=\"*\" path=\"*.asmx\"/>\n <add verb=\"*\" path=\"*.asmx\" validate=\"false\" type=\"System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n <add verb=\"*\" path=\"*_AppService.axd\" validate=\"false\" type=\"System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n <add verb=\"GET,HEAD\" path=\"ScriptResource.axd\" type=\"System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" validate=\"false\"/>\n</httpHandlers>\n<httpModules>\n <add name=\"ScriptModule\" type=\"System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n</httpModules>\n</system.web>\n"
},
{
"answer_id": 13631823,
"author": "GoldBishop",
"author_id": 659246,
"author_profile": "https://Stackoverflow.com/users/659246",
"pm_score": 0,
"selected": false,
"text": "web.config Sys is undefined rts.Ignore(\"{resource}.axd/{*pathInfo}\") 'Ignores any Resource cache references, used heavily in AJAX interactions.\n"
},
{
"answer_id": 16109767,
"author": "RacerNerd",
"author_id": 1634605,
"author_profile": "https://Stackoverflow.com/users/1634605",
"pm_score": 0,
"selected": false,
"text": "<system.webServer>\n <handlers>\n <clear />\n <add name=\"ScriptResource\" preCondition=\"integratedMode\" verb=\"GET,HEAD\" path=\"ScriptResource.axd\" type=\"System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" />\n <!-- Make sure wildcard rules are below the ScriptResource tag -->\n </handlers>\n <modules>\n <add name=\"ScriptModule\" type=\"System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n <!-- Other modules are added here -->\n </modules>\n </system.webServer>\n"
},
{
"answer_id": 17256975,
"author": "goodeye",
"author_id": 292060,
"author_profile": "https://Stackoverflow.com/users/292060",
"pm_score": 3,
"selected": false,
"text": "$(document).ready(function () {\n Sys. calls here\n});\n"
},
{
"answer_id": 18301056,
"author": "Farschidus",
"author_id": 1379217,
"author_profile": "https://Stackoverflow.com/users/1379217",
"pm_score": 1,
"selected": false,
"text": "<asp:ScriptManager> <ajaxtoolkit:ToolkitScriptManager>"
},
{
"answer_id": 28965519,
"author": "onlyme",
"author_id": 3954673,
"author_profile": "https://Stackoverflow.com/users/3954673",
"pm_score": 0,
"selected": false,
"text": "<script></script> and not <script />.\n"
},
{
"answer_id": 30093900,
"author": "Jawad Siddiqui",
"author_id": 1085016,
"author_profile": "https://Stackoverflow.com/users/1085016",
"pm_score": 0,
"selected": false,
"text": "if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded(); \n"
},
{
"answer_id": 32057625,
"author": "Alexandre N.",
"author_id": 1398758,
"author_profile": "https://Stackoverflow.com/users/1398758",
"pm_score": 3,
"selected": false,
"text": "<system.web.extensions>\n<scripting>\n<scriptResourceHandler enableCompression=\"false\" enableCaching=\"true\" />\n</scripting>\n</system.web.extensions>\n <script src=\"/MyWebApp/ScriptResource.axd?[snip - long query string]\" type=\"text/javascript\"></script>\n <system.webServer/><handlers/> <add name=\"ScriptResource\" preCondition=\"integratedMode\" verb=\"GET,HEAD\" path=\"ScriptResource.axd\" type=\"System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" />\n <system.web/><httpHandlers/>"
},
{
"answer_id": 37473809,
"author": "hsobhy",
"author_id": 1030977,
"author_profile": "https://Stackoverflow.com/users/1030977",
"pm_score": 0,
"selected": false,
"text": "routes.MapPageRoute(\"siteDefault\", \"{culture}/\", \"~/default.aspx\", false, new RouteValueDictionary(new { culture = \"(\\\\w{2})|(\\\\w{2}-\\\\w{2})\" }));\n"
},
{
"answer_id": 39619160,
"author": "Fernando Meneses Gomes",
"author_id": 1291937,
"author_profile": "https://Stackoverflow.com/users/1291937",
"pm_score": 1,
"selected": false,
"text": " protected override void OnPreRenderComplete(EventArgs e)\n {\n if (grv.Rows.Count > 0)\n {\n grv.HeaderRow.TableSection = TableRowSection.TableHeader;\n }\n }\n"
},
{
"answer_id": 46821137,
"author": "Hawkeye",
"author_id": 4036454,
"author_profile": "https://Stackoverflow.com/users/4036454",
"pm_score": 3,
"selected": false,
"text": "EnableCdn=\"true\" ScriptManager <asp:ScriptManager ID=\"ScriptManager1\" runat=\"server\" EnableCdn=\"true\" />\n Sys. Sys EnableCdn=\"true\" Sys <script src=\"https://ajax.aspnetcdn.com/ajax/4.5.1/1/MicrosoftAjax.js\" type=\"text/javascript\"></script>\n EnableCdn=\"true\" Sys"
},
{
"answer_id": 64142737,
"author": "Bm Z",
"author_id": 1542087,
"author_profile": "https://Stackoverflow.com/users/1542087",
"pm_score": 0,
"selected": false,
"text": " private void RegisterRoutes(RouteCollection routes)\n {\n routes.IgnoreRoute(\"{resource}.aspx/{*pathInfo}\");\n routes.IgnoreRoute(\"{resource}.axd/{*pathInfo}\");\n\n routes.MapRoute(\n \"Default\", \n \"{controller}/{action}/{id}\", \n new { controller = \"Test\", action = \"Index\", id = UrlParameter.Optional }\n );\n }\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
75,340 |
<p>Can anyone recommend an efficient method to execute XSLT transforms of XML data within a Ruby application? The XSL gem (REXSL) is not available yet, and while I have seen a project or two that implement it, I'm wary of using them so early on. A friend had recommended a shell out call to Perl, but I'm worried about resources. </p>
<p>This is for a linux environment.</p>
|
[
{
"answer_id": 75460,
"author": "Compulsion",
"author_id": 3675,
"author_profile": "https://Stackoverflow.com/users/3675",
"pm_score": 3,
"selected": false,
"text": "<asp:ScriptManager ID=\"ScriptManager1\" runat=\"server\" EnablePartialRendering=\"true\" /> \n"
},
{
"answer_id": 200316,
"author": "Tom Carter",
"author_id": 2839,
"author_profile": "https://Stackoverflow.com/users/2839",
"pm_score": 2,
"selected": false,
"text": "if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();\n"
},
{
"answer_id": 538200,
"author": "MadMax1138",
"author_id": 65187,
"author_profile": "https://Stackoverflow.com/users/65187",
"pm_score": 2,
"selected": false,
"text": "<compilation debug=\"true\"> <compilation debug=\"false\"> <xhtmlConformance mode=\"Legacy\"/>"
},
{
"answer_id": 1718513,
"author": "Dean L",
"author_id": 127887,
"author_profile": "https://Stackoverflow.com/users/127887",
"pm_score": 6,
"selected": false,
"text": "<script type=\"text/javascript\"></script> <asp:Content/> <asp:Content/>"
},
{
"answer_id": 2563888,
"author": "Ray",
"author_id": 4872,
"author_profile": "https://Stackoverflow.com/users/4872",
"pm_score": 4,
"selected": false,
"text": "<system.web> <httpHandlers>\n <remove verb=\"*\" path=\"*.asmx\"/>\n <add verb=\"*\" path=\"*.asmx\" validate=\"false\" type=\"System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n <add verb=\"GET\" path=\"ScriptResource.axd\" type=\"System.Web.Handlers.ScriptResourceHandler\" validate=\"false\"/>\n</httpHandlers>\n"
},
{
"answer_id": 3757770,
"author": "Anish",
"author_id": 453539,
"author_profile": "https://Stackoverflow.com/users/453539",
"pm_score": -1,
"selected": false,
"text": " <!--<add verb=\"*\" path=\"*.asmx\" validate=\"false\" type=\"Microsoft.Web.Script.Services.ScriptHandlerFactory, Microsoft.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" />\n <add verb=\"GET\" path=\"ScriptResource.axd\" type=\"Microsoft.Web.Handlers.ScriptResourceHandler\" validate=\"false\" />-->\n <add verb=\"*\" path=\"*.asmx\" validate=\"false\" type=\"System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n <add verb=\"GET\" path=\"ScriptResource.axd\" type=\"System.Web.Handlers.ScriptResourceHandler\" validate=\"false\"/>\n"
},
{
"answer_id": 4260550,
"author": "Alcides Martínez",
"author_id": 518003,
"author_profile": "https://Stackoverflow.com/users/518003",
"pm_score": 3,
"selected": false,
"text": "<httpHandlers>\n <remove verb=\"*\" path=\"*.asmx\"/>\n <add verb=\"*\" path=\"*.asmx\" validate=\"false\" type=\"System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n <add verb=\"*\" path=\"*_AppService.axd\" validate=\"false\" type=\"System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n <add verb=\"GET,HEAD\" path=\"ScriptResource.axd\" type=\"System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" validate=\"false\"/>\n</httpHandlers>\n<httpModules>\n <add name=\"ScriptModule\" type=\"System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n</httpModules>\n</system.web>\n"
},
{
"answer_id": 6020313,
"author": "JonK",
"author_id": 755955,
"author_profile": "https://Stackoverflow.com/users/755955",
"pm_score": 0,
"selected": false,
"text": "<rewrite> <outboundRules> <preConditions>\n <preCondition name=\"IsHTML\">\n <add input=\"{RESPONSE_CONTENT_TYPE}\" pattern=\"^text/html\"/>\n </preCondition>\n</preConditions>\n <rule preCondition=\"IsHTML\" name=\"MyOutboundRule\">\n"
},
{
"answer_id": 6291807,
"author": "Zara_me",
"author_id": 121336,
"author_profile": "https://Stackoverflow.com/users/121336",
"pm_score": 1,
"selected": false,
"text": " <configuration>\n<configSections>\n <sectionGroup name=\"system.web.extensions\" type=\"System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\">\n <sectionGroup name=\"scripting\" type=\"System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\">\n <section name=\"scriptResourceHandler\" type=\"System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" requirePermission=\"false\" allowDefinition=\"MachineToApplication\"/>\n</sectionGroup>\n\n </sectionGroup>\n</configSections>\n <assemblies>\n\n <add assembly=\"System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n\n </assemblies>\n </compilation>\n <httpHandlers>\n <remove verb=\"*\" path=\"*.asmx\"/>\n <add verb=\"*\" path=\"*.asmx\" validate=\"false\" type=\"System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n <add verb=\"*\" path=\"*_AppService.axd\" validate=\"false\" type=\"System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n <add verb=\"GET,HEAD\" path=\"ScriptResource.axd\" type=\"System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" validate=\"false\"/>\n </httpHandlers>\n <httpModules>\n <add name=\"ScriptModule\" type=\"System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n </httpModules>\n</system.web>\n <system.webServer>\n <validation validateIntegratedModeConfiguration=\"false\"/>\n <modules>\n <add name=\"ScriptModule\" preCondition=\"integratedMode\" type=\"System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n </modules>\n <handlers>\n <remove name=\"WebServiceHandlerFactory-Integrated\"/>\n <add name=\"ScriptHandlerFactory\" verb=\"*\" path=\"*.asmx\" preCondition=\"integratedMode\" type=\"System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n <add name=\"ScriptHandlerFactoryAppServices\" verb=\"*\" path=\"*_AppService.axd\" preCondition=\"integratedMode\" type=\"System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n <add name=\"ScriptResource\" preCondition=\"integratedMode\" verb=\"GET,HEAD\" path=\"ScriptResource.axd\" type=\"System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n </handlers>\n</system.webServer>\n"
},
{
"answer_id": 9350258,
"author": "Zviadi",
"author_id": 299203,
"author_profile": "https://Stackoverflow.com/users/299203",
"pm_score": 3,
"selected": false,
"text": "<location path=\"Telerik.Web.UI.WebResource.axd\"> \n <system.web> \n <authorization> \n <allow users=\"*\"/> \n </authorization> \n </system.web> \n</location>\n"
},
{
"answer_id": 9442728,
"author": "v s",
"author_id": 1023156,
"author_profile": "https://Stackoverflow.com/users/1023156",
"pm_score": 0,
"selected": false,
"text": "<compilation debug=\"true\">\n <httpHandlers>\n <remove verb=\"*\" path=\"*.asmx\"/>\n <add verb=\"*\" path=\"*.asmx\" validate=\"false\" type=\"System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n <add verb=\"*\" path=\"*_AppService.axd\" validate=\"false\" type=\"System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n <add verb=\"GET,HEAD\" path=\"ScriptResource.axd\" type=\"System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" validate=\"false\"/>\n</httpHandlers>\n<httpModules>\n <add name=\"ScriptModule\" type=\"System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n</httpModules>\n</system.web>\n"
},
{
"answer_id": 13631823,
"author": "GoldBishop",
"author_id": 659246,
"author_profile": "https://Stackoverflow.com/users/659246",
"pm_score": 0,
"selected": false,
"text": "web.config Sys is undefined rts.Ignore(\"{resource}.axd/{*pathInfo}\") 'Ignores any Resource cache references, used heavily in AJAX interactions.\n"
},
{
"answer_id": 16109767,
"author": "RacerNerd",
"author_id": 1634605,
"author_profile": "https://Stackoverflow.com/users/1634605",
"pm_score": 0,
"selected": false,
"text": "<system.webServer>\n <handlers>\n <clear />\n <add name=\"ScriptResource\" preCondition=\"integratedMode\" verb=\"GET,HEAD\" path=\"ScriptResource.axd\" type=\"System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" />\n <!-- Make sure wildcard rules are below the ScriptResource tag -->\n </handlers>\n <modules>\n <add name=\"ScriptModule\" type=\"System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n <!-- Other modules are added here -->\n </modules>\n </system.webServer>\n"
},
{
"answer_id": 17256975,
"author": "goodeye",
"author_id": 292060,
"author_profile": "https://Stackoverflow.com/users/292060",
"pm_score": 3,
"selected": false,
"text": "$(document).ready(function () {\n Sys. calls here\n});\n"
},
{
"answer_id": 18301056,
"author": "Farschidus",
"author_id": 1379217,
"author_profile": "https://Stackoverflow.com/users/1379217",
"pm_score": 1,
"selected": false,
"text": "<asp:ScriptManager> <ajaxtoolkit:ToolkitScriptManager>"
},
{
"answer_id": 28965519,
"author": "onlyme",
"author_id": 3954673,
"author_profile": "https://Stackoverflow.com/users/3954673",
"pm_score": 0,
"selected": false,
"text": "<script></script> and not <script />.\n"
},
{
"answer_id": 30093900,
"author": "Jawad Siddiqui",
"author_id": 1085016,
"author_profile": "https://Stackoverflow.com/users/1085016",
"pm_score": 0,
"selected": false,
"text": "if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded(); \n"
},
{
"answer_id": 32057625,
"author": "Alexandre N.",
"author_id": 1398758,
"author_profile": "https://Stackoverflow.com/users/1398758",
"pm_score": 3,
"selected": false,
"text": "<system.web.extensions>\n<scripting>\n<scriptResourceHandler enableCompression=\"false\" enableCaching=\"true\" />\n</scripting>\n</system.web.extensions>\n <script src=\"/MyWebApp/ScriptResource.axd?[snip - long query string]\" type=\"text/javascript\"></script>\n <system.webServer/><handlers/> <add name=\"ScriptResource\" preCondition=\"integratedMode\" verb=\"GET,HEAD\" path=\"ScriptResource.axd\" type=\"System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" />\n <system.web/><httpHandlers/>"
},
{
"answer_id": 37473809,
"author": "hsobhy",
"author_id": 1030977,
"author_profile": "https://Stackoverflow.com/users/1030977",
"pm_score": 0,
"selected": false,
"text": "routes.MapPageRoute(\"siteDefault\", \"{culture}/\", \"~/default.aspx\", false, new RouteValueDictionary(new { culture = \"(\\\\w{2})|(\\\\w{2}-\\\\w{2})\" }));\n"
},
{
"answer_id": 39619160,
"author": "Fernando Meneses Gomes",
"author_id": 1291937,
"author_profile": "https://Stackoverflow.com/users/1291937",
"pm_score": 1,
"selected": false,
"text": " protected override void OnPreRenderComplete(EventArgs e)\n {\n if (grv.Rows.Count > 0)\n {\n grv.HeaderRow.TableSection = TableRowSection.TableHeader;\n }\n }\n"
},
{
"answer_id": 46821137,
"author": "Hawkeye",
"author_id": 4036454,
"author_profile": "https://Stackoverflow.com/users/4036454",
"pm_score": 3,
"selected": false,
"text": "EnableCdn=\"true\" ScriptManager <asp:ScriptManager ID=\"ScriptManager1\" runat=\"server\" EnableCdn=\"true\" />\n Sys. Sys EnableCdn=\"true\" Sys <script src=\"https://ajax.aspnetcdn.com/ajax/4.5.1/1/MicrosoftAjax.js\" type=\"text/javascript\"></script>\n EnableCdn=\"true\" Sys"
},
{
"answer_id": 64142737,
"author": "Bm Z",
"author_id": 1542087,
"author_profile": "https://Stackoverflow.com/users/1542087",
"pm_score": 0,
"selected": false,
"text": " private void RegisterRoutes(RouteCollection routes)\n {\n routes.IgnoreRoute(\"{resource}.aspx/{*pathInfo}\");\n routes.IgnoreRoute(\"{resource}.axd/{*pathInfo}\");\n\n routes.MapRoute(\n \"Default\", \n \"{controller}/{action}/{id}\", \n new { controller = \"Test\", action = \"Index\", id = UrlParameter.Optional }\n );\n }\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13320/"
] |
75,347 |
<p>I've been asked to implement some code that will update a row in a MS SQL Server database and then use a stored proc to insert the update in a history table. We can't add a stored proc to do this since we don't control the database. I know in stored procs you can do the update and then call execute on another stored proc. Can I set it up to do this in code using one SQL command?</p>
|
[
{
"answer_id": 75852,
"author": "osp70",
"author_id": 2357,
"author_profile": "https://Stackoverflow.com/users/2357",
"pm_score": 0,
"selected": false,
"text": "sSQL = \"BEGIN TRANSACTION;\" & _\n \" Update table set col1 = @col1, col2 = @col2\" & _\n \" where col3 = @col3 and \" & _\n \" EXECUTE addcontacthistoryentry @parm1, @parm2, @parm3, @parm4, @parm5, @parm6; \" & _\n \"COMMIT TRANSACTION;\"\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2357/"
] |
75,361 |
<p>I have a column containing the strings 'Operator (1)' and so on until 'Operator (600)' so far.</p>
<p>I want to get them numerically ordered and I've come up with</p>
<pre><code>select colname from table order by
cast(replace(replace(colname,'Operator (',''),')','') as int)
</code></pre>
<p>which is very very ugly.</p>
<p>Better suggestions?</p>
|
[
{
"answer_id": 150106,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 0,
"selected": false,
"text": "operator"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5190/"
] |
75,379 |
<p>The problem is simple, but I'm struggling a bit already.</p>
<pre><code>Server server = new Server(8080);
Context context = new Context(server, "/", Context.NO_SESSIONS);
context.addServlet(MainPageView.class, "/");
context.addServlet(UserView.class, "/signup");
server.start();
</code></pre>
<p>That's a pretty standard piece of code that you can find anywhere in Jetty world. I have an application that embeds Jetty as a servlet engine and has some servlets. </p>
<p>Instantiation of some of these servlets requires heavy work on startup. Say – reading additional config files, connecting to the database, etc. How can I make the servlet engine instantiate all servlets eagerly, so that I can do all the hard work upfront and not on the first user request?</p>
|
[
{
"answer_id": 75424,
"author": "Justin Rudd",
"author_id": 12968,
"author_profile": "https://Stackoverflow.com/users/12968",
"pm_score": 0,
"selected": false,
"text": "Context.addServlet ServletHolder ServletHolder Servlet myServlet = new MyServlet();\nServletHolder holder = new ServletHolder(myServlet);\ncontext.addServlet(holder, \"/\");\n"
},
{
"answer_id": 75760,
"author": "delux247",
"author_id": 5569,
"author_profile": "https://Stackoverflow.com/users/5569",
"pm_score": 3,
"selected": true,
"text": "Context context = new Context(server, \"/\", Context.NO_SESSIONS);\nServletHolder mainPageViewHolder = new ServletHolder(MainPageView.class);\n// Do this to force Jetty to instantiate the servlet\nmainPageViewHolder.getServlet(); \ncontext.addServlet(mainPageViewHolder, \"/\");\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3105/"
] |
75,385 |
<p>The Visual Studio compiler does not seem to warn on signed/unsigned assignments, only on comparisons. For example the code below will generate a warning on the if statement but not the initial assignments.</p>
<p>Is there anyway to make it catch these? I'm already at W4 but thought (hoped) there may be another setting somewhere.</p>
<p>Thanks,</p>
<pre><code>int foo(void)
{
unsigned int fooUnsigned = 0xffffffff;
int fooSigned = fooUnsigned; // no warning
if (fooSigned < fooUnsigned) // warning
{
return 0;
}
return fooSigned;
}
</code></pre>
<p>Update:</p>
<p>Quamrana is right, this is controlled by warning 4365 which appears to be off by default, even at W4. However you can explicitly enable it for a given warning level like so;</p>
<pre><code>#pragma warning (4 : 4365)
</code></pre>
<p>Which results in;</p>
<pre><code>warning C4365: 'initializing' : conversion from 'unsigned int' to 'int', signed/unsigned mismatch
</code></pre>
|
[
{
"answer_id": 75711,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 0,
"selected": false,
"text": "C:\\Temp>cl /Wall /c foo.c\nMicrosoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.21022.08 for 80x86\nCopyright (C) Microsoft Corporation. All rights reserved.\n\nfoo.c\nfoo.c(6) : warning C4018: '<' : signed/unsigned mismatch\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1043/"
] |
75,401 |
<p>User <a href="https://stackoverflow.com/users/1065/kokos">kokos</a> answered the wonderful <em><a href="https://stackoverflow.com/questions/9033/hidden-features-of-c">Hidden Features of C#</a></em> question by mentioning the <code>using</code> keyword. Can you elaborate on that? What are the uses of <code>using</code>?</p>
|
[
{
"answer_id": 75426,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 7,
"selected": false,
"text": "using (var conn = new SqlConnection(\"connection string\"))\n{\n conn.Open();\n\n // Execute SQL statement here on the connection you created\n}\n SqlConnection .Close() try catch finally"
},
{
"answer_id": 75435,
"author": "Gilligan",
"author_id": 12356,
"author_profile": "https://Stackoverflow.com/users/12356",
"pm_score": 0,
"selected": false,
"text": "using"
},
{
"answer_id": 75444,
"author": "MagicKat",
"author_id": 8505,
"author_profile": "https://Stackoverflow.com/users/8505",
"pm_score": 5,
"selected": false,
"text": "using (SqlConnection cnn = new SqlConnection()) { /* Code */}\nusing f1 = System.Windows.Forms.Form;\n"
},
{
"answer_id": 75461,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 1,
"selected": false,
"text": "using (Font font2 = new Font(\"Arial\", 10.0f))\n{\n // Use font2\n}\n"
},
{
"answer_id": 75480,
"author": "Bob Wintemberg",
"author_id": 12999,
"author_profile": "https://Stackoverflow.com/users/12999",
"pm_score": 2,
"selected": false,
"text": "using (File file = new File (parameters))\n{\n // Code to do stuff with the file\n}\n"
},
{
"answer_id": 75483,
"author": "paulwhit",
"author_id": 7301,
"author_profile": "https://Stackoverflow.com/users/7301",
"pm_score": 10,
"selected": true,
"text": "using using (MyResource myRes = new MyResource())\n{\n myRes.DoSomething();\n}\n { // Limits scope of myRes\n MyResource myRes= new MyResource();\n try\n {\n myRes.DoSomething();\n }\n finally\n {\n // Check for a null resource.\n if (myRes != null)\n // Call the object's Dispose method.\n ((IDisposable)myRes).Dispose();\n }\n}\n using var myRes = new MyResource();\nmyRes.DoSomething();\n myRes"
},
{
"answer_id": 75516,
"author": "Sam Schutte",
"author_id": 146,
"author_profile": "https://Stackoverflow.com/users/146",
"pm_score": 3,
"selected": false,
"text": " using (FileStream fs = new FileStream(\"c:\\file.txt\", FileMode.Open))\n {\n using (BufferedStream bs = new BufferedStream(fs))\n {\n using (System.IO.StreamReader sr = new StreamReader(bs))\n {\n string output = sr.ReadToEnd();\n }\n }\n }\n"
},
{
"answer_id": 75867,
"author": "BlackTigerX",
"author_id": 8411,
"author_profile": "https://Stackoverflow.com/users/8411",
"pm_score": 7,
"selected": false,
"text": "using (System.IO.StreamReader r = new System.IO.StreamReader(\"\"))\nusing (System.IO.StreamReader r2 = new System.IO.StreamReader(\"\")) {\n //code\n}\n using (System.IO.StreamReader r = new System.IO.StreamReader(\"\"), r2 = new System.IO.StreamReader(\"\")) {\n //code\n}\n"
},
{
"answer_id": 76192,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "IDisposable using IDisposable IDisposable Dispose finally"
},
{
"answer_id": 76232,
"author": "Brendan Kendrick",
"author_id": 13473,
"author_profile": "https://Stackoverflow.com/users/13473",
"pm_score": 1,
"selected": false,
"text": "using (IDataReader myReader = DataFunctions.ExecuteReader(CommandType.Text, sql.ToString(), dp.Parameters, myConnectionString)) \n{\n while (myReader.Read()) \n {\n MyObject theObject = new MyObject();\n theObject.PublicProperty = myReader.GetString(0);\n myCollection.Add(theObject);\n }\n}\n"
},
{
"answer_id": 76278,
"author": "Lucas",
"author_id": 5966,
"author_profile": "https://Stackoverflow.com/users/5966",
"pm_score": 3,
"selected": false,
"text": "Using frm as new Form1\n\n Form1.ShowDialog\n\n ' Do stuff here\n\nEnd Using\n"
},
{
"answer_id": 204957,
"author": "Amanda Mitchell",
"author_id": 26628,
"author_profile": "https://Stackoverflow.com/users/26628",
"pm_score": 4,
"selected": false,
"text": "using (var foo = new Bar())\n{\n Baz();\n}\n var foo = new Bar();\ntry\n{\n Baz();\n}\nfinally\n{\n foo.Dispose();\n}\n using (new Scope(() => IsWorking = false))\n{\n IsWorking = true;\n MundaneYetDangerousWork();\n}\n"
},
{
"answer_id": 204987,
"author": "milot",
"author_id": 22637,
"author_profile": "https://Stackoverflow.com/users/22637",
"pm_score": 1,
"selected": false,
"text": "using(SqlDataAdapter adapter_object = new SqlDataAdapter(sql_command_parameter))\n{\n // do stuff\n} // here adapter_object is disposed automatically\n"
},
{
"answer_id": 13175552,
"author": "Shiraj Momin",
"author_id": 1787655,
"author_profile": "https://Stackoverflow.com/users/1787655",
"pm_score": 2,
"selected": false,
"text": "public class ClassA:IDisposable\n{\n #region IDisposable Members\n public void Dispose()\n {\n GC.SuppressFinalize(this);\n }\n #endregion\n}\n public void fn_Data()\n{\n using (ClassA ObjectName = new ClassA())\n {\n // Use objectName\n }\n}\n"
},
{
"answer_id": 20271484,
"author": "Riya Patil",
"author_id": 2191381,
"author_profile": "https://Stackoverflow.com/users/2191381",
"pm_score": -1,
"selected": false,
"text": "Using(SqlConnection conn = new SqlConnection(ConnectionString)\n{\n Conn.Open()\n\n // Execute SQL statements here.\n // You do not have to close the connection explicitly\n // here as \"USING\" will close the connection once the\n // object Conn goes out of the defined scope.\n}\n"
},
{
"answer_id": 22994945,
"author": "VictorySaber",
"author_id": 2878135,
"author_profile": "https://Stackoverflow.com/users/2878135",
"pm_score": 3,
"selected": false,
"text": "using LegacyEntities = CompanyFoo.CoreLib.x86.VBComponents.CompanyObjects;\n LegacyEntities.Account\n CompanyFoo.CoreLib.x86.VBComponents.CompanyObjects.Account\n Account // It is not obvious this is a legacy entity\n"
},
{
"answer_id": 29897576,
"author": "Pluc",
"author_id": 1338607,
"author_profile": "https://Stackoverflow.com/users/1338607",
"pm_score": 3,
"selected": false,
"text": "using (var db = new DbContext())\n{\n if(db.State == State.Closed)\n throw new Exception(\"Database connection is closed.\");\n return db.Something.ToList();\n}\n"
},
{
"answer_id": 34465332,
"author": "Aureliano Buendia",
"author_id": 738587,
"author_profile": "https://Stackoverflow.com/users/738587",
"pm_score": 4,
"selected": false,
"text": "namespace HelloWorld\n{\n using AppFunc = Func<IDictionary<DateTime, string>, List<string>>;\n public class Startup\n {\n public static AppFunc OrderEvents() \n {\n AppFunc appFunc = (IDictionary<DateTime, string> events) =>\n {\n if ((events != null) && (events.Count > 0))\n {\n List<string> result = events.OrderBy(ev => ev.Key)\n .Select(ev => ev.Value)\n .ToList();\n return result;\n }\n throw new ArgumentException(\"Event dictionary is null or empty.\");\n };\n return appFunc;\n }\n }\n}\n"
},
{
"answer_id": 41463137,
"author": "Siamand",
"author_id": 2276651,
"author_profile": "https://Stackoverflow.com/users/2276651",
"pm_score": 1,
"selected": false,
"text": "class LoggerScope:IDisposable {\n static ThreadLocal<LoggerScope> threadScope = \n new ThreadLocal<LoggerScope>();\n private LoggerScope previous;\n\n public static LoggerScope Current=> threadScope.Value;\n\n public bool WithTime{get;}\n\n public LoggerScope(bool withTime){\n previous = threadScope.Value;\n threadScope.Value = this;\n WithTime=withTime;\n }\n\n public void Dispose(){\n threadScope.Value = previous;\n }\n}\n\n\nclass Program {\n public static void Main(params string[] args){\n new Program().Run();\n }\n\n public void Run(){\n log(\"something happend!\");\n using(new LoggerScope(false)){\n log(\"the quick brown fox jumps over the lazy dog!\");\n using(new LoggerScope(true)){\n log(\"nested scope!\");\n }\n }\n }\n\n void log(string message){\n if(LoggerScope.Current!=null){\n Console.WriteLine(message);\n if(LoggerScope.Current.WithTime){\n Console.WriteLine(DateTime.Now);\n }\n }\n }\n\n}\n"
},
{
"answer_id": 51590168,
"author": "Chamila Maddumage",
"author_id": 8194089,
"author_profile": "https://Stackoverflow.com/users/8194089",
"pm_score": 2,
"selected": false,
"text": "using using using System.IO;\n using using string connString = \"Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;\";\n\nusing (SqlConnection conn = new SqlConnection(connString))\n{\n SqlCommand cmd = conn.CreateCommand();\n cmd.CommandText = \"SELECT CustomerId, CompanyName FROM Customers\";\n conn.Open();\n using (SqlDataReader dr = cmd.ExecuteReader())\n {\n while (dr.Read())\n Console.WriteLine(\"{0}\\t{1}\", dr.GetString(0), dr.GetString(1));\n }\n}\n using using using (SqlConnection conn = new SqlConnection(connString)"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13332/"
] |
75,432 |
<p>I am using URLDownloadToFile to retrieve a file from a website. Subsequent calls return the original file rather than an updated version. I assume it is retrieving a cached version.</p>
|
[
{
"answer_id": 20701711,
"author": "user3122475",
"author_id": 3122475,
"author_profile": "https://Stackoverflow.com/users/3122475",
"pm_score": 2,
"selected": false,
"text": "// Limpa cache do Internet Explorer\nprocedure DeletaIECache;\nvar\n lpEntryInfo: PInternetCacheEntryInfo;\n hCacheDir: LongWord;\n dwEntrySize: LongWord;\nbegin\n dwEntrySize := 0;\n FindFirstUrlCacheEntry(nil, TInternetCacheEntryInfo(nil^), dwEntrySize) ;\n GetMem(lpEntryInfo, dwEntrySize) ;\n if dwEntrySize > 0 then lpEntryInfo^.dwStructSize := dwEntrySize;\n hCacheDir := FindFirstUrlCacheEntry(nil, lpEntryInfo^, dwEntrySize) ;\n if hCacheDir <> 0 then\n begin\n repeat\n DeleteUrlCacheEntry(lpEntryInfo^.lpszSourceUrlName) ;\n FreeMem(lpEntryInfo, dwEntrySize) ;\n dwEntrySize := 0;\n FindNextUrlCacheEntry(hCacheDir, TInternetCacheEntryInfo(nil^), dwEntrySize) ;\n GetMem(lpEntryInfo, dwEntrySize) ;\n if dwEntrySize > 0 then lpEntryInfo^.dwStructSize := dwEntrySize;\n until not FindNextUrlCacheEntry(hCacheDir, lpEntryInfo^, dwEntrySize) ;\n end;\n FreeMem(lpEntryInfo, dwEntrySize) ;\n FindCloseUrlCache(hCacheDir) ;\nend;\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8761/"
] |
75,440 |
<p>What method do I call to get the name of a class?</p>
|
[
{
"answer_id": 75456,
"author": "clahey",
"author_id": 8453,
"author_profile": "https://Stackoverflow.com/users/8453",
"pm_score": 5,
"selected": false,
"text": "__name__ class.__name__ object.__class__.__name__"
},
{
"answer_id": 75467,
"author": "Mr Shark",
"author_id": 6093,
"author_profile": "https://Stackoverflow.com/users/6093",
"pm_score": 7,
"selected": true,
"text": "In [1]: class Test:\n ...: pass\n ...: \n\nIn [2]: Test.__name__\nOut[2]: 'Test'\n"
},
{
"answer_id": 77222,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "str('2'.__class__) \"<type 'str'>\" str(len.__class__) \"<type 'builtin_function_or_method'>\" str(4.6.__class__) \"<type 'float'>\" 4.6.__class__.__name__ 'float'"
},
{
"answer_id": 83155,
"author": "Jon Cage",
"author_id": 15369,
"author_profile": "https://Stackoverflow.com/users/15369",
"pm_score": 4,
"selected": false,
"text": "__class__ >>> class test():\n... pass\n...\n>>> a_test = test()\n>>>\n>>> a_test.__name__\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nAttributeError: test instance has no attribute '__name__'\n>>>\n>>> a_test.__class__\n<class __main__.test at 0x009EEDE0>\n"
},
{
"answer_id": 53653620,
"author": "Azat Ibrakov",
"author_id": 5997596,
"author_profile": "https://Stackoverflow.com/users/5997596",
"pm_score": 2,
"selected": false,
"text": "__qualname__ __name__ >>> class A:\n class B:\n pass\n>>> A.B.__name__\n'B'\n>>> A.B.__qualname__\n'A.B'\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8453/"
] |
75,441 |
<p>As part of the Nant copy task, I would like to change the properties of the files in the target location. For instance make the files "read-write" from "read-only". How would I do this?</p>
|
[
{
"answer_id": 75481,
"author": "Phillip Wells",
"author_id": 3012,
"author_profile": "https://Stackoverflow.com/users/3012",
"pm_score": 4,
"selected": true,
"text": "<attrib file=\"test.txt\" readonly=\"false\"/>\n"
},
{
"answer_id": 76863,
"author": "LordHits",
"author_id": 8088,
"author_profile": "https://Stackoverflow.com/users/8088",
"pm_score": 3,
"selected": false,
"text": "<attrib readonly=\"false\">\n <fileset basedir=\"mydirectory\">\n <include name=\"**\"/>\n </fileset>\n</attrib>\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8088/"
] |
75,446 |
<p>I have just started reading DDD. I am unable to completely grasp the concept of Entity vs Value objects.. Can someone please explain the problems (maintainability, performance.. etc) a system could face when a Value object is designed as a Entity object? Example would be great...</p>
|
[
{
"answer_id": 47422311,
"author": "Ramin Farajpour",
"author_id": 3269793,
"author_profile": "https://Stackoverflow.com/users/3269793",
"pm_score": 2,
"selected": false,
"text": "Entities Value Objects"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
75,463 |
<p>Does anyone know of some good resources related to setting up heirarchical user account systems? I'm currently setting one up and am struggling with some of the more complex logic (especially with determining permissions). I was hoping I might be able to find some resources to help me along.</p>
<p><strong>Some Background:</strong>
I'm building a user account system for a web CMS that allows for a nested group hierarchy. Each group can be allowed/denied access to read, write, add, and delete (either explicitly for that group, or implicitly by one of its parents). As if that weren't complicated enough, the system also allows for users to be members of multiple groups. -- This is where I'm stuck. I've got everything set up, but I'm struggling with the actual logic for determining pemissions for a given user.</p>
|
[
{
"answer_id": 458047,
"author": "Ben Aston",
"author_id": 38522,
"author_profile": "https://Stackoverflow.com/users/38522",
"pm_score": 2,
"selected": false,
"text": "00 Permission A Permission B 01 10 OR Permission set for Group A 01\nPermission set for Group B 10 OR \n ----\nResultant permission set 11 (i.e. both permission A and B are conferred)\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5291/"
] |
75,482 |
<p>I am serving all content through apache with <code>Content-Encoding: zip</code> but that compresses on the fly. A good amount of my content is static files on the disk. I want to gzip the files beforehand rather than compressing them every time they are requested.</p>
<p>This is something that, I believe, <code>mod_gzip</code> did in Apache 1.x automatically, but just having the file with .gz next to it. That's no longer the case with <code>mod_deflate</code>.</p>
|
[
{
"answer_id": 75682,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 5,
"selected": true,
"text": "MultiViews Options AddEncoding"
},
{
"answer_id": 75697,
"author": "Brian Matthews",
"author_id": 1969,
"author_profile": "https://Stackoverflow.com/users/1969",
"pm_score": 0,
"selected": false,
"text": "mod_cache mod_deflate"
},
{
"answer_id": 75727,
"author": "Aeon",
"author_id": 13289,
"author_profile": "https://Stackoverflow.com/users/13289",
"pm_score": 1,
"selected": false,
"text": "cd /var/www/.../data/\nfor file in *; do\n gzip -c $file > $file.gz;\ndone;\n"
},
{
"answer_id": 97155,
"author": "Otto",
"author_id": 9594,
"author_profile": "https://Stackoverflow.com/users/9594",
"pm_score": 3,
"selected": false,
"text": "Options FollowSymLinks MultiViews\n namespace :static do\n desc \"Gzip compress the static content so Apache doesn't need to do it on-the-fly.\"\n task :compress do\n puts \"Gzipping js, html and css files.\"\n Dir.glob(\"#{RAILS_ROOT}/public/**/*.{js,html,css}\") do |file|\n system \"gzip -c -9 #{file} > #{file}.gz\"\n end\n end\nend\n"
},
{
"answer_id": 609051,
"author": "brianegge",
"author_id": 14139,
"author_profile": "https://Stackoverflow.com/users/14139",
"pm_score": 2,
"selected": false,
"text": "Options Indexes FollowSymLinks MultiViews\n AddEncoding x-compress .Z\nAddEncoding x-gzip .gz .tgz\n #AddType application/x-compress .Z\n#AddType application/x-gzip .gz .tgz\n"
},
{
"answer_id": 25556606,
"author": "Vivien",
"author_id": 2191299,
"author_profile": "https://Stackoverflow.com/users/2191299",
"pm_score": 0,
"selected": false,
"text": "http://www.domain.com/(...)/bigfile.json\n-> Content-Encoding:gzip, Content-Type: Content-Encoding:gzip\n // Note there is no bigfile.json\n(...)/bigfile.json.gz\n(...)/bigfile.json.json\n <Directory (...)>\n AddEncoding gzip .gz\n Options +Multiviews\n <Files *.json.gz>\n ForceType application/json\n </Files>\n</Directory>\n"
},
{
"answer_id": 34932031,
"author": "Kevinoid",
"author_id": 503410,
"author_profile": "https://Stackoverflow.com/users/503410",
"pm_score": 3,
"selected": false,
"text": "mod_negotiation foo.js foo.js.gz /foo.js /foo foo.js foo.js.js /foo.js foo.js.js foo.js.gz Options +MultiViews\nRemoveType .gz\nAddEncoding gzip .gz\n\n# Send .tar.gz without Content-Encoding: gzip\n<FilesMatch \".+\\.tar\\.gz$\">\n RemoveEncoding .gz\n # Note: Can use application/x-gzip for backwards-compatibility\n AddType application/gzip .gz\n</FilesMatch>\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9594/"
] |
75,489 |
<p>I am pulling a long timestamp from a database, but want to present it as a Date using Tags only, no embedded java in the JSP.<br><br> I've created my own tag to do this because I was unable to get the parseDate and formatDate tags to work, but that's not to say they don't work.<br>
<br>
Any advice?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 75674,
"author": "ScArcher2",
"author_id": 1310,
"author_profile": "https://Stackoverflow.com/users/1310",
"pm_score": 4,
"selected": true,
"text": "long longvalue = ...;//from database.\njava.util.Date dateValue = new java.util.Date(longvalue);\nrequest.setAttribute(\"dateValue\", dateValue);\n <fmt:formatDate value=\"${dateValue}\" pattern=\"MM/dd/yyyy HH:mm\"/>\n"
},
{
"answer_id": 2628641,
"author": "BenM",
"author_id": 43850,
"author_profile": "https://Stackoverflow.com/users/43850",
"pm_score": 6,
"selected": false,
"text": "jsp:useBean jsp:setProperty <%@ taglib uri=\"http://java.sun.com/jsp/jstl/fmt\" prefix=\"fmt\" %>\n<jsp:useBean id=\"dateValue\" class=\"java.util.Date\"/>\n<jsp:setProperty name=\"dateValue\" property=\"time\" value=\"${timestampValue}\"/>\n<fmt:formatDate value=\"${dateValue}\" pattern=\"MM/dd/yyyy HH:mm\"/>\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9450/"
] |
75,495 |
<p>When creating a UserControl in WPF, I find it convenient to give it some arbitrary Height and Width values so that I can view my changes in the Visual Studio designer. When I run the control, however, I want the Height and Width to be undefined, so that the control will expand to fill whatever container I place it in. How can I acheive this same functionality without having to remove the Height and Width values before building my control? (Or without using DockPanel in the parent container.)</p>
<p>The following code demonstrates the problem:</p>
<pre><code><Window x:Class="ExampleApplication3.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="clr-namespace:ExampleApplication3"
Title="Example" Height="600" Width="600">
<Grid Background="LightGray">
<loc:UserControl1 />
</Grid>
</Window>
</code></pre>
<p>The following definition of <code>UserControl1</code> displays reasonably at design time but displays as a fixed size at run time:</p>
<pre><code><UserControl x:Class="ExampleApplication3.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="300" Width="300">
<Grid Background="LightCyan" />
</UserControl>
</code></pre>
<p>The following definition of <code>UserControl1</code> displays as a dot at design time but expands to fill the parent <code>Window1</code> at run time:</p>
<pre><code><UserControl x:Class="ExampleApplication3.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid Background="LightCyan" />
</UserControl>
</code></pre>
|
[
{
"answer_id": 75527,
"author": "Brian Leahy",
"author_id": 580,
"author_profile": "https://Stackoverflow.com/users/580",
"pm_score": 6,
"selected": false,
"text": " xmlns:d=\"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\" \nmc:Ignorable=\"d\"\n d:DesignHeight=\"500\" d:DesignWidth=\"600\"\n"
},
{
"answer_id": 75606,
"author": "Alex Duggleby",
"author_id": 5790,
"author_profile": "https://Stackoverflow.com/users/5790",
"pm_score": 6,
"selected": true,
"text": "public UserControl1()\n{\n InitializeComponent();\n if (LicenseManager.UsageMode != LicenseUsageMode.Designtime)\n {\n this.Width = double.NaN; ;\n this.Height = double.NaN; ;\n }\n}\n"
},
{
"answer_id": 79134,
"author": "AndyL",
"author_id": 9944,
"author_profile": "https://Stackoverflow.com/users/9944",
"pm_score": 3,
"selected": false,
"text": "<loc:UserControl1 Width=\"auto\" Height=\"auto\" />"
},
{
"answer_id": 311897,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "protected override void OnVisualParentChanged(DependencyObject oldParent)\n{\n if (this.Parent != null)\n {\n this.Width = double.NaN;\n this.Height = double.NaN;\n }\n}\n"
},
{
"answer_id": 421841,
"author": "Paul",
"author_id": 44636,
"author_profile": "https://Stackoverflow.com/users/44636",
"pm_score": 0,
"selected": false,
"text": "If LicenseManager.UsageMode <> LicenseUsageMode.Designtime Then\n Me.Width = Double.NaN\n Me.Height = Double.NaN\nEnd If\n"
},
{
"answer_id": 1208106,
"author": "jpierson",
"author_id": 83658,
"author_profile": "https://Stackoverflow.com/users/83658",
"pm_score": 0,
"selected": false,
"text": "if(!DesignerProperties.GetIsInDesignMode(this))\n{\n this.Width = double.NaN;\n this.Height = double.NaN;\n}\n protected override void OnVisualParentChanged(DependencyObject oldParent)\n{\n base.OnVisualParentChanged(oldParent);\n\n ...\n}\n"
},
{
"answer_id": 5526765,
"author": "CLaRGe",
"author_id": 20507,
"author_profile": "https://Stackoverflow.com/users/20507",
"pm_score": 3,
"selected": false,
"text": "d: d:DesignHeight d:DesignWidth d:IsDesignTimeCreatable d:CreateList"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/317/"
] |
75,500 |
<p>I have around 1000 pdf filesand I need to convert them to 300 dpi tiff files. What is the best way to do this? If there is an SDK or something or a tool that can be scripted that would be ideal. </p>
|
[
{
"answer_id": 75567,
"author": "Aeon",
"author_id": 13289,
"author_profile": "https://Stackoverflow.com/users/13289",
"pm_score": 7,
"selected": true,
"text": "convert foo.pdf pages-%03d.tiff\n gs -q -dNOPAUSE -sDEVICE=tiffg4 -sOutputFile=a.tif foo.pdf -c quit\n"
},
{
"answer_id": 113276,
"author": "tomasso",
"author_id": 15043,
"author_profile": "https://Stackoverflow.com/users/15043",
"pm_score": 6,
"selected": false,
"text": "gswin32c -dNOPAUSE -q -g300x300 -sDEVICE=tiffg4 -dBATCH -sOutputFile=output_file_name.tif input_file_name.pdf gs -dNOPAUSE -q -g300x300 -sDEVICE=tiffg4 -dBATCH -sOutputFile=output_file_name.tif input_file_name.pdf"
},
{
"answer_id": 120316,
"author": "gyurisc",
"author_id": 260,
"author_profile": "https://Stackoverflow.com/users/260",
"pm_score": 4,
"selected": false,
"text": "$tool = 'C:\\Program Files\\gs\\gs8.63\\bin\\gswin32c.exe'\n$pdfs = get-childitem . -recurse | where {$_.Extension -match \"pdf\"}\n\nforeach($pdf in $pdfs)\n{\n\n $tiff = $pdf.FullName.split('.')[0] + '.tiff'\n if(test-path $tiff)\n {\n \"tiff file already exists \" + $tiff\n }\n else \n { \n 'Processing ' + $pdf.Name \n $param = \"-sOutputFile=$tiff\"\n & $tool -q -dNOPAUSE -sDEVICE=tiffg4 $param -r300 $pdf.FullName -c quit\n }\n}\n"
},
{
"answer_id": 221341,
"author": "Setori",
"author_id": 21537,
"author_profile": "https://Stackoverflow.com/users/21537",
"pm_score": 3,
"selected": false,
"text": "import os\nos.popen(' '.join([\n self._ghostscriptPath + 'gswin32c.exe', \n '-q',\n '-dNOPAUSE',\n '-dBATCH',\n '-r300',\n '-sDEVICE=tiff12nc',\n '-sPAPERSIZE=a4',\n '-sOutputFile=%s %s' % (tifDest, pdfSource),\n ]))\n"
},
{
"answer_id": 3790112,
"author": "Tyler",
"author_id": 457635,
"author_profile": "https://Stackoverflow.com/users/457635",
"pm_score": 3,
"selected": false,
"text": "for %%f in (%*) DO \"C:\\Program Files\\ImageMagick-6.6.4-Q16\\convert.exe\" -density 300 -compress lzw %%f %%f.tiff\n"
},
{
"answer_id": 7511450,
"author": "Russell Wong",
"author_id": 360257,
"author_profile": "https://Stackoverflow.com/users/360257",
"pm_score": 2,
"selected": false,
"text": "import os\n\ndef pdf2tiff(source, destination):\n idx = destination.rindex('.')\n destination = destination[:idx]\n args = [\n '-q', '-dNOPAUSE', '-dBATCH',\n '-sDEVICE=tiffg4',\n '-r600', '-sPAPERSIZE=a4',\n '-sOutputFile=' + destination + '__%03d.tiff'\n ]\n gs_cmd = 'gs ' + ' '.join(args) +' '+ source\n os.system(gs_cmd)\n args = [destination + '__*.tiff', destination + '.tiff' ]\n tiffcp_cmd = 'tiffcp ' + ' '.join(args)\n os.system(tiffcp_cmd)\n args = [destination + '__*.tiff']\n rm_cmd = 'rm ' + ' '.join(args)\n os.system(rm_cmd) \npdf2tiff('abc.pdf', 'abc.tiff')\n"
},
{
"answer_id": 8065301,
"author": "Sally",
"author_id": 1037695,
"author_profile": "https://Stackoverflow.com/users/1037695",
"pm_score": 2,
"selected": false,
"text": " SautinSoft.PdfFocus f = new SautinSoft.PdfFocus();\n\n string[] pdfFiles = Directory.GetFiles(@\"d:\\Folder with 1000 pdfs\\\", \"*.pdf\");\n string folderWithTiffs = @\"d:\\Folder with TIFFs\\\";\n\n foreach (string pdffile in pdfFiles)\n {\n f.OpenPdf(pdffile);\n\n if (f.PageCount > 0)\n {\n //save all pages to tiff files with 300 dpi\n f.ToImage(folderWithTiffs, Path.GetFileNameWithoutExtension(pdffile), System.Drawing.Imaging.ImageFormat.Tiff, 300);\n }\n f.ClosePdf();\n }\n"
},
{
"answer_id": 8353467,
"author": "k venkat",
"author_id": 1076963,
"author_profile": "https://Stackoverflow.com/users/1076963",
"pm_score": 2,
"selected": false,
"text": "SautinSoft.PdfFocus f = new SautinSoft.PdfFocus(); \n\nstring pdfPath = @\"c:\\My.pdf\";\n\nstring imageFolder = @\"c:\\images\\\";\n\nf.OpenPdf(pdfPath);\n\nif (f.PageCount > 0)\n{\n //Save all PDF pages to image folder as tiff images, 200 dpi\n int result = f.ToImage(imageFolder, \"page\",System.Drawing.Imaging.ImageFormat.Tiff, 200);\n}\n //Convert PDF file to Multipage TIFF file\n\nSautinSoft.PdfFocus f = new SautinSoft.PdfFocus();\n\nstring pdfPath = @\"c:\\Document.pdf\";\nstring tiffPath = @\"c:\\Result.tiff\";\n\nf.OpenPdf(pdfPath);\n\nif (f.PageCount > 0)\n{\n f.ToMultipageTiff(tiffPath, 120) == 0)\n {\n System.Diagnostics.Process.Start(tiffPath);\n }\n} \n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/260/"
] |
75,508 |
<p>I have 28,000 images I need to convert into a movie.
I tried </p>
<pre><code>mencoder mf://*.jpg -mf w=640:h=480:fps=30:type=jpg -ovc lavc -lavcopts vcodec=msmpeg4v2 -nosound -o ../output-msmpeg4v2.avi
</code></pre>
<p>But it seems to crap out at 7500 frames.</p>
<p>The files are named
webcam_2007-04-16_070804.jpg
webcam_2007-04-16_071004.jpg
webcam_2007-04-16_071204.jpg
webcam_2007-04-16_071404.jpg
Up to march 2008 or so.</p>
<p>Is there another way I can pass the filenames to mencoder so it doesn't stop part way?</p>
<pre><code>MEncoder 2:1.0~rc2-0ubuntu13 (C) 2000-2007 MPlayer Team
CPU: Intel(R) Pentium(R) 4 CPU 2.40GHz (Family: 15, Model: 2, Stepping: 7)
CPUflags: Type: 15 MMX: 1 MMX2: 1 3DNow: 0 3DNow2: 0 SSE: 1 SSE2: 1
Compiled with runtime CPU detection.
success: format: 16 data: 0x0 - 0x0
MF file format detected.
[mf] search expr: *.jpg
[mf] number of files: 28617 (114468)
VIDEO: [IJPG] 640x480 24bpp 30.000 fps 0.0 kbps ( 0.0 kbyte/s)
[V] filefmt:16 fourcc:0x47504A49 size:640x480 fps:30.00 ftime:=0.0333
Opening video filter: [expand osd=1]
Expand: -1 x -1, -1 ; -1, osd: 1, aspect: 0.000000, round: 1
==========================================================================
Opening video decoder: [ffmpeg] FFmpeg's libavcodec codec family
Selected video codec: [ffmjpeg] vfm: ffmpeg (FFmpeg MJPEG decoder)
==========================================================================
VDec: vo config request - 640 x 480 (preferred colorspace: Planar YV12)
VDec: using Planar YV12 as output csp (no 3)
Movie-Aspect is 1.33:1 - prescaling to correct movie aspect.
videocodec: libavcodec (640x480 fourcc=3234504d [MP42])
Writing header...
ODML: Aspect information not (yet?) available or unspecified, not writing vprp header.
Writing header...
ODML: Aspect information not (yet?) available or unspecified, not writing vprp header.
Pos: 251.3s 7539f ( 0%) 47.56fps Trem: 0min 0mb A-V:0.000 [1202:0]
Flushing video frames.
Writing index...
Writing header...
ODML: Aspect information not (yet?) available or unspecified, not writing vprp header.
Video stream: 1202.480 kbit/s (150310 B/s) size: 37772908 bytes 251.300 secs 7539 frames
</code></pre>
|
[
{
"answer_id": 75668,
"author": "moonshadow",
"author_id": 11834,
"author_profile": "https://Stackoverflow.com/users/11834",
"pm_score": 3,
"selected": true,
"text": "mf://@filename"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11950/"
] |
75,533 |
<p>I'm trying to have the same KDE Konsole experience within Mac OS X.</p>
<p>Here's my (overly complicated?) setup:</p>
<ul>
<li>I have Control and Command swapped at the System Preferences level. (Can't live without this)</li>
<li>Parallels lets you, at the Parallels application level, also reverse Control and Command. So I can undo the System Preferences setting (and get the setup I want within virtual Linux)</li>
</ul>
<p>I want this same per-application-opt-out for the Mac OS X Terminal app. Is it possible?</p>
|
[
{
"answer_id": 194426,
"author": "haa",
"author_id": 12115,
"author_profile": "https://Stackoverflow.com/users/12115",
"pm_score": 2,
"selected": false,
"text": "ssh -X user@host_or_ipaddress emacs& X11.app launchd"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8913/"
] |
75,538 |
<p>No C++ love when it comes to the "hidden features of" line of questions? Figured I would throw it out there. What are some of the hidden features of C++?</p>
|
[
{
"answer_id": 76606,
"author": "MSN",
"author_id": 6210,
"author_profile": "https://Stackoverflow.com/users/6210",
"pm_score": 6,
"selected": false,
"text": "const MyClass& x = MyClass(); // temporary exists as long as x is in scope\n"
},
{
"answer_id": 78484,
"author": "Jason Mock",
"author_id": 13630,
"author_profile": "https://Stackoverflow.com/users/13630",
"pm_score": 7,
"selected": false,
"text": "namespace fs = boost::filesystem;\n\nfs::path myPath( strPath, fs::native );\n"
},
{
"answer_id": 78840,
"author": "Ben",
"author_id": 13950,
"author_profile": "https://Stackoverflow.com/users/13950",
"pm_score": 8,
"selected": false,
"text": "void foo() {\n http://stackoverflow.com/\n int bar = 4;\n\n ...\n}\n"
},
{
"answer_id": 132815,
"author": "AareP",
"author_id": 11741,
"author_profile": "https://Stackoverflow.com/users/11741",
"pm_score": 4,
"selected": false,
"text": "struct global\n{\n void main()\n {\n a = 1;\n b();\n }\n int a;\n void b(){}\n}\nsingleton;\n string result = \n a==0 ? \"zero\" :\n a==1 ? \"one\" :\n a==2 ? \"two\" :\n 0;\n void a();\nint b();\nfloat c = (a(),b(),1.0f);\n FStruct s = {0};\n int angle = (short)((+180+30)*65536/360) * 360/65536; //==-150\n struct ref\n{\n int& r;\n ref(int& r):r(r){}\n};\nint b;\nref a(b);\nint c;\n*(int**)&a = &c;\n"
},
{
"answer_id": 152659,
"author": "vividos",
"author_id": 23740,
"author_profile": "https://Stackoverflow.com/users/23740",
"pm_score": 6,
"selected": false,
"text": "int Function()\ntry\n{\n // do something here\n return 42;\n}\ncatch(...)\n{\n return -1;\n}\n"
},
{
"answer_id": 169114,
"author": "Sumant",
"author_id": 25014,
"author_profile": "https://Stackoverflow.com/users/25014",
"pm_score": 5,
"selected": false,
"text": "std::bad_exception std::bad_exception bad_exception . -> :: A[i] i[A] struct Bar {\n void modify() {}\n}\nint main (void) {\n Bar().modify(); /* non-const function invoked on a temporary. */\n}\n : ?: void foo (int) {}\nvoid foo (double) {}\nstruct X {\n X (double d = 0.0) {}\n};\nvoid foo (X) {} \n\nint main(void) {\n int i = 1;\n foo(i ? 0 : 0.0); // calls foo(double)\n X x;\n foo(i ? 0.0 : x); // calls foo(X)\n}\n"
},
{
"answer_id": 170597,
"author": "Sirish",
"author_id": 7965,
"author_profile": "https://Stackoverflow.com/users/7965",
"pm_score": 5,
"selected": false,
"text": "int class clName\n{\n clName();\n int a[10];\n};\n clName::clName() : a()\n{\n}\n"
},
{
"answer_id": 172357,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 5,
"selected": false,
"text": "map::operator[] map<int, string> m;\nstring& s = m[42]; // no need for map::find()\nif (s.empty()) { // assuming we never store empty values in m\n s.assign(...);\n}\ncout << s;\n"
},
{
"answer_id": 218306,
"author": "Jim Hunziker",
"author_id": 6160,
"author_profile": "https://Stackoverflow.com/users/6160",
"pm_score": 4,
"selected": false,
"text": "static"
},
{
"answer_id": 302563,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 8,
"selected": false,
"text": "x = (y < 0) ? 10 : 20;\n (a == 0 ? a : b) = 1;\n if (a == 0)\n a = 1;\nelse\n b = 1;\n"
},
{
"answer_id": 304187,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 4,
"selected": false,
"text": " vector<string> V;\n copy(istream_iterator<string>(cin), istream_iterator<string>(),\n back_inserter(V));\n"
},
{
"answer_id": 312449,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 5,
"selected": false,
"text": "if(int * p = getPointer()) {\n // do something\n}\n struct MutexLocker { \n MutexLocker(Mutex&);\n ~MutexLocker(); \n operator bool() const { return false; } \nprivate:\n Mutex &m;\n};\n\n#define locked(mutex) if(MutexLocker const& lock = MutexLocker(mutex)) {} else \n\nvoid someCriticalPath() {\n locked(myLocker) { /* ... */ }\n}\n switch(int value = getIt()) {\n // ...\n}\n while(SomeThing t = getSomeThing()) {\n // ...\n}\n"
},
{
"answer_id": 409233,
"author": "Özgür",
"author_id": 12652,
"author_profile": "https://Stackoverflow.com/users/12652",
"pm_score": 2,
"selected": false,
"text": "template<class T> // (a) a base template\nvoid f(T) {\n std::cout << \"f(T)\\n\";\n}\n\ntemplate<>\nvoid f<>(int*) { // (b) an explicit specialization\n std::cout << \"f(int *) specilization\\n\";\n}\n\ntemplate<class T> // (c) another, overloads (a)\nvoid f(T*) {\n std::cout << \"f(T *)\\n\";\n}\n\ntemplate<>\nvoid f<>(int*) { // (d) another identical explicit specialization\n std::cout << \"f(int *) another specilization\\n\";\n}\n"
},
{
"answer_id": 421896,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 4,
"selected": false,
"text": "SomeType t = u;\nSomeType t(u);\nSomeType t();\nSomeType t;\nSomeType t(SomeType(u));\n SomeType u SomeType SomeType u"
},
{
"answer_id": 432333,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 6,
"selected": false,
"text": "template<typename From, typename To>\nunion union_cast {\n From from;\n To to;\n\n union_cast(From from)\n :from(from) { }\n\n To getTo() const { return to; }\n};\n"
},
{
"answer_id": 456773,
"author": "Özgür",
"author_id": 12652,
"author_profile": "https://Stackoverflow.com/users/12652",
"pm_score": 4,
"selected": false,
"text": "template <typename T> \nclass Creator { \n friend void appear() { // a new function ::appear(), but it doesn't \n … // exist until Creator is instantiated \n } \n};\nCreator<void> miracle; // ::appear() is created at this point \nCreator<double> oops; // ERROR: ::appear() is created a second time! \n template <typename T> \nclass Creator { \n friend void feed(Creator<T>*){ // every T generates a different \n … // function ::feed() \n } \n}; \n\nCreator<void> one; // generates ::feed(Creator<void>*) \nCreator<double> two; // generates ::feed(Creator<double>*) \n"
},
{
"answer_id": 456787,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "Fred* f = new(ram) Fred(); http://www.parashift.com/c++-faq-lite/dtors.html#faq-11.10\nf->~Fred();\n class A\n{\n};\n\nstruct B\n{\n A a;\n operator A&() { return a; }\n};\n\nvoid func(A a) { }\n\nint main()\n{\n A a, c;\n B b;\n a=c;\n func(b); //yeah baby\n a=b; //gotta love this\n}\n"
},
{
"answer_id": 572900,
"author": "dirkgently",
"author_id": 66692,
"author_profile": "https://Stackoverflow.com/users/66692",
"pm_score": 0,
"selected": false,
"text": "class Empty {};\n\nnamespace std {\n // #1 specializing from std namespace is okay under certain circumstances\n template<>\n void swap<Empty>(Empty&, Empty&) {} \n}\n\n/* #2 The following function has no arguments. \n There is no 'unknown argument list' as we do\n in C.\n*/\nvoid my_function() { \n cout << \"whoa! an error\\n\"; // #3 using can be scoped, as it is in main below\n // and this doesn't affect things outside of that scope\n}\n\nint main() {\n using namespace std; /* #4 you can use using in function scopes */\n cout << sizeof(Empty) << \"\\n\"; /* #5 sizeof(Empty) is never 0 */\n /* #6 falling off of main without an explicit return means \"return 0;\" */\n}\n"
},
{
"answer_id": 674995,
"author": "Özgür",
"author_id": 12652,
"author_profile": "https://Stackoverflow.com/users/12652",
"pm_score": 1,
"selected": false,
"text": "template <class T>\nclass Ptr\n{\npublic:\n operator bool() const\n {\n return (rawptr ? true: false);\n }\n//..more stuff\nprivate:\n T * rawptr;\n};\n Ptr<int> ptr(new int);\nif(ptr ) //calls operator bool()\n cout<<\"int value is: \"<<*ptr <<endl;\nelse\n cout<<\"empty\"<<endl;\n if (shared_ptr<X> px = dynamic_pointer_cast<X>(py))\n{\n //we get here only of px isn't empty\n} \n Ptr <int> p1;\nPtr <double> p2;\n\n//surprise #1\ncout<<\"p1 + p2 = \"<< p1+p2 <<endl; \n//prints 0, 1, or 2, although there isn't an overloaded operator+()\n\nPtr <File> pf;\nPtr <Query> pq; // Query and File are unrelated \n\n//surprise #2\nif(pf==pq) //compares bool values, not pointers! \n"
},
{
"answer_id": 691496,
"author": "Özgür",
"author_id": 12652,
"author_profile": "https://Stackoverflow.com/users/12652",
"pm_score": 2,
"selected": false,
"text": "struct S\n{\n void func(){};\n};\nint main(){\nvoid (S::*pmf)()=&S::func;// & is mandatory\n}\n void func(int){}\nint main(){\nvoid (*pf)(int)=func; // & is unnecessary it can be &func as well; \n}\n cout<<hex<<56; //otherwise you would have to write cout<<&hex<<56, not neat.\n"
},
{
"answer_id": 754133,
"author": "Özgür",
"author_id": 12652,
"author_profile": "https://Stackoverflow.com/users/12652",
"pm_score": -1,
"selected": false,
"text": "int var;\nstring *str = reinterpret_cast<string*>(&var);\n int var; \nstring *str = static_cast<string*>(static_cast<void*>(&var));\n"
},
{
"answer_id": 876180,
"author": "a_m0d",
"author_id": 106762,
"author_profile": "https://Stackoverflow.com/users/106762",
"pm_score": 1,
"selected": false,
"text": "// this is completely valid C++:\nclass A;\nstruct A { virtual ~A() = 0; };\nclass B : public A { public: virtual ~B(); };\n\n// means the exact same as:\nstruct A;\nclass A { public: virtual ~A() = 0; };\nstruct B : A { virtual ~B(); };\n\n// you can't even tell the difference from other code whether 'struct'\n// or 'class' was used for A and B\n"
},
{
"answer_id": 889001,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 7,
"selected": false,
"text": "for for(struct { int a; float b; } loop = { 1, 2 }; ...; ...) {\n ...\n}\n"
},
{
"answer_id": 1029069,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "int i(3);\n"
},
{
"answer_id": 1064070,
"author": "vobject",
"author_id": 53911,
"author_profile": "https://Stackoverflow.com/users/53911",
"pm_score": 2,
"selected": false,
"text": "namespace {\n // Classes, functions, and objects here.\n}\n namespace __unique_name__ { /* empty body */ }\nusing namespace __unique_name__;\nnamespace __unique_name__ {\n // original namespace body\n}\n"
},
{
"answer_id": 1065606,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 5,
"selected": false,
"text": "struct A {\nprotected:\n int a;\n};\n\nstruct B : A {\n // error: can't access protected member\n static int get(A &x) { return x.a; }\n};\n\nstruct C : A { };\n C B x std::stack void f(std::stack<int> &s) {\n // now, let's decide to mess with that stack!\n struct pillager : std::stack<int> {\n static std::deque<int> &get(std::stack<int> &s) {\n // error: stack<int>::c is protected\n return s.c;\n }\n };\n\n // haha, now let's inspect the stack's middle elements!\n std::deque<int> &d = pillager::get(s);\n}\n struct A {\nprotected:\n int a;\n};\n\nstruct B : A {\n // valid: *can* access protected member\n static int get(A &x) { return x.*(&B::a); }\n};\n\nstruct C : A { };\n std::stack void f(std::stack<int> &s) {\n // now, let's decide to mess with that stack!\n struct pillager : std::stack<int> {\n static std::deque<int> &get(std::stack<int> &s) {\n return s.*(pillager::c);\n }\n };\n\n // haha, now let's inspect the stack's middle elements!\n std::deque<int> &d = pillager::get(s);\n}\n void f(std::stack<int> &s) {\n // now, let's decide to mess with that stack!\n struct pillager : std::stack<int> {\n using std::stack<int>::c;\n };\n\n // haha, now let's inspect the stack's middle elements!\n std::deque<int> &d = s.*(&pillager::c);\n}\n"
},
{
"answer_id": 1402670,
"author": "Kamil Szot",
"author_id": 166921,
"author_profile": "https://Stackoverflow.com/users/166921",
"pm_score": 0,
"selected": false,
"text": "#include <stdio.h>\nstruct A { int d; int e() { return d; } };\nint main() {\n A* a = new A();\n a->d = 8;\n printf(\"%d %d\\n\", a ->* &A::d, (a ->* &A::e)() );\n return 0;\n}\n var f = A.e\nf.call(a) \n a['d']\n"
},
{
"answer_id": 1414869,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 5,
"selected": false,
"text": "identity id // void (*f)(); // same\nid<void()>::type *f;\n\n// void (*f(void(*p)()))(int); // same\nid<void(int)>::type *f(id<void()>::type *p);\n\n// int (*p)[2] = new int[10][2]; // same\nid<int[2]>::type *p = new int[10][2];\n\n// void (C::*p)(int) = 0; // same\nid<void(int)>::type C::*p = 0;\n // boost::identity is pretty much the same\ntemplate<typename T> \nstruct id { typedef T type; };\n"
},
{
"answer_id": 1573354,
"author": "Macke",
"author_id": 72312,
"author_profile": "https://Stackoverflow.com/users/72312",
"pm_score": 1,
"selected": false,
"text": "template<class int>\nclass foo;\n\ntemplate\nclass foo<0> {\n int* get<0>() { return array; }\n int* array; \n};\n\ntemplate<class int>\nclass foo<i> : public foo<i-1> {\n int* get<i>() { return array + 1; } \n};\n"
},
{
"answer_id": 1771776,
"author": "Jeffrey Faust",
"author_id": 215580,
"author_profile": "https://Stackoverflow.com/users/215580",
"pm_score": 2,
"selected": false,
"text": "int main(){}\n"
},
{
"answer_id": 1771843,
"author": "Kaz Dragon",
"author_id": 24913,
"author_profile": "https://Stackoverflow.com/users/24913",
"pm_score": 4,
"selected": false,
"text": "template <size_t X, size_t Y>\nstruct bitfield\n{\n char left : X;\n char right : Y;\n};\n"
},
{
"answer_id": 1966865,
"author": "Rune FS",
"author_id": 112407,
"author_profile": "https://Stackoverflow.com/users/112407",
"pm_score": 0,
"selected": false,
"text": "class clC\n{\npublic:\n clC& operator=(const clC& other)\n {\n //do some assignment stuff\n return copy(other);\n }\n virtual clC& copy(const clC& other);\n}\n\nclass clB : public clC\n{\npublic:\n clB() : m_copy()\n {\n }\n\n clC& copy(const clC& other)\n {\n return m_copy;\n }\n\nprivate:\n class clInnerB : public clC\n {\n }\n clInnerB m_copy;\n}\n"
},
{
"answer_id": 2176229,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 4,
"selected": false,
"text": "void f() { }\nvoid g() { return f(); }\n void f() { return (void)\"i'm discarded\"; }\n void void template<typename T>\nstruct sample {\n // assume f<T> may return void\n T dosomething() { return f<T>(); }\n\n // better than T t = f<T>(); /* ... */ return t; !\n};\n"
},
{
"answer_id": 2176258,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 5,
"selected": false,
"text": "void() for(T i, j; can_continue(i, j); ++i, void(), ++j)\n do_code(i, j);\n void()"
},
{
"answer_id": 2339965,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "$ touch empty.cpp\n$ g++ -E -dM empty.cpp | sort >gxx-macros.txt\n$ icc -E -dM empty.cpp | sort >icx-macros.txt\n$ touch empty.c\n$ gcc -E -dM empty.c | sort >gcc-macros.txt\n$ icc -E -dM empty.c | sort >icc-macros.txt\n $ diff gxx-macros.txt icx-macros.txt\n $ diff gxx-macros.txt gcc-macros.txt\n $ diff icx-macros.txt icc-macros.txt\n"
},
{
"answer_id": 2339999,
"author": "AnT stands with Russia",
"author_id": 187690,
"author_profile": "https://Stackoverflow.com/users/187690",
"pm_score": 4,
"selected": false,
"text": "?: void ?: i = a > b ? a : throw something();\n void void foo()\n{\n return throw something();\n}\n"
},
{
"answer_id": 2340305,
"author": "Viktor Sehr",
"author_id": 100724,
"author_profile": "https://Stackoverflow.com/users/100724",
"pm_score": 2,
"selected": false,
"text": "map::insert(std::pair(key, value)); class MyClass {public: /* code */} myClass;\n"
},
{
"answer_id": 2340449,
"author": "aheld",
"author_id": 259873,
"author_profile": "https://Stackoverflow.com/users/259873",
"pm_score": -1,
"selected": false,
"text": "class foo\n{\n int x;\n\n int* GetX(){\n return &x;\n }\n}\n int a = *GetX();\n *GetX() = 17;\n"
},
{
"answer_id": 2912402,
"author": "mihai",
"author_id": 350838,
"author_profile": "https://Stackoverflow.com/users/350838",
"pm_score": -1,
"selected": false,
"text": "#define private public \n"
},
{
"answer_id": 3056080,
"author": "Martín Fixman",
"author_id": 305597,
"author_profile": "https://Stackoverflow.com/users/305597",
"pm_score": -1,
"selected": false,
"text": "int s ;\nvector <int> a ;\nvector <int> b ;\n\nint &G(int h)\n{\n if ( h < a.size() ) return a[h] ;\n if ( h - a.size() < b.size() ) return b[ h - a.size() ] ;\n return s ;\n}\n\nint main()\n{\n a = vector <int> (100) ;\n b = vector <int> (100) ;\n\n G( 20) = 40 ; //a[20] becomes 40\n G(120) = 40 ; //b[20] becomes 40\n G(424) = 40 ; //s becomes 40\n}\n"
},
{
"answer_id": 3100801,
"author": "Alexandre C.",
"author_id": 373025,
"author_profile": "https://Stackoverflow.com/users/373025",
"pm_score": 3,
"selected": false,
"text": "struct MyAwesomeAbstractClass\n{ ... };\n\n\ntemplate <typename T>\nMyAwesomeAbstractClass*\ncreate_awesome(T param)\n{\n struct ans : MyAwesomeAbstractClass\n {\n // Make the implementation depend on T\n };\n\n return new ans(...);\n}\n"
},
{
"answer_id": 3176148,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 3,
"selected": false,
"text": "struct Person {\n char name[255];\n Person():name(\"???\") { }\n};\n strcpy"
},
{
"answer_id": 3176186,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 5,
"selected": false,
"text": "template<typename Func1, typename Func2>\nclass callable {\n Func1 *m_f1;\n Func2 *m_f2;\n\npublic:\n callable(Func1 *f1, Func2 *f2):m_f1(f1), m_f2(f2) { }\n operator Func1*() { return m_f1; }\n operator Func2*() { return m_f2; }\n};\n\nvoid foo(int i) { std::cout << \"foo: \" << i << std::endl; }\nvoid bar(long il) { std::cout << \"bar: \" << il << std::endl; }\n\nint main() {\n callable<void(int), void(long)> c(foo, bar);\n c(42); // calls foo\n c(42L); // calls bar\n}\n"
},
{
"answer_id": 3182557,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 6,
"selected": false,
"text": "+ +AnEnumeratorValue\n struct Foo {\n static int const value = 42;\n};\n\n// This does something interesting...\ntemplate<typename T>\nvoid f(T const&);\n\nint main() {\n // fails to link - tries to get the address of \"Foo::value\"!\n f(Foo::value);\n\n // works - pass a temporary value\n f(+Foo::value);\n}\n // This does something interesting...\ntemplate<typename T>\nvoid f(T const& a, T const& b);\n\nint main() {\n int a[2];\n int b[3];\n f(a, b); // won't work! different values for \"T\"!\n f(+a, +b); // works! T is \"int*\" both time\n}\n"
},
{
"answer_id": 3189052,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 4,
"selected": false,
"text": "struct A { void f() { } };\n\nstruct B : virtual A { void f() { cout << \"B!\"; } };\nstruct C : virtual A { };\n\n// name-lookup sees B::f and A::f, but B::f dominates over A::f !\nstruct D : B, C { void g() { f(); } };\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2328/"
] |
75,608 |
<p>I'm working on a product feature that will allow the user to export data from a SQL CE database on one copy of my application and re-import it into SQL CE on the other end. This data is not whole tables, but the result of queries.</p>
<p>I had hoped to take advantage of .net's built-in XML-based serialization like in DataTable.WriteXML. But, none of the methods for executing queries against a SqlCeCommand provide an obvious way of serializing to XML or extracting a DataTable, which could provide the method.</p>
<p>Is there something I'm missing? Do I have to write my own serialization-deserialization methods or is there a built-in way.</p>
|
[
{
"answer_id": 75681,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "SqlCeDataAdapter .Fill() .WriteXml()"
},
{
"answer_id": 75702,
"author": "Jonathan Rupp",
"author_id": 12502,
"author_profile": "https://Stackoverflow.com/users/12502",
"pm_score": 3,
"selected": true,
"text": "using(var dr = cmd.ExecuteReader())\n{\n DataSet ds = new DataSet();\n DataTable dt = ds.Tables.Add();\n dt.Load(dr);\n ds.WriteXML(...);\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5287/"
] |
75,614 |
<p>The following question answers how to get large memory pages on Windows :<br>
"<a href="https://stackoverflow.com/questions/39059/how-do-i-run-my-app-with-large-pages-in-windows">how do i run my app with large pages in windows</a>".</p>
<p>The problem I'm trying to solve is how do I configure it on Vista and 2008 Server.</p>
<p>Normally you just allow a specific user to lock pages in memory and you are done. However on Vista and 2008 this only works if you are using an Administrator account. It doesn't help if the user is actually part of the Administrators group. All other users always get a 1300 error code stating that some rights are missing.</p>
<p>Anyone have a clue as to what else needs to be configured?</p>
<p>Thanks,
Staffan</p>
|
[
{
"answer_id": 75681,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "SqlCeDataAdapter .Fill() .WriteXml()"
},
{
"answer_id": 75702,
"author": "Jonathan Rupp",
"author_id": 12502,
"author_profile": "https://Stackoverflow.com/users/12502",
"pm_score": 3,
"selected": true,
"text": "using(var dr = cmd.ExecuteReader())\n{\n DataSet ds = new DataSet();\n DataTable dt = ds.Tables.Add();\n dt.Load(dr);\n ds.WriteXML(...);\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8782/"
] |
75,621 |
<p>I have a web report that uses a Django form (new forms) for fields that control the query used to generate the report (start date, end date, ...). The issue I'm having is that the page should work using the form's initial values (unbound), but I can't access the cleaned_data field unless I call <code>is_valid()</code>. But <code>is_valid()</code> always fails on unbound forms.</p>
<p>It seems like Django's forms were designed with the use case of editing data such that an unbound form isn't really useful for anything other than displaying HTML.</p>
<p>For example, if I have:</p>
<pre><code>if request.method == 'GET':
form = MyForm()
else:
form = MyForm(request.method.POST)
if form.is_valid():
do_query(form.cleaned_data['start_date'], form.cleaned_data['end_date'])
</code></pre>
<p>is_valid() will fail if this is a GET (since it's unbound), and if I do:</p>
<pre><code>if request.method == 'GET':
form = MyForm()
do_query(form.cleaned_data['start_date'], form.cleaned_data['end_date'])
else:
form = MyForm(request.method.POST)
if form.is_valid():
do_query(form.cleaned_data['start_date'], form.cleaned_data['end_date'])
</code></pre>
<p>the first call to do_query triggers exceptions on form.cleaned_data, which is not a valid field because <code>is_valid()</code> has not been called. It seems like I have to do something like:</p>
<pre><code>if request.method == 'GET':
form = MyForm()
do_query(form['start_date'].field.initial, form['end_date'].field.initial)
else:
form = MyForm(request.method.POST)
if form.is_valid():
do_query(form.cleaned_data['start_date'], form.cleaned_data['end_date'])
</code></pre>
<p>that is, there isn't a common interface for retrieving the form's values between a bound form and an unbound one.</p>
<p>Does anyone see a cleaner way to do this?</p>
|
[
{
"answer_id": 75815,
"author": "Justin Voss",
"author_id": 5616,
"author_profile": "https://Stackoverflow.com/users/5616",
"pm_score": 0,
"selected": false,
"text": "if request.method == \"GET\":\n # calculate my_start_date and my_end_date here...\n form = MyForm( { 'start_date': my_start_date, 'end_date': my_end_date} )\n...\n if request.method == \"GET\":\n form = MyForm()\n form['start_date'] = form['start_date'].field.initial\n form['end_date'] = form['end_date'].field.initial\nelse:\n form = MyForm(request.method.POST)\nif form.is_valid():\n do_query(form.cleaned_data['start_date'], form.cleaned_data['end_date'])\n"
},
{
"answer_id": 75923,
"author": "Matthew Christensen",
"author_id": 2123,
"author_profile": "https://Stackoverflow.com/users/2123",
"pm_score": 4,
"selected": true,
"text": "def get_cleaned_or_initial(self, fieldname):\n if hasattr(self, 'cleaned_data'):\n return self.cleaned_data.get(fieldname)\n else:\n return self[fieldname].field.initial\n if request.method == 'GET':\n form = MyForm()\nelse:\n form = MyForm(request.method.POST)\n form.is_valid()\n\ndo_query(form.get_cleaned_or_initial('start_date'), form.get_cleaned_or_initial('end_date'))\n"
},
{
"answer_id": 81301,
"author": "zgoda",
"author_id": 12138,
"author_profile": "https://Stackoverflow.com/users/12138",
"pm_score": 2,
"selected": false,
"text": "cleaned_data"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8247/"
] |
75,626 |
<p>I have a JSP page that contains a scriplet where I instantiate an object. I would like to pass that object to the JSP tag without using any cache. </p>
<p>For example I would like to accomplish this: </p>
<pre><code><%@ taglib prefix="wf" uri="JspCustomTag" %>
<%
Object myObject = new Object();
%>
<wf:my-tag obj=myObject />
</code></pre>
<p>I'm trying to avoid directly interacting with any of the caches (page, session, servletcontext), I would rather have my tag handle that.</p>
|
[
{
"answer_id": 75843,
"author": "Garth Gilmour",
"author_id": 2635682,
"author_profile": "https://Stackoverflow.com/users/2635682",
"pm_score": 3,
"selected": false,
"text": "<wf:my-tag obj=\"<%= myObject %>\" />\n"
},
{
"answer_id": 76187,
"author": "Pavel Feldman",
"author_id": 5507,
"author_profile": "https://Stackoverflow.com/users/5507",
"pm_score": 2,
"selected": false,
"text": "<% Object myObject = new Object();\n pageContext.setAttribute(\"myObject\", myObject);\n%>\n<wf:my-tag obj=\"${myObject}\" />\n <wf:my-tag obj=\"<%= myObject %>\" />"
},
{
"answer_id": 355242,
"author": "Adeel Ansari",
"author_id": 42769,
"author_profile": "https://Stackoverflow.com/users/42769",
"pm_score": 4,
"selected": false,
"text": "<jsp:useBean id=\"myObject\" class=\"java.lang.Object\" scope=\"page\" />\n<wf:my-tag obj=\"${myObject}\" />\n"
},
{
"answer_id": 1228031,
"author": "dfrankow",
"author_id": 34935,
"author_profile": "https://Stackoverflow.com/users/34935",
"pm_score": 5,
"selected": false,
"text": "<%@ attribute name=\"field\" \n required=\"true\"\n type=\"com.mycompany.MyClass\" %>\n"
},
{
"answer_id": 27396614,
"author": "Mike Clark",
"author_id": 4261022,
"author_profile": "https://Stackoverflow.com/users/4261022",
"pm_score": 1,
"selected": false,
"text": " <wf:my-tag obj=\"<%= myObject %>\"/>\n <wf:my-tag obj=\"<%= myObject.variableName %>\"/>\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13393/"
] |
75,650 |
<p>I'm working in a team environment where each developer works from their local desktop and deploys to a virtual machine that they own on the network. What I'm trying to do is set up the Visual Studio solution so that when they build the solution each projects deployment is handled in the post-build event to that developers virtual machine.</p>
<p>What I'd really like to do is give ownership of those scripts to the individual developer as well so that they own their post build steps and they don't have to be the same for everyone.</p>
<p>A couple of questions:</p>
<ul>
<li>Is a post build event the place to execute this type of deployment operation? If not what is the best place to do it?</li>
<li>What software, tools, or tutorials/blog posts are available to assist in developing an automatic deployment system that supports these scenarios?</li>
</ul>
<p><strong>Edit:</strong> MSBuild seems to be the way to go in this situation. Anyone use alternative technologies with any success?</p>
<p><strong>Edit:</strong> If you are reading this question and wondering how to execute a different set of MSBuild tasks for each developer please see this question; <a href="https://stackoverflow.com/questions/78018/executing-different-set-of-msbuild-tasks-for-each-user">Executing different set of MSBuild tasks for each user?</a></p>
|
[
{
"answer_id": 75843,
"author": "Garth Gilmour",
"author_id": 2635682,
"author_profile": "https://Stackoverflow.com/users/2635682",
"pm_score": 3,
"selected": false,
"text": "<wf:my-tag obj=\"<%= myObject %>\" />\n"
},
{
"answer_id": 76187,
"author": "Pavel Feldman",
"author_id": 5507,
"author_profile": "https://Stackoverflow.com/users/5507",
"pm_score": 2,
"selected": false,
"text": "<% Object myObject = new Object();\n pageContext.setAttribute(\"myObject\", myObject);\n%>\n<wf:my-tag obj=\"${myObject}\" />\n <wf:my-tag obj=\"<%= myObject %>\" />"
},
{
"answer_id": 355242,
"author": "Adeel Ansari",
"author_id": 42769,
"author_profile": "https://Stackoverflow.com/users/42769",
"pm_score": 4,
"selected": false,
"text": "<jsp:useBean id=\"myObject\" class=\"java.lang.Object\" scope=\"page\" />\n<wf:my-tag obj=\"${myObject}\" />\n"
},
{
"answer_id": 1228031,
"author": "dfrankow",
"author_id": 34935,
"author_profile": "https://Stackoverflow.com/users/34935",
"pm_score": 5,
"selected": false,
"text": "<%@ attribute name=\"field\" \n required=\"true\"\n type=\"com.mycompany.MyClass\" %>\n"
},
{
"answer_id": 27396614,
"author": "Mike Clark",
"author_id": 4261022,
"author_profile": "https://Stackoverflow.com/users/4261022",
"pm_score": 1,
"selected": false,
"text": " <wf:my-tag obj=\"<%= myObject %>\"/>\n <wf:my-tag obj=\"<%= myObject.variableName %>\"/>\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3957/"
] |
75,652 |
<p>or "How do I answer questions on SO in Firefox using gVim inside the textboxes?"</p>
|
[
{
"answer_id": 75686,
"author": "Clinton Dreisbach",
"author_id": 6262,
"author_profile": "https://Stackoverflow.com/users/6262",
"pm_score": 3,
"selected": false,
"text": "#!/bin/sh\nexec xterm -e /usr/bin/vim \"$@\"\n"
},
{
"answer_id": 830078,
"author": "Hamish Downer",
"author_id": 3189,
"author_profile": "https://Stackoverflow.com/users/3189",
"pm_score": 2,
"selected": false,
"text": "au LocationChange .* :set editor=\"gvim -f\"\nau LocationChange stackoverflow\\.com :set editor=\"gvim -f -c 'set ft=mkd'\"\n"
},
{
"answer_id": 837650,
"author": "Simon Hartcher",
"author_id": 459159,
"author_profile": "https://Stackoverflow.com/users/459159",
"pm_score": 2,
"selected": false,
"text": ":set editor=\"C:\\\\\\\\Program\\\\ Files\\\\ (x86)\\\\\\\\Vim\\\\\\\\vim72\\\\\\\\gvim.exe\" -f\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13060/"
] |
75,675 |
<p>How do I dump the data, and only the data, not the schema, of some SQLite3 tables of a database (not all the tables)?
The dump should be in SQL format, as it should be easily re-entered into the database later and should be done from the command line. Something like</p>
<pre><code>sqlite3 db .dump
</code></pre>
<p>but without dumping the schema and selecting which tables to dump.</p>
|
[
{
"answer_id": 79168,
"author": "harningt",
"author_id": 12713,
"author_profile": "https://Stackoverflow.com/users/12713",
"pm_score": 2,
"selected": false,
"text": "SELECT 'INSERT INTO ' || tableName || ' VALUES( ' || \n {for each value} ' quote(' || value || ')' (+ commas until final)\n|| ')' FROM 'tableName' ORDER BY rowid DESC\n src/shell.c:838"
},
{
"answer_id": 199221,
"author": "CyberFonic",
"author_id": 23999,
"author_profile": "https://Stackoverflow.com/users/23999",
"pm_score": 8,
"selected": false,
"text": ".mode csv \n-- use '.separator SOME_STRING' for something other than a comma.\n.headers on \n.out file.csv \nselect * from MyTable;\n .mode insert <target_table_name>\n.out file.sql \nselect * from MyTable;\n"
},
{
"answer_id": 422842,
"author": "polyglot",
"author_id": 45383,
"author_profile": "https://Stackoverflow.com/users/45383",
"pm_score": 5,
"selected": false,
"text": "sqlite3 database.db3 .dump | grep '^INSERT INTO \"tablename\"'\n"
},
{
"answer_id": 1938480,
"author": "Paul Egan",
"author_id": 2211429,
"author_profile": "https://Stackoverflow.com/users/2211429",
"pm_score": 5,
"selected": false,
"text": "sqlite3 db \".dump 'table1' 'table2'\""
},
{
"answer_id": 7526055,
"author": "jellyfish",
"author_id": 534951,
"author_profile": "https://Stackoverflow.com/users/534951",
"pm_score": 8,
"selected": false,
"text": "sqlite3 some.db .schema > schema.sql\nsqlite3 some.db .dump > dump.sql\ngrep -vx -f schema.sql dump.sql > data.sql\n data.sql BEGIN TRANSACTION;\nINSERT INTO \"table1\" VALUES ...;\n...\nINSERT INTO \"table2\" VALUES ...;\n...\nCOMMIT;\n"
},
{
"answer_id": 7974100,
"author": "Drew",
"author_id": 295290,
"author_profile": "https://Stackoverflow.com/users/295290",
"pm_score": 3,
"selected": false,
"text": "sqlite3 database.db3 '.dump \"table1\" \"table2\"' | grep '^INSERT'\n sqlite3 database.db3 '.dump \"table1\" \"table2\"' | grep -v '^CREATE'\n"
},
{
"answer_id": 10619827,
"author": "Elia Schito",
"author_id": 601782,
"author_profile": "https://Stackoverflow.com/users/601782",
"pm_score": 2,
"selected": false,
"text": "sqlite3 database.sqlite3 .dump | grep -v '^CREATE' CREATE"
},
{
"answer_id": 20014210,
"author": "retracile",
"author_id": 100073,
"author_profile": "https://Stackoverflow.com/users/100073",
"pm_score": 4,
"selected": false,
"text": "CREATE INSERT sqlite3 $DB .dump CREATE TABLE CREATE INSERT INSERT for t in $(sqlite3 $DB .tables); do\n echo -e \".mode insert $t\\nselect * from $t;\"\ndone | sqlite3 $DB > backup.sql\n $(sqlite $DB .tables | grep -v -e one -e two -e three) one two three"
},
{
"answer_id": 23658679,
"author": "Davoud Taghawi-Nejad",
"author_id": 236830,
"author_profile": "https://Stackoverflow.com/users/236830",
"pm_score": 3,
"selected": false,
"text": "from os import path \nimport csv \n\ndef convert_to_csv(directory, db_name):\n conn = sqlite3.connect(path.join(directory, db_name + '.db'))\n cursor = conn.cursor()\n cursor.execute(\"SELECT name FROM sqlite_master WHERE type='table';\")\n tables = cursor.fetchall()\n for table in tables:\n table = table[0]\n cursor.execute('SELECT * FROM ' + table)\n column_names = [column_name[0] for column_name in cursor.description]\n with open(path.join(directory, table + '.csv'), 'w') as csv_file:\n csv_writer = csv.writer(csv_file)\n csv_writer.writerow(column_names)\n while True:\n try:\n csv_writer.writerow(cursor.fetchone())\n except csv.Error:\n break\n if 'id' in column_names:\n with open(path.join(directory, table + '_aggregate.csv'), 'w') as csv_file:\n csv_writer = csv.writer(csv_file)\n column_names.remove('id')\n column_names.remove('round')\n sum_string = ','.join('sum(%s)' % item for item in column_names)\n cursor.execute('SELECT round, ' + sum_string +' FROM ' + table + ' GROUP BY round;')\n csv_writer.writerow(['round'] + column_names)\n while True:\n try:\n csv_writer.writerow(cursor.fetchone())\n except csv.Error:\n break \n"
},
{
"answer_id": 28554255,
"author": "Walty Yeung",
"author_id": 176423,
"author_profile": "https://Stackoverflow.com/users/176423",
"pm_score": 0,
"selected": false,
"text": ".dump .dump"
},
{
"answer_id": 37296788,
"author": "Francisco Puga",
"author_id": 930271,
"author_profile": "https://Stackoverflow.com/users/930271",
"pm_score": 3,
"selected": false,
"text": "sqlite3 database.db3 .dump | grep '^INSERT INTO \"tablename\"'\n for t in $(sqlite3 $DB .tables); do\n echo -e \".mode insert $t\\nselect * from $t;\"\ndone | sqlite3 $DB > backup.sql\n sqlite3 some.db .schema > schema.sql\nsqlite3 some.db .dump > dump.sql\ngrep -v -f schema.sql dump > data.sql\n grep -Pzo \"(?s)^INSERT.*\\);[ \\t]*$\"\n .dump TABLES='table1 table2 table3'\n\necho '' > /tmp/backup.sql\nfor t in $TABLES ; do\n echo -e \".dump ${t}\" | sqlite3 database.db3 | grep -Pzo \"(?s)^INSERT.*?\\);$\" >> /tmp/backup.sql\ndone\n TABLES='table1 table2 table3'\n\necho 'BEGIN TRANSACTION;' > /tmp/backup.sql\necho '' >> /tmp/backup.sql\nfor t in $TABLES ; do\n echo -e \".dump ${t}\" | sqlite3 $1 | grep -Pzo \"(?s)^INSERT.*?\\);$\" | grep -v -e 'PRAGMA foreign_keys=OFF;' -e 'BEGIN TRANSACTION;' -e 'COMMIT;' >> /tmp/backup.sql\ndone\n\necho '' >> /tmp/backup.sql\necho 'COMMIT;' >> /tmp/backup.sql\n ); sqlite3 -bail database.db3 < /tmp/backup.sql\n"
},
{
"answer_id": 41738349,
"author": "PeterCo",
"author_id": 2613621,
"author_profile": "https://Stackoverflow.com/users/2613621",
"pm_score": 2,
"selected": false,
"text": "sqlite> .header on\nsqlite> .mode csv\nsqlite> .once c:/work/dataout.csv\nsqlite> SELECT * FROM tab1;\nsqlite> .exit\n sqlite> .mode csv\nsqlite> .import C:/work/dataout.csv tab1\nsqlite> .exit\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6068/"
] |
75,677 |
<p>How can I convert a uniform distribution (as most random number generators produce, e.g. between 0.0 and 1.0) into a normal distribution? What if I want a mean and standard deviation of my choosing?</p>
|
[
{
"answer_id": 77976,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "function distRandom(){\n do{\n x=random(DISTRIBUTION_DOMAIN);\n }while(random(DISTRIBUTION_RANGE)>=distributionFunction(x));\n return x;\n}\n"
},
{
"answer_id": 88547,
"author": "jilles de wit",
"author_id": 7531,
"author_profile": "https://Stackoverflow.com/users/7531",
"pm_score": 3,
"selected": false,
"text": "(1/12) * (1/sqrt(N))"
},
{
"answer_id": 196941,
"author": "user5084",
"author_id": 5084,
"author_profile": "https://Stackoverflow.com/users/5084",
"pm_score": 5,
"selected": false,
"text": "/*\n * Returns member of set with a given mean and standard deviation\n * mean: mean\n * standard deviation: std_dev \n */\nfunction createMemberInNormalDistribution(mean,std_dev){\n return mean + (gaussRandom()*std_dev);\n}\n\n/*\n * Returns random number in normal distribution centering on 0.\n * ~95% of numbers returned should fall between -2 and 2\n * ie within two standard deviations\n */\nfunction gaussRandom() {\n var u = 2*Math.random()-1;\n var v = 2*Math.random()-1;\n var r = u*u + v*v;\n /*if outside interval [0,1] start over*/\n if(r == 0 || r >= 1) return gaussRandom();\n\n var c = Math.sqrt(-2*Math.log(r)/r);\n return u*c;\n\n /* todo: optimize this algorithm by caching (v*c) \n * and returning next time gaussRandom() is called.\n * left out for simplicity */\n}\n"
},
{
"answer_id": 7771542,
"author": "Erik Aronesty",
"author_id": 627042,
"author_profile": "https://Stackoverflow.com/users/627042",
"pm_score": 3,
"selected": false,
"text": "sqrt(-2*log(R1))*cos(2*pi*R2)\n"
},
{
"answer_id": 8932273,
"author": "Hippo",
"author_id": 1159325,
"author_profile": "https://Stackoverflow.com/users/1159325",
"pm_score": 0,
"selected": false,
"text": "=norminv(rand();0;1) =norminv(rand();50;3)"
},
{
"answer_id": 47537485,
"author": "madx",
"author_id": 3138238,
"author_profile": "https://Stackoverflow.com/users/3138238",
"pm_score": 1,
"selected": false,
"text": "randn_box_muller.m function [values] = randn_box_muller(n, mean, std_dev)\n if nargin == 1\n mean = 0;\n std_dev = 1;\n end\n\n r = gaussRandomN(n);\n values = r.*std_dev - mean;\nend\n\nfunction [values] = gaussRandomN(n)\n [u, v, r] = gaussRandomNValid(n);\n\n c = sqrt(-2*log(r)./r);\n values = u.*c;\nend\n\nfunction [u, v, r] = gaussRandomNValid(n)\n r = zeros(n, 1);\n u = zeros(n, 1);\n v = zeros(n, 1);\n\n filter = r==0 | r>=1;\n\n % if outside interval [0,1] start over\n while n ~= 0\n u(filter) = 2*rand(n, 1)-1;\n v(filter) = 2*rand(n, 1)-1;\n r(filter) = u(filter).*u(filter) + v(filter).*v(filter);\n\n filter = r==0 | r>=1;\n n = size(r(filter),1);\n end\nend\n histfit(randn_box_muller(10000000),100);"
},
{
"answer_id": 53217176,
"author": "great_minds_think_alike",
"author_id": 10625359,
"author_profile": "https://Stackoverflow.com/users/10625359",
"pm_score": 0,
"selected": false,
"text": "set.seed(123)\nn <- 1000\nu <- runif(n) #creates U\nx <- -log(u)\ny <- runif(n, max=u*sqrt((2*exp(1))/pi)) #create Y\nz <- ifelse (y < dnorm(x)/2, -x, NA)\nz <- ifelse ((y > dnorm(x)/2) & (y < dnorm(x)), x, z)\nz <- z[!is.na(z)]\n"
},
{
"answer_id": 54334875,
"author": "peterweethetbeter",
"author_id": 10928083,
"author_profile": "https://Stackoverflow.com/users/10928083",
"pm_score": 0,
"selected": false,
"text": "n <- length(z)\nt0 <- Sys.time()\nz <- rnorm(n)\nt1 <- Sys.time()\nt1-t0\n"
},
{
"answer_id": 60476443,
"author": "Alessandro Jacopson",
"author_id": 15485,
"author_profile": "https://Stackoverflow.com/users/15485",
"pm_score": 1,
"selected": false,
"text": "function normal_random(mean,stddev)\n{\n var V1\n var V2\n var S\n do{\n var U1 = Math.random() // return uniform distributed in [0,1[\n var U2 = Math.random()\n V1 = 2*U1-1\n V2 = 2*U2-1\n S = V1*V1+V2*V2\n }while(S >= 1)\n if(S===0) return 0\n return mean+stddev*(V1*Math.sqrt(-2*Math.log(S)/S))\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8062/"
] |
75,700 |
<p>I have one applicationContext.xml file, and it has two org.springframework.orm.jpa.JpaTransactionManager (each with its own persistence unit, different databases) configured in a Spring middleware custom application.
<br><br>I want to use annotation based transactions (@Transactional), to not mess around with TransactionStatus commit, save, and rollback.<br><br>
A coworker mentioned that something gets confused doing this when there are multiple transaction managers, even though the context file is set configured correctly (the references go to the correct persistence unit.
Anyone ever see an issue?</p>
<hr>
<p>In your config, would you have two transaction managers?
Would you have txManager1 and txManager2?<br><br>
That's what I have with JPA, two different Spring beans that are transaction managers.</p>
|
[
{
"answer_id": 78479,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 4,
"selected": true,
"text": "<bean id=\"firstRealService\" class=\"com.acme.FirstServiceImpl\"/>\n<bean id=\"firstService\" \n class=\"org.springframework.transaction.interceptor.TransactionProxyFactoryBean\">\n <property name=\"transactionManager\" ref=\"firstJpaTm\"/>\n <property name=\"target\" ref=\"firstRealService\"/>\n <property name=\"transactionAttributes\">\n <props>\n <prop key=\"insert*\">PROPAGATION_REQUIRED</prop>\n <prop key=\"update*\">PROPAGATION_REQUIRED</prop>\n <prop key=\"*\">PROPAGATION_REQUIRED,readOnly</prop>\n </props>\n </property>\n</bean>\n<!-- similar for your second service -->\n <tx:annotation-driven transaction-manager=\"txManager\"/>\n\n<bean id=\"txManager\" \n class=\"org.springframework.transaction.jta.JtaTransactionManager\">\n <property name=\"transactionManagerName\" value=\"appserver/jndi/path\" />\n</bean>\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13143/"
] |
75,701 |
<p>Let's say I write a DLL in C++, and declare a global object of a class with a non-trivial destructor. Will the destructor be called when the DLL is unloaded?</p>
|
[
{
"answer_id": 76677,
"author": "MSN",
"author_id": 6210,
"author_profile": "https://Stackoverflow.com/users/6210",
"pm_score": 3,
"selected": false,
"text": "%ProgramFiles%\\Visual Studio 8\\vc\\crt\\src\\dllcrt0.c _cexit()"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13313/"
] |
75,704 |
<p>I see that within MySQL there are <code>Cast()</code> and <code>Convert()</code> functions to create integers from values, but is there any way to check to see if a value is an integer? Something like <code>is_int()</code> in PHP is what I am looking for.</p>
|
[
{
"answer_id": 75739,
"author": "JBB",
"author_id": 12332,
"author_profile": "https://Stackoverflow.com/users/12332",
"pm_score": 4,
"selected": false,
"text": "CREATE FUNCTION IsNumeric (sIn varchar(1024)) RETURNS tinyint\nRETURN sIn REGEXP '^(-|\\\\+){0,1}([0-9]+\\\\.[0-9]*|[0-9]*\\\\.[0-9]+|[0-9]+)$';\n"
},
{
"answer_id": 75880,
"author": "Jumpy",
"author_id": 9416,
"author_profile": "https://Stackoverflow.com/users/9416",
"pm_score": 9,
"selected": true,
"text": "select field from table where field REGEXP '^-?[0-9]+$';\n ceil(field) = field\n"
},
{
"answer_id": 5244724,
"author": "Jayjitraj",
"author_id": 376948,
"author_profile": "https://Stackoverflow.com/users/376948",
"pm_score": 3,
"selected": false,
"text": "select * from calender where year > 0\n"
},
{
"answer_id": 10626708,
"author": "Bill Kelly",
"author_id": 1399626,
"author_profile": "https://Stackoverflow.com/users/1399626",
"pm_score": 1,
"selected": false,
"text": "SELECT '12 INCHES' REGEXP '^(-|\\\\+){0,1}([0-9]+\\\\.[0-9]*|[0-9]*\\\\.[0-9]+|[0-9]+)$' FROM ...\n 1 TRUE TRUE 0 SELECT 'TOP 10' REGEXP '^(-|\\\\+){0,1}([0-9]+\\\\.[0-9]*|[0-9]*\\\\.[0-9]+|[0-9]+)$' FROM ...\n 0 FALSE"
},
{
"answer_id": 11693466,
"author": "Tom Auger",
"author_id": 467386,
"author_profile": "https://Stackoverflow.com/users/467386",
"pm_score": 2,
"selected": false,
"text": "WHERE table.field = \"0\" or CAST(table.field as SIGNED) != 0\n WHERE table.field != \"0\" and CAST(table.field as SIGNED) = 0\n"
},
{
"answer_id": 12577316,
"author": "Tarun Sood",
"author_id": 1696374,
"author_profile": "https://Stackoverflow.com/users/1696374",
"pm_score": 4,
"selected": false,
"text": "a41q\n1458\nxwe8\n1475\nasde\n9582\n.\n.\n.\n.\n.\nqe84\n SELECT Max(column_name) from table_name where column_name REGEXP '^[0-9]+$'\n"
},
{
"answer_id": 20761038,
"author": "Riad",
"author_id": 1957432,
"author_profile": "https://Stackoverflow.com/users/1957432",
"pm_score": 3,
"selected": false,
"text": "CAST( coulmn_value AS UNSIGNED ) // will return 0 if not numeric string.\n SELECT CAST('a123' AS UNSIGNED) // returns 0\nSELECT CAST('123' AS UNSIGNED) // returns 123 i.e. > 0\n"
},
{
"answer_id": 31694100,
"author": "minhas23",
"author_id": 2458916,
"author_profile": "https://Stackoverflow.com/users/2458916",
"pm_score": 3,
"selected": false,
"text": "SELECT col1 FROM table WHERE concat('',col * 1) = col;\n"
},
{
"answer_id": 34655769,
"author": "PodTech.io",
"author_id": 1842743,
"author_profile": "https://Stackoverflow.com/users/1842743",
"pm_score": 1,
"selected": false,
"text": "WHERE concat('',fieldname * 1) != fieldname \n"
},
{
"answer_id": 41845958,
"author": "Tim",
"author_id": 7467766,
"author_profile": "https://Stackoverflow.com/users/7467766",
"pm_score": 0,
"selected": false,
"text": "CREATE FUNCTION IsNumeric (SIN VARCHAR(1024)) RETURNS TINYINT\nRETURN SIN REGEXP '^(-|\\\\+){0,1}([0-9]+\\\\.[0-9]*|[0-9]*\\\\.[0-9]+|[0-9]+)$';\n 234jk456 12 inches"
},
{
"answer_id": 49898031,
"author": "Raymond Nijland",
"author_id": 2548147,
"author_profile": "https://Stackoverflow.com/users/2548147",
"pm_score": 2,
"selected": false,
"text": "CAST() LENGTH() SELECT (LENGTH(CAST(<data> AS UNSIGNED))) = (LENGTH(<data>)) AS is_int\n SELECT <data>, (LENGTH(CAST(<data> AS UNSIGNED))) = CASE WHEN CAST(<data> AS UNSIGNED) = 0 THEN CAST(<data> AS UNSIGNED) ELSE (LENGTH(<data>)) END AS is_int;\n **Query #1**\n\n SELECT 1, (LENGTH(CAST(1 AS UNSIGNED))) = CASE WHEN CAST(1 AS UNSIGNED) = 0 THEN CAST(1 AS UNSIGNED) ELSE (LENGTH(1)) END AS is_int;\n\n| 1 | is_int |\n| --- | ------ |\n| 1 | 1 |\n\n---\n**Query #2**\n\n SELECT 1.1, (LENGTH(CAST(1 AS UNSIGNED))) = CASE WHEN CAST(1.1 AS UNSIGNED) = 0 THEN CAST(1.1 AS UNSIGNED) ELSE (LENGTH(1.1)) END AS is_int;\n\n| 1.1 | is_int |\n| --- | ------ |\n| 1.1 | 0 |\n\n---\n**Query #3**\n\n SELECT \"1\", (LENGTH(CAST(\"1\" AS UNSIGNED))) = CASE WHEN CAST(\"1\" AS UNSIGNED) = 0 THEN CAST(\"1\" AS UNSIGNED) ELSE (LENGTH(\"1\")) END AS is_int;\n\n| 1 | is_int |\n| --- | ------ |\n| 1 | 1 |\n\n---\n**Query #4**\n\n SELECT \"1.1\", (LENGTH(CAST(\"1.1\" AS UNSIGNED))) = CASE WHEN CAST(\"1.1\" AS UNSIGNED) = 0 THEN CAST(\"1.1\" AS UNSIGNED) ELSE (LENGTH(\"1.1\")) END AS is_int;\n\n| 1.1 | is_int |\n| --- | ------ |\n| 1.1 | 0 |\n\n---\n**Query #5**\n\n SELECT \"1a\", (LENGTH(CAST(\"1.1\" AS UNSIGNED))) = CASE WHEN CAST(\"1a\" AS UNSIGNED) = 0 THEN CAST(\"1a\" AS UNSIGNED) ELSE (LENGTH(\"1a\")) END AS is_int;\n\n| 1a | is_int |\n| --- | ------ |\n| 1a | 0 |\n\n---\n**Query #6**\n\n SELECT \"1.1a\", (LENGTH(CAST(\"1.1a\" AS UNSIGNED))) = CASE WHEN CAST(\"1.1a\" AS UNSIGNED) = 0 THEN CAST(\"1.1a\" AS UNSIGNED) ELSE (LENGTH(\"1.1a\")) END AS is_int;\n\n| 1.1a | is_int |\n| ---- | ------ |\n| 1.1a | 0 |\n\n---\n**Query #7**\n\n SELECT \"a1\", (LENGTH(CAST(\"1.1a\" AS UNSIGNED))) = CASE WHEN CAST(\"a1\" AS UNSIGNED) = 0 THEN CAST(\"a1\" AS UNSIGNED) ELSE (LENGTH(\"a1\")) END AS is_int;\n\n| a1 | is_int |\n| --- | ------ |\n| a1 | 0 |\n\n---\n**Query #8**\n\n SELECT \"a1.1\", (LENGTH(CAST(\"a1.1\" AS UNSIGNED))) = CASE WHEN CAST(\"a1.1\" AS UNSIGNED) = 0 THEN CAST(\"a1.1\" AS UNSIGNED) ELSE (LENGTH(\"a1.1\")) END AS is_int;\n\n| a1.1 | is_int |\n| ---- | ------ |\n| a1.1 | 0 |\n\n---\n**Query #9**\n\n SELECT \"a\", (LENGTH(CAST(\"a\" AS UNSIGNED))) = CASE WHEN CAST(\"a\" AS UNSIGNED) = 0 THEN CAST(\"a\" AS UNSIGNED) ELSE (LENGTH(\"a\")) END AS is_int;\n\n| a | is_int |\n| --- | ------ |\n| a | 0 |\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8224/"
] |
75,705 |
<p>I have searched for various techniques on how to read/write dBase III (dbf) files using OLEDB or ODBC with C#/.NET. I have tried almost all of the tecniques posted, but without success. Can someone point me in the right direction?</p>
<p>Thanks for your time.</p>
|
[
{
"answer_id": 75915,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 3,
"selected": false,
"text": " ConnectionString = \"Provider=Microsoft.Jet.OLEDB.4.0;\" & _\n\"Data Source=e:\\My Documents\\dBase;Extended Properties=dBase III\"\nDim dBaseConnection As New System.Data.OleDb.OleDbConnection(ConnectionString )\ndBaseConnection.Open()\n"
},
{
"answer_id": 10492908,
"author": "Dejan Janjušević",
"author_id": 828023,
"author_profile": "https://Stackoverflow.com/users/828023",
"pm_score": 3,
"selected": false,
"text": "public partial class MyTable \n{\n public System.Int32 ID { get; set; }\n public System.Decimal Field1 { get; set; }\n public System.String Field2 { get; set; }\n public System.String Field3 { get; set; }\n}\n public partial class Context : DbEntityContextBase \n{\n public Context(string connectionString)\n : this(connectionString, typeof(ContextAttributes).FullName) \n {\n }\n\n public Context(string connectionString, string mappingId)\n : this(VfpQueryProvider.Create(connectionString, mappingId)) \n {\n }\n\n public Context(VfpQueryProvider provider)\n : base(provider) \n {\n }\n\n public virtual IEntityTable<MyTable> MyTables \n {\n get { return this.GetTable<MyTable>(); }\n }\n}\n public partial class ContextAttributes : Context \n{\n public ContextAttributes(string connectionString)\n : base(connectionString) {\n }\n\n [Table(Name=\"mytable\")]\n [Column(Member=\"ID\", IsPrimaryKey=true)]\n [Column(Member=\"Field1\")]\n [Column(Member=\"Field2\")]\n [Column(Member=\"Field3\")]\n public override IEntityTable<MyTable> MyTables \n {\n get { return base.MyTables; }\n }\n}\n Data\\ <connectionStrings>\n <add name=\"VfpData\" providerName=\"System.Data.OleDb\"\n connectionString=\"Provider=VFPOLEDB.1;Data Source=Data\\;\"/>\n</connectionStrings>\n // Construct a new context\nvar context = new Context(ConfigurationManager.ConnectionStrings[\"VfpData\"].ConnectionString);\n\n// Write to MyTable.dbf\nvar my = new MyTable\n{\n ID = 1,\n Field1 = 10,\n Field2 = \"foo\",\n Field3 = \"bar\"\n}\ncontext.MyTables.Insert(my);\n\n// Read from MyTable.dbf\nConsole.WriteLine(\"Count: \" + context.MyTables.Count());\nforeach (var o in context.MyTables)\n{\n Console.WriteLine(o.Field2 + \" \" + o.Field3);\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10333/"
] |
75,712 |
<p>I'm using membership and roles for authentication in my vb .net application. We have about 5 roles in the application with certain roles filling out a specific profile value. Example is the role is store and the profile value is store number. Obviously if you work for headquarters you don't have a store number so I don't care about it. Each store can also have more than 1 employee.</p>
<p>I need to get the users for a specific store number. Meaning I would only want the users that belong to store number 101 to show up that list. The way that we are doing this now is going through all the users and adding the users that fit the criteria into a sorted list. This functions but the problem is when you start passing about 3,000 users or so. It just becomes to slow to be any good. </p>
<p>How would you guys find a different way of doing it? I really don't want to do custom stored procedure or changing the underlying classes because I'm afraid of it all breaking on a later version of .net that they change membership and roles.</p>
|
[
{
"answer_id": 76517,
"author": "Alfonso Pajares",
"author_id": 12369,
"author_profile": "https://Stackoverflow.com/users/12369",
"pm_score": 0,
"selected": false,
"text": " Public Shared Function LoadALLUsersInRole(ByVal Code As Integer, ByVal Role As String) As ArrayList\n Dim pb As ProfileBase\n Dim usersArrayList As New ArrayList\n Dim i As Integer\n Dim AllUsersInRole() As String = Roles.GetUsersInRole(Role)\n\n For i = 0 To AllUsersInRole.Length - 1\n\n pb = ProfileBase.Create(AllUsersInRole(i), True)\n\n 'Check to see if the current user in the collect belongs to this Store.\n If CType(pb.GetPropertyValue(\"Store.Code\"), Integer) = Code Then \n usersArrayList.Add(AllUsersInRole(i)) \n End If\n pb = Nothing\n Next\n\n Return usersArrayList\n End Function\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12369/"
] |
75,713 |
<p>I'm trying to bind controls in a WPF form to an interface and I get a runtime error that it can't find the interface's properties.</p>
<p>Here's the class I'm using as a datasource:</p>
<pre><code>public interface IPerson
{
string UserId { get; set; }
string UserName { get; set; }
string Email { get; set; }
}
public class Person : EntityBase, IPerson
{
public virtual string UserId { get; set; }
public string UserName { get; set; }
public virtual string Email { get; set; }
}
</code></pre>
<p>Here's the XAML (an excerpt):</p>
<pre><code><TextBox Name="userIdTextBox" Text="{Binding UserId}" />
<TextBox Name="userNameTextBox" Text="{Binding UserName}" />
<TextBox Name="emailTextBox" Text="{Binding Email}" />
</code></pre>
<p>Here's the code behind (again, an excerpt):</p>
<pre><code>var person = PolicyInjection.Wrap<IPerson>(new Person());
person.UserId = "jdoe";
person.UserName = "John Doe";
person.Email = "[email protected]";
this.DataContext = person;
</code></pre>
<p>Note that the class I'm using as the data source needs to be an entity because I'm using Policy Injection through the entlib's Policy Injection Application Block.</p>
<p>I'm getting this error at runtime:</p>
<pre><code>System.Windows.Data Error: 16 : Cannot get 'Email' value (type 'String') from '' (type 'Person'). BindingExpression:Path=Email; DataItem='Person' (HashCode=22322349); target element is 'TextBox' (Name='emailTextBox'); target property is 'Text' (type 'String') TargetException:'System.Reflection.TargetException: Object does not match target type.
at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[] index)
at MS.Internal.Data.PropertyPathWorker.GetValue(Object item, Int32 level)
at MS.Internal.Data.PropertyPathWorker.RawValue(Int32 k)'
</code></pre>
|
[
{
"answer_id": 77322,
"author": "Robert Jeppesen",
"author_id": 9436,
"author_profile": "https://Stackoverflow.com/users/9436",
"pm_score": 3,
"selected": true,
"text": "var person = PolicyInjection.Wrap<IPerson>(new Person());\n IPerson person = new Person();\n"
},
{
"answer_id": 77356,
"author": "Senkwe",
"author_id": 6419,
"author_profile": "https://Stackoverflow.com/users/6419",
"pm_score": 0,
"selected": false,
"text": "public partial class Window1 : Window\n{\n public Window1()\n {\n InitializeComponent();\n\n IPerson person = new Person() { FirstName = \"Hovito\" };\n\n this.DataContext = person;\n }\n}\n\npublic class Person : IPerson\n{\n public virtual string FirstName { get; set; }\n public string LastName { get; set; }\n}\n\npublic interface IPerson\n{\n string FirstName { get; set; }\n string LastName { get; set; }\n}\n"
},
{
"answer_id": 9040770,
"author": "Philipp Munin",
"author_id": 508797,
"author_profile": "https://Stackoverflow.com/users/508797",
"pm_score": 0,
"selected": false,
"text": "<TextBox Name=\"userIdTextBox\" Text=\"{Binding (myns:IPerson.UserId)}\" /> \n<TextBox Name=\"userNameTextBox\" Text=\"{Binding (myns:IPerson.UserName)}\" /> \n<TextBox Name=\"emailTextBox\" Text=\"{Binding (myns:IPerson.Email)}\" /> \n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6542/"
] |
75,722 |
<p>In C#, if I want to deterministically clean up non-managed resources, I can use the "using" keyword. But for multiple dependent objects, this ends up nesting further and further:</p>
<pre><code>using (FileStream fs = new FileStream("c:\file.txt", FileMode.Open))
{
using (BufferedStream bs = new BufferedStream(fs))
{
using (StreamReader sr = new StreamReader(bs))
{
// use sr, and have everything cleaned up when done.
}
}
}
</code></pre>
<p>In C++, I'm used to being able to use destructors to do it like this:</p>
<pre><code>{
FileStream fs("c:\file.txt", FileMode.Open);
BufferedStream bs(fs);
StreamReader sr(bs);
// use sr, and have everything cleaned up when done.
}
</code></pre>
<p>Is there a better way in C# to do this? Or am I stuck with the multiple levels of nesting?</p>
|
[
{
"answer_id": 75741,
"author": "Abe Heidebrecht",
"author_id": 9268,
"author_profile": "https://Stackoverflow.com/users/9268",
"pm_score": -1,
"selected": false,
"text": " try\n {\n obj declaration\n ...\n }\n finally\n {\n obj.Dispose();\n }\n"
},
{
"answer_id": 75755,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 6,
"selected": true,
"text": "using (FileStream fs = new FileStream(\"c:\\file.txt\", FileMode.Open))\nusing (BufferedStream bs = new BufferedStream(fs))\nusing (StreamReader sr = new StreamReader(bs))\n{\n // all three get disposed when you're done\n}\n"
},
{
"answer_id": 75761,
"author": "Bob Wintemberg",
"author_id": 12999,
"author_profile": "https://Stackoverflow.com/users/12999",
"pm_score": 3,
"selected": false,
"text": " using (StreamWriter w1 = File.CreateText(\"W1\"))\n using (StreamWriter w2 = File.CreateText(\"W2\"))\n {\n // code here\n }\n"
},
{
"answer_id": 75764,
"author": "JeffFoster",
"author_id": 9853,
"author_profile": "https://Stackoverflow.com/users/9853",
"pm_score": 2,
"selected": false,
"text": "using (FileStream fs = new FileStream(\"c:\\file.txt\", FileMode.Open))\nusing (BufferedStream bs = new BufferedStream(fs))\nusing (StreamReader sr = new StreamReader(bs))\n{\n}\n"
},
{
"answer_id": 75778,
"author": "Paul van Brenk",
"author_id": 1837197,
"author_profile": "https://Stackoverflow.com/users/1837197",
"pm_score": 0,
"selected": false,
"text": "using (FileStream fs = new FileStream(\"c:\\file.txt\", FileMode.Open))\nusing (BufferedStream bs = new BufferedStream(fs))\nusing (StreamReader sr = new StreamReader(bs))\n{\n // use sr, and have everything cleaned up when done.\n}\n FileStream fs = new FileStream(\"c:\\file.txt\", FileMode.Open);\nBufferedStream bs = new BufferedStream(fs);\nStreamReader sr = new StreamReader(bs);\ntry\n{\n // use sr, and have everything cleaned up when done.\n}finally{\n sr.Close(); // should be enough since you hand control to the reader\n}\n"
},
{
"answer_id": 75836,
"author": "Michael Meadows",
"author_id": 7643,
"author_profile": "https://Stackoverflow.com/users/7643",
"pm_score": 0,
"selected": false,
"text": "using (StreamWrapper wrapper = new StreamWrapper(\"c:\\file.txt\", FileMode.Open))\n{\n // do stuff using wrapper.Reader\n}\n private class StreamWrapper : IDisposable\n{\n private readonly FileStream fs;\n private readonly BufferedStream bs;\n private readonly StreamReader sr;\n\n public StreamWrapper(string fileName, FileMode mode)\n {\n fs = new FileStream(fileName, mode);\n bs = new BufferedStream(fs);\n sr = new StreamReader(bs);\n }\n\n public StreamReader Reader\n {\n get { return sr; }\n }\n\n public void Dispose()\n {\n sr.Dispose();\n bs.Dispose();\n fs.Dispose();\n }\n}\n"
},
{
"answer_id": 76587,
"author": "Jesse C. Slicer",
"author_id": 3312,
"author_profile": "https://Stackoverflow.com/users/3312",
"pm_score": 1,
"selected": false,
"text": "StreamWrapper Dispose() Dispose() var exceptions = new List<Exception>();\n\n try\n {\n this.sr.Dispose();\n }\n catch (Exception ex)\n {\n exceptions.Add(ex);\n }\n\n try\n {\n this.bs.Dispose();\n }\n catch (Exception ex)\n {\n exceptions.Add(ex);\n }\n\n try\n {\n this.fs.Dispose();\n }\n catch (Exception ex)\n {\n exceptions.Add(ex);\n }\n\n if (exceptions.Count > 0)\n {\n throw new AggregateException(exceptions);\n }\n }\n"
},
{
"answer_id": 78362,
"author": "Joel Lucsy",
"author_id": 645,
"author_profile": "https://Stackoverflow.com/users/645",
"pm_score": 0,
"selected": false,
"text": "using (Stream Reader sr = new StreamReader( new BufferedStream( new FileStream(\"c:\\file.txt\", FileMode.Open))))\n{\n // all three get disposed when you're done\n}\n"
},
{
"answer_id": 6076898,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "const string fname = @\"c:\\1.xml\";\n\nStreamReader sr=new StreamReader(new BufferedStream(new FileStream(fname,FileMode.Open,FileAccess.Read,FileShare.Delete)));\ntextBox1.Text = sr.ReadToEnd();\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8701/"
] |
75,732 |
<p>I've seen numerous people mentions that you shouldn't use widths and padding or margins on the same element with CSS. Why is that?</p>
|
[
{
"answer_id": 78455,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 0,
"selected": false,
"text": "#content {\n width: 100%;\n padding: 0 10px;\n}\n <div id=\"content\">\n <div class=\"inner\">\n content here.\n </div>\n</div>\n\n#content {\n width: 100%;\n}\n#content .inner {\n padding: 0 10px;\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12930/"
] |
75,746 |
<pre><code>EmployeeNumber =
string.IsNullOrEmpty(employeeNumberTextBox.Text)
? null
: Convert.ToInt32(employeeNumberTextBox.Text),
</code></pre>
<p>I often find myself wanting to do things like this (<code>EmployeeNumber</code> is a <code>Nullable<int></code> as it's a property on a LINQ-to-SQL dbml object where the column allows NULL values). Unfortunately, the compiler feels that</p>
<blockquote>
<p>There is no implicit conversion between 'null' and 'int'</p>
</blockquote>
<p>even though both types would be valid in an assignment operation to a nullable int on their own.</p>
<p>Using the null coalescing operator is not an option as far as I can see because of the inline conversion that needs to happen on the <code>.Text</code> string if it's not null.</p>
<p>As far as I know the only way to do this is to use an if statement and/or assign it in two steps. In this particular case I find that very frustrating because I wanted to use the object initializer syntax and this assignment would be in the initialization block...</p>
<p>Does anyone know a more elegant solution?</p>
|
[
{
"answer_id": 75795,
"author": "Abe Heidebrecht",
"author_id": 9268,
"author_profile": "https://Stackoverflow.com/users/9268",
"pm_score": 2,
"selected": false,
"text": "EmployeeNumber = string.IsNullOrEmpty(employeeNumberTextBox.Text)\n ? null\n : (int?)Convert.ToInt32(employeeNumberTextBox.Text)\n"
},
{
"answer_id": 75822,
"author": "Alex Lyman",
"author_id": 5897,
"author_profile": "https://Stackoverflow.com/users/5897",
"pm_score": 7,
"selected": true,
"text": "null Int32 Nullable<Int32> Nullable<Int32> EmployeeNumber =\n string.IsNullOrEmpty(employeeNumberTextBox.Text)\n ? (int?)null\n : Convert.ToInt32(employeeNumberTextBox.Text),\n EmployeeNumber =\n string.IsNullOrEmpty(employeeNumberTextBox.Text)\n ? null\n : (int?)Convert.ToInt32(employeeNumberTextBox.Text),\n"
},
{
"answer_id": 75944,
"author": "NerdFury",
"author_id": 6146,
"author_profile": "https://Stackoverflow.com/users/6146",
"pm_score": 3,
"selected": false,
"text": "public static class Convert\n{\n public static T? To<T>(string value, Converter<string, T> converter) where T: struct\n {\n return string.IsNullOrEmpty(value) ? null : (T?)converter(value);\n }\n}\n EmployeeNumber = Convert.To<int>(employeeNumberTextBox.Text, Int32.Parse);\n"
},
{
"answer_id": 76049,
"author": "user13493",
"author_id": 13493,
"author_profile": "https://Stackoverflow.com/users/13493",
"pm_score": 3,
"selected": false,
"text": "TryParse int value;\nint? EmployeeNumber = int.TryParse(employeeNumberTextBox.Text, out value)\n ? (int?)value\n : null;\n 1b Convert.ToInt32(string)"
},
{
"answer_id": 29851598,
"author": "Sandeep",
"author_id": 1604050,
"author_profile": "https://Stackoverflow.com/users/1604050",
"pm_score": 1,
"selected": false,
"text": "//Some operation to populate Posid.I am not interested in zero or null\nint? Posid = SvcClient.GetHolidayCount(xDateFrom.Value.Date,xDateTo.Value.Date).Response;\nvar x1 = (Posid.HasValue && Posid.Value > 0) ? (int?)Posid.Value : null;\n Posid int X1 (int?) Posid.Value GetHolidayCount WCF null"
},
{
"answer_id": 62727948,
"author": "Glorfindel",
"author_id": 4751173,
"author_profile": "https://Stackoverflow.com/users/4751173",
"pm_score": 0,
"selected": false,
"text": "Person person = student ?? customer; // Shared base type\nint? result = b ? 0 : null; // nullable value type\n EmployeeNumber =\nstring.IsNullOrEmpty(employeeNumberTextBox.Text)\n ? null\n : Convert.ToInt32(employeeNumberTextBox.Text),\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12975/"
] |
75,752 |
<p>I'm building a quick csv from a mysql table with a query like:</p>
<pre><code>select DATE(date),count(date) from table group by DATE(date) order by date asc;
</code></pre>
<p>and just dumping them to a file in perl over a:</p>
<pre><code>while(my($date,$sum) = $sth->fetchrow) {
print CSV "$date,$sum\n"
}
</code></pre>
<p>There are date gaps in the data, though:</p>
<pre><code>| 2008-08-05 | 4 |
| 2008-08-07 | 23 |
</code></pre>
<p>I would like to pad the data to fill in the missing days with zero-count entries to end up with:</p>
<pre><code>| 2008-08-05 | 4 |
| 2008-08-06 | 0 |
| 2008-08-07 | 23 |
</code></pre>
<p>I slapped together a really awkward (and almost certainly buggy) workaround with an array of days-per-month and some math, but there has to be something more straightforward either on the mysql or perl side. </p>
<p>Any genius ideas/slaps in the face for why me am being so dumb?</p>
<hr>
<p>I ended up going with a stored procedure which generated a temp table for the date range in question for a couple of reasons:</p>
<ul>
<li>I know the date range I'll be looking for every time</li>
<li>The server in question unfortunately was not one that I can install perl modules on atm, and the state of it was decrepit enough that it didn't have anything remotely Date::-y installed</li>
</ul>
<p>The perl Date/DateTime-iterating answers were also very good, I wish I could select multiple answers!</p>
|
[
{
"answer_id": 75807,
"author": "Aeon",
"author_id": 13289,
"author_profile": "https://Stackoverflow.com/users/13289",
"pm_score": 3,
"selected": false,
"text": "SELECT DATE(r.date),count(d.date) \nFROM dates AS r \nLEFT JOIN table AS d ON d.date = r.date \nGROUP BY DATE(r.date) \nORDER BY r.date ASC;\n"
},
{
"answer_id": 75865,
"author": "coffeepac",
"author_id": 13421,
"author_profile": "https://Stackoverflow.com/users/13421",
"pm_score": 2,
"selected": false,
"text": "my $current_date = Date::EzDate->new();\n$current_date->{'default'} = '{YEAR}-{MONTH NUMBER BASE 1}-{DAY OF MONTH}';\nwhile ($current_date <= $final_date)\n{\n print \"$current_date\\t|\\t%hash_o_data{$current_date}\"; # EzDate provides for automatic stringification in the format specfied in 'default'\n $current_date++;\n}\n"
},
{
"answer_id": 75928,
"author": "GSerg",
"author_id": 11683,
"author_profile": "https://Stackoverflow.com/users/11683",
"pm_score": 5,
"selected": true,
"text": "create procedure sp1(d1 date, d2 date)\n declare d datetime;\n\n create temporary table foo (d date not null);\n\n set d = d1\n while d <= d2 do\n insert into foo (d) values (d)\n set d = date_add(d, interval 1 day)\n end while\n\n select foo.d, count(date)\n from foo left join table on foo.d = table.date\n group by foo.d order by foo.d asc;\n\n drop temporary table foo;\nend procedure\n"
},
{
"answer_id": 76081,
"author": "8jean",
"author_id": 10011,
"author_profile": "https://Stackoverflow.com/users/10011",
"pm_score": 2,
"selected": false,
"text": "use DateTime;\nmy $dt;\n\nwhile ( my ($date, $sum) = $sth->fetchrow ) {\n if (defined $dt) {\n print CSV $dt->ymd . \",0\\n\" while $dt->add(days => 1)->ymd lt $date;\n }\n else {\n my ($y, $m, $d) = split /-/, $date;\n $dt = DateTime->new(year => $y, month => $m, day => $d);\n }\n print CSV, \"$date,$sum\\n\";\n}\n DateTime $dt $dt CSV"
},
{
"answer_id": 76147,
"author": "castaway",
"author_id": 4840,
"author_profile": "https://Stackoverflow.com/users/4840",
"pm_score": 1,
"selected": false,
"text": "use DateTime;\nuse DateTime::Format::Strptime;\nmy @row = $sth->fetchrow;\nmy $countdate = strptime(\"%Y-%m-%d\", $firstrow[0]);\nmy $thisdate = strptime(\"%Y-%m-%d\", $firstrow[0]);\n\nwhile ($countdate) {\n # keep looping countdate until it hits the next db row date\n if(DateTime->compare($countdate, $thisdate) == -1) {\n # counter not reached next date yet\n print CSV $countdate->ymd . \",0\\n\";\n $countdate = $countdate->add( days => 1 );\n $next;\n }\n\n # countdate is equal to next row's date, so print that instead\n print CSV $thisdate->ymd . \",$row[1]\\n\";\n\n # increase both\n @row = $sth->fetchrow;\n $thisdate = strptime(\"%Y-%m-%d\", $firstrow[0]);\n $countdate = $countdate->add( days => 1 );\n}\n"
},
{
"answer_id": 6156000,
"author": "theazureshadow",
"author_id": 177633,
"author_profile": "https://Stackoverflow.com/users/177633",
"pm_score": 1,
"selected": false,
"text": "Ordinal CREATE TABLE IF NOT EXISTS `Ordinal` (\n `n` int(10) unsigned NOT NULL AUTO_INCREMENT, PRIMARY KEY (`n`)\n);\nINSERT INTO `Ordinal` (`n`)\nVALUES (NULL), (NULL), (NULL); #etc\n LEFT JOIN Ordinal SELECT CURDATE() - INTERVAL `n` DAY AS `day`\nFROM `Ordinal` WHERE `n` <= 7\nORDER BY `n` ASC\n SET @var = 'value' SET @end = CURDATE() - INTERVAL DAY(CURDATE()) DAY;\nSET @begin = @end - INTERVAL 3 MONTH;\nSET @period = DATEDIFF(@end, @begin);\n\nSELECT @begin + INTERVAL (`n` + 1) DAY AS `date`\nFROM `Ordinal` WHERE `n` < @period\nORDER BY `n` ASC;\n SELECT COUNT(`msg`.`id`) AS `message_count`, `ord`.`date` FROM (\n SELECT ((CURDATE() - INTERVAL DAY(CURDATE()) DAY) - INTERVAL 3 MONTH) + INTERVAL (`n` + 1) DAY AS `date`\n FROM `Ordinal`\n WHERE `n` < (DATEDIFF((CURDATE() - INTERVAL DAY(CURDATE()) DAY), ((CURDATE() - INTERVAL DAY(CURDATE()) DAY) - INTERVAL 3 MONTH)))\n ORDER BY `n` ASC\n) AS `ord`\nLEFT JOIN `Message` AS `msg`\n ON `ord`.`date` = `msg`.`date`\nGROUP BY `ord`.`date`\n Ordinal Ordinal Ordinal Ordinal Ordinal INSERT INTO ... SELECT"
},
{
"answer_id": 16318007,
"author": "Igor Kryltsov",
"author_id": 1051674,
"author_profile": "https://Stackoverflow.com/users/1051674",
"pm_score": 2,
"selected": false,
"text": "select * from (\nselect date_add('2003-01-01 00:00:00.000', INTERVAL n5.num*10000+n4.num*1000+n3.num*100+n2.num*10+n1.num DAY ) as date from\n(select 0 as num\n union all select 1\n union all select 2\n union all select 3\n union all select 4\n union all select 5\n union all select 6\n union all select 7\n union all select 8\n union all select 9) n1,\n(select 0 as num\n union all select 1\n union all select 2\n union all select 3\n union all select 4\n union all select 5\n union all select 6\n union all select 7\n union all select 8\n union all select 9) n2,\n(select 0 as num\n union all select 1\n union all select 2\n union all select 3\n union all select 4\n union all select 5\n union all select 6\n union all select 7\n union all select 8\n union all select 9) n3,\n(select 0 as num\n union all select 1\n union all select 2\n union all select 3\n union all select 4\n union all select 5\n union all select 6\n union all select 7\n union all select 8\n union all select 9) n4,\n(select 0 as num\n union all select 1\n union all select 2\n union all select 3\n union all select 4\n union all select 5\n union all select 6\n union all select 7\n union all select 8\n union all select 9) n5\n) a\nwhere date >'2011-01-02 00:00:00.000' and date < NOW()\norder by date\n select n3.num*100+n2.num*10+n1.num as date\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13196/"
] |
75,759 |
<p>What's the best way to implement the enum idiom in Ruby? I'm looking for something which I can use (almost) like the Java/C# enums.</p>
|
[
{
"answer_id": 75787,
"author": "Jan Krüger",
"author_id": 12471,
"author_profile": "https://Stackoverflow.com/users/12471",
"pm_score": 1,
"selected": false,
"text": ":foo_bar"
},
{
"answer_id": 75801,
"author": "emk",
"author_id": 12089,
"author_profile": "https://Stackoverflow.com/users/12089",
"pm_score": 6,
"selected": false,
"text": "enum {\n FOO,\n BAR,\n BAZ\n}\n\nmyFunc(FOO);\n # You don't actually need to declare these, of course--this is\n# just to show you what symbols look like.\n:foo\n:bar\n:baz\n\nmy_func(:foo)\n"
},
{
"answer_id": 76046,
"author": "mlibby",
"author_id": 13468,
"author_profile": "https://Stackoverflow.com/users/13468",
"pm_score": 9,
"selected": true,
"text": ":foo FOO postal_code[:minnesota] = \"MN\"\npostal_code[:new_york] = \"NY\"\n module Foo\n BAR = 1\n BAZ = 2\n BIZ = 4\nend\n \nflags = Foo::BAR | Foo::BAZ # flags = 3\n COMMODITY_TYPE = {\n currency: 1,\n investment: 2,\n}\n\ndef commodity_type_string(value)\n COMMODITY_TYPE.key(value)\nend\n\nCOMMODITY_TYPE[:currency]\n"
},
{
"answer_id": 76722,
"author": "mislav",
"author_id": 11687,
"author_profile": "https://Stackoverflow.com/users/11687",
"pm_score": 2,
"selected": false,
"text": "Set >> enum = Set['a', 'b', 'c']\n=> #<Set: {\"a\", \"b\", \"c\"}>\n>> enum.member? \"b\"\n=> true\n>> enum.member? \"d\"\n=> false\n>> enum.add? \"b\"\n=> nil\n>> enum.add? \"d\"\n=> #<Set: {\"a\", \"b\", \"c\", \"d\"}>\n"
},
{
"answer_id": 164514,
"author": "Jonke",
"author_id": 15638,
"author_profile": "https://Stackoverflow.com/users/15638",
"pm_score": 2,
"selected": false,
"text": "#server_roles.rb\nmodule EnumLike\n\n def EnumLike.server_role\n server_Symb=[ :SERVER_CLOUD, :SERVER_DESKTOP, :SERVER_WORKSTATION]\n server_Enum=Hash.new\n i=0\n server_Symb.each{ |e| server_Enum[e]=i; i +=1}\n return server_Symb,server_Enum\n end\n\nend\n require 'server_roles'\n\nsSymb, sEnum =EnumLike.server_role()\n\nforeignvec[sEnum[:SERVER_WORKSTATION]]=8\n"
},
{
"answer_id": 5332215,
"author": "dB.",
"author_id": 123094,
"author_profile": "https://Stackoverflow.com/users/123094",
"pm_score": 3,
"selected": false,
"text": "class Gender\n include Enum\n\n Gender.define :MALE, \"male\"\n Gender.define :FEMALE, \"female\"\nend\n\nGender.all\nGender::MALE\n"
},
{
"answer_id": 5332950,
"author": "Andrew Grimm",
"author_id": 38765,
"author_profile": "https://Stackoverflow.com/users/38765",
"pm_score": 3,
"selected": false,
"text": "fetch [] my_value = my_hash.fetch(:key)\n my_hash = Hash.new do |hash, key|\n raise \"You tried to access using #{key.inspect} when the only keys we have are #{hash.keys.inspect}\"\nend\n my_hash = Hash[[[1,2]]]\nmy_hash.default_proc = proc do |hash, key|\n raise \"You tried to access using #{key.inspect} when the only keys we have are #{hash.keys.inspect}\"\nend\n"
},
{
"answer_id": 5675566,
"author": "Alexey",
"author_id": 126529,
"author_profile": "https://Stackoverflow.com/users/126529",
"pm_score": 6,
"selected": false,
"text": "class MyClass\n MY_ENUM = [MY_VALUE_1 = 'value1', MY_VALUE_2 = 'value2']\nend\n MY_ENUM MY_VALUE_1 MyClass::MY_VALUE_1"
},
{
"answer_id": 6170494,
"author": "Charles",
"author_id": 48483,
"author_profile": "https://Stackoverflow.com/users/48483",
"pm_score": 6,
"selected": false,
"text": "class Enum\n\n private\n\n def self.enum_attr(name, num)\n name = name.to_s\n\n define_method(name + '?') do\n @attrs & num != 0\n end\n\n define_method(name + '=') do |set|\n if set\n @attrs |= num\n else\n @attrs &= ~num\n end\n end\n end\n\n public\n\n def initialize(attrs = 0)\n @attrs = attrs\n end\n\n def to_i\n @attrs\n end\nend\n class FileAttributes < Enum\n enum_attr :readonly, 0x0001\n enum_attr :hidden, 0x0002\n enum_attr :system, 0x0004\n enum_attr :directory, 0x0010\n enum_attr :archive, 0x0020\n enum_attr :in_rom, 0x0040\n enum_attr :normal, 0x0080\n enum_attr :temporary, 0x0100\n enum_attr :sparse, 0x0200\n enum_attr :reparse_point, 0x0400\n enum_attr :compressed, 0x0800\n enum_attr :rom_module, 0x2000\nend\n >> example = FileAttributes.new(3)\n=> #<FileAttributes:0x629d90 @attrs=3>\n>> example.readonly?\n=> true\n>> example.hidden?\n=> true\n>> example.system?\n=> false\n>> example.system = true\n=> true\n>> example.system?\n=> true\n>> example.to_i\n=> 7\n"
},
{
"answer_id": 9482922,
"author": "Masuschi",
"author_id": 1238002,
"author_profile": "https://Stackoverflow.com/users/1238002",
"pm_score": 2,
"selected": false,
"text": "module EnumType\n\n def self.find_by_id id\n if id.instance_of? String\n id = id.to_i\n end \n values.each do |type|\n if id == type.id\n return type\n end\n end\n nil\n end\n\n def self.values\n [@ENUM_1, @ENUM_2] \n end\n\n class Enum\n attr_reader :id, :label\n\n def initialize id, label\n @id = id\n @label = label\n end\n end\n\n @ENUM_1 = Enum.new(1, \"first\")\n @ENUM_2 = Enum.new(2, \"second\")\n\nend\n EnumType.ENUM_1.label\n enum = EnumType.find_by_id 1\n valueArray = EnumType.values\n"
},
{
"answer_id": 9582957,
"author": "Anu",
"author_id": 1252072,
"author_profile": "https://Stackoverflow.com/users/1252072",
"pm_score": 1,
"selected": false,
"text": "irb(main):016:0> num=[1,2,3,4]\nirb(main):017:0> alph=['a','b','c','d']\nirb(main):018:0> l_enum=alph.to_enum\nirb(main):019:0> s_enum=num.to_enum\nirb(main):020:0> loop do\nirb(main):021:1* puts \"#{s_enum.next} - #{l_enum.next}\"\nirb(main):022:1> end\n"
},
{
"answer_id": 11432676,
"author": "Hossein",
"author_id": 1107992,
"author_profile": "https://Stackoverflow.com/users/1107992",
"pm_score": 2,
"selected": false,
"text": "module Status\n BAD = 13\n GOOD = 24\n\n def self.to_str(status)\n for sym in self.constants\n if self.const_get(sym) == status\n return sym.to_s\n end\n end\n end\n\nend\n\n\nmystatus = Status::GOOD\n\nputs Status::to_str(mystatus)\n GOOD\n"
},
{
"answer_id": 11455651,
"author": "johnnypez",
"author_id": 366277,
"author_profile": "https://Stackoverflow.com/users/366277",
"pm_score": 4,
"selected": false,
"text": "module Kernel\n def enum(values)\n Module.new do |mod|\n values.each_with_index{ |v,i| mod.const_set(v.to_s.capitalize, 2**i) }\n\n def mod.inspect\n \"#{self.name} {#{self.constants.join(', ')}}\"\n end\n end\n end\nend\n\nStates = enum %w(Draft Published Trashed)\n=> States {Draft, Published, Trashed} \n\nStates::Draft\n=> 1\n\nStates::Published\n=> 2\n\nStates::Trashed\n=> 4\n\nStates::Draft | States::Trashed\n=> 5\n"
},
{
"answer_id": 13764335,
"author": "Oded Niv",
"author_id": 1056158,
"author_profile": "https://Stackoverflow.com/users/1056158",
"pm_score": 4,
"selected": false,
"text": "COLORS = Enum.new(:COLORS, :red => 1, :green => 2, :blue => 3)\n=> COLORS(:red => 1, :green => 2, :blue => 3)\nCOLORS.red == 1 && COLORS.red == :red\n=> true\n\nclass Car < ActiveRecord::Base \n attr_enum :color, :COLORS, :red => 1, :black => 2\nend\ncar = Car.new\ncar.color = :red / \"red\" / 1 / \"1\"\ncar.color\n=> Car::COLORS.red\ncar.color.black?\n=> false\nCar.red.to_sql\n=> \"SELECT `cars`.* FROM `cars` WHERE `cars`.`color` = 1\"\nCar.last.red?\n=> true\n"
},
{
"answer_id": 14087590,
"author": "Daniel Doubleday",
"author_id": 1104754,
"author_profile": "https://Stackoverflow.com/users/1104754",
"pm_score": 0,
"selected": false,
"text": "class Enum\n def self.new(values = nil)\n enum = Class.new do\n unless values\n def self.const_missing(name)\n const_set(name, new(name))\n end\n end\n\n def initialize(name)\n @enum_name = name\n end\n\n def to_s\n \"#{self.class}::#@enum_name\"\n end\n end\n\n if values\n enum.instance_eval do\n values.each { |e| const_set(e, enum.new(e)) }\n end\n end\n\n enum\n end\nend\n\nGenre = Enum.new %w(Gothic Metal) # creates closed enum\nArchitecture = Enum.new # creates open enum\n\nGenre::Gothic == Genre::Gothic # => true\nGenre::Gothic != Architecture::Gothic # => true\n"
},
{
"answer_id": 16046129,
"author": "jjk",
"author_id": 1965639,
"author_profile": "https://Stackoverflow.com/users/1965639",
"pm_score": 2,
"selected": false,
"text": "#model\nclass Profession\n def self.pro_enum\n {:BAKER => 0, \n :MANAGER => 1, \n :FIREMAN => 2, \n :DEV => 3, \n :VAL => [\"BAKER\", \"MANAGER\", \"FIREMAN\", \"DEV\"]\n }\n end\nend\n\nProfession.pro_enum[:DEV] #=>3\nProfession.pro_enum[:VAL][1] #=>MANAGER\n"
},
{
"answer_id": 27349423,
"author": "Vedant Agarwala",
"author_id": 1396264,
"author_profile": "https://Stackoverflow.com/users/1396264",
"pm_score": 4,
"selected": false,
"text": "class Conversation < ActiveRecord::Base\n enum status: [ :active, :archived ]\nend\n\n# conversation.update! status: 0\nconversation.active!\nconversation.active? # => true\nconversation.status # => \"active\"\n\n# conversation.update! status: 1\nconversation.archived!\nconversation.archived? # => true\nconversation.status # => \"archived\"\n\n# conversation.update! status: 1\nconversation.status = \"archived\"\n\n# conversation.update! status: nil\nconversation.status = nil\nconversation.status.nil? # => true\nconversation.status # => nil\n"
},
{
"answer_id": 27574382,
"author": "Daniel Lubarov",
"author_id": 714009,
"author_profile": "https://Stackoverflow.com/users/714009",
"pm_score": 3,
"selected": false,
"text": "module MyConstants\n ABC = Class.new\n DEF = Class.new\n GHI = Class.new\nend\n MyConstants::ABC\n=> MyConstants::ABC\n MyConstants.constants\n=> [:ABC, :DEF, :GHI] \n MyConstants.constants.index :GHI\n=> 2\n"
},
{
"answer_id": 32149803,
"author": "dark_src",
"author_id": 371572,
"author_profile": "https://Stackoverflow.com/users/371572",
"pm_score": 1,
"selected": false,
"text": "module Enum\n def get_value(str)\n const_get(str)\n end\n def get_name(sym)\n sym.to_s.upcase\n end\n end\n\n class Fruits\n include Enum\n APPLE = \"Delicious\"\n MANGO = \"Sweet\"\n end\n\n Fruits.get_value('APPLE') #'Delicious'\n Fruits.get_value('MANGO') # 'Sweet'\n\n Fruits.get_name(:apple) # 'APPLE'\n Fruits.get_name(:mango) # 'MANGO'\n"
},
{
"answer_id": 45097718,
"author": "Roger",
"author_id": 549010,
"author_profile": "https://Stackoverflow.com/users/549010",
"pm_score": 3,
"selected": false,
"text": "# bar.rb\nrequire 'ostruct' # not needed when using Rails\n\n# by patching Array you have a simple way of creating a ENUM-style\nclass Array\n def to_enum(base=0)\n OpenStruct.new(map.with_index(base).to_h)\n end\nend\n\nclass Bar\n\n MY_ENUM = OpenStruct.new(ONE: 1, TWO: 2, THREE: 3)\n MY_ENUM2 = %w[ONE TWO THREE].to_enum\n\n def use_enum (value)\n case value\n when MY_ENUM.ONE\n puts \"Hello, this is ENUM 1\"\n when MY_ENUM.TWO\n puts \"Hello, this is ENUM 2\"\n when MY_ENUM.THREE\n puts \"Hello, this is ENUM 3\"\n else\n puts \"#{value} not found in ENUM\"\n end\n end\n\nend\n\n# usage\nfoo = Bar.new \nfoo.use_enum 1\nfoo.use_enum 2\nfoo.use_enum 9\n\n\n# put this code in a file 'bar.rb', start IRB and type: load 'bar.rb'\n"
},
{
"answer_id": 48199917,
"author": "horun",
"author_id": 3940165,
"author_profile": "https://Stackoverflow.com/users/3940165",
"pm_score": 1,
"selected": false,
"text": "class Color < Inum::Base\n define :RED\n define :GREEN\n define :BLUE\nend\n Color::RED \nColor.parse('blue') # => Color::BLUE\nColor.parse(2) # => Color::GREEN\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4110/"
] |
75,763 |
<p>1.exe doesn't give enough time for me to launch the IDE and attach 1.exe to the debugger to break into.</p>
|
[
{
"answer_id": 75803,
"author": "Greg Hurlman",
"author_id": 35,
"author_profile": "https://Stackoverflow.com/users/35",
"pm_score": 0,
"selected": false,
"text": "#ifdef DEBUG\nThread.Sleep(10000);\n#endif\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13432/"
] |
75,777 |
<p>I assumed that the C# margin property had a meaning like in CSS - the spacing around the outside of the control. But Margin values seem to be ignored to matter what values I enter.</p>
<p>Then I read on the SDK: </p>
<blockquote>
<p>Setting the Margin property on a
docked control has no effect on the
distance of the control from the the
edges of its container.</p>
</blockquote>
<p>Given that I'm placing controls on forms, and perhaps docking them, what does the Margin property get me?</p>
|
[
{
"answer_id": 75911,
"author": "OwenP",
"author_id": 2547,
"author_profile": "https://Stackoverflow.com/users/2547",
"pm_score": 3,
"selected": false,
"text": "TableLayoutPanel using System.Drawing;\nusing System.Windows.Forms;\n\nnamespace WindowsFormsApplication1\n{\n public partial class Form1 : Form\n {\n public Form1()\n {\n InitializeComponent();\n\n TableLayoutPanel pnl = new TableLayoutPanel();\n pnl.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50));\n pnl.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50));\n pnl.Dock = DockStyle.Fill;\n this.Controls.Add(pnl);\n\n Button btn1 = new Button();\n btn1.Text = \"No margin\";\n btn1.Dock = DockStyle.Fill;\n\n Button btn2 = new Button();\n btn2.Margin = new Padding(25);\n btn2.Text = \"Margin\";\n btn2.Dock = DockStyle.Fill;\n\n pnl.Controls.Add(btn1, 0, 0);\n pnl.Controls.Add(btn2, 1, 0);\n }\n }\n} FlowLayoutPanel TableLayoutPanel"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12597/"
] |
75,785 |
<p>Is there any complete guidance on doing AppBar docking (such as locking to the screen edge) in WPF? I understand there are InterOp calls that need to be made, but I'm looking for either a proof of concept based on a simple WPF form, or a componentized version that can be consumed.</p>
<p>Related resources:</p>
<ul>
<li><a href="http://www.codeproject.com/KB/dotnet/AppBar.aspx" rel="noreferrer">http://www.codeproject.com/KB/dotnet/AppBar.aspx</a></li>
<li><a href="http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/05c73c9c-e85d-4ecd-b9b6-4c714a65e72b/" rel="noreferrer">http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/05c73c9c-e85d-4ecd-b9b6-4c714a65e72b/</a></li>
</ul>
|
[
{
"answer_id": 84987,
"author": "Philip Rieck",
"author_id": 12643,
"author_profile": "https://Stackoverflow.com/users/12643",
"pm_score": 8,
"selected": true,
"text": "AppBarFunctions.SetAppBar( this, ABEdge.Right );\n AppBarFunctions.SetAppBar( this, ABEdge.None );\n using System;\nusing System.Collections.Generic;\nusing System.Runtime.InteropServices;\nusing System.Windows;\nusing System.Windows.Interop;\nusing System.Windows.Threading;\n\nnamespace AppBarApplication\n{ \n public enum ABEdge : int\n {\n Left = 0,\n Top,\n Right,\n Bottom,\n None\n }\n\n internal static class AppBarFunctions\n {\n [StructLayout(LayoutKind.Sequential)]\n private struct RECT\n {\n public int left;\n public int top;\n public int right;\n public int bottom;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n private struct APPBARDATA\n {\n public int cbSize;\n public IntPtr hWnd;\n public int uCallbackMessage;\n public int uEdge;\n public RECT rc;\n public IntPtr lParam;\n }\n\n private enum ABMsg : int\n {\n ABM_NEW = 0,\n ABM_REMOVE,\n ABM_QUERYPOS,\n ABM_SETPOS,\n ABM_GETSTATE,\n ABM_GETTASKBARPOS,\n ABM_ACTIVATE,\n ABM_GETAUTOHIDEBAR,\n ABM_SETAUTOHIDEBAR,\n ABM_WINDOWPOSCHANGED,\n ABM_SETSTATE\n }\n private enum ABNotify : int\n {\n ABN_STATECHANGE = 0,\n ABN_POSCHANGED,\n ABN_FULLSCREENAPP,\n ABN_WINDOWARRANGE\n }\n\n [DllImport(\"SHELL32\", CallingConvention = CallingConvention.StdCall)]\n private static extern uint SHAppBarMessage(int dwMessage, ref APPBARDATA pData);\n\n [DllImport(\"User32.dll\", CharSet = CharSet.Auto)]\n private static extern int RegisterWindowMessage(string msg);\n\n private class RegisterInfo\n {\n public int CallbackId { get; set; }\n public bool IsRegistered { get; set; }\n public Window Window { get; set; }\n public ABEdge Edge { get; set; }\n public WindowStyle OriginalStyle { get; set; } \n public Point OriginalPosition { get; set; }\n public Size OriginalSize { get; set; }\n public ResizeMode OriginalResizeMode { get; set; }\n\n\n public IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, \n IntPtr lParam, ref bool handled)\n {\n if (msg == CallbackId)\n {\n if (wParam.ToInt32() == (int)ABNotify.ABN_POSCHANGED)\n {\n ABSetPos(Edge, Window);\n handled = true;\n }\n }\n return IntPtr.Zero;\n }\n\n }\n private static Dictionary<Window, RegisterInfo> s_RegisteredWindowInfo \n = new Dictionary<Window, RegisterInfo>();\n private static RegisterInfo GetRegisterInfo(Window appbarWindow)\n {\n RegisterInfo reg;\n if( s_RegisteredWindowInfo.ContainsKey(appbarWindow))\n {\n reg = s_RegisteredWindowInfo[appbarWindow];\n }\n else\n {\n reg = new RegisterInfo()\n {\n CallbackId = 0,\n Window = appbarWindow,\n IsRegistered = false,\n Edge = ABEdge.Top,\n OriginalStyle = appbarWindow.WindowStyle, \n OriginalPosition =new Point( appbarWindow.Left, appbarWindow.Top),\n OriginalSize = \n new Size( appbarWindow.ActualWidth, appbarWindow.ActualHeight),\n OriginalResizeMode = appbarWindow.ResizeMode,\n };\n s_RegisteredWindowInfo.Add(appbarWindow, reg);\n }\n return reg;\n }\n\n private static void RestoreWindow(Window appbarWindow)\n {\n RegisterInfo info = GetRegisterInfo(appbarWindow);\n\n appbarWindow.WindowStyle = info.OriginalStyle; \n appbarWindow.ResizeMode = info.OriginalResizeMode;\n appbarWindow.Topmost = false;\n\n Rect rect = new Rect(info.OriginalPosition.X, info.OriginalPosition.Y, \n info.OriginalSize.Width, info.OriginalSize.Height);\n appbarWindow.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle,\n new ResizeDelegate(DoResize), appbarWindow, rect);\n\n }\n\n public static void SetAppBar(Window appbarWindow, ABEdge edge)\n {\n RegisterInfo info = GetRegisterInfo(appbarWindow);\n info.Edge = edge;\n\n APPBARDATA abd = new APPBARDATA();\n abd.cbSize = Marshal.SizeOf(abd);\n abd.hWnd = new WindowInteropHelper(appbarWindow).Handle;\n\n if( edge == ABEdge.None)\n {\n if( info.IsRegistered)\n {\n SHAppBarMessage((int)ABMsg.ABM_REMOVE, ref abd);\n info.IsRegistered = false;\n }\n RestoreWindow(appbarWindow);\n return;\n }\n\n if (!info.IsRegistered)\n {\n info.IsRegistered = true; \n info.CallbackId = RegisterWindowMessage(\"AppBarMessage\");\n abd.uCallbackMessage = info.CallbackId;\n\n uint ret = SHAppBarMessage((int)ABMsg.ABM_NEW, ref abd);\n\n HwndSource source = HwndSource.FromHwnd(abd.hWnd);\n source.AddHook(new HwndSourceHook(info.WndProc));\n }\n\n appbarWindow.WindowStyle = WindowStyle.None; \n appbarWindow.ResizeMode = ResizeMode.NoResize;\n appbarWindow.Topmost = true;\n\n ABSetPos(info.Edge, appbarWindow); \n }\n\n private delegate void ResizeDelegate(Window appbarWindow, Rect rect);\n private static void DoResize(Window appbarWindow, Rect rect)\n {\n appbarWindow.Width = rect.Width;\n appbarWindow.Height = rect.Height;\n appbarWindow.Top = rect.Top;\n appbarWindow.Left = rect.Left;\n }\n\n\n\n private static void ABSetPos(ABEdge edge, Window appbarWindow)\n {\n APPBARDATA barData = new APPBARDATA();\n barData.cbSize = Marshal.SizeOf(barData);\n barData.hWnd = new WindowInteropHelper(appbarWindow).Handle;\n barData.uEdge = (int)edge;\n\n if (barData.uEdge == (int)ABEdge.Left || barData.uEdge == (int)ABEdge.Right)\n {\n barData.rc.top = 0;\n barData.rc.bottom = (int)SystemParameters.PrimaryScreenHeight;\n if (barData.uEdge == (int)ABEdge.Left)\n {\n barData.rc.left = 0;\n barData.rc.right = (int)Math.Round(appbarWindow.ActualWidth);\n }\n else\n {\n barData.rc.right = (int)SystemParameters.PrimaryScreenWidth;\n barData.rc.left = barData.rc.right - (int)Math.Round(appbarWindow.ActualWidth);\n }\n }\n else\n {\n barData.rc.left = 0;\n barData.rc.right = (int)SystemParameters.PrimaryScreenWidth;\n if (barData.uEdge == (int)ABEdge.Top)\n {\n barData.rc.top = 0;\n barData.rc.bottom = (int)Math.Round(appbarWindow.ActualHeight);\n }\n else\n {\n barData.rc.bottom = (int)SystemParameters.PrimaryScreenHeight;\n barData.rc.top = barData.rc.bottom - (int)Math.Round(appbarWindow.ActualHeight);\n }\n }\n\n SHAppBarMessage((int)ABMsg.ABM_QUERYPOS, ref barData);\n SHAppBarMessage((int)ABMsg.ABM_SETPOS, ref barData);\n\n Rect rect = new Rect((double)barData.rc.left, (double)barData.rc.top, \n (double)(barData.rc.right - barData.rc.left), (double)(barData.rc.bottom - barData.rc.top));\n //This is done async, because WPF will send a resize after a new appbar is added. \n //if we size right away, WPFs resize comes last and overrides us.\n appbarWindow.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, \n new ResizeDelegate(DoResize), appbarWindow, rect);\n }\n }\n}\n"
},
{
"answer_id": 779175,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": " SHAppBarMessage((int)ABMsg.ABM_QUERYPOS, ref barData);\n\n if (barData.uEdge == (int)ABEdge.Top)\n barData.rc.bottom = barData.rc.top + (int)Math.Round(appbarWindow.ActualHeight);\n else if (barData.uEdge == (int)ABEdge.Bottom)\n barData.rc.top = barData.rc.bottom - (int)Math.Round(appbarWindow.ActualHeight);\n\n SHAppBarMessage((int)ABMsg.ABM_SETPOS, ref barData);\n"
},
{
"answer_id": 5610186,
"author": "Dmitry Andreev",
"author_id": 700625,
"author_profile": "https://Stackoverflow.com/users/700625",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Runtime.InteropServices;\nusing System.Windows;\nusing System.Windows.Interop;\nusing System.Windows.Threading;\n\nnamespace wpf_appbar\n{\n public enum ABEdge : int\n {\n Left,\n Top,\n Right,\n Bottom,\n None\n }\n\n internal static class AppBarFunctions\n {\n [StructLayout(LayoutKind.Sequential)]\n private struct RECT\n {\n public int Left;\n public int Top;\n public int Right;\n public int Bottom;\n public RECT(Rect r)\n {\n Left = (int)r.Left;\n Right = (int)r.Right;\n Top = (int)r.Top;\n Bottom = (int)r.Bottom;\n }\n public static bool operator ==(RECT r1, RECT r2)\n {\n return r1.Bottom == r2.Bottom && r1.Left == r2.Left && r1.Right == r2.Right && r1.Top == r2.Top;\n }\n public static bool operator !=(RECT r1, RECT r2)\n {\n return !(r1 == r2);\n }\n public override bool Equals(object obj)\n {\n return base.Equals(obj);\n }\n public override int GetHashCode()\n {\n return base.GetHashCode();\n }\n }\n\n [StructLayout(LayoutKind.Sequential)]\n private struct APPBARDATA\n {\n public int cbSize;\n public IntPtr hWnd;\n public int uCallbackMessage;\n public int uEdge;\n public RECT rc;\n public IntPtr lParam;\n }\n\n private enum ABMsg : int\n {\n ABM_NEW = 0,\n ABM_REMOVE,\n ABM_QUERYPOS,\n ABM_SETPOS,\n ABM_GETSTATE,\n ABM_GETTASKBARPOS,\n ABM_ACTIVATE,\n ABM_GETAUTOHIDEBAR,\n ABM_SETAUTOHIDEBAR,\n ABM_WINDOWPOSCHANGED,\n ABM_SETSTATE\n }\n private enum ABNotify : int\n {\n ABN_STATECHANGE = 0,\n ABN_POSCHANGED,\n ABN_FULLSCREENAPP,\n ABN_WINDOWARRANGE\n }\n\n private enum TaskBarPosition : int\n {\n Left,\n Top,\n Right,\n Bottom\n }\n\n [StructLayout(LayoutKind.Sequential)]\n class TaskBar\n {\n public TaskBarPosition Position;\n public TaskBarPosition PreviousPosition;\n public RECT Rectangle;\n public RECT PreviousRectangle;\n public int Width;\n public int PreviousWidth;\n public int Height;\n public int PreviousHeight;\n public TaskBar()\n {\n Refresh();\n }\n public void Refresh()\n {\n APPBARDATA msgData = new APPBARDATA();\n msgData.cbSize = Marshal.SizeOf(msgData);\n SHAppBarMessage((int)ABMsg.ABM_GETTASKBARPOS, ref msgData);\n PreviousPosition = Position;\n PreviousRectangle = Rectangle;\n PreviousHeight = Height;\n PreviousWidth = Width;\n Rectangle = msgData.rc;\n Width = Rectangle.Right - Rectangle.Left;\n Height = Rectangle.Bottom - Rectangle.Top;\n int h = (int)SystemParameters.PrimaryScreenHeight;\n int w = (int)SystemParameters.PrimaryScreenWidth;\n if (Rectangle.Bottom == h && Rectangle.Top != 0) Position = TaskBarPosition.Bottom;\n else if (Rectangle.Top == 0 && Rectangle.Bottom != h) Position = TaskBarPosition.Top;\n else if (Rectangle.Right == w && Rectangle.Left != 0) Position = TaskBarPosition.Right;\n else if (Rectangle.Left == 0 && Rectangle.Right != w) Position = TaskBarPosition.Left;\n }\n }\n\n [DllImport(\"SHELL32\", CallingConvention = CallingConvention.StdCall)]\n private static extern uint SHAppBarMessage(int dwMessage, ref APPBARDATA pData);\n\n [DllImport(\"User32.dll\", CharSet = CharSet.Auto)]\n private static extern int RegisterWindowMessage(string msg);\n\n private class RegisterInfo\n {\n public int CallbackId { get; set; }\n public bool IsRegistered { get; set; }\n public Window Window { get; set; }\n public ABEdge Edge { get; set; }\n public ABEdge PreviousEdge { get; set; }\n public WindowStyle OriginalStyle { get; set; }\n public Point OriginalPosition { get; set; }\n public Size OriginalSize { get; set; }\n public ResizeMode OriginalResizeMode { get; set; }\n\n\n public IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam,\n IntPtr lParam, ref bool handled)\n {\n if (msg == CallbackId)\n {\n if (wParam.ToInt32() == (int)ABNotify.ABN_POSCHANGED)\n {\n PreviousEdge = Edge;\n ABSetPos(Edge, PreviousEdge, Window);\n handled = true;\n }\n }\n return IntPtr.Zero;\n }\n\n }\n private static Dictionary<Window, RegisterInfo> s_RegisteredWindowInfo\n = new Dictionary<Window, RegisterInfo>();\n private static RegisterInfo GetRegisterInfo(Window appbarWindow)\n {\n RegisterInfo reg;\n if (s_RegisteredWindowInfo.ContainsKey(appbarWindow))\n {\n reg = s_RegisteredWindowInfo[appbarWindow];\n }\n else\n {\n reg = new RegisterInfo()\n {\n CallbackId = 0,\n Window = appbarWindow,\n IsRegistered = false,\n Edge = ABEdge.None,\n PreviousEdge = ABEdge.None,\n OriginalStyle = appbarWindow.WindowStyle,\n OriginalPosition = new Point(appbarWindow.Left, appbarWindow.Top),\n OriginalSize =\n new Size(appbarWindow.ActualWidth, appbarWindow.ActualHeight),\n OriginalResizeMode = appbarWindow.ResizeMode,\n };\n s_RegisteredWindowInfo.Add(appbarWindow, reg);\n }\n return reg;\n }\n\n private static void RestoreWindow(Window appbarWindow)\n {\n RegisterInfo info = GetRegisterInfo(appbarWindow);\n\n appbarWindow.WindowStyle = info.OriginalStyle;\n appbarWindow.ResizeMode = info.OriginalResizeMode;\n appbarWindow.Topmost = false;\n\n Rect rect = new Rect(info.OriginalPosition.X, info.OriginalPosition.Y,\n info.OriginalSize.Width, info.OriginalSize.Height);\n appbarWindow.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle,\n new ResizeDelegate(DoResize), appbarWindow, rect);\n\n }\n\n\n public static void SetAppBar(Window appbarWindow, ABEdge edge)\n {\n RegisterInfo info = GetRegisterInfo(appbarWindow);\n info.Edge = edge;\n\n APPBARDATA abd = new APPBARDATA();\n abd.cbSize = Marshal.SizeOf(abd);\n abd.hWnd = new WindowInteropHelper(appbarWindow).Handle;\n\n if (edge == ABEdge.None)\n {\n if (info.IsRegistered)\n {\n SHAppBarMessage((int)ABMsg.ABM_REMOVE, ref abd);\n info.IsRegistered = false;\n }\n RestoreWindow(appbarWindow);\n info.PreviousEdge = info.Edge;\n return;\n }\n\n if (!info.IsRegistered)\n {\n info.IsRegistered = true;\n info.CallbackId = RegisterWindowMessage(\"AppBarMessage\");\n abd.uCallbackMessage = info.CallbackId;\n\n uint ret = SHAppBarMessage((int)ABMsg.ABM_NEW, ref abd);\n\n HwndSource source = HwndSource.FromHwnd(abd.hWnd);\n source.AddHook(new HwndSourceHook(info.WndProc));\n }\n\n appbarWindow.WindowStyle = WindowStyle.None;\n appbarWindow.ResizeMode = ResizeMode.NoResize;\n appbarWindow.Topmost = true;\n\n ABSetPos(info.Edge, info.PreviousEdge, appbarWindow);\n }\n\n private delegate void ResizeDelegate(Window appbarWindow, Rect rect);\n private static void DoResize(Window appbarWindow, Rect rect)\n {\n appbarWindow.Width = rect.Width;\n appbarWindow.Height = rect.Height;\n appbarWindow.Top = rect.Top;\n appbarWindow.Left = rect.Left;\n }\n\n static TaskBar tb = new TaskBar();\n\n private static void ABSetPos(ABEdge edge, ABEdge prevEdge, Window appbarWindow)\n {\n APPBARDATA barData = new APPBARDATA();\n barData.cbSize = Marshal.SizeOf(barData);\n barData.hWnd = new WindowInteropHelper(appbarWindow).Handle;\n barData.uEdge = (int)edge;\n RECT wa = new RECT(SystemParameters.WorkArea);\n tb.Refresh();\n switch (edge)\n {\n case ABEdge.Top:\n barData.rc.Left = wa.Left - (prevEdge == ABEdge.Left ? (int)Math.Round(appbarWindow.ActualWidth) : 0);\n barData.rc.Right = wa.Right + (prevEdge == ABEdge.Right ? (int)Math.Round(appbarWindow.ActualWidth) : 0);\n barData.rc.Top = wa.Top - (prevEdge == ABEdge.Top ? (int)Math.Round(appbarWindow.ActualHeight) : 0) - ((tb.Position != TaskBarPosition.Top && tb.PreviousPosition == TaskBarPosition.Top) ? tb.Height : 0) + ((tb.Position == TaskBarPosition.Top && tb.PreviousPosition != TaskBarPosition.Top) ? tb.Height : 0);\n barData.rc.Bottom = barData.rc.Top + (int)Math.Round(appbarWindow.ActualHeight);\n break;\n case ABEdge.Bottom:\n barData.rc.Left = wa.Left - (prevEdge == ABEdge.Left ? (int)Math.Round(appbarWindow.ActualWidth) : 0);\n barData.rc.Right = wa.Right + (prevEdge == ABEdge.Right ? (int)Math.Round(appbarWindow.ActualWidth) : 0);\n barData.rc.Bottom = wa.Bottom + (prevEdge == ABEdge.Bottom ? (int)Math.Round(appbarWindow.ActualHeight) : 0) - 1 + ((tb.Position != TaskBarPosition.Bottom && tb.PreviousPosition == TaskBarPosition.Bottom) ? tb.Height : 0) - ((tb.Position == TaskBarPosition.Bottom && tb.PreviousPosition != TaskBarPosition.Bottom) ? tb.Height : 0);\n barData.rc.Top = barData.rc.Bottom - (int)Math.Round(appbarWindow.ActualHeight);\n break;\n }\n\n SHAppBarMessage((int)ABMsg.ABM_QUERYPOS, ref barData);\n switch (barData.uEdge)\n {\n case (int)ABEdge.Bottom:\n if (tb.Position == TaskBarPosition.Bottom && tb.PreviousPosition == tb.Position)\n {\n barData.rc.Top += (tb.PreviousHeight - tb.Height);\n barData.rc.Bottom = barData.rc.Top + (int)appbarWindow.ActualHeight;\n }\n break;\n case (int)ABEdge.Top:\n if (tb.Position == TaskBarPosition.Top && tb.PreviousPosition == tb.Position)\n {\n if (tb.PreviousHeight - tb.Height > 0) barData.rc.Top -= (tb.PreviousHeight - tb.Height);\n barData.rc.Bottom = barData.rc.Top + (int)appbarWindow.ActualHeight;\n }\n break;\n }\n SHAppBarMessage((int)ABMsg.ABM_SETPOS, ref barData);\n\n Rect rect = new Rect((double)barData.rc.Left, (double)barData.rc.Top, (double)(barData.rc.Right - barData.rc.Left), (double)(barData.rc.Bottom - barData.rc.Top));\n appbarWindow.Dispatcher.BeginInvoke(new ResizeDelegate(DoResize), DispatcherPriority.ApplicationIdle, appbarWindow, rect);\n }\n }\n}\n"
},
{
"answer_id": 18896608,
"author": "Miky Jadro",
"author_id": 2795750,
"author_profile": "https://Stackoverflow.com/users/2795750",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Runtime.InteropServices;\nusing System.Windows;\nusing System.Windows.Interop;\nusing System.Windows.Threading;\n\nnamespace AppBarApplication\n{\n public enum ABEdge : int\n {\n Left = 0,\n Top,\n Right,\n Bottom,\n None\n }\n\n internal static class AppBarFunctions\n {\n [StructLayout(LayoutKind.Sequential)]\n private struct RECT\n {\n public int left;\n public int top;\n public int right;\n public int bottom;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n private struct APPBARDATA\n {\n public int cbSize;\n public IntPtr hWnd;\n public int uCallbackMessage;\n public int uEdge;\n public RECT rc;\n public IntPtr lParam;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n private struct MONITORINFO\n {\n public int cbSize;\n public RECT rcMonitor;\n public RECT rcWork;\n public int dwFlags;\n }\n\n private enum ABMsg : int\n {\n ABM_NEW = 0,\n ABM_REMOVE,\n ABM_QUERYPOS,\n ABM_SETPOS,\n ABM_GETSTATE,\n ABM_GETTASKBARPOS,\n ABM_ACTIVATE,\n ABM_GETAUTOHIDEBAR,\n ABM_SETAUTOHIDEBAR,\n ABM_WINDOWPOSCHANGED,\n ABM_SETSTATE\n }\n private enum ABNotify : int\n {\n ABN_STATECHANGE = 0,\n ABN_POSCHANGED,\n ABN_FULLSCREENAPP,\n ABN_WINDOWARRANGE\n }\n\n [DllImport(\"SHELL32\", CallingConvention = CallingConvention.StdCall)]\n private static extern uint SHAppBarMessage(int dwMessage, ref APPBARDATA pData);\n\n [DllImport(\"User32.dll\", CharSet = CharSet.Auto)]\n private static extern int RegisterWindowMessage(string msg);\n\n [DllImport(\"User32.dll\", CharSet = CharSet.Auto)]\n private static extern IntPtr MonitorFromWindow(IntPtr hwnd, uint dwFlags);\n\n [DllImport(\"User32.dll\", CharSet = CharSet.Auto)]\n private static extern bool GetMonitorInfo(IntPtr hMonitor, ref MONITORINFO mi);\n\n\n private const int MONITOR_DEFAULTTONEAREST = 0x2;\n private const int MONITORINFOF_PRIMARY = 0x1;\n\n private class RegisterInfo\n {\n public int CallbackId { get; set; }\n public bool IsRegistered { get; set; }\n public Window Window { get; set; }\n public ABEdge Edge { get; set; }\n public WindowStyle OriginalStyle { get; set; }\n public Point OriginalPosition { get; set; }\n public Size OriginalSize { get; set; }\n public ResizeMode OriginalResizeMode { get; set; }\n\n\n public IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam,\n IntPtr lParam, ref bool handled)\n {\n if (msg == CallbackId)\n {\n if (wParam.ToInt32() == (int)ABNotify.ABN_POSCHANGED)\n {\n ABSetPos(Edge, Window);\n handled = true;\n }\n }\n return IntPtr.Zero;\n }\n\n }\n private static Dictionary<Window, RegisterInfo> s_RegisteredWindowInfo\n = new Dictionary<Window, RegisterInfo>();\n private static RegisterInfo GetRegisterInfo(Window appbarWindow)\n {\n RegisterInfo reg;\n if (s_RegisteredWindowInfo.ContainsKey(appbarWindow))\n {\n reg = s_RegisteredWindowInfo[appbarWindow];\n }\n else\n {\n reg = new RegisterInfo()\n {\n CallbackId = 0,\n Window = appbarWindow,\n IsRegistered = false,\n Edge = ABEdge.Top,\n OriginalStyle = appbarWindow.WindowStyle,\n OriginalPosition = new Point(appbarWindow.Left, appbarWindow.Top),\n OriginalSize =\n new Size(appbarWindow.ActualWidth, appbarWindow.ActualHeight),\n OriginalResizeMode = appbarWindow.ResizeMode,\n };\n s_RegisteredWindowInfo.Add(appbarWindow, reg);\n }\n return reg;\n }\n\n private static void RestoreWindow(Window appbarWindow)\n {\n RegisterInfo info = GetRegisterInfo(appbarWindow);\n\n appbarWindow.WindowStyle = info.OriginalStyle;\n appbarWindow.ResizeMode = info.OriginalResizeMode;\n appbarWindow.Topmost = false;\n\n Rect rect = new Rect(info.OriginalPosition.X, info.OriginalPosition.Y,\n info.OriginalSize.Width, info.OriginalSize.Height);\n appbarWindow.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle,\n new ResizeDelegate(DoResize), appbarWindow, rect);\n\n }\n\n public static void SetAppBar(Window appbarWindow, ABEdge edge)\n {\n RegisterInfo info = GetRegisterInfo(appbarWindow);\n\n info.Edge = edge;\n\n APPBARDATA abd = new APPBARDATA();\n abd.cbSize = Marshal.SizeOf(abd);\n abd.hWnd = new WindowInteropHelper(appbarWindow).Handle;\n\n if (edge == ABEdge.None)\n {\n if (info.IsRegistered)\n {\n SHAppBarMessage((int)ABMsg.ABM_REMOVE, ref abd);\n info.IsRegistered = false;\n }\n RestoreWindow(appbarWindow);\n return;\n }\n\n if (!info.IsRegistered)\n {\n info.IsRegistered = true;\n info.CallbackId = RegisterWindowMessage(\"AppBarMessage\");\n abd.uCallbackMessage = info.CallbackId;\n\n uint ret = SHAppBarMessage((int)ABMsg.ABM_NEW, ref abd);\n\n HwndSource source = HwndSource.FromHwnd(abd.hWnd);\n source.AddHook(new HwndSourceHook(info.WndProc));\n }\n\n appbarWindow.WindowStyle = WindowStyle.None;\n appbarWindow.ResizeMode = ResizeMode.NoResize;\n appbarWindow.Topmost = true;\n\n ABSetPos(info.Edge, appbarWindow);\n }\n\n private delegate void ResizeDelegate(Window appbarWindow, Rect rect);\n private static void DoResize(Window appbarWindow, Rect rect)\n {\n appbarWindow.Width = rect.Width;\n appbarWindow.Height = rect.Height;\n appbarWindow.Top = rect.Top;\n appbarWindow.Left = rect.Left;\n }\n\n private static void GetActualScreenData(ABEdge edge, Window appbarWindow, ref int leftOffset, ref int topOffset, ref int actualScreenWidth, ref int actualScreenHeight)\n {\n IntPtr handle = new WindowInteropHelper(appbarWindow).Handle;\n IntPtr monitorHandle = MonitorFromWindow(handle, MONITOR_DEFAULTTONEAREST);\n\n MONITORINFO mi = new MONITORINFO();\n mi.cbSize = Marshal.SizeOf(mi);\n\n if (GetMonitorInfo(monitorHandle, ref mi))\n {\n if (mi.dwFlags == MONITORINFOF_PRIMARY)\n {\n return;\n }\n leftOffset = mi.rcWork.left;\n topOffset = mi.rcWork.top;\n actualScreenWidth = mi.rcWork.right - leftOffset;\n actualScreenHeight = mi.rcWork.bottom - mi.rcWork.top;\n }\n }\n\n private static void ABSetPos(ABEdge edge, Window appbarWindow)\n {\n APPBARDATA barData = new APPBARDATA();\n barData.cbSize = Marshal.SizeOf(barData);\n barData.hWnd = new WindowInteropHelper(appbarWindow).Handle;\n barData.uEdge = (int)edge;\n\n int leftOffset = 0;\n int topOffset = 0;\n int actualScreenWidth = (int)SystemParameters.PrimaryScreenWidth;\n int actualScreenHeight = (int)SystemParameters.PrimaryScreenHeight;\n\n GetActualScreenData(edge, appbarWindow, ref leftOffset, ref topOffset, ref actualScreenWidth, ref actualScreenHeight);\n\n if (barData.uEdge == (int)ABEdge.Left || barData.uEdge == (int)ABEdge.Right)\n {\n barData.rc.top = topOffset;\n barData.rc.bottom = actualScreenHeight;\n if (barData.uEdge == (int)ABEdge.Left)\n {\n barData.rc.left = leftOffset;\n barData.rc.right = (int)Math.Round(appbarWindow.ActualWidth) + leftOffset;\n }\n else\n {\n barData.rc.right = actualScreenWidth + leftOffset;\n barData.rc.left = barData.rc.right - (int)Math.Round(appbarWindow.ActualWidth);\n }\n }\n else\n {\n barData.rc.left = leftOffset;\n barData.rc.right = actualScreenWidth + leftOffset;\n if (barData.uEdge == (int)ABEdge.Top)\n {\n barData.rc.top = topOffset;\n barData.rc.bottom = (int)Math.Round(appbarWindow.ActualHeight) + topOffset;\n }\n else\n {\n barData.rc.bottom = actualScreenHeight + topOffset;\n barData.rc.top = barData.rc.bottom - (int)Math.Round(appbarWindow.ActualHeight);\n }\n }\n\n SHAppBarMessage((int)ABMsg.ABM_QUERYPOS, ref barData);\n SHAppBarMessage((int)ABMsg.ABM_SETPOS, ref barData);\n\n Rect rect = new Rect((double)barData.rc.left, (double)barData.rc.top,\n (double)(barData.rc.right - barData.rc.left), (double)(barData.rc.bottom - barData.rc.top));\n //This is done async, because WPF will send a resize after a new appbar is added. \n //if we size right away, WPFs resize comes last and overrides us.\n appbarWindow.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle,\n new ResizeDelegate(DoResize), appbarWindow, rect);\n }\n }\n}\n"
},
{
"answer_id": 43024177,
"author": "Mitch",
"author_id": 138200,
"author_profile": "https://Stackoverflow.com/users/138200",
"pm_score": 3,
"selected": false,
"text": "AppBarWindow <apb:AppBarWindow x:Class=\"WpfAppBarDemo.MainWindow\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:apb=\"clr-namespace:WpfAppBar;assembly=WpfAppBar\"\n DataContext=\"{Binding RelativeSource={RelativeSource Self}}\" Title=\"MainWindow\" \n DockedWidthOrHeight=\"200\" MinHeight=\"100\" MinWidth=\"100\">\n <Grid>\n <Button x:Name=\"btClose\" Content=\"Close\" HorizontalAlignment=\"Left\" VerticalAlignment=\"Top\" Width=\"75\" Height=\"23\" Margin=\"10,10,0,0\" Click=\"btClose_Click\"/>\n <ComboBox x:Name=\"cbMonitor\" SelectedItem=\"{Binding Path=Monitor, Mode=TwoWay}\" HorizontalAlignment=\"Left\" VerticalAlignment=\"Top\" Width=\"120\" Margin=\"10,38,0,0\"/>\n <ComboBox x:Name=\"cbEdge\" SelectedItem=\"{Binding Path=DockMode, Mode=TwoWay}\" HorizontalAlignment=\"Left\" Margin=\"10,65,0,0\" VerticalAlignment=\"Top\" Width=\"120\"/>\n\n <Thumb Width=\"5\" HorizontalAlignment=\"Right\" Background=\"Gray\" x:Name=\"rzThumb\" Cursor=\"SizeWE\" DragCompleted=\"rzThumb_DragCompleted\" />\n </Grid>\n</apb:AppBarWindow>\n public partial class MainWindow\n{\n public MainWindow()\n {\n InitializeComponent();\n\n this.cbEdge.ItemsSource = new[]\n {\n AppBarDockMode.Left,\n AppBarDockMode.Right,\n AppBarDockMode.Top,\n AppBarDockMode.Bottom\n };\n this.cbMonitor.ItemsSource = MonitorInfo.GetAllMonitors();\n }\n\n private void btClose_Click(object sender, RoutedEventArgs e)\n {\n Close();\n }\n\n private void rzThumb_DragCompleted(object sender, DragCompletedEventArgs e)\n {\n this.DockedWidthOrHeight += (int)(e.HorizontalChange / VisualTreeHelper.GetDpi(this).PixelsPerDip);\n }\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7301/"
] |
75,786 |
<p>(Eclipse 3.4, Ganymede)</p>
<p>I have an existing Dynamic Web Application project in Eclipse. When I created the project, I specified 'Default configuration for Apache Tomcat v6' under the 'Configuration' drop down.</p>
<p>It's a month or 2 down the line, and I would now like to change the configuration to Tomcat 'v5.5'. (This will be the version of Tomcat on the production server.)</p>
<p>I have tried the following steps (without success):</p>
<ul>
<li>I selected <code>Targeted Runtimes</code> under the Project <code>Properties</code><br>
The <code>Tomcat v5.5</code> option was disabled and The UI displayed this message:<br>
<code>If the runtime you want to select is not displayed or is disabled you may need to uninstall one or more of the currently installed project facets.</code> </li>
<li>I then clicked on the <code>Uninstall Facets...</code> link.<br>
Under the <code>Runtimes</code> tab, only <code>Tomcat 6</code> displayed.<br>
For <code>Dynamic Web Module</code>, I selected version <code>2.4</code> in place of <code>2.5</code>.<br>
Under the <code>Runtimes</code> tab, <code>Tomcat 5.5</code> now displayed.<br>
However, the UI now displayed this message:<br>
<code>Cannot change version of project facet Dynamic Web Module to 2.4.</code><br>
The <code>Finish</code> button was disabled - so I reached a dead-end.</li>
</ul>
<p>I CAN successfully create a NEW Project with a Tomcat v5.5 configuration. For some reason, though, it will not let me downgrade' an existing Project.</p>
<p>As a work-around, I created a new Project and copied the source files from the old Project. Nonetheless, the work-around was fairly painful and somewhat clumsy.</p>
<p>Can anyone explain how I can 'downgrade' the Project configuration from 'Tomcat 6' to 'Tomcat 5'? Or perhaps shed some light on why this happened?</p>
<p>Thanks<br>
Pete</p>
|
[
{
"answer_id": 76205,
"author": "William",
"author_id": 9193,
"author_profile": "https://Stackoverflow.com/users/9193",
"pm_score": 7,
"selected": true,
"text": "org.eclipse.wst.common.project.facet.core.xml \n <installed facet=\"jst.web\" version=\"2.5\"/>\n <web-app version=\"2.4\" \n xmlns=\"http://java.sun.com/xml/ns/j2ee\" \n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation=\"http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd\">\n"
},
{
"answer_id": 4830219,
"author": "Karthik",
"author_id": 594073,
"author_profile": "https://Stackoverflow.com/users/594073",
"pm_score": 3,
"selected": false,
"text": ">mvn eclipse:eclipse -Dwtpversion=2.0"
},
{
"answer_id": 5571788,
"author": "sarabrab",
"author_id": 695500,
"author_profile": "https://Stackoverflow.com/users/695500",
"pm_score": 0,
"selected": false,
"text": "web.xml"
},
{
"answer_id": 5956380,
"author": "Dante",
"author_id": 682844,
"author_profile": "https://Stackoverflow.com/users/682844",
"pm_score": -1,
"selected": false,
"text": "<dependency>\n <groupId>org.apache.tomcat</groupId>\n <artifactId>servlet-api</artifactId>\n <version>6.0.32</version>\n</dependency> \n <faceted-project>\n ...\n <installed facet=\"jst.web\" version=\"6.0\"/>\n ...\n</faceted-project>\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13360/"
] |
75,798 |
<p>I'm wondering if there's such a thing as Django-like ease of web app development combined with good deployment, debugging and other tools? </p>
<p>Django is a very productive framework for building content-heavy sites; the best I've tried and a breath of fresh air compared to some of the Java monstrosities out there. However it's written in Python which means there's little real support in the way of deployment/packaging, debugging, profilers and other tools that make building and maintaining applications much easier. </p>
<p>Ruby has similar issues and although I do like Ruby <strong>much</strong> better than I like Python, I get the impression that Rails is roughly in the same boat at Django when it comes to managing/supporting the app. </p>
<p>Has anyone here tried both Django and Grails (or other web frameworks) for non-trivial projects? How did they compare?</p>
|
[
{
"answer_id": 97778,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": false,
"text": "/opt/this /opt/that"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13436/"
] |
75,809 |
<p>Given the case I made <strong>two independent changes</strong> in <em>one</em> file: eg. added a new method and changed another method.</p>
<p>I often don't want to commit both changes as <strong>one</strong> commit, but as <strong>two</strong> independent commits.</p>
<p>On a git repository I would use the <strong>Interactive Mode</strong> of <a href="http://linux.die.net/man/1/git-add" rel="noreferrer">git-add(1)</a> to split the <em>hunk</em> into smaller ones:</p>
<pre><code> git add --patch
</code></pre>
<p>What's the easiest way to do this with Subversion? (Maybe even using an Eclipse plug-in)</p>
<p><strong>Update:</strong><br/>
In <a href="http://tomayko.com/writings/the-thing-about-git" rel="noreferrer">The Thing About Git</a>, Ryan calls it: <em>“The Tangled Working Copy Problem.”</em></p>
|
[
{
"answer_id": 75918,
"author": "Aeon",
"author_id": 13289,
"author_profile": "https://Stackoverflow.com/users/13289",
"pm_score": 2,
"selected": false,
"text": "cp file file.new\nsvn revert file\nopendiff file.new file -merge file\n svn ci -m 'first hunk' file\nmv file.new file\nsvn ci -m 'second hunk' file\n"
},
{
"answer_id": 75950,
"author": "Chris",
"author_id": 13488,
"author_profile": "https://Stackoverflow.com/users/13488",
"pm_score": 5,
"selected": false,
"text": "svn diff > out.patch out.patch out.patch.add out.patch.modify svn revert out.c patch svn commit out.patch.modify svn co http://location/repository methodAdd svn co http://location/repository methodModify svn up"
},
{
"answer_id": 46731868,
"author": "michaeljt",
"author_id": 213180,
"author_profile": "https://Stackoverflow.com/users/213180",
"pm_score": 0,
"selected": false,
"text": "svn diff svn revert patch diff"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4308/"
] |
75,819 |
<p>I'm having an issue with a query that currently uses </p>
<pre><code>LEFT JOIN weblog_data AS pwd
ON (pwd.field_id_41 != ''
AND pwd.field_id_41 LIKE CONCAT('%', ewd.field_id_32, '%'))
</code></pre>
<p>However I'm discovering that I need it to only use that if there is no exact match first. What's happening is that the query is double dipping due to the use of <code>LIKE</code>, so if it tests for an exact match first then it will avoid the double dipping issue. Can anyone provide me with any further guidance?</p>
|
[
{
"answer_id": 75973,
"author": "Jonathan Rupp",
"author_id": 12502,
"author_profile": "https://Stackoverflow.com/users/12502",
"pm_score": 3,
"selected": true,
"text": "LEFT JOIN weblog_data AS pwd1 ON (pwd.field_id_41 != '' AND pwd.field_id_41 = ewd.field_id_32)\nLEFT JOIN weblog_data AS pwd2 ON (pwd.field_id_41 != '' AND pwd.field_id_41 LIKE CONCAT('%', ewd.field_id_32, '%'))\n select\n isnull(pwd1.field, pwd2.field)\n select\n case pwd1.nonnullfield is null then pwd2.field else pwd1.field end\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12073/"
] |
75,829 |
<p>All the docs for SQLAlchemy give <code>INSERT</code> and <code>UPDATE</code> examples using the local table instance (e.g. <code>tablename.update()</code>... )</p>
<p>Doing this seems difficult with the declarative syntax, I need to reference <code>Base.metadata.tables["tablename"]</code> to get the table reference.</p>
<p>Am I supposed to do this another way? Is there a different syntax for <code>INSERT</code> and <code>UPDATE</code> recommended when using the declarative syntax? Should I just switch to the old way?</p>
|
[
{
"answer_id": 77962,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "__table__"
},
{
"answer_id": 156968,
"author": "GHZ",
"author_id": 18138,
"author_profile": "https://Stackoverflow.com/users/18138",
"pm_score": 3,
"selected": false,
"text": "class Users(Base):\n __tablename__ = 'users'\n __table_args__ = {'autoload':True}\n\nusers = Users()\nprint users.__table__.select()\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
75,848 |
<p>I'm trying to insert a <a href="http://en.wikipedia.org/wiki/Spry_framework" rel="nofollow noreferrer">Spry</a> <a href="http://en.wikipedia.org/wiki/Accordion_(GUI)" rel="nofollow noreferrer">accordion</a> into an already existing <a href="http://en.wikipedia.org/wiki/JavaServer_Faces" rel="nofollow noreferrer">JSF</a> page using <a href="http://en.wikipedia.org/wiki/Adobe_Dreamweaver" rel="nofollow noreferrer">Dreamweaver</a>. Is this possible? </p>
<p>I've already tried several things, and only the labels show up.</p>
|
[
{
"answer_id": 81534,
"author": "Dave Smylie",
"author_id": 1505600,
"author_profile": "https://Stackoverflow.com/users/1505600",
"pm_score": 3,
"selected": true,
"text": " <div id=\"Accordion1\" class=\"Accordion\">\n <div class=\"AccordionPanel\">\n <div class=\"AccordionPanelTab\">Panel 1</div>\n <div class=\"AccordionPanelContent\">\n Panel 1 Content<br/>\n Panel 1 Content<br/>\n Panel 1 Content<br/>\n </div>\n </div>\n </div>\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1459442/"
] |
75,891 |
<p>I need an algorithm that can determine whether two images are 'similar' and recognizes similar patterns of color, brightness, shape etc.. I might need some pointers as to what parameters the human brain uses to 'categorize' images. .. </p>
<p>I have looked at hausdorff based matching but that seems mainly for matching transformed objects and patterns of shape.</p>
|
[
{
"answer_id": 49534462,
"author": "duhaime",
"author_id": 1727392,
"author_profile": "https://Stackoverflow.com/users/1727392",
"pm_score": 3,
"selected": false,
"text": "from __future__ import absolute_import, division, print_function\n\n\"\"\"\n\nThis is a modification of the classify_images.py\nscript in Tensorflow. The original script produces\nstring labels for input images (e.g. you input a picture\nof a cat and the script returns the string \"cat\"); this\nmodification reads in a directory of images and \ngenerates a vector representation of the image using\nthe penultimate layer of neural network weights.\n\nUsage: python classify_images.py \"../image_dir/*.jpg\"\n\n\"\"\"\n\n# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Simple image classification with Inception.\n\nRun image classification with Inception trained on ImageNet 2012 Challenge data\nset.\n\nThis program creates a graph from a saved GraphDef protocol buffer,\nand runs inference on an input JPEG image. It outputs human readable\nstrings of the top 5 predictions along with their probabilities.\n\nChange the --image_file argument to any jpg image to compute a\nclassification of that image.\n\nPlease see the tutorial and website for a detailed description of how\nto use this script to perform image recognition.\n\nhttps://tensorflow.org/tutorials/image_recognition/\n\"\"\"\n\nimport os.path\nimport re\nimport sys\nimport tarfile\nimport glob\nimport json\nimport psutil\nfrom collections import defaultdict\nimport numpy as np\nfrom six.moves import urllib\nimport tensorflow as tf\n\nFLAGS = tf.app.flags.FLAGS\n\n# classify_image_graph_def.pb:\n# Binary representation of the GraphDef protocol buffer.\n# imagenet_synset_to_human_label_map.txt:\n# Map from synset ID to a human readable string.\n# imagenet_2012_challenge_label_map_proto.pbtxt:\n# Text representation of a protocol buffer mapping a label to synset ID.\ntf.app.flags.DEFINE_string(\n 'model_dir', '/tmp/imagenet',\n \"\"\"Path to classify_image_graph_def.pb, \"\"\"\n \"\"\"imagenet_synset_to_human_label_map.txt, and \"\"\"\n \"\"\"imagenet_2012_challenge_label_map_proto.pbtxt.\"\"\")\ntf.app.flags.DEFINE_string('image_file', '',\n \"\"\"Absolute path to image file.\"\"\")\ntf.app.flags.DEFINE_integer('num_top_predictions', 5,\n \"\"\"Display this many predictions.\"\"\")\n\n# pylint: disable=line-too-long\nDATA_URL = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz'\n# pylint: enable=line-too-long\n\n\nclass NodeLookup(object):\n \"\"\"Converts integer node ID's to human readable labels.\"\"\"\n\n def __init__(self,\n label_lookup_path=None,\n uid_lookup_path=None):\n if not label_lookup_path:\n label_lookup_path = os.path.join(\n FLAGS.model_dir, 'imagenet_2012_challenge_label_map_proto.pbtxt')\n if not uid_lookup_path:\n uid_lookup_path = os.path.join(\n FLAGS.model_dir, 'imagenet_synset_to_human_label_map.txt')\n self.node_lookup = self.load(label_lookup_path, uid_lookup_path)\n\n def load(self, label_lookup_path, uid_lookup_path):\n \"\"\"Loads a human readable English name for each softmax node.\n\n Args:\n label_lookup_path: string UID to integer node ID.\n uid_lookup_path: string UID to human-readable string.\n\n Returns:\n dict from integer node ID to human-readable string.\n \"\"\"\n if not tf.gfile.Exists(uid_lookup_path):\n tf.logging.fatal('File does not exist %s', uid_lookup_path)\n if not tf.gfile.Exists(label_lookup_path):\n tf.logging.fatal('File does not exist %s', label_lookup_path)\n\n # Loads mapping from string UID to human-readable string\n proto_as_ascii_lines = tf.gfile.GFile(uid_lookup_path).readlines()\n uid_to_human = {}\n p = re.compile(r'[n\\d]*[ \\S,]*')\n for line in proto_as_ascii_lines:\n parsed_items = p.findall(line)\n uid = parsed_items[0]\n human_string = parsed_items[2]\n uid_to_human[uid] = human_string\n\n # Loads mapping from string UID to integer node ID.\n node_id_to_uid = {}\n proto_as_ascii = tf.gfile.GFile(label_lookup_path).readlines()\n for line in proto_as_ascii:\n if line.startswith(' target_class:'):\n target_class = int(line.split(': ')[1])\n if line.startswith(' target_class_string:'):\n target_class_string = line.split(': ')[1]\n node_id_to_uid[target_class] = target_class_string[1:-2]\n\n # Loads the final mapping of integer node ID to human-readable string\n node_id_to_name = {}\n for key, val in node_id_to_uid.items():\n if val not in uid_to_human:\n tf.logging.fatal('Failed to locate: %s', val)\n name = uid_to_human[val]\n node_id_to_name[key] = name\n\n return node_id_to_name\n\n def id_to_string(self, node_id):\n if node_id not in self.node_lookup:\n return ''\n return self.node_lookup[node_id]\n\n\ndef create_graph():\n \"\"\"Creates a graph from saved GraphDef file and returns a saver.\"\"\"\n # Creates graph from saved graph_def.pb.\n with tf.gfile.FastGFile(os.path.join(\n FLAGS.model_dir, 'classify_image_graph_def.pb'), 'rb') as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n _ = tf.import_graph_def(graph_def, name='')\n\n\ndef run_inference_on_images(image_list, output_dir):\n \"\"\"Runs inference on an image list.\n\n Args:\n image_list: a list of images.\n output_dir: the directory in which image vectors will be saved\n\n Returns:\n image_to_labels: a dictionary with image file keys and predicted\n text label values\n \"\"\"\n image_to_labels = defaultdict(list)\n\n create_graph()\n\n with tf.Session() as sess:\n # Some useful tensors:\n # 'softmax:0': A tensor containing the normalized prediction across\n # 1000 labels.\n # 'pool_3:0': A tensor containing the next-to-last layer containing 2048\n # float description of the image.\n # 'DecodeJpeg/contents:0': A tensor containing a string providing JPEG\n # encoding of the image.\n # Runs the softmax tensor by feeding the image_data as input to the graph.\n softmax_tensor = sess.graph.get_tensor_by_name('softmax:0')\n\n for image_index, image in enumerate(image_list):\n try:\n print(\"parsing\", image_index, image, \"\\n\")\n if not tf.gfile.Exists(image):\n tf.logging.fatal('File does not exist %s', image)\n\n with tf.gfile.FastGFile(image, 'rb') as f:\n image_data = f.read()\n\n predictions = sess.run(softmax_tensor,\n {'DecodeJpeg/contents:0': image_data})\n\n predictions = np.squeeze(predictions)\n\n ###\n # Get penultimate layer weights\n ###\n\n feature_tensor = sess.graph.get_tensor_by_name('pool_3:0')\n feature_set = sess.run(feature_tensor,\n {'DecodeJpeg/contents:0': image_data})\n feature_vector = np.squeeze(feature_set) \n outfile_name = os.path.basename(image) + \".npz\"\n out_path = os.path.join(output_dir, outfile_name)\n np.savetxt(out_path, feature_vector, delimiter=',')\n\n # Creates node ID --> English string lookup.\n node_lookup = NodeLookup()\n\n top_k = predictions.argsort()[-FLAGS.num_top_predictions:][::-1]\n for node_id in top_k:\n human_string = node_lookup.id_to_string(node_id)\n score = predictions[node_id]\n print(\"results for\", image)\n print('%s (score = %.5f)' % (human_string, score))\n print(\"\\n\")\n\n image_to_labels[image].append(\n {\n \"labels\": human_string,\n \"score\": str(score)\n }\n )\n\n # close the open file handlers\n proc = psutil.Process()\n open_files = proc.open_files()\n\n for open_file in open_files:\n file_handler = getattr(open_file, \"fd\")\n os.close(file_handler)\n except:\n print('could not process image index',image_index,'image', image)\n\n return image_to_labels\n\n\ndef maybe_download_and_extract():\n \"\"\"Download and extract model tar file.\"\"\"\n dest_directory = FLAGS.model_dir\n if not os.path.exists(dest_directory):\n os.makedirs(dest_directory)\n filename = DATA_URL.split('/')[-1]\n filepath = os.path.join(dest_directory, filename)\n if not os.path.exists(filepath):\n def _progress(count, block_size, total_size):\n sys.stdout.write('\\r>> Downloading %s %.1f%%' % (\n filename, float(count * block_size) / float(total_size) * 100.0))\n sys.stdout.flush()\n filepath, _ = urllib.request.urlretrieve(DATA_URL, filepath, _progress)\n print()\n statinfo = os.stat(filepath)\n print('Succesfully downloaded', filename, statinfo.st_size, 'bytes.')\n tarfile.open(filepath, 'r:gz').extractall(dest_directory)\n\n\ndef main(_):\n maybe_download_and_extract()\n if len(sys.argv) < 2:\n print(\"please provide a glob path to one or more images, e.g.\")\n print(\"python classify_image_modified.py '../cats/*.jpg'\")\n sys.exit()\n\n else:\n output_dir = \"image_vectors\"\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\n images = glob.glob(sys.argv[1])\n image_to_labels = run_inference_on_images(images, output_dir)\n\n with open(\"image_to_labels.json\", \"w\") as img_to_labels_out:\n json.dump(image_to_labels, img_to_labels_out)\n\n print(\"all done\")\nif __name__ == '__main__':\n tf.app.run()\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13466/"
] |
75,924 |
<p>This may be a no-brainer for the WPF cognoscenti, but I'd like to know if there's a simple way to put text on the WPF ProgressBar. To me, an empty progress bar looks naked. That's screen real estate that could carry a message about <strong>what</strong> is in progress, or even just add numbers to the representation. Now, WPF is all about containers and extensions and I'm slowly wrapping my mind around that, but since I don't see a "Text" or "Content" property, I'm thinking I'm going to have to add something to the container that is my progress bar. Is there a technique or two out there that is more natural than my original WinForms impulses will be? What's the best, most WPF-natural way to add text to that progress bar?</p>
|
[
{
"answer_id": 99245,
"author": "SmartyP",
"author_id": 18005,
"author_profile": "https://Stackoverflow.com/users/18005",
"pm_score": 6,
"selected": false,
"text": "CustomControl Adorner <Grid Width=\"300\" Height=\"50\"> \n <ProgressBar Value=\"50\" />\n <TextBlock HorizontalAlignment=\"Center\" VerticalAlignment=\"Center\">\n My Text\n </TextBlock>\n</Grid>\n"
},
{
"answer_id": 30941868,
"author": "Felix D.",
"author_id": 4610605,
"author_profile": "https://Stackoverflow.com/users/4610605",
"pm_score": 5,
"selected": false,
"text": "Style TextBlock ProgressBar Binding TextBock.Text ProgressBar.Value <Grid>\n <ProgressBar Minimum=\"0\" \n Maximum=\"100\" \n Value=\"{Binding InsertBindingHere}\" \n Name=\"pbStatus\" />\n <TextBlock Text=\"{Binding ElementName=pbStatus, Path=Value, StringFormat={}{0:0}%}\" \n HorizontalAlignment=\"Center\" \n VerticalAlignment=\"Center\" />\n</Grid>\n"
},
{
"answer_id": 35081337,
"author": "AnjumSKhan",
"author_id": 3667257,
"author_profile": "https://Stackoverflow.com/users/3667257",
"pm_score": 1,
"selected": false,
"text": "ProgressBar TextBlock Grid <Border BorderBrush=\"{TemplateBinding BorderBrush}\" BorderThickness=\"{TemplateBinding BorderThickness}\" CornerRadius=\"2\"/>\n <TextBlock Background=\"Transparent\" Text=\"work in progress\" Foreground=\"Black\" TextAlignment=\"Center\"/>\n </Grid>\n <ControlTemplate.Triggers>\n"
},
{
"answer_id": 54175304,
"author": "Andrew___Pls_Support_UA",
"author_id": 4423545,
"author_profile": "https://Stackoverflow.com/users/4423545",
"pm_score": 2,
"selected": false,
"text": "<Grid>\n <ProgressBar Name=\"pbUsrLvl\"\n Minimum=\"1\" \n Maximum=\"99\" \n Value=\"59\" \n Margin=\"5\" \n Height=\"24\" Foreground=\"#FF62FF7F\"/>\n <TextBlock HorizontalAlignment=\"Center\" VerticalAlignment=\"Center\">\n <TextBlock.Text>\n <MultiBinding StringFormat=\"{}UserLvl:{0}/{1}\">\n <Binding Path=\"Value\" ElementName=\"pbUsrLvl\" />\n <Binding Path=\"Maximum\" ElementName=\"pbUsrLvl\" />\n </MultiBinding>\n </TextBlock.Text>\n </TextBlock>\n</Grid>\n <Grid>\n <ProgressBar Name=\"pbLifePassed\"\n Minimum=\"0\" \n Value=\"59\" \n Maximum=\"100\"\n Margin=\"5\" Height=\"24\" Foreground=\"#FF62FF7F\"/>\n <TextBlock Text=\"{Binding ElementName=pbLifePassed, Path=Value, StringFormat={}{0:0}%}\" \n HorizontalAlignment=\"Center\" VerticalAlignment=\"Center\" />\n</Grid>\n"
},
{
"answer_id": 58972019,
"author": "Julian",
"author_id": 9479890,
"author_profile": "https://Stackoverflow.com/users/9479890",
"pm_score": 1,
"selected": false,
"text": "<Grid>\n <metro:MetroProgressBar x:Name=\"pbar\" Value=\"50\" Height=\"20\"></metro:MetroProgressBar>\n <TextBlock HorizontalAlignment=\"Center\" VerticalAlignment=\"Center\" Text=\"{Binding ElementName=pbar, Path=Value, StringFormat={}{0:0}%}\"></TextBlock>\n</Grid>\n <Grid>\n <ProgressBar x:Name=\"pbar\" Value=\"50\" Height=\"20\" Style=\"{StaticResource MetroProgressBar}\"></ProgressBar>\n <TextBlock HorizontalAlignment=\"Center\" VerticalAlignment=\"Center\" Text=\"{Binding ElementName=pbar, Path=Value, StringFormat={}{0:0}%}\"></TextBlock>\n</Grid>\n <Grid>\n <ProgressBar x:Name=\"pbar\" Value=\"60\" Height=\"20\" Style=\"{x:Null}\"></ProgressBar>\n <TextBlock HorizontalAlignment=\"Center\" VerticalAlignment=\"Center\" Text=\"{Binding ElementName=pbar, Path=Value, StringFormat={}{0:0}%}\"></TextBlock>\n</Grid>\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1336/"
] |
75,937 |
<p>I am using <strong>gcc</strong> for <strong>windows</strong>. The OS is <strong>windows XP</strong>.
How do I import the homepath variable into my c program so I can write to c:\%homepath%\desktop? I would like to use something similar to:</p>
<p><code>fd = fopen("C:\\%%homepath%%\\desktop\\helloworld.txt","w")</code>;</p>
|
[
{
"answer_id": 76146,
"author": "ljorquera",
"author_id": 9132,
"author_profile": "https://Stackoverflow.com/users/9132",
"pm_score": 1,
"selected": false,
"text": "getenv(\"homepath\") getenv NULL sprintf char * homepath = getenv(\"homepath\");\n\nif(homepath == null) {\n /* variable HOMEPATH has not been defined */ \n}\n\nsprintf(path,\"%s\\\\desktop\\\\helloworld.txt\",homepath);\n homepath \\\\desktop\\\\helloworld.txt \\\\ \\"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13461/"
] |
75,943 |
<p>I'm working on a web page where I'm making an AJAX call that returns a chunk of HTML like: </p>
<pre><code><div>
<!-- some html -->
<script type="text/javascript">
/** some javascript */
</script>
</div>
</code></pre>
<p>I'm inserting the whole thing into the DOM, but the JavaScript isn't being run. Is there a way to run it? </p>
<p>Some details: I can't control what's in the script block (so I can't change it to a function that could be called), I just need the whole block to be executed. I can't call eval on the response because the JavaScript is within a larger block of HTML. I could do some kind of regex to separate out the JavaScript and then call eval on it, but that's pretty yucky. Anyone know a better way?</p>
|
[
{
"answer_id": 76003,
"author": "Scott Nichols",
"author_id": 4299,
"author_profile": "https://Stackoverflow.com/users/4299",
"pm_score": 4,
"selected": false,
"text": "div.innerHTML = response;\nvar scripts = div.getElementsByTagName('script');\nfor (var ix = 0; ix < scripts.length; ix++) {\n eval(scripts[ix].text);\n}\n"
},
{
"answer_id": 35462561,
"author": "Roman Vottner",
"author_id": 1377895,
"author_profile": "https://Stackoverflow.com/users/1377895",
"pm_score": 3,
"selected": false,
"text": "innerHTML innerHTML <html>\n<head>\n<script type='text/javascript'>\nfunction addScript()\n{\n var newdiv = document.createElement('div');\n\n var p = document.createElement('p');\n p.innerHTML = \"Dynamically added text\";\n newdiv.appendChild(p);\n\n var script = document.createElement('script');\n script.innerHTML = \"alert('i am here');\";\n newdiv.appendChild(script);\n\n document.getElementById('target').appendChild(newdiv);\n}\n</script>\n</head>\n<body>\n<input type=\"button\" value=\"add script\" onclick=\"addScript()\"/>\n<div>hello world</div>\n<div id=\"target\"></div>\n</body>\n</html>\n"
},
{
"answer_id": 63677480,
"author": "Matthew Beck",
"author_id": 2413712,
"author_profile": "https://Stackoverflow.com/users/2413712",
"pm_score": 0,
"selected": false,
"text": "// This is the HTML with script element(s) we want to inject\nvar newHtml = '<b>After!</b>\\r\\n<' +\n 'script>\\r\\nchangeColorEverySecond();\\r\\n</' +\n 'script>';\n \n// Here, we separate the script tags from the non-script HTML\nvar parts = separateScriptElementsFromHtml(newHtml);\n\nfunction separateScriptElementsFromHtml(fullHtmlString) {\n var inner = [], outer = [], m;\n while (m = /<script>([^<]*)<\\/script>/gi.exec(fullHtmlString)) {\n outer.push(fullHtmlString.substr(0, m.index));\n inner.push(m[1]);\n fullHtmlString = fullHtmlString.substr(m.index + m[0].length);\n }\n outer.push(fullHtmlString);\n return {\n html: outer.join('\\r\\n'),\n js: inner.join('\\r\\n')\n };\n}\n\n// In 2 seconds, inject the new HTML, and run the JS\nsetTimeout(function(){\n document.getElementsByTagName('P')[0].innerHTML = parts.html;\n eval(parts.js);\n}, 2000);\n\n\n// This is the function inside the script tag\nfunction changeColorEverySecond() {\n document.getElementsByTagName('p')[0].style.color = getRandomColor();\n setTimeout(changeColorEverySecond, 1000);\n}\n\n// Here is a fun fun function copied from:\n// https://stackoverflow.com/a/1484514/2413712\nfunction getRandomColor() {\n var letters = '0123456789ABCDEF';\n var color = '#';\n for (var i = 0; i < 6; i++) {\n color += letters[Math.floor(Math.random() * 16)];\n }\n return color;\n} <p>Before</p>"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4243/"
] |
75,976 |
<p>I've always been told that adding an element to an array happens like this:</p>
<blockquote>
<p>An empty copy of the array+1element is
created and then the data from the
original array is copied into it then
the new data for the new element is
then loaded</p>
</blockquote>
<p>If this is true, then using an array within a scenario that requires a lot of element activity is contra-indicated due to memory and CPU utilization, correct?</p>
<p>If that is the case, shouldn't you try to avoid using an array as much as possible when you will be adding a lot of elements? Should you use iStringMap instead? If so, what happens if you need more than two dimensions AND need to add a lot of element additions. Do you just take the performance hit or is there something else that should be used?</p>
|
[
{
"answer_id": 76001,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 6,
"selected": true,
"text": "List<T>"
},
{
"answer_id": 76059,
"author": "Alex Lyman",
"author_id": 5897,
"author_profile": "https://Stackoverflow.com/users/5897",
"pm_score": 4,
"selected": false,
"text": "T[] array;\nint i;\nT value;\n...\nif (i >= 0 && i <= array.Length)\n array[i] = value;\n list.Capacity += numberOfAddedElements"
},
{
"answer_id": 76520,
"author": "Michael Meadows",
"author_id": 7643,
"author_profile": "https://Stackoverflow.com/users/7643",
"pm_score": 1,
"selected": false,
"text": "myArray[i] LinkedList<T> List<T> LinkedList<T> IEnumerable<T>"
},
{
"answer_id": 19907490,
"author": "nawfal",
"author_id": 661933,
"author_profile": "https://Stackoverflow.com/users/661933",
"pm_score": 2,
"selected": false,
"text": "params params IEnumerable<T> string[] strings = ...\n object[] objects = strings;\n objects[0] = 1; //compiles, but gives a runtime exception.\n struct Value { public int mutable; }\n\n var array = new[] { new Value() }; \n array[0].mutable = 1; //<-- compiles !\n //a List<Value>[0].mutable = 1; doesnt compile since editing a copy makes no sense\n print array[0].mutable // 1, expected or unexpected? confusing surely\n ICollection<T>.Contains Equals Equals public class Class : IEquatable<Class>\n {\n public bool Equals(Class other)\n {\n Console.WriteLine(\"generic\");\n return true;\n }\n public override bool Equals(object obj)\n {\n Console.WriteLine(\"non generic\");\n return true;\n } \n }\n\n public struct Struct : IEquatable<Struct>\n {\n public bool Equals(Struct other)\n {\n Console.WriteLine(\"generic\");\n return true;\n }\n public override bool Equals(object obj)\n {\n Console.WriteLine(\"non generic\");\n return true;\n } \n }\n\n class[].Contains(test); //prints \"non generic\"\n struct[].Contains(test); //prints \"generic\"\n Length [] T[] ArrayLength ArrayIndex Expression<Func<string>> e = () => new[] { \"a\" }[0];\n //e.Body.NodeType == ExpressionType.ArrayIndex\n\n Expression<Func<string>> e = () => new List<string>() { \"a\" }[0];\n //e.Body.NodeType == ExpressionType.Call;\n string[].IsReadOnly false IList<string>.IsReadOnly true (object)new ConsoleColor[0] is int[] true new ConsoleColor[0] is int[] false uint[] int[] List<T> List<T> ReadOnlyCollection<T>"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/730/"
] |
75,978 |
<p>In a .NET Win console application, I would like to access an App.config file in a location different from the console application binary. For example, how can C:\bin\Text.exe get its settings from C:\Test.exe.config?</p>
|
[
{
"answer_id": 76067,
"author": "Santiago Palladino",
"author_id": 12791,
"author_profile": "https://Stackoverflow.com/users/12791",
"pm_score": 3,
"selected": false,
"text": "ConfigurationManager.OpenExeConfiguration(exePath)\n"
},
{
"answer_id": 76071,
"author": "Michael Meadows",
"author_id": 7643,
"author_profile": "https://Stackoverflow.com/users/7643",
"pm_score": 2,
"selected": false,
"text": "AppDomainSetup domainSetup = new AppDomainSetup();\ndomainSetup.ConfigurationFile = fileLocation;\nAppDomain add = AppDomain.CreateDomain(\"myNewAppDomain\", securityInfo, domainSetup);\n"
},
{
"answer_id": 76085,
"author": "jeff.willis",
"author_id": 9829,
"author_profile": "https://Stackoverflow.com/users/9829",
"pm_score": 5,
"selected": true,
"text": "using System.Configuration; \n\nConfiguration config =\nConfigurationManager.OpenExeConfiguration(\"C:\\Test.exe\");\n"
},
{
"answer_id": 18218068,
"author": "CodeNaked",
"author_id": 142794,
"author_profile": "https://Stackoverflow.com/users/142794",
"pm_score": 3,
"selected": false,
"text": "AppDomain.SetData AppDomain.GetData \"APP_CONFIG_FILE\" \"APP_CONFIG_FILE\" app.config public class Program\n{\n public static void Main()\n {\n AppDomain.CurrentDomain.SetData(\"APP_CONFIG_FILE\", @\"C:\\Temp\\test.config\");\n //...\n }\n}\n"
},
{
"answer_id": 62144686,
"author": "Balaji Dinakaran",
"author_id": 4890791,
"author_profile": "https://Stackoverflow.com/users/4890791",
"pm_score": 0,
"selected": false,
"text": "AppDomainSetup domainSetup = new AppDomainSetup();\n domainSetup.ConfigurationFile = @\"D:\\Mine\\Company\\\";\n string browserName = ConfigurationManager.AppSettings[\"browser\"];\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2748/"
] |
75,980 |
<p>When encoding a query string to be sent to a web server - when do you use <code>escape()</code> and when do you use <code>encodeURI()</code> or <code>encodeURIComponent()</code>:</p>
<p>Use escape:</p>
<pre><code>escape("% +&=");
</code></pre>
<p>OR</p>
<p>use encodeURI() / encodeURIComponent()</p>
<pre><code>encodeURI("http://www.google.com?var1=value1&var2=value2");
encodeURIComponent("var1=value1&var2=value2");
</code></pre>
|
[
{
"answer_id": 3608791,
"author": "Arne Evertsson",
"author_id": 16686,
"author_profile": "https://Stackoverflow.com/users/16686",
"pm_score": 12,
"selected": true,
"text": "escape() %xx %uxxxx query = *( pchar / \"/\" / \"?\" )\npchar = unreserved / pct-encoded / sub-delims / \":\" / \"@\"\nunreserved = ALPHA / DIGIT / \"-\" / \".\" / \"_\" / \"~\"\npct-encoded = \"%\" HEXDIG HEXDIG\nsub-delims = \"!\" / \"$\" / \"&\" / \"'\" / \"(\" / \")\"\n / \"*\" / \"+\" / \",\" / \";\" / \"=\"\n u encodeURI(\"http://www.example.org/a file with spaces.html\")\n http://www.example.org/a%20file%20with%20spaces.html\n http%3A%2F%2Fwww.example.org%2Fa%20file%20with%20spaces.html\n var p1 = encodeURIComponent(\"http://example.org/?a=12&b=55\")\n var url = \"http://example.net/?param1=\" + p1 + \"¶m2=99\";\n http://example.net/?param1=http%3A%2F%2Fexample.org%2F%Ffa%3D12%26b%3D55¶m2=99 ' href='MyUrl' \" ' '"
},
{
"answer_id": 12796866,
"author": "Damien",
"author_id": 438970,
"author_profile": "https://Stackoverflow.com/users/438970",
"pm_score": 6,
"selected": false,
"text": "String: \"A + B\"\nExpected Query String Encoding: \"A+%2B+B\"\nescape(\"A + B\") = \"A%20+%20B\" Wrong!\nencodeURI(\"A + B\") = \"A%20+%20B\" Wrong!\nencodeURIComponent(\"A + B\") = \"A%20%2B%20B\" Acceptable, but strange\n\nEncoded String: \"A+%2B+B\"\nExpected Decoding: \"A + B\"\nunescape(\"A+%2B+B\") = \"A+++B\" Wrong!\ndecodeURI(\"A+%2B+B\") = \"A+++B\" Wrong!\ndecodeURIComponent(\"A+%2B+B\") = \"A+++B\" Wrong!\n"
},
{
"answer_id": 16435373,
"author": "Kirankumar Sripati",
"author_id": 2191887,
"author_profile": "https://Stackoverflow.com/users/2191887",
"pm_score": 5,
"selected": false,
"text": "-_.!~*'() <xml><text x=\"100\" y=\"150\" value=\"It's a value with single quote\" />\n</xml> encodeURI %3Cxml%3E%3Ctext%20x=%22100%22%20y=%22150%22%20value=%22It's%20a%20value%20with%20single%20quote%22%20/%3E%20%3C/xml%3E function encodeData(s:String):String{\n return encodeURIComponent(s).replace(/\\-/g, \"%2D\").replace(/\\_/g, \"%5F\").replace(/\\./g, \"%2E\").replace(/\\!/g, \"%21\").replace(/\\~/g, \"%7E\").replace(/\\*/g, \"%2A\").replace(/\\'/g, \"%27\").replace(/\\(/g, \"%28\").replace(/\\)/g, \"%29\");\n}\n function decodeData(s:String):String{\n try{\n return decodeURIComponent(s.replace(/\\%2D/g, \"-\").replace(/\\%5F/g, \"_\").replace(/\\%2E/g, \".\").replace(/\\%21/g, \"!\").replace(/\\%7E/g, \"~\").replace(/\\%2A/g, \"*\").replace(/\\%27/g, \"'\").replace(/\\%28/g, \"(\").replace(/\\%29/g, \")\"));\n }catch (e:Error) {\n }\n return \"\";\n}\n"
},
{
"answer_id": 17235463,
"author": "molokoloco",
"author_id": 174449,
"author_profile": "https://Stackoverflow.com/users/174449",
"pm_score": 1,
"selected": false,
"text": "var escapeURIparam = function(url) {\n if (encodeURIComponent) url = encodeURIComponent(url);\n else if (encodeURI) url = encodeURI(url);\n else url = escape(url);\n url = url.replace(/\\+/g, '%2B'); // Force the replacement of \"+\"\n return url;\n};\n"
},
{
"answer_id": 23250699,
"author": "Jerry Joseph",
"author_id": 1001217,
"author_profile": "https://Stackoverflow.com/users/1001217",
"pm_score": 4,
"selected": false,
"text": "var fileName = 'my file(2).txt';\nvar header = \"Content-Disposition: attachment; filename*=UTF-8''\" + encodeRFC5987ValueChars(fileName);\n\nconsole.log(header); \n// logs \"Content-Disposition: attachment; filename*=UTF-8''my%20file%282%29.txt\"\n\n\nfunction encodeRFC5987ValueChars (str) {\n return encodeURIComponent(str).\n // Note that although RFC3986 reserves \"!\", RFC5987 does not,\n // so we do not need to escape it\n replace(/['()]/g, escape). // i.e., %27 %28 %29\n replace(/\\*/g, '%2A').\n // The following are not required for percent-encoding per RFC5987, \n // so we can allow for a little better readability over the wire: |`^\n replace(/%(?:7C|60|5E)/g, unescape);\n}\n"
},
{
"answer_id": 23842171,
"author": "Johann Echavarria",
"author_id": 2391782,
"author_profile": "https://Stackoverflow.com/users/2391782",
"pm_score": 9,
"selected": false,
"text": "encodeURI() encodeURIComponent() var arr = [];\nfor(var i=0;i<256;i++) {\n var char=String.fromCharCode(i);\n if(encodeURI(char)!==encodeURIComponent(char)) {\n arr.push({\n character:char,\n encodeURI:encodeURI(char),\n encodeURIComponent:encodeURIComponent(char)\n });\n }\n}\nconsole.table(arr);"
},
{
"answer_id": 33019871,
"author": "30thh",
"author_id": 608164,
"author_profile": "https://Stackoverflow.com/users/608164",
"pm_score": 4,
"selected": false,
"text": "1. Java URLEncoder.encode (using UTF8 charset)\n2. JavaScript encodeURIComponent\n3. JavaScript escape\n4. PHP urlencode\n5. PHP rawurlencode\n\nchar JAVA JavaScript --PHP---\n[ ] + %20 %20 + %20\n[!] %21 ! %21 %21 %21\n[*] * * * %2A %2A\n['] %27 ' %27 %27 %27 \n[(] %28 ( %28 %28 %28\n[)] %29 ) %29 %29 %29\n[;] %3B %3B %3B %3B %3B\n[:] %3A %3A %3A %3A %3A\n[@] %40 %40 @ %40 %40\n[&] %26 %26 %26 %26 %26\n[=] %3D %3D %3D %3D %3D\n[+] %2B %2B + %2B %2B\n[$] %24 %24 %24 %24 %24\n[,] %2C %2C %2C %2C %2C\n[/] %2F %2F / %2F %2F\n[?] %3F %3F %3F %3F %3F\n[#] %23 %23 %23 %23 %23\n[[] %5B %5B %5B %5B %5B\n[]] %5D %5D %5D %5D %5D\n----------------------------------------\n[~] %7E ~ %7E %7E ~\n[-] - - - - -\n[_] _ _ _ _ _\n[%] %25 %25 %25 %25 %25\n[\\] %5C %5C %5C %5C %5C\n----------------------------------------\nchar -JAVA- --JavaScript-- -----PHP------\n[ä] %C3%A4 %C3%A4 %E4 %C3%A4 %C3%A4\n[ф] %D1%84 %D1%84 %u0444 %D1%84 %D1%84\n"
},
{
"answer_id": 43537042,
"author": "Gaurav Tiwari",
"author_id": 7220283,
"author_profile": "https://Stackoverflow.com/users/7220283",
"pm_score": 3,
"selected": false,
"text": "escape() @*/+ encodeURI() ~!@#$&*()=:/,;?+' encodeURI('http://stackoverflow.com'); encodeURIComponent() - _ . ! ~ * ' ( ) encodeURIComponent('http://stackoverflow.com');"
},
{
"answer_id": 46441344,
"author": "Michael",
"author_id": 599912,
"author_profile": "https://Stackoverflow.com/users/599912",
"pm_score": 2,
"selected": false,
"text": "function fixedEncodeURIComponent(str) {\n return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {\n return '%' + c.charCodeAt(0).toString(16);\n });\n}\n\n// fixedEncodeURIComponent(\"'\") --> \"%27\"\n"
},
{
"answer_id": 48697555,
"author": "ryanpcmcquen",
"author_id": 2662028,
"author_profile": "https://Stackoverflow.com/users/2662028",
"pm_score": 2,
"selected": false,
"text": "console.log(\n Array(256)\n .fill()\n .map((ignore, i) => String.fromCharCode(i))\n .filter(\n (char) =>\n encodeURI(char) !== encodeURIComponent(char)\n ? {\n character: char,\n encodeURI: encodeURI(char),\n encodeURIComponent: encodeURIComponent(char)\n }\n : false\n )\n) console.log console.table"
},
{
"answer_id": 54630088,
"author": "akinuri",
"author_id": 2202732,
"author_profile": "https://Stackoverflow.com/users/2202732",
"pm_score": 2,
"selected": false,
"text": "var ascii = \" !\\\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\";\n\nvar encoded = [];\n\nascii.split(\"\").forEach(function (char) {\n var obj = { char };\n if (char != encodeURI(char))\n obj.encodeURI = encodeURI(char);\n if (char != encodeURIComponent(char))\n obj.encodeURIComponent = encodeURIComponent(char);\n if (obj.encodeURI || obj.encodeURIComponent)\n encoded.push(obj);\n});\n\nconsole.table(encoded); urlencode() rawurlencode() <script>\n<?php\n$ascii = str_split(\" !\\\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\", 1);\n$encoded = [];\nforeach ($ascii as $char) {\n $obj = [\"char\" => $char];\n if ($char != urlencode($char))\n $obj[\"urlencode\"] = urlencode($char);\n if ($char != rawurlencode($char))\n $obj[\"rawurlencode\"] = rawurlencode($char);\n if (isset($obj[\"rawurlencode\"]) || isset($obj[\"rawurlencode\"]))\n $encoded[] = $obj;\n}\necho \"var encoded = \" . json_encode($encoded) . \";\";\n?>\nconsole.table(encoded);\n</script>\n"
},
{
"answer_id": 62436236,
"author": "HoldOffHunger",
"author_id": 2430549,
"author_profile": "https://Stackoverflow.com/users/2430549",
"pm_score": 3,
"selected": false,
"text": "encodeURI() encodeURIComponent() console.log(encodeURIComponent('@#$%^&*')); @#$%^&* %40%23%24%25%5E%26* * linux command \"$string\" fixedEncodeURIComponent() fixedEncodeURI() encodeURI() encodeURI() fixedEncodeURI() function fixedEncodeURI(str) {\n return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']');\n}\n encodeURIComponent() encodeURIComponent() !'()* fixedEncodeURIComponent() function fixedEncodeURIComponent(str) {\n return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {\n return '%' + c.charCodeAt(0).toString(16);\n });\n}\n fixedEncodeURI() fixedEncodeURIComponent() fixedEncodeURI() +@?=:#;,$& & + fixedEncodeURIComponent()"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/75980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1341/"
] |
76,065 |
<p>I know that with mysql you can write SQL statements into a .sql file and run the file from the mysql command line like this:</p>
<pre><code>mysql> source script.sql
</code></pre>
<p>How do I pass a variable to the script? For example, if I want to run a script that retrieves all the employees in a department, I want to be able to pass in the number of the department as a variable.</p>
<p>I am not trying to run queries through a shell script. There are simple queries I run from the mysql command line. I'm tired of retyping them all the time, and writing a shell script for them would be overkill.</p>
|
[
{
"answer_id": 76124,
"author": "Brad Choate",
"author_id": 553,
"author_profile": "https://Stackoverflow.com/users/553",
"pm_score": 6,
"selected": true,
"text": "set @department := 'Engineering';\n @department update employee set salary = salary + 10000 where department = @department;\n"
},
{
"answer_id": 25109187,
"author": "Yordan Georgiev",
"author_id": 65706,
"author_profile": "https://Stackoverflow.com/users/65706",
"pm_score": 5,
"selected": false,
"text": " #!/bin/bash\n\n #verify the passed params\n echo 1 cmd arg : $1\n echo 2 cmd arg : $2\n\n export db=$1\n export tbl=$2\n\n #set the params ... Note the quotes ( needed for non-numeric values )\n mysql -uroot -pMySecretPaassword \\\n -e \"set @db='${db}';set @tbl='${tbl}';source run.sql ;\" ;\n\n #usage: bash run.sh my_db my_table\n #\n #eof file: run.sh\n\n --file:run.sql\n\n SET @query = CONCAT('Select * FROM ', @db , '.' , @tbl ) ;\n SELECT 'RUNNING THE FOLLOWING query : ' , @query ;\n PREPARE stmt FROM @query;\n EXECUTE stmt;\n DEALLOCATE PREPARE stmt;\n\n --eof file: run.sql\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13519/"
] |
76,074 |
<p>I have a couple old services that I want to completely uninstall. How can I do this?</p>
|
[
{
"answer_id": 76101,
"author": "Mark Schill",
"author_id": 9482,
"author_profile": "https://Stackoverflow.com/users/9482",
"pm_score": 6,
"selected": false,
"text": "regedit HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services"
},
{
"answer_id": 76127,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 11,
"selected": true,
"text": "SC STOP shortservicename\nSC DELETE shortservicename\n sc set-content sc delete service delete service sc.exe delete service SC QUERY state= all >\"C:\\Service List.txt\"\n SC QUERY state= all | FIND \"_NAME\"\n SERVICE_NAME: MyService\nDISPLAY_NAME: My Special Service\n SC STOP MyService\nSC DELETE MyService\n"
},
{
"answer_id": 76158,
"author": "asquithea",
"author_id": 13530,
"author_profile": "https://Stackoverflow.com/users/13530",
"pm_score": 5,
"selected": false,
"text": "sc stop servicexyz\nsc delete servicexyz\n"
},
{
"answer_id": 76239,
"author": "Lucas",
"author_id": 5966,
"author_profile": "https://Stackoverflow.com/users/5966",
"pm_score": 2,
"selected": false,
"text": "Set servicelist = GetObject(\"winmgmts:\").InstancesOf (\"Win32_Service\")\n\nfor each service in servicelist\n sname = lcase(service.name)\n If sname = \"NameOfMyService\" Then \n msgbox(sname)\n service.delete ' the internal name of your service\n end if\nnext\n"
},
{
"answer_id": 15275825,
"author": "user2145033",
"author_id": 2145033,
"author_profile": "https://Stackoverflow.com/users/2145033",
"pm_score": 3,
"selected": false,
"text": "sc delete [your service name as shown in service.msc e.g moneytransfer]\n sc delete moneytransfer C:\\Program Files\\BBRTL\\moneytransfer\\ HKEY_CLASSES_ROOT\\Installer\\Products\\\n HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\\n HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Services\\EventLog\\\n HKEY_LOCAL_MACHINE\\System\\CurrentControlSet002\\Services\\\n HKEY_LOCAL_MACHINE\\System\\CurrentControlSet002\\Services\\EventLog\\\n HKEY_LOCAL_MACHINE\\Software\\Classes\\Installer\\Assemblies\\ [remove .exe references]\n HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\Folders\n"
},
{
"answer_id": 18865199,
"author": "Sachidananda naik",
"author_id": 1664913,
"author_profile": "https://Stackoverflow.com/users/1664913",
"pm_score": 4,
"selected": false,
"text": "SC DELETE \"service name\"\n"
},
{
"answer_id": 36133683,
"author": "Dilmasegure",
"author_id": 6094055,
"author_profile": "https://Stackoverflow.com/users/6094055",
"pm_score": 1,
"selected": false,
"text": "services.msc"
},
{
"answer_id": 49165398,
"author": "Nic",
"author_id": 2450507,
"author_profile": "https://Stackoverflow.com/users/2450507",
"pm_score": 5,
"selected": false,
"text": "sc delete ServiceName\n sc.exe sc Set-Content C:\\Windows\\System32\\sc.exe delete ServiceName\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1204/"
] |
76,076 |
<p>I am trying to solve numerically a set of partial differential equations in three dimensions. In each of the equations the next value of the unknown in a point depends on the current value of each unknown in the closest points.</p>
<p>To write an efficient code I need to keep the points close in the three dimensions close in the (one-dimensional) memory space, so that each value is called from memory just once.</p>
<p>I was thinking of using octtrees, but I was wondering if someone knows a better method.</p>
|
[
{
"answer_id": 83362,
"author": "Nils Pipenbrinck",
"author_id": 15955,
"author_profile": "https://Stackoverflow.com/users/15955",
"pm_score": 3,
"selected": false,
"text": "int morton3 (int a)\n{\n int result = 0;\n int i;\n for (i=0; i<11; i++)\n {\n // check if the i'th bit is set.\n int bit = a&(1<<i);\n if (bit)\n {\n // if so set the 3*i'th bit in the result:\n result |= 1<<(i*3);\n }\n }\n return result;\n}\n index = morton3 (position.x) + \n morton3 (position.y)*2 +\n morton3 (position.z)*4;\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13405/"
] |
76,079 |
<p>can anyone please suggest a <strong>good code example</strong> of vb.net/c# code to put the application in system tray when minized.</p>
|
[
{
"answer_id": 76120,
"author": "Phillip Wells",
"author_id": 3012,
"author_profile": "https://Stackoverflow.com/users/3012",
"pm_score": 5,
"selected": true,
"text": " private void frm_main_Resize(object sender, EventArgs e)\n {\n if (this.WindowState == FormWindowState.Minimized)\n {\n this.ShowInTaskbar = false;\n this.Hide();\n notifyIcon1.Visible = true;\n }\n }\n\n private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)\n {\n this.Show();\n this.WindowState = FormWindowState.Normal;\n this.ShowInTaskbar = true;\n notifyIcon1.Visible = false;\n }\n"
},
{
"answer_id": 76160,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 2,
"selected": false,
"text": "public void Form_Dispose(object sender, EventArgs e)\n{\n if (this.Disposing)\n notifyIcon1.Dispose();\n}\n"
},
{
"answer_id": 76708,
"author": "Sean Gough",
"author_id": 12842,
"author_profile": "https://Stackoverflow.com/users/12842",
"pm_score": 0,
"selected": false,
"text": "Module AnimatedMinimizeToTray\nStructure RECT\n Public left As Integer\n Public top As Integer\n Public right As Integer\n Public bottom As Integer\nEnd Structure\n\nStructure APPBARDATA\n Public cbSize As Integer\n Public hWnd As IntPtr\n Public uCallbackMessage As Integer\n Public uEdge As ABEdge\n Public rc As RECT\n Public lParam As IntPtr\nEnd Structure\n\nEnum ABMsg\n ABM_NEW = 0\n ABM_REMOVE = 1\n ABM_QUERYPOS = 2\n ABM_SETPOS = 3\n ABM_GETSTATE = 4\n ABM_GETTASKBARPOS = 5\n ABM_ACTIVATE = 6\n ABM_GETAUTOHIDEBAR = 7\n ABM_SETAUTOHIDEBAR = 8\n ABM_WINDOWPOSCHANGED = 9\n ABM_SETSTATE = 10\nEnd Enum\n\nEnum ABNotify\n ABN_STATECHANGE = 0\n ABN_POSCHANGED\n ABN_FULLSCREENAPP\n ABN_WINDOWARRANGE\nEnd Enum\n\nEnum ABEdge\n ABE_LEFT = 0\n ABE_TOP\n ABE_RIGHT\n ABE_BOTTOM\nEnd Enum\n\nPublic Declare Function SHAppBarMessage Lib \"shell32.dll\" Alias \"SHAppBarMessage\" (ByVal dwMessage As Integer, ByRef pData As APPBARDATA) As Integer\nPublic Const ABM_GETTASKBARPOS As Integer = &H5&\nPublic Const WM_SYSCOMMAND As Integer = &H112\nPublic Const SC_MINIMIZE As Integer = &HF020\n\nPublic Sub AnimateWindow(ByVal ToTray As Boolean, ByRef frm As Form, ByRef icon As NotifyIcon)\n ' get the screen dimensions\n Dim screenRect As Rectangle = Screen.GetBounds(frm.Location)\n\n ' figure out where the taskbar is (and consequently the tray)\n Dim destPoint As Point\n Dim BarData As APPBARDATA\n BarData.cbSize = System.Runtime.InteropServices.Marshal.SizeOf(BarData)\n SHAppBarMessage(ABMsg.ABM_GETTASKBARPOS, BarData)\n Select Case BarData.uEdge\n Case ABEdge.ABE_BOTTOM, ABEdge.ABE_RIGHT\n ' Tray is to the Bottom Right\n destPoint = New Point(screenRect.Width, screenRect.Height)\n\n Case ABEdge.ABE_LEFT\n ' Tray is to the Bottom Left\n destPoint = New Point(0, screenRect.Height)\n\n Case ABEdge.ABE_TOP\n ' Tray is to the Top Right\n destPoint = New Point(screenRect.Width, 0)\n\n End Select\n\n ' setup our loop based on the direction\n Dim a, b, s As Single\n If ToTray Then\n a = 0\n b = 1\n s = 0.05\n Else\n a = 1\n b = 0\n s = -0.05\n End If\n\n ' \"animate\" the window\n Dim curPoint As Point, curSize As Size\n Dim startPoint As Point = frm.Location\n Dim dWidth As Integer = destPoint.X - startPoint.X\n Dim dHeight As Integer = destPoint.Y - startPoint.Y\n Dim startWidth As Integer = frm.Width\n Dim startHeight As Integer = frm.Height\n Dim i As Single\n For i = a To b Step s\n curPoint = New Point(startPoint.X + i * dWidth, startPoint.Y + i * dHeight)\n curSize = New Size((1 - i) * startWidth, (1 - i) * startHeight)\n ControlPaint.DrawReversibleFrame(New Rectangle(curPoint, curSize), frm.BackColor, FrameStyle.Thick)\n System.Threading.Thread.Sleep(15)\n ControlPaint.DrawReversibleFrame(New Rectangle(curPoint, curSize), frm.BackColor, FrameStyle.Thick)\n Next\n\n\n If ToTray Then\n ' hide the form and show the notifyicon\n frm.Hide()\n icon.Visible = True\n Else\n ' hide the notifyicon and show the form\n icon.Visible = False\n frm.Show()\n End If\n\nEnd Sub\nEnd Module\n Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)\n If m.Msg = WM_SYSCOMMAND AndAlso m.WParam.ToInt32() = SC_MINIMIZE Then\n AnimateWindow(True, Me, NotifyIcon1)\n Exit Sub\n End If\n MyBase.WndProc(m)\nEnd Sub\n\nPrivate Sub NotifyIcon1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles NotifyIcon1.DoubleClick\n AnimateWindow(False, Me, NotifyIcon1)\nEnd Sub\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13337/"
] |
76,080 |
<p>We need to reliably get the Quick Launch folder for both All and Current users under both Vista and XP. I'm developing in C++, but this is probably more of a general Windows API question.</p>
<p>For reference, here is code to get the Application Data folder under both systems:</p>
<pre><code> HRESULT hres;
CString basePath;
hres = SHGetSpecialFolderPath(this->GetSafeHwnd(), basePath.GetBuffer(MAX_PATH), CSIDL_APPDATA, FALSE);
basePath.ReleaseBuffer();
</code></pre>
<p>I suspect this is just a matter of knowing which sub-folder Microsoft uses.</p>
<p>Under Windows XP, the app data subfolder is:</p>
<p>Microsoft\Internet Explorer\Quick Launch</p>
<p>Under Vista, it appears that the sub-folder has been changed to:</p>
<p>Roaming\Microsoft\Internet Explorer\Quick Launch</p>
<p>but I'd like to make sure that this is the correct way to determine the correct location.</p>
<p>Finding the <em>correct</em> way to determine this location is quite important, as relying on hard coded folder names almost always breaks as you move into international installs, etc... The fact that the folder is named 'Roaming' in Vista makes me wonder if there is some special handling related to that folder (akin to the Local Settings folder under XP).</p>
<p>EDIT:
The following msdn article: <a href="http://msdn.microsoft.com/en-us/library/bb762494.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/bb762494.aspx</a> indicates that CSIDL_APPDATA has an equivalent ID of FOLDERID_RoamingAppData, which does seem to support StocksR's assertion that CSIDL_APPDATA does return C:\Users\xxxx\AppData\Roaming, so it should be possible to use the same relative path for CSIDL_APPDATA to get to quick launch (\Microsoft\Internet Explorer\Quick Launch).</p>
<p>So the following algorithm is correct per MS:</p>
<pre><code>HRESULT hres;
CString basePath;
hres = SHGetSpecialFolderPath(this->GetSafeHwnd(), basePath.GetBuffer(MAX_PATH), CSIDL_APPDATA, FALSE);
basePath.ReleaseBuffer();
CString qlPath = basePath + "\\Microsoft\\Internet Explorer\\Quick Launch";
</code></pre>
<p>it would also be a good idea to check hres to ensure that the call to SHGetSpecialFolderPath was successful.</p>
|
[
{
"answer_id": 76323,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 1,
"selected": false,
"text": "GetSpecialFolderPath(APP_DATA) + \"\\\\Fonts\""
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10973/"
] |
76,096 |
<p>I'm trying to keep dependencies to a minimum for a program I contribute to, it's a small text editor.</p>
<p>GTK Textview doesn't seem to come with a built-in undo function. Is there any reference implementation I've been missing on so far? Is everyone writing their own undo function for their TextView widgets?</p>
<p>I'll be happy about any sample code - most happy about python sample code, as our project is in python.</p>
|
[
{
"answer_id": 48927176,
"author": "oxidworks",
"author_id": 1907997,
"author_profile": "https://Stackoverflow.com/users/1907997",
"pm_score": 0,
"selected": false,
"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport gi\ngi.require_version('Gtk', '3.0')\nfrom gi.repository import Gtk\nfrom gi.repository import Gdk\ngi.require_version('GtkSource', '3.0')\nfrom gi.repository import GtkSource\n\nimport os\n\n\nclass TreeviewWindow(Gtk.Window):\n def __init__(self):\n Gtk.Window.__init__(self, title=\"TreeviewWindow\")\n self.set_size_request(300, 300)\n self.connect(\"key-press-event\", self._key_press_event)\n self.mainbox = Gtk.VBox(spacing=10)\n self.add(self.mainbox) \n\n self.textbuffer = GtkSource.Buffer()\n textview = GtkSource.View(buffer=self.textbuffer)\n textview.set_editable(True)\n textview.set_cursor_visible(True)\n textview.set_show_line_numbers(True)\n self.mainbox.pack_start(textview, True, True, 0)\n self.show_all() \n\n def _key_press_event(self, widget, event):\n keyval_name = Gdk.keyval_name(event.keyval)\n ctrl = (event.state & Gdk.ModifierType.CONTROL_MASK)\n if ctrl and keyval_name == 'y':\n if self.textbuffer.can_redo():\n self.textbuffer.do_redo(self.textbuffer)\n \n def main(self):\n Gtk.main()\n \nif __name__ == \"__main__\":\n base = TreeviewWindow()\n base.main()\n \n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/64673/"
] |
76,134 |
<p>I have 4 2D points in screen-space, and I need to reverse-project them back into 3D space. I know that each of the 4 points is a corner of a 3D-rotated rigid rectangle, and I know the size of the rectangle. How can I get 3D coordinates from this?</p>
<p>I am not using any particular API, and I do not have an existing projection matrix. I'm just looking for basic math to do this. Of course there isn't enough data to convert a single 2D point to 3D with no other reference, but I imagine that if you have 4 points, you know that they're all at right-angles to each other on the same plane, and you know the distance between them, you should be able to figure it out from there. Unfortunately I can't quite work out how though.</p>
<p>This might fall under the umbrella of photogrammetry, but google searches for that haven't led me to any helpful information. </p>
|
[
{
"answer_id": 78057,
"author": "user14208",
"author_id": 14208,
"author_profile": "https://Stackoverflow.com/users/14208",
"pm_score": 3,
"selected": false,
"text": "void YCamera :: CalculateWorldCoordinates(float x, float y, YVector3 *vec)\n{\n // START\n GLint viewport[4];\n GLdouble mvmatrix[16], projmatrix[16];\n \n GLint real_y;\n GLdouble mx, my, mz;\n\n glGetIntegerv(GL_VIEWPORT, viewport);\n glGetDoublev(GL_MODELVIEW_MATRIX, mvmatrix);\n glGetDoublev(GL_PROJECTION_MATRIX, projmatrix);\n\n real_y = viewport[3] - (GLint) y - 1; // viewport[3] is height of window in pixels\n gluUnProject((GLdouble) x, (GLdouble) real_y, 1.0, mvmatrix, projmatrix, viewport, &mx, &my, &mz);\n\n /* 'mouse' is the point where mouse projection reaches FAR_PLANE.\n World coordinates is intersection of line(camera->mouse) with plane(z=0) (see LaMothe 306)\n \n Equation of line in 3D:\n (x-x0)/a = (y-y0)/b = (z-z0)/c \n\n Intersection of line with plane:\n z = 0\n x-x0 = a(z-z0)/c <=> x = x0+a(0-z0)/c <=> x = x0 -a*z0/c\n y = y0 - b*z0/c\n \n */\n double lx = fPosition.x - mx;\n double ly = fPosition.y - my;\n double lz = fPosition.z - mz;\n double sum = lx*lx + ly*ly + lz*lz;\n double normal = sqrt(sum);\n double z0_c = fPosition.z / (lz/normal);\n \n vec->x = (float) (fPosition.x - (lx/normal)*z0_c);\n vec->y = (float) (fPosition.y - (ly/normal)*z0_c);\n vec->z = 0.0f;\n}\n"
},
{
"answer_id": 33976739,
"author": "Vegard",
"author_id": 1697183,
"author_profile": "https://Stackoverflow.com/users/1697183",
"pm_score": 7,
"selected": false,
"text": "(318, 247) (326, 312) (418, 241) (452, 303) (0, 0, 0) (0, 0, 1) (1, 0, 0) (1, 0, 1) [x, y, z, 1] gluProject() gluProject() # Known 2D coordinates of our rectangle\ni0 = Point2(318, 247)\ni1 = Point2(326, 312)\ni2 = Point2(418, 241)\ni3 = Point2(452, 303)\n\n# 3D coordinates corresponding to i0, i1, i2, i3\nr0 = Point3(0, 0, 0)\nr1 = Point3(0, 0, 1)\nr2 = Point3(1, 0, 0)\nr3 = Point3(1, 0, 1)\n mat = [\n [1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 1],\n]\n def project(p, mat):\n x = mat[0][0] * p.x + mat[0][1] * p.y + mat[0][2] * p.z + mat[0][3] * 1\n y = mat[1][0] * p.x + mat[1][1] * p.y + mat[1][2] * p.z + mat[1][3] * 1\n w = mat[3][0] * p.x + mat[3][1] * p.y + mat[3][2] * p.z + mat[3][3] * 1\n return Point(720 * (x / w + 1) / 2., 576 - 576 * (y / w + 1) / 2.)\n gluProject() # The squared distance between two points a and b\ndef norm2(a, b):\n dx = b.x - a.x\n dy = b.y - a.y\n return dx * dx + dy * dy\n\ndef evaluate(mat): \n c0 = project(r0, mat)\n c1 = project(r1, mat)\n c2 = project(r2, mat)\n c3 = project(r3, mat)\n return norm2(i0, c0) + norm2(i1, c1) + norm2(i2, c2) + norm2(i3, c3)\n def perturb(amount):\n from copy import deepcopy\n from random import randrange, uniform\n mat2 = deepcopy(mat)\n mat2[randrange(4)][randrange(4)] += uniform(-amount, amount)\n project() mat[2] mat[*][1] perturb() def approximate(mat, amount, n=100000):\n est = evaluate(mat)\n\n for i in xrange(n):\n mat2 = perturb(mat, amount)\n est2 = evaluate(mat2)\n if est2 < est:\n mat = mat2\n est = est2\n\n return mat, est\n for i in xrange(100):\n mat = approximate(mat, 1)\n mat = approximate(mat, .1)\n [\n [1.0836000765696232, 0, 0.16272110011060575, -0.44811064935115597],\n [0.09339193527789781, 1, -0.7990570384334473, 0.539087345090207 ],\n [0, 0, 1, 0 ],\n [0.06700844759602216, 0, -0.8333379578853196, 3.875290562060915 ],\n]\n 2.6e-5 glLoadMatrix() def transpose(m):\n return [\n [m[0][0], m[1][0], m[2][0], m[3][0]],\n [m[0][1], m[1][1], m[2][1], m[3][1]],\n [m[0][2], m[1][2], m[2][2], m[3][2]],\n [m[0][3], m[1][3], m[2][3], m[3][3]],\n ]\n\nglLoadMatrixf(transpose(mat))\n glTranslate(0, 0, frame)\nframe = frame + 1\n\nglBegin(GL_QUADS)\nglVertex3f(0, 0, 0)\nglVertex3f(0, 0, 1)\nglVertex3f(1, 0, 1)\nglVertex3f(1, 0, 0)\nglEnd()\n"
},
{
"answer_id": 39877333,
"author": "BBSysDyn",
"author_id": 423805,
"author_profile": "https://Stackoverflow.com/users/423805",
"pm_score": 2,
"selected": false,
"text": "import pandas as pd\nimport numpy as np\n\nclass Point2:\n def __init__(self,x,y):\n self.x = x\n self.y = y\n\nclass Point3:\n def __init__(self,x,y,z):\n self.x = x\n self.y = y\n self.z = z\n\n# Known 2D coordinates of our rectangle\ni0 = Point2(318, 247)\ni1 = Point2(326, 312)\ni2 = Point2(418, 241)\ni3 = Point2(452, 303)\n\n# 3D coordinates corresponding to i0, i1, i2, i3\nr0 = Point3(0, 0, 0)\nr1 = Point3(0, 0, 1)\nr2 = Point3(1, 0, 0)\nr3 = Point3(1, 0, 1)\n\nmat = [\n [1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 1],\n]\n\ndef project(p, mat):\n #print mat\n x = mat[0][0] * p.x + mat[0][1] * p.y + mat[0][2] * p.z + mat[0][3] * 1\n y = mat[1][0] * p.x + mat[1][1] * p.y + mat[1][2] * p.z + mat[1][3] * 1\n w = mat[3][0] * p.x + mat[3][1] * p.y + mat[3][2] * p.z + mat[3][3] * 1\n return Point2(720 * (x / w + 1) / 2., 576 - 576 * (y / w + 1) / 2.)\n\n# The squared distance between two points a and b\ndef norm2(a, b):\n dx = b.x - a.x\n dy = b.y - a.y\n return dx * dx + dy * dy\n\ndef evaluate(mat): \n c0 = project(r0, mat)\n c1 = project(r1, mat)\n c2 = project(r2, mat)\n c3 = project(r3, mat)\n return norm2(i0, c0) + norm2(i1, c1) + norm2(i2, c2) + norm2(i3, c3) \n\ndef perturb(mat, amount):\n from copy import deepcopy\n from random import randrange, uniform\n mat2 = deepcopy(mat)\n mat2[randrange(4)][randrange(4)] += uniform(-amount, amount)\n return mat2\n\ndef approximate(mat, amount, n=1000):\n est = evaluate(mat)\n for i in xrange(n):\n mat2 = perturb(mat, amount)\n est2 = evaluate(mat2)\n if est2 < est:\n mat = mat2\n est = est2\n\n return mat, est\n\nfor i in xrange(1000):\n mat,est = approximate(mat, 1)\n print mat\n print est\n [[0.7576315397559887, 0, 0.11439449272592839, -0.314856490473439], \n[0.06440497208710227, 1, -0.5607502645413118, 0.38338196981556827], \n[0, 0, 1, 0], \n[0.05421620936883742, 0, -0.5673977598434641, 2.693116299312736]]\n"
},
{
"answer_id": 43801764,
"author": "Inflight",
"author_id": 2388690,
"author_profile": "https://Stackoverflow.com/users/2388690",
"pm_score": 0,
"selected": false,
"text": "Cv2.CalibrateCamera(new List<List<Point3f>>() { points3d }, new List<List<Point2f>>() { points2d }, new Size(height, width), cameraMatrix, distCoefs, out rvecs, out tvecs, CalibrationFlags.ZeroTangentDist | CalibrationFlags.FixK1 | CalibrationFlags.FixK2 | CalibrationFlags.FixK3);\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8409/"
] |
76,194 |
<p>I seldom use inheritance, but when I do, I never use protected attributes because I think it breaks the encapsulation of the inherited classes.</p>
<p>Do you use protected attributes ? what do you use them for ?</p>
|
[
{
"answer_id": 87360,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 2,
"selected": false,
"text": "[+] Base\n |\n +--[+] BaseMap\n | |\n | +--[+] Map\n | |\n | +--[+] HashMap\n |\n +--[+] // something else ?\n"
},
{
"answer_id": 1546563,
"author": "Pascal Thivent",
"author_id": 70604,
"author_profile": "https://Stackoverflow.com/users/70604",
"pm_score": 5,
"selected": true,
"text": "AbstractList removeRange subList List clear List clear List"
},
{
"answer_id": 2034079,
"author": "Calmarius",
"author_id": 58805,
"author_profile": "https://Stackoverflow.com/users/58805",
"pm_score": 1,
"selected": false,
"text": "static Random rnd=new Random();\n//...\nif (rnd.Next()%1000==0) throw new Exception(\"My base class sucks! HAHAHAHA! xD\");\n//...\n private _foo;\npublic foo\n{\n get {return _foo;}\n set {_foo=value;}\n}\n"
},
{
"answer_id": 36660453,
"author": "Jim Balter",
"author_id": 544557,
"author_profile": "https://Stackoverflow.com/users/544557",
"pm_score": 2,
"selected": false,
"text": "protected protected protected private public public protected"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13501/"
] |
76,204 |
<p>I am receiving a 3rd party feed of which I cannot be certain of the namespace so I am currently having to use the local-name() function in my XSLT to get the element values. However I need to get an attribute from one such element and I don't know how to do this when the namespaces are unknown (hence need for local-name() function).</p>
<p>N.B. I am using .net 2.0 to process the XSLT</p>
<p>Here is a sample of the XML:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<id>some id</id>
<title>some title</title>
<updated>2008-09-11T15:53:31+01:00</updated>
<link rel="self" href="http://www.somefeedurl.co.uk" />
<author>
<name>some author</name>
<uri>http://someuri.co.uk</uri>
</author>
<generator uri="http://aardvarkmedia.co.uk/">AardvarkMedia script</generator>
<entry>
<id>http://soemaddress.co.uk/branded3/80406</id>
<title type="html">My Ttile</title>
<link rel="alternate" href="http://www.someurl.co.uk" />
<updated>2008-02-13T00:00:00+01:00</updated>
<published>2002-09-11T14:16:20+01:00</published>
<category term="mycategorytext" label="restaurant">Test</category>
<content type="xhtml">
<div xmlns="http://www.w3.org/1999/xhtml">
<div class="vcard">
<p class="fn org">some title</p>
<p class="adr">
<abbr class="type" title="POSTAL" />
<span class="street-address">54 Some Street</span>
,
<span class="locality" />
,
<span class="country-name">UK</span>
</p>
<p class="tel">
<span class="value">0123456789</span>
</p>
<div class="geo">
<span class="latitude">51.99999</span>
,
<span class="longitude">-0.123456</span>
</div>
<p class="note">
<span class="type">Review</span>
<span class="value">Some content</span>
</p>
<p class="note">
<span class="type">Overall rating</span>
<span class="value">8</span>
</p>
</div>
</div>
</content>
<category term="cuisine-54" label="Spanish" />
<Point xmlns="http://www.w3.org/2003/01/geo/wgs84_pos#">
<lat>51.123456789</lat>
<long>-0.11111111</long>
</Point>
</entry>
</feed>
</code></pre>
<p>This is XSLT</p>
<pre><code><?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:wgs="http://www.w3.org/2003/01/geo/wgs84_pos#" exclude-result-prefixes="atom wgs">
<xsl:output method="xml" indent="yes"/>
<xsl:key name="uniqueVenuesKey" match="entry" use="id"/>
<xsl:key name="uniqueCategoriesKey" match="entry" use="category/@term"/>
<xsl:template match="/">
<locations>
<!-- Get all unique venues -->
<xsl:for-each select="/*[local-name()='feed']/*[local-name()='entry']">
<xsl:variable name="CurrentVenueKey" select="*[local-name()='id']" ></xsl:variable>
<xsl:variable name="CurrentVenueName" select="*[local-name()='title']" ></xsl:variable>
<xsl:variable name="CurrentVenueAddress1" select="*[local-name()='content']/*[local-name()='div']/*[local-name()='div']/*[local-name()='p'][@class='adr']/*[local-name()='span'][@class='street-address']" ></xsl:variable>
<xsl:variable name="CurrentVenueCity" select="*[local-name()='content']/*[local-name()='div']/*[local-name()='div']/*[local-name()='p'][@class='adr']/*[local-name()='span'][@class='locality']" ></xsl:variable>
<xsl:variable name="CurrentVenuePostcode" select="*[local-name()='postcode']" ></xsl:variable>
<xsl:variable name="CurrentVenueTelephone" select="*[local-name()='telephone']" ></xsl:variable>
<xsl:variable name="CurrentVenueLat" select="*[local-name()='Point']/*[local-name()='lat']" ></xsl:variable>
<xsl:variable name="CurrentVenueLong" select="*[local-name()='Point']/*[local-name()='long']" ></xsl:variable>
<xsl:variable name="CurrentCategory" select="WHATDOIPUTHERE"></xsl:variable>
<location>
<locationName>
<xsl:value-of select = "$CurrentVenueName" />
</locationName>
<category>
<xsl:value-of select = "$CurrentCategory" />
</category>
<description>
<xsl:value-of select = "$CurrentVenueName" />
</description>
<venueAddress>
<streetName>
<xsl:value-of select = "$CurrentVenueAddress1" />
</streetName>
<town>
<xsl:value-of select = "$CurrentVenueCity" />
</town>
<postcode>
<xsl:value-of select = "$CurrentVenuePostcode" />
</postcode>
<wgs84_latitude>
<xsl:value-of select = "$CurrentVenueLat" />
</wgs84_latitude>
<wgs84_longitude>
<xsl:value-of select = "$CurrentVenueLong" />
</wgs84_longitude>
</venueAddress>
<venuePhone>
<phonenumber>
<xsl:value-of select = "$CurrentVenueTelephone" />
</phonenumber>
</venuePhone>
</location>
</xsl:for-each>
</locations>
</xsl:template>
</xsl:stylesheet>
</code></pre>
<p>I'm trying to replace the $CurrentCategory variable the appropriate code to display <em>mycategorytext</em></p>
|
[
{
"answer_id": 76497,
"author": "Santiago Palladino",
"author_id": 12791,
"author_profile": "https://Stackoverflow.com/users/12791",
"pm_score": 5,
"selected": true,
"text": "*[local-name()='category']/@*[local-name()='term']\n"
},
{
"answer_id": 76627,
"author": "elarson",
"author_id": 5434,
"author_profile": "https://Stackoverflow.com/users/5434",
"pm_score": 0,
"selected": false,
"text": "<xsl:stylesheet xmlns=\"http://www.w3.org/2005/Atom\" ..>\n\n<xsl:template match=\"feed\">\n <xsl:apply-templates />\n</xsl:template>\n\n<xsl:template match=\"entry\">\n ... \n <xsl:variable name=\"current-category\" select=\"category/@term\" />\n ...\n</xsl:template>\n"
},
{
"answer_id": 76658,
"author": "Dominic Cronin",
"author_id": 9967,
"author_profile": "https://Stackoverflow.com/users/9967",
"pm_score": 2,
"selected": false,
"text": " <xsl:for-each select=\"/atom:feed/atom:entry\">\n <xsl:variable name=\"CurrentVenueKey\" select=\"atom:id\" />\n <xsl:variable name=\"CurrentVenueName\" select=\"atom:title\" />\n <xsl:variable name=\"CurrentVenueAddress1\" \n select=\"atom:content/xhtml:div/xhtml:div/xhtml:p[@class='adr']/xhtml:span[@class='street-address']\" />\n <xsl:variable name=\"CurrentVenueCity\" \n select=\"atom:content/xhtml:div/xhtml:div'/xhtml:p[@class='adr']/xhtml:span[@class='locality'] />\n...\n <xsl:variable name=\"CurrentCategory\" select=\"atom:category/@term\" />\n\n..... \n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/258/"
] |
76,208 |
<p>Is there a good way to time SQL queries when using Linq to SQL? I really like logging feature, but it would be great if you could somehow also time that query. Any ideas?</p>
|
[
{
"answer_id": 76262,
"author": "Quintin Robinson",
"author_id": 12707,
"author_profile": "https://Stackoverflow.com/users/12707",
"pm_score": 2,
"selected": false,
"text": "System.Diagnostics.Stopwatch Console.Out"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11063/"
] |
76,223 |
<p>I am working on a project where the requirement is to have a date calculated as being the last Friday of a given month. I think I have a solution that only uses standard Java, but I was wondering if anyone knew of anything more concise or efficient. Below is what I tested with for this year:</p>
<pre><code> for (int month = 0; month < 13; month++) {
GregorianCalendar d = new GregorianCalendar();
d.set(d.MONTH, month);
System.out.println("Last Week of Month in " + d.getDisplayName(d.MONTH, Calendar.LONG, Locale.ENGLISH) + ": " + d.getLeastMaximum(d.WEEK_OF_MONTH));
d.set(d.DAY_OF_WEEK, d.FRIDAY);
d.set(d.WEEK_OF_MONTH, d.getActualMaximum(d.WEEK_OF_MONTH));
while (d.get(d.MONTH) > month || d.get(d.MONTH) < month) {
d.add(d.WEEK_OF_MONTH, -1);
}
Date dt = d.getTime();
System.out.println("Last Friday of Last Week in " + d.getDisplayName(d.MONTH, Calendar.LONG, Locale.ENGLISH) + ": " + dt.toString());
}
</code></pre>
|
[
{
"answer_id": 76389,
"author": "Binil Thomas",
"author_id": 3973,
"author_profile": "https://Stackoverflow.com/users/3973",
"pm_score": 1,
"selected": false,
"text": "public int getLastFriday(int month, int year) {\n Calendar cal = Calendar.getInstance();\n cal.set(year, month, 1, 0, 0, 0); // set to first day of the month\n cal.set(Calendar.MILLISECOND, 0);\n\n int friday = -1;\n while (cal.get(Calendar.MONTH) == month) { \n if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) { // is it a friday?\n friday = cal.get(Calendar.DAY_OF_MONTH);\n cal.add(Calendar.DAY_OF_MONTH, 7); // skip 7 days\n } else {\n cal.add(Calendar.DAY_OF_MONTH, 1); // skip 1 day\n }\n }\n return friday;\n}\n"
},
{
"answer_id": 76430,
"author": "Hans Doggen",
"author_id": 9504,
"author_profile": "https://Stackoverflow.com/users/9504",
"pm_score": 3,
"selected": false,
"text": "DateTime now = new DateTime(); \nDateTime dt = now.dayOfMonth().withMaximumValue().withDayOfWeek(DateTimeConstants.FRIDAY);\nif (dt.getMonthOfYear() != now.getMonthOfYear()) {\n dt = dt.minusDays(7);\n} \nSystem.out.println(dt);\n"
},
{
"answer_id": 76447,
"author": "Benno Richters",
"author_id": 3565,
"author_profile": "https://Stackoverflow.com/users/3565",
"pm_score": 1,
"selected": false,
"text": "int year = 2008;\nfor (int m = Calendar.JANUARY; m <= Calendar.DECEMBER; m++) {\n Calendar cal = new GregorianCalendar(year, m, 1);\n cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));\n int diff = Calendar.FRIDAY - cal.get(Calendar.DAY_OF_WEEK);\n if (diff > 0) {\n diff -= 7;\n }\n cal.add(Calendar.DAY_OF_MONTH, diff);\n System.out.println(cal.getTime());\n}\n"
},
{
"answer_id": 77077,
"author": "ColinD",
"author_id": 13792,
"author_profile": "https://Stackoverflow.com/users/13792",
"pm_score": 6,
"selected": true,
"text": "public Date getLastFriday( int month, int year ) {\n Calendar cal = Calendar.getInstance();\n cal.set( year, month + 1, 1 );\n cal.add( Calendar.DAY_OF_MONTH, -( cal.get( Calendar.DAY_OF_WEEK ) % 7 + 1 ) );\n return cal.getTime();\n}\n"
},
{
"answer_id": 77315,
"author": "Aaron",
"author_id": 7659,
"author_profile": "https://Stackoverflow.com/users/7659",
"pm_score": 2,
"selected": false,
"text": "public static int getLastFriday(int month, int year)\n{\nCalendar cal = Calendar.getInstance();\ncal.set(year, month, 1, 0, 0, 0); // set to first day of the month\ncal.set(Calendar.MILLISECOND, 0);\n\nint firstDay = cal.get(Calendar.DAY_OF_WEEK);\nint daysOfMonth = cal.getMaximum(Calendar.DAY_OF_MONTH);\n\nswitch (firstDay)\n{\n case Calendar.SUNDAY :\n return 27;\n case Calendar.MONDAY :\n return 26;\n case Calendar.TUESDAY :\n return 25;\n case Calendar.WEDNESDAY :\n if (daysOfMonth == 31) return 31;\n return 24;\n case Calendar.THURSDAY :\n if (daysOfMonth >= 30) return 30;\n return 23;\n case Calendar.FRIDAY :\n if (daysOfMonth >= 29) return 29;\n return 22;\n case Calendar.SATURDAY :\n return 28;\n}\nthrow new RuntimeException(\"what day of the month?\");\n}}\n"
},
{
"answer_id": 1067710,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "public static void getSundaysInThisMonth(int monthNumber, int yearNumber){\n //int year =2009;\n //int dayOfWeek = Calendar.SUNDAY;\n // instantiate Calender and set to first Sunday of 2009\n Calendar cal = new GregorianCalendar();\n cal.set(Calendar.MONTH, monthNumber-1);\n cal.set(Calendar.YEAR, yearNumber);\n cal.set(Calendar.DATE, 1);\n int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);\n int dateOfWeek = cal.get(Calendar.DATE);\n while (dayOfWeek != Calendar.SUNDAY) {\n cal.set(Calendar.DATE, ++dateOfWeek);\n dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);\n }\n cal.set(Calendar.DATE, dateOfWeek);\n\n int i = 1;\n while (cal.get(Calendar.YEAR) == yearNumber && cal.get(Calendar.MONTH)==monthNumber-1)\n {\n System.out.println(\"Sunday \" + \" \" + i + \": \" + cal.get(Calendar.DAY_OF_MONTH));\n cal.add(Calendar.DAY_OF_MONTH, 7);\n i++;\n }\n\n }\n public static void main(String args[]){\n getSundaysInThisMonth(1,2009);\n }\n"
},
{
"answer_id": 2545695,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "pCal.set(GregorianCalendar.DAY_OF_WEEK,Calendar.FRIDAY);\npCal.set(GregorianCalendar.DAY_OF_WEEK_IN_MONTH, -1);\n"
},
{
"answer_id": 7806120,
"author": "josephus",
"author_id": 611228,
"author_profile": "https://Stackoverflow.com/users/611228",
"pm_score": 2,
"selected": false,
"text": "Calendar thisMonth = Calendar.getInstance();\ndayOfWeek = Calendar.FRIDAY; // or whatever\nthisMonth.set(Calendar.WEEK_OF_MONTH, thisMonth.getActualMaximum(Calendar.WEEK_OF_MONTH);;\nthisMonth.set(Calendar.DAY_OF_WEEK, dayOfWeek);\nint lastDay = thisMonth.get(Calendar.DAY_OF_MONTH); // this should be it.\n"
},
{
"answer_id": 9469295,
"author": "Alexeyy Alexeyy",
"author_id": 1192726,
"author_profile": "https://Stackoverflow.com/users/1192726",
"pm_score": -1,
"selected": false,
"text": "public static Calendar getNthDow(int month, int year, int dayOfWeek, int n) {\n Calendar cal = Calendar.getInstance();\n cal.set(year, month, 1);\n cal.set(Calendar.DAY_OF_WEEK, dayOfWeek);\n cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, n);\n return (cal.get(Calendar.MONTH) == month) && (cal.get(Calendar.YEAR) == year) ? cal : null;\n}\n"
},
{
"answer_id": 10922864,
"author": "akshay jangid",
"author_id": 1440879,
"author_profile": "https://Stackoverflow.com/users/1440879",
"pm_score": 1,
"selected": false,
"text": "offset=0 getLastFridayofMonth(int offset) import java.text.SimpleDateFormat;\nimport java.util.Calendar;\n\npublic class LastFriday {\n\n public static Calendar getLastFriday(Calendar cal,int offset){\n int dayofweek;//1-Sunday,2-Monday so on....\n cal.set(Calendar.MONTH,cal.get(Calendar.MONTH)+offset);\n cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH)); //set calendar to last day of month\n dayofweek=cal.get(Calendar.DAY_OF_WEEK); //get the day of the week for last day of month set above,1-sunday,2-monday etc\n if(dayofweek<Calendar.FRIDAY) //Calendar.FRIDAY will return integer value =5 \n cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH)-7+Calendar.FRIDAY-dayofweek);\n else\n cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH)+Calendar.FRIDAY-dayofweek); \n\n return cal;\n }\n\n public static String getLastFridayofMonth(int offset) { //offset=0 mean current month\n final String DATE_FORMAT_NOW = \"dd-MMM-yyyy\";\n Calendar cal = Calendar.getInstance();\n SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);\n cal=getLastFriday(cal,offset);\n return sdf.format(cal.getTime()); \n\n }\n\n public static void main(String[] args) {\n System.out.println(getLastFridayofMonth(0)); //0 = current month\n System.out.println(getLastFridayofMonth(1));//1=next month\n System.out.println(getLastFridayofMonth(2));//2=month after next month\n }\n\n}\n"
},
{
"answer_id": 22397346,
"author": "Dhananjay Chauhan",
"author_id": 3418626,
"author_profile": "https://Stackoverflow.com/users/3418626",
"pm_score": 0,
"selected": false,
"text": "public static int lastSundayDate()\n{\n Calendar cal = getCalendarInstance();\n cal.setTime(new Date(getUTCTimeMillis()));\n cal.set( Calendar.DAY_OF_MONTH , 25 );\n return (25 + 8 - (cal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY ? cal.get(Calendar.DAY_OF_WEEK) : 8));\n}\n"
},
{
"answer_id": 33867973,
"author": "Przemek",
"author_id": 1981559,
"author_profile": "https://Stackoverflow.com/users/1981559",
"pm_score": 4,
"selected": false,
"text": "TemporalAdjusters.lastInMonth val now = LocalDate.now() \nval lastInMonth = now.with(TemporalAdjusters.lastInMonth(DayOfWeek.FRIDAY))\n DayOfWeek LocalDate LocalDateTime lastFriday.atStartOfDay() // e.g. 2015-11-27T00:00\n"
},
{
"answer_id": 40993952,
"author": "KayV",
"author_id": 3956731,
"author_profile": "https://Stackoverflow.com/users/3956731",
"pm_score": 1,
"selected": false,
"text": "LocalDate lastFridayOfMonth = LocalDate\n .now()\n .with(lastDayOfMonth())\n .with(previous(DayOfWeek.FRIDAY));\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7008/"
] |
76,227 |
<p>I'm teaching a kid programming, and am introducing some basic artificial intelligence concepts at the moment. To begin with we're going to implement a tic-tac-toe game that searches the entire game tree and as such plays perfectly. Once we finish that I want to apply the same concepts to a game that has too many positions to evaluate every single one, so that we need to implement a heuristic to evaluate intermediate positions.</p>
<p>The best thing I could think of was <a href="http://en.wikipedia.org/wiki/Dots-and-boxes" rel="nofollow noreferrer">Dots and Boxes</a>. It has the advantage that I can set the board size arbitrarily large to stop him from searching the entire tree, and I can make a very basic scoring function be the number of my boxes minus the number of opponent boxes. Unfortunately this means that for most of the beginning of the game every position will be evaluated equivalently with a score of 0, because it takes quite a few moves before players actually start making boxes.</p>
<p>Does anyone have any better ideas for games? (Or a better scoring function for dots and boxes)?</p>
|
[
{
"answer_id": 500848,
"author": "mdm",
"author_id": 25318,
"author_profile": "https://Stackoverflow.com/users/25318",
"pm_score": 1,
"selected": false,
"text": "eval_score = 0\nfor all possible rows/lines/diagonals of length 4 on the board:\n if (#player_pieces = 0) // possible to connect four here?\n if (#computer_pieces = 4)\n eval_score = 10000\n break for loop\n else\n eval_score = eval_score + #computer_pieces\n (less pieces to go -> higher score)\n end if\n else if (#player_pieces = 4)\n eval_score = -10000\n break for loop\n end if\nend for\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12981/"
] |
76,254 |
<p>Any advice on how to read auto-incrementing identity field assigned to newly created record from call through <code>java.sql.Statement.executeUpdate</code>?</p>
<p>I know how to do this in SQL for several DB platforms, but would like to know what database independent interfaces exist in <code>java.sql</code> to do this, and any input on people's experience with this across DB platforms.</p>
|
[
{
"answer_id": 76348,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 6,
"selected": true,
"text": "PreparedStatement stmt = conn.prepareStatement(sql, \n Statement.RETURN_GENERATED_KEYS);\n// ...\n\nResultSet res = stmt.getGeneratedKeys();\nwhile (res.next())\n System.out.println(\"Generated key: \" + res.getInt(1));\n SELECT NEXTVAL(...) executeUpdate(...)"
},
{
"answer_id": 76381,
"author": "marcospereira",
"author_id": 4600,
"author_profile": "https://Stackoverflow.com/users/4600",
"pm_score": 2,
"selected": false,
"text": "ResultSet keys = statement.getGeneratedKeys();\n"
},
{
"answer_id": 76451,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 0,
"selected": false,
"text": "INSERT INSERT"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5446/"
] |
76,274 |
<p>In Microsoft IL, to call a method on a value type you need an indirect reference. Lets say we have an ILGenerator named "il" and that currently we have a Nullable on top of the stack, if we want to check whether it has a value then we could emit the following:</p>
<pre><code>var local = il.DeclareLocal(typeof(Nullable<int>));
il.Emit(OpCodes.Stloc, local);
il.Emit(OpCodes.Ldloca, local);
var method = typeof(Nullable<int>).GetMethod("get_HasValue");
il.EmitCall(OpCodes.Call, method, null);
</code></pre>
<p>However it would be nice to skip saving it as a local variable, and simply call the method on the address of the variable already on the stack, something like:</p>
<pre><code>il.Emit(/* not sure */);
var method = typeof(Nullable<int>).GetMethod("get_HasValue");
il.EmitCall(OpCodes.Call, method, null);
</code></pre>
<p>The ldind family of instructions looks promising (particularly ldind_ref) but I can't find sufficient documentation to know whether this would cause boxing of the value, which I suspect it might.</p>
<p>I've had a look at the C# compiler output, but it uses local variables to achieve this, which makes me believe the first way may be the only way. Anyone have any better ideas?</p>
<p>**** Edit: Additional Notes ****</p>
<p>Attempting to call the method directly, as in the following program with the lines commented out, doesn't work (the error will be "Operation could destabilise the runtime"). Uncomment the lines and you'll see that it does work as expected, returning "True".</p>
<pre><code>var m = new DynamicMethod("M", typeof(bool), Type.EmptyTypes);
var il = m.GetILGenerator();
var ctor = typeof(Nullable<int>).GetConstructor(new[] { typeof(int) });
il.Emit(OpCodes.Ldc_I4_6);
il.Emit(OpCodes.Newobj, ctor);
//var local = il.DeclareLocal(typeof(Nullable<int>));
//il.Emit(OpCodes.Stloc, local);
//il.Emit(OpCodes.Ldloca, local);
var getValue = typeof(Nullable<int>).GetMethod("get_HasValue");
il.Emit(OpCodes.Call, getValue);
il.Emit(OpCodes.Ret);
Console.WriteLine(m.Invoke(null, null));
</code></pre>
<p>So you can't simply call the method with the value on the stack because it's a value type (though you could if it was a reference type).</p>
<p>What I'd like to achieve (or to know whether it is possible) is to replace the three lines that are shown commented out, but keep the program working, without using a temporary local.</p>
|
[
{
"answer_id": 76320,
"author": "Abe Heidebrecht",
"author_id": 9268,
"author_profile": "https://Stackoverflow.com/users/9268",
"pm_score": 3,
"selected": true,
"text": "DynamicMethod method = new DynamicMethod(\"M\", typeof(bool), Type.EmptyTypes);\nILGenerator il = method.GetILGenerator();\nType nullable = typeof(Nullable<int>);\nConstructorInfo ctor = nullable.GetConstructor(new Type[] { typeof(int) });\nMethodInfo getValue = nullable.GetProperty(\"HasValue\").GetGetMethod();\nLocalBuilder value = il.DeclareLocal(nullable); \n\n// load the variable to assign the value from the ctor to\nil.Emit(OpCodes.Ldloca_S, value);\n// load constructor args\nil.Emit(OpCodes.Ldc_I4_6);\nil.Emit(OpCodes.Call, ctor);\nil.Emit(OpCodes.Ldloca_S, value);\n\nil.Emit(OpCodes.Call, getValue);\nil.Emit(OpCodes.Ret);\nConsole.WriteLine(method.Invoke(null, null));\n"
},
{
"answer_id": 10883566,
"author": "Mark",
"author_id": 64084,
"author_profile": "https://Stackoverflow.com/users/64084",
"pm_score": 0,
"selected": false,
"text": " IL_0008: ldarg.0\n IL_0009: ldarg.1\n IL_000a: newobj instance void valuetype [mscorlib]System.Nullable`1<int32>::.ctor(!0)\n IL_000f: stfld valuetype [mscorlib]System.Nullable`1<int32> ConsoleApplication3.Temptress::_X\n IL_0014: nop\n IL_0015: ret\n"
},
{
"answer_id": 36076570,
"author": "Mayoor",
"author_id": 4167620,
"author_profile": "https://Stackoverflow.com/users/4167620",
"pm_score": 2,
"selected": false,
"text": "unbox unbox.any box unbox var m = new DynamicMethod(\"M\", typeof(bool), Type.EmptyTypes);\nvar il = m.GetILGenerator();\nvar ctor = typeof(Nullable<int>).GetConstructor(new[] { typeof(int) });\nil.Emit(OpCodes.Ldc_I4_6);\nil.Emit(OpCodes.Newobj, ctor);\nil.Emit(OpCodes.Box, typeof(Nullable<int>)); // box followed by unbox\nil.Emit(OpCodes.Unbox, typeof(Nullable<int>));\nvar getValue = typeof(Nullable<int>).GetMethod(\"get_HasValue\");\nil.Emit(OpCodes.Call, getValue);\nil.Emit(OpCodes.Ret);\nConsole.WriteLine(m.Invoke(null, null));\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13552/"
] |
76,275 |
<p>I have multiple users running attachemate on a Windows 2003 server. I want to kill attachemate.exe started by user_1 without killing attachemate.exe started by user_2.</p>
<p>I want to use VBScript.</p>
|
[
{
"answer_id": 89397,
"author": "unrealtrip",
"author_id": 11130,
"author_profile": "https://Stackoverflow.com/users/11130",
"pm_score": 4,
"selected": true,
"text": "strComputer = \".\"\nstrOwner = \"A111111\"\nstrProcess = \"'notepad.exe'\"\n\n' Connect to WMI service and Win32_Process filtering by name'\nSet objWMIService = GetObject(\"winmgmts:{impersonationLevel=impersonate}!\\\\\" _\n & strComputer & \"\\root\\cimv2\")\nSet colProcessbyName = objWMIService.ExecQuery(\"Select * from Win32_Process Where Name = \" _\n & strProcess)\n\n' Get the process ID for the process started by the user in question'\nFor Each objProcess in colProcessbyName\n colProperties = objProcess.GetOwner(strUsername,strUserDomain)\n if strUsername = strOwner then\n strProcessID = objProcess.ProcessId\n end if\nnext\n\n' We have the process ID for the app in question for the user, now we kill it'\nSet colProcessList = objWMIService.ExecQuery(\"Select * from Win32_Process where ProcessId =\" & strProcessID)\nFor Each objProcess in colProcess\n objProcess.Terminate()\nNext\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9882/"
] |
76,300 |
<p>In my SWT Java app I often want to return information from inside a Display.syncExec() call. The best way I've found so far to do this is:</p>
<pre><code>final ArrayList<Integer> result = new ArrayList<Integer>();
GUI.display().syncExec(new Runnable(){ public void run() {
MessageBox mb = /* ... */;
/* set up messagebox */
result.add(mb.open());
}});
if (SWT.OK == result.get(0)) { /* ... */ }
</code></pre>
<p>I think this is allowed because ArrayList is thread-safe, but is there a better container I should be using, or an easier way altogether?</p>
|
[
{
"answer_id": 76431,
"author": "Heath Borders",
"author_id": 9636,
"author_profile": "https://Stackoverflow.com/users/9636",
"pm_score": 4,
"selected": true,
"text": "ArrayList List Collections.synchronizedList AtomicInteger AtomicReference final AtomicInteger resultAtomicInteger = new AtomicInteger();\nDisplay.getCurrent().syncExec(new Runnable() { \n public void run() {\n MessageBox mb = /* ... */;\n /* set up messagebox */\n resultAtomicInteger.set(mb.open());\n}});\nif (SWT.OK == resultAtomicInteger.get()) { /* ... */ }\n"
},
{
"answer_id": 76443,
"author": "James A. N. Stauffer",
"author_id": 6770,
"author_profile": "https://Stackoverflow.com/users/6770",
"pm_score": 1,
"selected": false,
"text": "final Integer[] result = new Integer[1];\n"
},
{
"answer_id": 8941478,
"author": "crevos",
"author_id": 1160611,
"author_profile": "https://Stackoverflow.com/users/1160611",
"pm_score": 2,
"selected": false,
"text": "abstract class MyRunnable<T> implements Runnable{\n T result;\n}\nMyRunnable<Integer> runBlock = new MyRunnable<Integer>(){\n MessageBox mb = /* ... */;\n /* set up messagebox */\n result = mb.open();\n}\nGUI.display().syncExec(runBlock);\nrunBlock.result; //holds a result Integer\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13581/"
] |
76,314 |
<p>I'm trying to figure out what a Java applet's class file is doing under the hood. Opening it up with Notepad or Textpad just shows a bunch of gobbledy-gook.</p>
<p>Is there any way to wrangle it back into a somewhat-readable format so I can try to figure out what it's doing?</p>
<ul>
<li>Environment == Windows w/ VS 2008 installed.</li>
</ul>
|
[
{
"answer_id": 76351,
"author": "Drew Frezell",
"author_id": 10954,
"author_profile": "https://Stackoverflow.com/users/10954",
"pm_score": 3,
"selected": false,
"text": "javap"
},
{
"answer_id": 76375,
"author": "Michael Myers",
"author_id": 13531,
"author_profile": "https://Stackoverflow.com/users/13531",
"pm_score": 6,
"selected": false,
"text": "Usage: javap <options> <classes>...\n\nwhere options include:\n -c Disassemble the code\n -classpath <pathlist> Specify where to find user class files\n -extdirs <dirs> Override location of installed extensions\n -help Print this usage message\n -J<flag> Pass <flag> directly to the runtime system\n -l Print line number and local variable tables\n -public Show only public classes and members\n -protected Show protected/public classes and members\n -package Show package/protected/public classes\n and members (default)\n -private Show all classes and members\n -s Print internal type signatures\n -bootclasspath <pathlist> Override location of class files loaded\n by the bootstrap class loader\n -verbose Print stack size, number of locals and args for methods\n If verifying, print reasons for failure\n"
},
{
"answer_id": 76392,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 0,
"selected": false,
"text": ".class javap .class javap"
},
{
"answer_id": 48830353,
"author": "Nilashish C",
"author_id": 9252645,
"author_profile": "https://Stackoverflow.com/users/9252645",
"pm_score": 4,
"selected": false,
"text": "javap -c <name of java class file> \n javap -c <name of java class file> > decompiled.txt\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2312/"
] |
76,324 |
<p>I really want to get the google Calendar Api up an running. I found a <a href="http://www.ibm.com/developerworks/library/x-googleclndr/" rel="nofollow noreferrer">great article</a> about how to get started. I downloaded the Zend GData classes. I have php 5 running on my dev box and all the exetensions should be loading.</p>
<p>I cant get openssl running and recieve the following error when I try to run any of the example page which should connect to my Google Calendar.</p>
<pre><code>Uncaught exception 'Zend_Gdata_App_HttpException' with message 'Unable to Connect to ssl://www.google.com:443. Error #24063472: Unable to find the socket transport "ssl" - did you forget to enable it when you configured PHP?'
</code></pre>
<p>I have looked in many places to try to get OpenSSL running on my machine and installed. </p>
<p>Does anyone know of a simple failsafe tutorial to get this combination up and running?</p>
|
[
{
"answer_id": 202809,
"author": "Daniel Rucci",
"author_id": 27604,
"author_profile": "https://Stackoverflow.com/users/27604",
"pm_score": 2,
"selected": false,
"text": "<?php echo phpinfo();?>\n [PHP_OPENSSL]\nextension=php_openssl.dll\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6244/"
] |
76,325 |
<p>How do I move an active directory group to another organizational unit using Powershell?</p>
<p>ie.</p>
<p>I would like to move the group "IT Department" from:</p>
<pre><code> (CN=IT Department, OU=Technology Department, OU=Departments,DC=Company,DC=ca)
</code></pre>
<p>to:</p>
<pre><code> (CN=IT Department, OU=Temporarily Moved Groups, DC=Company,DC=ca)
</code></pre>
|
[
{
"answer_id": 80253,
"author": "Steven Murawski",
"author_id": 1233,
"author_profile": "https://Stackoverflow.com/users/1233",
"pm_score": 2,
"selected": false,
"text": "$objectlocation= 'CN=IT Department, OU=Technology Department, OU=Departments,DC=Company,DC=ca'\n$newlocation = 'OU=Temporarily Moved Groups, DC=Company,DC=ca'\n\n$from = new-object System.DirectoryServices.DirectoryEntry(\"LDAP://$objectLocation\")\n$to = new-object System.DirectoryServices.DirectoryEntry(\"LDAP://$newlocation\")\n$from.MoveTo($newlocation,$from.name)\n"
},
{
"answer_id": 85685,
"author": "Eldila",
"author_id": 889,
"author_profile": "https://Stackoverflow.com/users/889",
"pm_score": 4,
"selected": true,
"text": "$from = [ADSI]\"LDAP://CN=IT Department, OU=Technology Department, OU=Departments,DC=Company,DC=ca\"\n$to = [ADSI]\"LDAP://OU=Temporarily Moved Groups, DC=Company,DC=ca\"\n$from.PSBase.MoveTo($to,\"cn=\"+$from.name)\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889/"
] |
76,327 |
<p>I'm writing a Java application that runs on Linux (using Sun's JDK). It keeps creating <code>/tmp/hsperfdata_username</code> directories, which I would like to prevent. Is there any way to stop java from creating these files?</p>
|
[
{
"answer_id": 76423,
"author": "Kyle Renfro",
"author_id": 8187,
"author_profile": "https://Stackoverflow.com/users/8187",
"pm_score": 6,
"selected": true,
"text": "-XX:+UsePerfData\n\n Enables the perfdata feature. This option is enabled by default\n to allow JVM monitoring and performance testing. Disabling it \n suppresses the creation of the hsperfdata_userid directories. \n To disable the perfdata feature, specify -XX:-UsePerfData.\n"
},
{
"answer_id": 3060276,
"author": "Zweiberg",
"author_id": 369132,
"author_profile": "https://Stackoverflow.com/users/369132",
"pm_score": 2,
"selected": false,
"text": "\"-XX:+PerfDisableSharedMem\" \"-XX:-UsePerfData\""
},
{
"answer_id": 3933583,
"author": "Jon Stafford",
"author_id": 277208,
"author_profile": "https://Stackoverflow.com/users/277208",
"pm_score": 5,
"selected": false,
"text": "-XX:-UsePerfData -XX:-UsePerfData -XX:+UsePerfData"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76327",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13582/"
] |
76,328 |
<p>PHP5 has a "magic method" <code>__call()</code>that can be defined on any class that is invoked when an undefined method is called -- it is roughly equivalent to Ruby's <code>method_missing</code> or Perl's <code>AUTOLOAD</code>. Is it possible to do something like this in older versions of PHP?</p>
|
[
{
"answer_id": 76399,
"author": "Adam Wright",
"author_id": 1200,
"author_profile": "https://Stackoverflow.com/users/1200",
"pm_score": 0,
"selected": false,
"text": "function __call($method_name, $parameters, &$return)\n{\n $return_value = \"You called ${method_name}!\";\n}\n"
},
{
"answer_id": 112606,
"author": "jes5199",
"author_id": 13195,
"author_profile": "https://Stackoverflow.com/users/13195",
"pm_score": 2,
"selected": false,
"text": "__call overload()"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13195/"
] |
76,334 |
<p>Does anyone know a mechanism to calculate at compile-time the LCM (Least Common Multiple) and/or GCD (Greatest Common Denominator) of at least two number in <strong>C</strong> (<strong>not C++</strong>, I know that template magic is available there)?</p>
<p>I generally use <strong>GCC</strong> and recall that it can calculate certain values at compile-time when all inputs are known (ex: sin, cos, etc...).</p>
<p>I'm looking for how to do this in <strong>GCC</strong> (preferably in a manner that other compilers could handle) and hope the same mechanism would work in Visual Studio.</p>
|
[
{
"answer_id": 76746,
"author": "Kevin",
"author_id": 6386,
"author_profile": "https://Stackoverflow.com/users/6386",
"pm_score": 3,
"selected": false,
"text": "#define GCD(a,b) ((a>=b)*GCD_1(a,b)+(a<b)*GCD_1(b,a))\n#define GCD_1(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_2((b), (a)%((b)+!(b))))\n#define GCD_2(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_3((b), (a)%((b)+!(b))))\n#define GCD_3(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_4((b), (a)%((b)+!(b))))\n#define GCD_4(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_5((b), (a)%((b)+!(b))))\n#define GCD_5(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_6((b), (a)%((b)+!(b))))\n#define GCD_6(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_7((b), (a)%((b)+!(b))))\n#define GCD_7(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_8((b), (a)%((b)+!(b))))\n#define GCD_8(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_last((b), (a)%((b)+!(b))))\n#define GCD_last(a,b) (a)\n\n#define LCM(a,b) (((a)*(b))/GCD(a,b))\n\n\nint main()\n{\n printf(\"%d, %d\\n\", GCD(21,6), LCM(21,6));\n return 0;\n}\n"
},
{
"answer_id": 77708,
"author": "Kevin Loney",
"author_id": 13834,
"author_profile": "https://Stackoverflow.com/users/13834",
"pm_score": 1,
"selected": false,
"text": "template<int A, int B>\nstruct GCD {\n enum { value = GCD<B, A % B>::value };\n};\n\n/*\nBecause GCD terminates when only one of the values is zero it is impossible to define a base condition to satisfy all GCD<N, 0>::value conditions\n*/\ntemplate<>\nstruct GCD<A, 0> { // This is obviously not legal\n enum { value = A };\n};\n\nint main(void)\n{\n ::printf(\"gcd(%d, %d) = %d\", 7, 35, GCD<7, 35>::value);\n}\n"
},
{
"answer_id": 78794,
"author": "harningt",
"author_id": 12713,
"author_profile": "https://Stackoverflow.com/users/12713",
"pm_score": 2,
"selected": false,
"text": "#define GCD(a,b) ( ((a) > (b)) ? ( GCD_1((a), (b)) ) : ( GCD_1((b), (a)) ) )\n\n#define GCD_1(a,b) ( ((b) == 0) ? (a) : GCD_2((b), (a) % (b) ) )\n#define GCD_2(a,b) ( ((b) == 0) ? (a) : GCD_3((b), (a) % (b) ) )\n#define GCD_3(a,b) ( ((b) == 0) ? (a) : GCD_4((b), (a) % (b) ) )\n#define GCD_4(a,b) ( ((b) == 0) ? (a) : GCD_5((b), (a) % (b) ) )\n#define GCD_5(a,b) ( ((b) == 0) ? (a) : GCD_6((b), (a) % (b) ) )\n#define GCD_6(a,b) ( ((b) == 0) ? (a) : GCD_7((b), (a) % (b) ) )\n#define GCD_7(a,b) ( ((b) == 0) ? (a) : GCD_8((b), (a) % (b) ) )\n#define GCD_8(a,b) ( ((b) == 0) ? (a) : GCD_9((b), (a) % (b) ) )\n#define GCD_9(a,b) (assert(0),-1)\n"
},
{
"answer_id": 70047263,
"author": "thisismyhomeworkaccount",
"author_id": 17464920,
"author_profile": "https://Stackoverflow.com/users/17464920",
"pm_score": -1,
"selected": false,
"text": " int gcd(int n1,int n2){\n while(n1!=n2){\n if(n1 > n2) n1 -= n2;\n else n2 -= n1;\n }\n return n1;\n}\nint lcm(int n1, int n2){\n int total =n1*n2;\n return total/gcd(n1,n2);\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12713/"
] |
76,346 |
<p>I just got surprised by something in TSQL. I thought that if xact_abort was on, calling something like</p>
<pre><code>raiserror('Something bad happened', 16, 1);
</code></pre>
<p>would stop execution of the stored procedure (or any batch).</p>
<p>But my ADO.NET error message just proved the opposite. I got both the raiserror error message in the exception message, plus the next thing that broke after that.</p>
<p>This is my workaround (which is my habit anyway), but it doesn't seem like it should be necessary:</p>
<pre><code>if @somethingBadHappened
begin;
raiserror('Something bad happened', 16, 1);
return;
end;
</code></pre>
<p>The docs say this:</p>
<blockquote>
<p>When SET XACT_ABORT is ON, if a Transact-SQL statement raises a run-time error, the entire transaction is terminated and rolled back.</p>
</blockquote>
<p>Does that mean I must be using an explicit transaction?</p>
|
[
{
"answer_id": 76416,
"author": "Philip Rieck",
"author_id": 12643,
"author_profile": "https://Stackoverflow.com/users/12643",
"pm_score": 6,
"selected": false,
"text": "RAISERROR 16"
},
{
"answer_id": 77140,
"author": "ninegrid",
"author_id": 13661,
"author_profile": "https://Stackoverflow.com/users/13661",
"pm_score": 5,
"selected": false,
"text": "-- first lets build a temporary table to hold errors\nif (object_id('tempdb..#RAISERRORS') is null)\n create table #RAISERRORS (ErrorNumber int, ErrorMessage varchar(400), ErrorSeverity int, ErrorState int, ErrorLine int, ErrorProcedure varchar(128));\n\n-- this will determine if the transaction level of the query to programatically determine if we need to begin a new transaction or create a save point to rollback to\ndeclare @tc as int;\nset @tc = @@trancount;\nif (@tc = 0)\n begin transaction;\nelse\n save transaction myTransaction;\n\n-- the code in the try block will be executed\nbegin try\n declare @return_value = '0';\n set @return_value = '0';\n declare\n @ErrorNumber as int,\n @ErrorMessage as varchar(400),\n @ErrorSeverity as int,\n @ErrorState as int,\n @ErrorLine as int,\n @ErrorProcedure as varchar(128);\n\n\n -- assume that this procedure fails...\n exec @return_value = [dbo].[AssumeThisFails]\n if (@return_value <> 0)\n raiserror('This is my error message', 17, 1);\n\n -- the error severity of 17 will be considered a system error execution of this query will skip the following statements and resume at the begin catch block\n if (@tc = 0)\n commit transaction;\n return(0);\nend try\n\n\n-- the code in the catch block will be executed on raiserror(\"message\", 17, 1)\nbegin catch\n select\n @ErrorNumber = ERROR_NUMBER(),\n @ErrorMessage = ERROR_MESSAGE(),\n @ErrorSeverity = ERROR_SEVERITY(),\n @ErrorState = ERROR_STATE(),\n @ErrorLine = ERROR_LINE(),\n @ErrorProcedure = ERROR_PROCEDURE();\n\n insert #RAISERRORS (ErrorNumber, ErrorMessage, ErrorSeverity, ErrorState, ErrorLine, ErrorProcedure)\n values (@ErrorNumber, @ErrorMessage, @ErrorSeverity, @ErrorState, @ErrorLine, @ErrorProcedure);\n\n -- if i started the transaction\n if (@tc = 0)\n begin\n if (XACT_STATE() <> 0)\n begin\n select * from #RAISERRORS;\n rollback transaction;\n insert into [dbo].[Errors] (ErrorNumber, ErrorMessage, ErrorSeverity, ErrorState, ErrorLine, ErrorProcedure)\n select * from #RAISERRORS;\n insert [dbo].[Errors] (ErrorNumber, ErrorMessage, ErrorSeverity, ErrorState, ErrorLine, ErrorProcedure)\n values (@ErrorNumber, @ErrorMessage, @ErrorSeverity, @ErrorState, @ErrorLine, @ErrorProcedure);\n return(1);\n end\n end\n -- if i didn't start the transaction\n if (XACT_STATE() = 1)\n begin\n rollback transaction myTransaction;\n if (object_id('tempdb..#RAISERRORS') is not null)\n insert #RAISERRORS (ErrorNumber, ErrorMessage, ErrorSeverity, ErrorState, ErrorLine, ErrorProcedure)\n values (@ErrorNumber, @ErrorMessage, @ErrorSeverity, @ErrorState, @ErrorLine, @ErrorProcedure);\n else\n raiserror(@ErrorMessage, @ErrorSeverity, @ErrorState);\n return(2); \n end\n else if (XACT_STATE() = -1)\n begin\n rollback transaction;\n if (object_id('tempdb..#RAISERRORS') is not null)\n insert #RAISERRORS (ErrorNumber, ErrorMessage, ErrorSeverity, ErrorState, ErrorLine, ErrorProcedure)\n values (@ErrorNumber, @ErrorMessage, @ErrorSeverity, @ErrorState, @ErrorLine, @ErrorProcedure);\n else\n raiserror(@ErrorMessage, @ErrorSeverity, @ErrorState);\n return(3);\n end\n end catch\nend\n"
},
{
"answer_id": 5991091,
"author": "piyush",
"author_id": 752253,
"author_profile": "https://Stackoverflow.com/users/752253",
"pm_score": 5,
"selected": false,
"text": "RETURN RAISERROR()"
},
{
"answer_id": 18222673,
"author": "Möoz",
"author_id": 1377865,
"author_profile": "https://Stackoverflow.com/users/1377865",
"pm_score": 4,
"selected": false,
"text": "SET XACT_ABORT THROW RAISERROR XACT_ABORT THROW"
},
{
"answer_id": 68637587,
"author": "Golden Lion",
"author_id": 4001177,
"author_profile": "https://Stackoverflow.com/users/4001177",
"pm_score": 0,
"selected": false,
"text": "set XACT_ABORT ON;\n\nBEGIN TRY\n BEGIN TRAN;\n \n insert into customers values('Mark','Davis','[email protected]', '55909090');\n insert into customer values('Zack','Roberts','[email protected]','555919191');\n COMMIT TRAN;\n END TRY\n\nBEGIN CATCH\n IF XACT_STATE()=-1\n ROLLBACK TRAN;\n IF XACT_STATE()=1\n COMMIT TRAN;\n SELECT ERROR_MESSAGE() AS error_message\nEND CATCH\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1219/"
] |
76,349 |
<p>I have VS2005 and I am currently trying to debug an ASP.net web application. I want to change some code around in the code behind file, but every time I stop at a break point and try to edit something I get the following error message: "Changes are not allowed when the debugger has been attached to an already running process or the code being debugged is optimized."</p>
<p>I'm pretty sure I have all the "Edit and Continue" options enabled. Any suggestions?</p>
|
[
{
"answer_id": 76414,
"author": "Jarrett Meyer",
"author_id": 5834,
"author_profile": "https://Stackoverflow.com/users/5834",
"pm_score": 1,
"selected": false,
"text": "*.aspx *.cs/*.vb *.designer.cs/*.designer.vb"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13556/"
] |
76,359 |
<p>Does ADOdb do data sanitation or escaping within the same functionality by default? Or am I just confusing it with Code Igniter's built-in processes?</p>
<p>Does binding variables to parameters in ADOdb for PHP prevent SQL injection in any way? </p>
|
[
{
"answer_id": 76528,
"author": "Brendon-Van-Heyzen",
"author_id": 1425,
"author_profile": "https://Stackoverflow.com/users/1425",
"pm_score": 2,
"selected": false,
"text": "$rs = $db->Execute('select * from table where val=?', array('10'));\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13320/"
] |
76,411 |
<p>How can I create a regular expression that will grab delimited text from a string? For example, given a string like </p>
<pre><code>text ###token1### text text ###token2### text text
</code></pre>
<p>I want a regex that will pull out <code>###token1###</code>. Yes, I do want the delimiter as well. By adding another group, I can get both:</p>
<pre><code>(###(.+?)###)
</code></pre>
|
[
{
"answer_id": 76427,
"author": "David Beleznay",
"author_id": 13359,
"author_profile": "https://Stackoverflow.com/users/13359",
"pm_score": 3,
"selected": true,
"text": "/###(.+?)###/\n /(###.+?###)/\n '###token1### text text ###token2###'"
},
{
"answer_id": 76445,
"author": "Jonathan Rupp",
"author_id": 12502,
"author_profile": "https://Stackoverflow.com/users/12502",
"pm_score": 0,
"selected": false,
"text": "/###.+###/\n"
},
{
"answer_id": 76490,
"author": "Colen",
"author_id": 13500,
"author_profile": "https://Stackoverflow.com/users/13500",
"pm_score": 0,
"selected": false,
"text": "text (#+.+#+) text text (#+.+#+) text text\n token1: \\1, token2: \\2\n token1: ###token1###, token2: ###token2###\n"
},
{
"answer_id": 76519,
"author": "Michael Cramer",
"author_id": 1496728,
"author_profile": "https://Stackoverflow.com/users/1496728",
"pm_score": 1,
"selected": false,
"text": "$text = 'text ###token1### text text ###token2### text text';\n\nwhile($text =~ m/###(.+?)###/g) {\n print $1, \"\\n\";\n}\n @tokens = $text =~ m/###(.+?)###/g;\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/410/"
] |
76,412 |
<p>When developing WPF UserControls, what is the best way to expose a DependencyProperty of a child control as a DependencyProperty of the UserControl? The following example shows how I would currently expose the Text property of a TextBox inside a UserControl. Surely there is a better / simpler way to accomplish this?</p>
<pre class="lang-xml prettyprint-override"><code> <UserControl x:Class="WpfApplication3.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel Background="LightCyan">
<TextBox Margin="8" Text="{Binding Text, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" />
</StackPanel>
</UserControl>
</code></pre>
<pre class="lang-cs prettyprint-override"><code> using System;
using System.Windows;
using System.Windows.Controls;
namespace WpfApplication3
{
public partial class UserControl1 : UserControl
{
public static DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(UserControl1), new PropertyMetadata(null));
public string Text
{
get { return GetValue(TextProperty) as string; }
set { SetValue(TextProperty, value); }
}
public UserControl1() { InitializeComponent(); }
}
}
</code></pre>
|
[
{
"answer_id": 77094,
"author": "user7116",
"author_id": 7116,
"author_profile": "https://Stackoverflow.com/users/7116",
"pm_score": 5,
"selected": true,
"text": "<UserControl x:Class=\"WpfApplication3.UserControl1\" x:Name=\"UserControl1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\">\n <StackPanel Background=\"LightCyan\">\n <TextBox Margin=\"8\" Text=\"{Binding Path=Text, ElementName=UserControl1}\" />\n </StackPanel>\n</UserControl>\n"
},
{
"answer_id": 1995911,
"author": "Lessneek",
"author_id": 240947,
"author_profile": "https://Stackoverflow.com/users/240947",
"pm_score": 1,
"selected": false,
"text": "DataContext = this;\n <TextBox Margin=\"8\" Text=\"{Binding Text} />\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/317/"
] |
76,424 |
<p>XmlElement.Attributes.Remove* methods are working fine for arbitrary attributes resulting in the removed attributes being removed from XmlDocument.OuterXml property. Xmlns attribute however is different. Here is an example:</p>
<pre><code>XmlDocument doc = new XmlDocument();
doc.InnerXml = @"<Element1 attr1=""value1"" xmlns=""http://mynamespace.com/"" attr2=""value2""/>";
doc.DocumentElement.Attributes.RemoveNamedItem("attr2");
Console.WriteLine("xmlns attr before removal={0}", doc.DocumentElement.Attributes["xmlns"]);
doc.DocumentElement.Attributes.RemoveNamedItem("xmlns");
Console.WriteLine("xmlns attr after removal={0}", doc.DocumentElement.Attributes["xmlns"]);
</code></pre>
<p>The resulting output is</p>
<pre><code>xmlns attr before removal=System.Xml.XmlAttribute
xmlns attr after removal=
<Element1 attr1="value1" xmlns="http://mynamespace.com/" />
</code></pre>
<p>The attribute seems to be removed from the Attributes collection, but it is not removed from XmlDocument.OuterXml.
I guess it is because of the special meaning of this attribute.</p>
<p>The question is how to remove the xmlns attribute using .NET XML API.
Obviously I can just remove the attribute from a String representation of this, but I wonder if it is possible to do the same thing using the API.</p>
<p>@Edit: I'm talking about .NET 2.0.</p>
|
[
{
"answer_id": 77502,
"author": "Vin",
"author_id": 1747,
"author_profile": "https://Stackoverflow.com/users/1747",
"pm_score": 2,
"selected": false,
"text": "XmlNamespaceManager mgr = new XmlNamespaceManager(\"xmlnametable\");\nmgr.RemoveNamespace(\"prefix\", \"uri\");\n"
},
{
"answer_id": 1875023,
"author": "ALI SHAH",
"author_id": 228093,
"author_profile": "https://Stackoverflow.com/users/228093",
"pm_score": 2,
"selected": false,
"text": "'Remove the Equifax / Transunian / Experian root node attribute that have xmlns and load xml without xmlns attributes.\nIf objXMLDom.DocumentElement.NamespaceURI <> String.Empty Then\n objXMLDom.LoadXml(objXMLDom.OuterXml.Replace(objXMLDom.DocumentElement.NamespaceURI, \"\"))\n objXMLDom.DocumentElement.RemoveAllAttributes()\n ResponseXML = objXMLDom.OuterXml\nEnd If\n"
},
{
"answer_id": 2251621,
"author": "Matt Harris",
"author_id": 271817,
"author_profile": "https://Stackoverflow.com/users/271817",
"pm_score": 2,
"selected": false,
"text": "var dom = new XmlDocument();\n dom.Load(\"C:/ExampleFITrade.xml));\n var loaded = new XDocument();\n if (dom.DocumentElement != null)\n if( dom.DocumentElement.NamespaceURI != String.Empty)\n {\n dom.LoadXml(dom.OuterXml.Replace(dom.DocumentElement.NamespaceURI, \"\"));\n dom.DocumentElement.RemoveAllAttributes();\n loaded = XDocument.Parse(dom.OuterXml);\n }\n"
},
{
"answer_id": 14287546,
"author": "pcmaniak",
"author_id": 1971348,
"author_profile": "https://Stackoverflow.com/users/1971348",
"pm_score": 1,
"selected": false,
"text": "public static string RemoveXmlns(string xml)\n{\n //Prepare a reader\n StringReader stringReader = new StringReader(xml);\n XmlTextReader xmlReader = new XmlTextReader(stringReader);\n xmlReader.Namespaces = false; //A trick to handle special xmlns attributes as regular\n //Build DOM\n XmlDocument xmlDocument = new XmlDocument();\n xmlDocument.Load(xmlReader);\n //Do the job\n xmlDocument.DocumentElement.RemoveAttribute(\"xmlns\"); \n //Prepare a writer\n StringWriter stringWriter = new StringWriter();\n XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);\n //Optional: Make an output nice ;)\n xmlWriter.Formatting = Formatting.Indented;\n xmlWriter.IndentChar = ' ';\n xmlWriter.Indentation = 2;\n //Build output\n xmlDocument.Save(xmlWriter);\n return stringWriter.ToString();\n}\n"
},
{
"answer_id": 29321085,
"author": "Rodrigo Serzedello",
"author_id": 2053300,
"author_profile": "https://Stackoverflow.com/users/2053300",
"pm_score": 0,
"selected": false,
"text": " Dim pathXmlTransformado As String = \"C:\\Fisconet4\\process\\11790941000192\\2015\\3\\28\\38387-1\\38387_transformado.xml\"\n Dim nfeXML As New XmlDocument\n Dim loaded As New XDocument\n\n nfeXML.Load(pathXmlTransformado)\n\n nfeXML.LoadXml(nfeXML.OuterXml.Replace(nfeXML.DocumentElement.NamespaceURI, \"\"))\n nfeXML.DocumentElement.RemoveAllAttributes()\n\n Dim dhCont As XmlNode = nfeXML.CreateElement(\"dhCont\")\n Dim xJust As XmlNode = nfeXML.CreateElement(\"xJust\")\n dhCont.InnerXml = 123\n xJust.InnerXml = 123777\n\n nfeXML.GetElementsByTagName(\"ide\")(0).AppendChild(dhCont)\n nfeXML.GetElementsByTagName(\"ide\")(0).AppendChild(xJust)\n\n nfeXML.Save(\"C:\\Fisconet4\\process\\11790941000192\\2015\\3\\28\\38387-1\\teste.xml\")\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/578/"
] |
76,455 |
<p>In C#.NET I am trying to programmatically change the color of the border in a group box.</p>
<p>Update: This question was asked when I was working on a winforms system before we switched to .NET.</p>
|
[
{
"answer_id": 5629954,
"author": "swajak",
"author_id": 100258,
"author_profile": "https://Stackoverflow.com/users/100258",
"pm_score": 1,
"selected": false,
"text": "GroupBox box = new GroupBox();\n[...]\nbox.Paint += delegate(object o, PaintEventArgs p)\n{\n p.Graphics.Clear(someColorHere);\n};\n"
},
{
"answer_id": 5827166,
"author": "Mick Bruno",
"author_id": 730366,
"author_profile": "https://Stackoverflow.com/users/730366",
"pm_score": 6,
"selected": true,
"text": "groupBox1.Paint += PaintBorderlessGroupBox;\n\nprivate void PaintBorderlessGroupBox(object sender, PaintEventArgs p)\n{\n GroupBox box = (GroupBox)sender;\n p.Graphics.Clear(SystemColors.Control);\n p.Graphics.DrawString(box.Text, box.Font, Brushes.Black, 0, 0);\n}\n"
},
{
"answer_id": 13653500,
"author": "Andy",
"author_id": 1867592,
"author_profile": "https://Stackoverflow.com/users/1867592",
"pm_score": 3,
"selected": false,
"text": " private void UserControl1_Paint(object sender, PaintEventArgs e)\n {\n ControlPaint.DrawBorder(e.Graphics, this.ClientRectangle, Color.Red, ButtonBorderStyle.Solid);\n\n }\n"
},
{
"answer_id": 20042058,
"author": "user1944617",
"author_id": 1944617,
"author_profile": "https://Stackoverflow.com/users/1944617",
"pm_score": 5,
"selected": false,
"text": " private void groupBox1_Paint(object sender, PaintEventArgs e)\n {\n GroupBox box = sender as GroupBox;\n DrawGroupBox(box, e.Graphics, Color.Red, Color.Blue);\n }\n\n\n private void DrawGroupBox(GroupBox box, Graphics g, Color textColor, Color borderColor)\n {\n if (box != null)\n {\n Brush textBrush = new SolidBrush(textColor);\n Brush borderBrush = new SolidBrush(borderColor);\n Pen borderPen = new Pen(borderBrush);\n SizeF strSize = g.MeasureString(box.Text, box.Font);\n Rectangle rect = new Rectangle(box.ClientRectangle.X,\n box.ClientRectangle.Y + (int)(strSize.Height / 2),\n box.ClientRectangle.Width - 1,\n box.ClientRectangle.Height - (int)(strSize.Height / 2) - 1);\n\n // Clear text and border\n g.Clear(this.BackColor);\n\n // Draw text\n g.DrawString(box.Text, box.Font, textBrush, box.Padding.Left, 0);\n\n // Drawing Border\n //Left\n g.DrawLine(borderPen, rect.Location, new Point(rect.X, rect.Y + rect.Height));\n //Right\n g.DrawLine(borderPen, new Point(rect.X + rect.Width, rect.Y), new Point(rect.X + rect.Width, rect.Y + rect.Height));\n //Bottom\n g.DrawLine(borderPen, new Point(rect.X, rect.Y + rect.Height), new Point(rect.X + rect.Width, rect.Y + rect.Height));\n //Top1\n g.DrawLine(borderPen, new Point(rect.X, rect.Y), new Point(rect.X + box.Padding.Left, rect.Y));\n //Top2\n g.DrawLine(borderPen, new Point(rect.X + box.Padding.Left + (int)(strSize.Width), rect.Y), new Point(rect.X + rect.Width, rect.Y));\n }\n }\n"
},
{
"answer_id": 50451872,
"author": "George",
"author_id": 5077953,
"author_profile": "https://Stackoverflow.com/users/5077953",
"pm_score": 1,
"selected": false,
"text": " private void groupSchitaCentru_Paint(object sender, PaintEventArgs e)\n {\n Pen blackPen = new Pen(Color.Black, 2);\n Point pointTopLeft = new Point(0, 7);\n Point pointBottomLeft = new Point(0, groupSchitaCentru.ClientRectangle.Height);\n Point pointTopRight = new Point(groupSchitaCentru.ClientRectangle.Width, 7);\n Point pointBottomRight = new Point(groupSchitaCentru.ClientRectangle.Width, groupSchitaCentru.ClientRectangle.Height);\n\n e.Graphics.DrawLine(blackPen, pointTopLeft, pointBottomLeft);\n e.Graphics.DrawLine(blackPen, pointTopLeft, pointTopRight);\n e.Graphics.DrawLine(blackPen, pointBottomRight, pointTopRight);\n e.Graphics.DrawLine(blackPen, pointBottomLeft, pointBottomRight);\n }\n"
},
{
"answer_id": 51663475,
"author": "NetXpert",
"author_id": 1542024,
"author_profile": "https://Stackoverflow.com/users/1542024",
"pm_score": 3,
"selected": false,
"text": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nnamespace BorderedGroupBox\n{\n public class BorderedGroupBox : GroupBox\n {\n private Color _borderColor = Color.Black;\n private int _borderWidth = 2;\n private int _borderRadius = 5;\n private int _textIndent = 10;\n\n public BorderedGroupBox() : base()\n {\n InitializeComponent();\n this.Paint += this.BorderedGroupBox_Paint;\n }\n\n public BorderedGroupBox(int width, float radius, Color color) : base()\n {\n this._borderWidth = Math.Max(1,width);\n this._borderColor = color;\n this._borderRadius = Math.Max(0,radius);\n InitializeComponent();\n this.Paint += this.BorderedGroupBox_Paint;\n }\n\n public Color BorderColor\n {\n get => this._borderColor;\n set\n {\n this._borderColor = value;\n DrawGroupBox();\n }\n }\n\n public int BorderWidth\n {\n get => this._borderWidth;\n set\n {\n if (value > 0)\n {\n this._borderWidth = Math.Min(value, 10);\n DrawGroupBox();\n }\n }\n }\n\n public int BorderRadius\n {\n get => this._borderRadius;\n set\n { // Setting a radius of 0 produces square corners...\n if (value >= 0)\n {\n this._borderRadius = value;\n this.DrawGroupBox();\n }\n }\n }\n\n public int LabelIndent\n {\n get => this._textIndent;\n set\n {\n this._textIndent = value;\n this.DrawGroupBox();\n }\n }\n\n private void BorderedGroupBox_Paint(object sender, PaintEventArgs e) =>\n DrawGroupBox(e.Graphics);\n\n private void DrawGroupBox() =>\n this.DrawGroupBox(this.CreateGraphics());\n\n private void DrawGroupBox(Graphics g)\n {\n Brush textBrush = new SolidBrush(this.ForeColor);\n SizeF strSize = g.MeasureString(this.Text, this.Font);\n\n Brush borderBrush = new SolidBrush(this.BorderColor);\n Pen borderPen = new Pen(borderBrush,(float)this._borderWidth);\n Rectangle rect = new Rectangle(this.ClientRectangle.X,\n this.ClientRectangle.Y + (int)(strSize.Height / 2),\n this.ClientRectangle.Width - 1,\n this.ClientRectangle.Height - (int)(strSize.Height / 2) - 1);\n\n Brush labelBrush = new SolidBrush(this.BackColor);\n\n // Clear text and border\n g.Clear(this.BackColor);\n\n // Drawing Border (added \"Fix\" from Jim Fell, Oct 6, '18)\n int rectX = (0 == this._borderWidth % 2) ? rect.X + this._borderWidth / 2 : rect.X + 1 + this._borderWidth / 2;\n int rectHeight = (0 == this._borderWidth % 2) ? rect.Height - this._borderWidth / 2 : rect.Height - 1 - this._borderWidth / 2;\n // NOTE DIFFERENCE: rectX vs rect.X and rectHeight vs rect.Height\n g.DrawRoundedRectangle(borderPen, rectX, rect.Y, rect.Width, rectHeight, (float)this._borderRadius);\n\n // Draw text\n if (this.Text.Length > 0)\n {\n // Do some work to ensure we don't put the label outside\n // of the box, regardless of what value is assigned to the Indent:\n int width = (int)rect.Width, posX;\n posX = (this._textIndent < 0) ? Math.Max(0-width,this._textIndent) : Math.Min(width, this._textIndent);\n posX = (posX < 0) ? rect.Width + posX - (int)strSize.Width : posX;\n g.FillRectangle(labelBrush, posX, 0, strSize.Width, strSize.Height);\n g.DrawString(this.Text, this.Font, textBrush, posX, 0);\n }\n }\n\n #region Component Designer generated code\n /// <summary>Required designer variable.</summary>\n private System.ComponentModel.IContainer components = null;\n\n /// <summary>Clean up any resources being used.</summary>\n /// <param name=\"disposing\">true if managed resources should be disposed; otherwise, false.</param>\n protected override void Dispose(bool disposing)\n {\n if (disposing && (components != null))\n components.Dispose();\n\n base.Dispose(disposing);\n }\n\n /// <summary>Required method for Designer support - Don't modify!</summary>\n private void InitializeComponent() => components = new System.ComponentModel.Container();\n #endregion\n }\n}\n static class GraphicsExtension\n{\n private static GraphicsPath GenerateRoundedRectangle(\n this Graphics graphics,\n RectangleF rectangle,\n float radius)\n {\n float diameter;\n GraphicsPath path = new GraphicsPath();\n if (radius <= 0.0F)\n {\n path.AddRectangle(rectangle);\n path.CloseFigure();\n return path;\n }\n else\n {\n if (radius >= (Math.Min(rectangle.Width, rectangle.Height)) / 2.0)\n return graphics.GenerateCapsule(rectangle);\n diameter = radius * 2.0F;\n SizeF sizeF = new SizeF(diameter, diameter);\n RectangleF arc = new RectangleF(rectangle.Location, sizeF);\n path.AddArc(arc, 180, 90);\n arc.X = rectangle.Right - diameter;\n path.AddArc(arc, 270, 90);\n arc.Y = rectangle.Bottom - diameter;\n path.AddArc(arc, 0, 90);\n arc.X = rectangle.Left;\n path.AddArc(arc, 90, 90);\n path.CloseFigure();\n }\n return path;\n }\n\n private static GraphicsPath GenerateCapsule(\n this Graphics graphics,\n RectangleF baseRect)\n {\n float diameter;\n RectangleF arc;\n GraphicsPath path = new GraphicsPath();\n try\n {\n if (baseRect.Width > baseRect.Height)\n {\n diameter = baseRect.Height;\n SizeF sizeF = new SizeF(diameter, diameter);\n arc = new RectangleF(baseRect.Location, sizeF);\n path.AddArc(arc, 90, 180);\n arc.X = baseRect.Right - diameter;\n path.AddArc(arc, 270, 180);\n }\n else if (baseRect.Width < baseRect.Height)\n {\n diameter = baseRect.Width;\n SizeF sizeF = new SizeF(diameter, diameter);\n arc = new RectangleF(baseRect.Location, sizeF);\n path.AddArc(arc, 180, 180);\n arc.Y = baseRect.Bottom - diameter;\n path.AddArc(arc, 0, 180);\n }\n else path.AddEllipse(baseRect);\n }\n catch { path.AddEllipse(baseRect); }\n finally { path.CloseFigure(); }\n return path;\n }\n\n /// <summary>\n /// Draws a rounded rectangle specified by a pair of coordinates, a width, a height and the radius\n /// for the arcs that make the rounded edges.\n /// </summary>\n /// <param name=\"brush\">System.Drawing.Pen that determines the color, width and style of the rectangle.</param>\n /// <param name=\"x\">The x-coordinate of the upper-left corner of the rectangle to draw.</param>\n /// <param name=\"y\">The y-coordinate of the upper-left corner of the rectangle to draw.</param>\n /// <param name=\"width\">Width of the rectangle to draw.</param>\n /// <param name=\"height\">Height of the rectangle to draw.</param>\n /// <param name=\"radius\">The radius of the arc used for the rounded edges.</param>\n public static void DrawRoundedRectangle(\n this Graphics graphics,\n Pen pen,\n float x,\n float y,\n float width,\n float height,\n float radius)\n {\n RectangleF rectangle = new RectangleF(x, y, width, height);\n GraphicsPath path = graphics.GenerateRoundedRectangle(rectangle, radius);\n SmoothingMode old = graphics.SmoothingMode;\n graphics.SmoothingMode = SmoothingMode.AntiAlias;\n graphics.DrawPath(pen, path);\n graphics.SmoothingMode = old;\n }\n\n /// <summary>\n /// Draws a rounded rectangle specified by a pair of coordinates, a width, a height and the radius\n /// for the arcs that make the rounded edges.\n /// </summary>\n /// <param name=\"brush\">System.Drawing.Pen that determines the color, width and style of the rectangle.</param>\n /// <param name=\"x\">The x-coordinate of the upper-left corner of the rectangle to draw.</param>\n /// <param name=\"y\">The y-coordinate of the upper-left corner of the rectangle to draw.</param>\n /// <param name=\"width\">Width of the rectangle to draw.</param>\n /// <param name=\"height\">Height of the rectangle to draw.</param>\n /// <param name=\"radius\">The radius of the arc used for the rounded edges.</param>\n\n public static void DrawRoundedRectangle(\n this Graphics graphics,\n Pen pen,\n int x,\n int y,\n int width,\n int height,\n int radius)\n {\n graphics.DrawRoundedRectangle(\n pen,\n Convert.ToSingle(x),\n Convert.ToSingle(y),\n Convert.ToSingle(width),\n Convert.ToSingle(height),\n Convert.ToSingle(radius));\n }\n}\n"
},
{
"answer_id": 68691524,
"author": "compound eye",
"author_id": 133507,
"author_profile": "https://Stackoverflow.com/users/133507",
"pm_score": 0,
"selected": false,
"text": " Rectangle rect = new Rectangle(this.ClientRectangle.X,\n this.ClientRectangle.Y + (int)(strSize.Height / 2),\n this.ClientRectangle.Width,\n this.ClientRectangle.Height - (int)(strSize.Height / 2));\n\n Brush labelBrush = new SolidBrush(this.BackColor);\n\n // Clear text and border\n g.Clear(this.BackColor);\n\n\n int drawX = rect.X;\n int drawY = rect.Y;\n int drawWidth = rect.Width;\n int drawHeight = rect.Height;\n\n if (this._borderWidth > 0)\n {\n drawX += this._borderWidth / 2;\n drawY += this._borderWidth / 2;\n\n drawWidth -= this._borderWidth;\n drawHeight -= this._borderWidth;\n \n if (this._borderWidth % 2 == 0)\n {\n drawX -= 1;\n drawWidth += 1;\n\n drawY -= 1;\n drawHeight += 1;\n }\n }\n\n g.DrawRoundedRectangle(borderPen, drawX, drawY, drawWidth, drawHeight, (float)this._borderRadius);\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/300930/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.