qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
---|---|---|---|---|
61,893 |
<p>I am attempting to copy a custom struct from kernel space to user space. inside user space errno returns 'bad address'. What is the usual cause of a bad address error?</p>
<pre><code>if(copy_to_user(info, &kernel_info, sizeof(struct prinfo)))
</code></pre>
|
[
{
"answer_id": 61948,
"author": "roo",
"author_id": 716,
"author_profile": "https://Stackoverflow.com/users/716",
"pm_score": 3,
"selected": false,
"text": "info info copy_to_user copy_to_user(void __user * to, const void * from, unsigned long n);\n info if(copy_to_user(&info, &kernel_info, sizeof(struct prinfo)) ) {\n //some stuff here i guess\n}\n"
},
{
"answer_id": 29774005,
"author": "Vijay Kumar Kanta",
"author_id": 1103688,
"author_profile": "https://Stackoverflow.com/users/1103688",
"pm_score": -1,
"selected": false,
"text": "if(copy_to_user(void *userbuf, void *kernelbuf, long len))\n return -EFAULT;\n\n// Continue with code..\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/61893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
61,894 |
<p>So I've done the trivial "warmup" apps with GAE. Now I'd like to build something with a more complex directory structure. Something along the lines of:</p>
<pre><code>siteroot/
models/
controllers/
controller1/
controller2/
...
templates/
template1/
template2/
...
</code></pre>
<p>..etc. The controllers will be Python modules handling requests. They would then need to locate (Django-style) templates in associated folders. Most of the demo apps I've seen resolve template paths like this:</p>
<pre><code>path = os.path.join(os.path.dirname(__file__), 'myPage.html')
</code></pre>
<p>...the __ file __ property resolves to the currently executing script. So, in my above example, if a Python script were running in controllers/controller1/, then the 'myPage.html' would resolve to that same directory -- controllers/controller1/myPage.html -- and I would rather cleanly separate my Python code and templates.</p>
<p>The solution I've hacked together feels... hacky:</p>
<pre><code>base_paths = os.path.split(os.path.dirname(__file__))
template_dir = os.path.join(base_paths[0], "templates")
</code></pre>
<p>So, I'm just snipping off the last element of the path for the currently running script and appending the template directory to the new path. The other (non-GAE specific) solutions I've seen for resolving Python paths seem pretty heavyweight (such as splitting paths into lists and manipulating accordingly). Django seems to have an answer for this, but I'd rather stick to the GAE API, vs. creating a full Django app and modifying it for GAE.</p>
<p>I'm assuming anything hard-coded would be non-starter, since the apps live on Google's infinite server farm. So what's a better way?</p>
|
[
{
"answer_id": 62121,
"author": "Toni Ruža",
"author_id": 6267,
"author_profile": "https://Stackoverflow.com/users/6267",
"pm_score": 1,
"selected": false,
"text": "dirname os.path.abspath(os.path.curdir) os.path.abspath template_dir = os.path.join(os.path.dirname(__file__), os.path.pardir, \"templates\")\n"
},
{
"answer_id": 102572,
"author": "Nick Johnson",
"author_id": 12030,
"author_profile": "https://Stackoverflow.com/users/12030",
"pm_score": 3,
"selected": true,
"text": "path = os.path.join(os.path.dirname(__file__), '..', 'templates', 'myPage.html')\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/61894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4904/"
] |
61,902 |
<p>I want to embed a wikipedia article into a page but I don't want all the wrapper (navigation, etc.) that sits around the articles. I saw it done here: <a href="http://www.dayah.com/periodic/" rel="nofollow noreferrer">http://www.dayah.com/periodic/</a>. Click on an element and the iframe is displayed and links to the article only (no wrapper). So how'd they do that? Seems like JavaScript handles showing the iframe and constructing the href but after browsing the pages javascript (<a href="http://www.dayah.com/periodic/Script/interactivity.js" rel="nofollow noreferrer">http://www.dayah.com/periodic/Script/interactivity.js</a>) I still can't figure out how the url is built. Thanks.</p>
|
[
{
"answer_id": 61907,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": -1,
"selected": false,
"text": "<div id=\"bodyContent\">"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/61902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5234/"
] |
61,906 |
<p>In Hibernate we have two classes with the following classes with JPA mapping:</p>
<pre><code>package com.example.hibernate
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
@Entity
public class Foo {
private long id;
private Bar bar;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
@ManyToOne(fetch = FetchType.LAZY)
public Bar getBar() {
return bar;
}
public void setBar(Bar bar) {
this.bar = bar;
}
}
package com.example.hibernate
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
public class Bar {
private long id;
private String title;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
</code></pre>
<p>Now when we load from the database an object from class Foo using session get e.g:</p>
<p>Foo foo = (Foo)session.get(Foo.class, 1 /* or some other id that exists in the DB*/);
the Bar member of foo is a proxy object (in our case javassist proxy but it can be cglib one depending on the bytecode provider you use), that is not initialized.
If you then use session.get to fetch the Bar object that is the member of the Foo class just loaded (we are in the same session), Hibernate does not issue another DB query and fetches the object from the session (first level) cache. The problem is this is a proxy to Bar class which is not initialized and trying to call this object getId() will return 0, and getTitle() will return null.
Our current solution is pretty ugly and checks if the object returned from get is a proxy here is the code (form a generic DAO implementation):</p>
<pre><code>@SuppressWarnings("unchecked")
@Override
@Transactional(readOnly = true)
public <T extends IEntity> T get(Class<T> clazz, Serializable primaryKey) throws DataAccessException {
T entity = (T) currentSession().get(clazz, primaryKey);
if (entity != null) {
if (LOG.isWarnEnabled()) {
LOG.warn("Object not found for class " + clazz.getName() + " with primary key " + primaryKey);
}
} else if (entity instanceof HibernateProxy){ // TODO: force initialization due to Hibernate bug
HibernateProxy proxy = (HibernateProxy)entity;
if (!Hibernate.isInitialized(proxy)) {
Hibernate.initialize(proxy);
}
entity = (T)proxy.getHibernateLazyInitializer().getImplementation();
}
return entity;
}
</code></pre>
<p>Is there a better way to do this, couldn't find a solution in the Hibernate forum, and didn't find the issue in Hibernate's JIRA.</p>
<p>Note: we cannot just use foo.getBar() (which will initialize the proxy properly) to get the Bar class object, because the session.get operation to fetch the Bar object does not know (or care for that matter) that the Bar class is also a lazy member of a Foo object that was just fetched.</p>
|
[
{
"answer_id": 61989,
"author": "Binil Thomas",
"author_id": 3973,
"author_profile": "https://Stackoverflow.com/users/3973",
"pm_score": 0,
"selected": false,
"text": "@Entity\npublic class Foo {\n private Long id; private String name; private Bar bar;\n\n public Foo() { }\n public Foo(String name) { this.name = name; }\n\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n public Long getId() { return id; }\n public void setId(Long id) { this.id = id; }\n\n @Basic\n public String getName() { return name; }\n public void setName(String name) { this.name = name; }\n\n @ManyToOne(fetch = FetchType.LAZY)\n public Bar getBar() { return bar; }\n public void setBar(Bar bar) { this.bar = bar; }\n}\n\n@Entity\npublic class Bar {\n private Long id; private String name;\n\n public Bar() { }\n public Bar(String name) { this.name = name; }\n\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n public Long getId() { return id; }\n public void setId(Long id) { this.id = id; }\n\n @Basic\n public String getName() { return name; }\n public void setName(String name) { this.name = name; }\n}\n\n public void testGets() {\n SessionFactory sf = new AnnotationConfiguration()\n .addPackage(\"hibtest\")\n .addAnnotatedClass(Foo.class)\n .addAnnotatedClass(Bar.class)\n .configure().buildSessionFactory();\n Session session = null;\n Transaction txn = null;\n\n // Create needed data\n try {\n session = sf.openSession();\n txn = session.beginTransaction();\n\n // Create a Bar\n Bar bar = new Bar(\"Test Bar\");\n session.save(bar);\n\n // Create a Foo\n Foo foo = new Foo(\"Test Foo\");\n session.save(foo);\n\n foo.setBar(bar);\n\n txn.commit();\n } catch (HibernateException ex) {\n if (txn != null) txn.rollback();\n throw ex;\n } finally {\n if (session != null) session.close();\n }\n\n // Try the fetch\n try {\n session = sf.openSession();\n Foo foo = (Foo) session.get(Foo.class, 1L);\n Bar bar = (Bar) session.get(Bar.class, 1L);\n System.out.println(bar.getName());\n } finally {\n if (session != null) session.close();\n }\n }\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/61906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3332/"
] |
61,953 |
<p>Let's say I have the following simple enum:</p>
<pre><code>enum Response
{
Yes = 1,
No = 2,
Maybe = 3
}
</code></pre>
<p>How can I bind this enum to a DropDownList control so that the descriptions are displayed in the list as well as retrieve the associated numeric value (1,2,3) once an option has been selected?</p>
|
[
{
"answer_id": 61961,
"author": "Mark Glorie",
"author_id": 952,
"author_profile": "https://Stackoverflow.com/users/952",
"pm_score": 8,
"selected": true,
"text": "Dim itemValues As Array = System.Enum.GetValues(GetType(Response))\nDim itemNames As Array = System.Enum.GetNames(GetType(Response))\n\nFor i As Integer = 0 To itemNames.Length - 1\n Dim item As New ListItem(itemNames(i), itemValues(i))\n dropdownlist.Items.Add(item)\nNext\n Array itemValues = System.Enum.GetValues(typeof(Response));\nArray itemNames = System.Enum.GetNames(typeof(Response));\n\nfor (int i = 0; i <= itemNames.Length - 1 ; i++) {\n ListItem item = new ListItem(itemNames[i], itemValues[i]);\n dropdownlist.Items.Add(item);\n}\n"
},
{
"answer_id": 61965,
"author": "rudigrobler",
"author_id": 5147,
"author_profile": "https://Stackoverflow.com/users/5147",
"pm_score": 3,
"selected": false,
"text": "Enum.GetValues(typeof(Response));\n"
},
{
"answer_id": 62023,
"author": "Leyu",
"author_id": 3359,
"author_profile": "https://Stackoverflow.com/users/3359",
"pm_score": 6,
"selected": false,
"text": "Enumeration IDictionary<int,string> public static class Enumeration\n{\n public static IDictionary<int, string> GetAll<TEnum>() where TEnum: struct\n {\n var enumerationType = typeof (TEnum);\n\n if (!enumerationType.IsEnum)\n throw new ArgumentException(\"Enumeration type is expected.\");\n\n var dictionary = new Dictionary<int, string>();\n\n foreach (int value in Enum.GetValues(enumerationType))\n {\n var name = Enum.GetName(enumerationType, value);\n dictionary.Add(value, name);\n }\n\n return dictionary;\n }\n}\n ddlResponse.DataSource = Enumeration.GetAll<Response>();\nddlResponse.DataTextField = \"Value\";\nddlResponse.DataValueField = \"Key\";\nddlResponse.DataBind();\n"
},
{
"answer_id": 62252,
"author": "Johan Danforth",
"author_id": 6415,
"author_profile": "https://Stackoverflow.com/users/6415",
"pm_score": 3,
"selected": false,
"text": "public class DropDownData\n{\n enum Responses { Yes = 1, No = 2, Maybe = 3 }\n\n public String Text { get; set; }\n public int Value { get; set; }\n\n public List<DropDownData> GetList()\n {\n var items = new List<DropDownData>();\n foreach (int value in Enum.GetValues(typeof(Responses)))\n {\n items.Add(new DropDownData\n {\n Text = Enum.GetName(typeof (Responses), value),\n Value = value\n });\n }\n return items;\n }\n}\n <asp:DropDownList ID=\"DropDownList1\" runat=\"server\" \n DataSourceID=\"ObjectDataSource1\" DataTextField=\"Text\" DataValueField=\"Value\">\n</asp:DropDownList>\n<asp:ObjectDataSource ID=\"ObjectDataSource1\" runat=\"server\" \n SelectMethod=\"GetList\" TypeName=\"DropDownData\"></asp:ObjectDataSource>\n enum Responses { Yes = 1, No = 2, Maybe = 3 }\n\nprotected void Page_Load(object sender, EventArgs e)\n{\n if (!IsPostBack)\n {\n foreach (int value in Enum.GetValues(typeof(Responses)))\n {\n DropDownList1.Items.Add(new ListItem(Enum.GetName(typeof(Responses), value), value.ToString()));\n }\n }\n}\n"
},
{
"answer_id": 135822,
"author": "VanOrman",
"author_id": 4550,
"author_profile": "https://Stackoverflow.com/users/4550",
"pm_score": 5,
"selected": false,
"text": "foreach (Response r in Enum.GetValues(typeof(Response)))\n{\n ListItem item = new ListItem(Enum.GetName(typeof(Response), r), r.ToString());\n DropDownList1.Items.Add(item);\n}\n"
},
{
"answer_id": 290408,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "public enum Color\n{\n RED,\n GREEN,\n BLUE\n}\n protected System.Web.UI.WebControls.DropDownList ddColor;\n\nprivate void Page_Load(object sender, System.EventArgs e)\n{\n if(!IsPostBack)\n {\n ddColor.DataSource = Enum.GetNames(typeof(Color));\n ddColor.DataBind();\n }\n}\n private void ddColor_SelectedIndexChanged(object sender, System.EventArgs e)\n {\n Color selectedColor = (Color)Enum.Parse(typeof(Color),ddColor.SelectedValue\n }\n"
},
{
"answer_id": 540741,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "Array itemValues = Enum.GetValues(typeof(TaskStatus));\nArray itemNames = Enum.GetNames(typeof(TaskStatus));\n\nfor (int i = 0; i <= itemNames.Length; i++)\n{\n ListItem item = new ListItem(itemNames.GetValue(i).ToString(),\n itemValues.GetValue(i).ToString());\n ddlStatus.Items.Add(item);\n}\n"
},
{
"answer_id": 1831886,
"author": "Mostafa",
"author_id": 1904217,
"author_profile": "https://Stackoverflow.com/users/1904217",
"pm_score": 1,
"selected": false,
"text": "\npublic static void BindToEnum(Type enumType, ListControl lc)\n {\n // get the names from the enumeration\n string[] names = Enum.GetNames(enumType);\n // get the values from the enumeration\n Array values = Enum.GetValues(enumType);\n // turn it into a hash table\n Hashtable ht = new Hashtable();\n for (int i = 0; i < names.Length; i++)\n // note the cast to integer here is important\n // otherwise we'll just get the enum string back again\n ht.Add(names[i], (int)values.GetValue(i));\n // return the dictionary to be bound to\n lc.DataSource = ht;\n lc.DataTextField = \"Key\";\n lc.DataValueField = \"Value\";\n lc.DataBind();\n }\n \nBindToEnum(typeof(NewsType), DropDownList1);\nBindToEnum(typeof(NewsType), CheckBoxList1);\nBindToEnum(typeof(NewsType), RadoBuuttonList1);\n"
},
{
"answer_id": 2080385,
"author": "Muhammed Qasim",
"author_id": 252516,
"author_profile": "https://Stackoverflow.com/users/252516",
"pm_score": 2,
"selected": false,
"text": "public static void BindControlToEnum(DataBoundControl ControlToBind, Type type)\n{\n //ListControl\n\n if (type == null)\n throw new ArgumentNullException(\"type\");\n else if (ControlToBind==null )\n throw new ArgumentNullException(\"ControlToBind\");\n if (!type.IsEnum)\n throw new ArgumentException(\"Only enumeration type is expected.\");\n\n Dictionary<int, string> pairs = new Dictionary<int, string>();\n\n foreach (int i in Enum.GetValues(type))\n {\n pairs.Add(i, Enum.GetName(type, i));\n }\n ControlToBind.DataSource = pairs;\n ListControl lstControl = ControlToBind as ListControl;\n if (lstControl != null)\n {\n lstControl.DataTextField = \"Value\";\n lstControl.DataValueField = \"Key\";\n }\n ControlToBind.DataBind();\n\n}\n"
},
{
"answer_id": 2416623,
"author": "Feryt",
"author_id": 82539,
"author_profile": "https://Stackoverflow.com/users/82539",
"pm_score": 5,
"selected": false,
"text": "Html.DropDownListFor(o => o.EnumProperty, Enum.GetValues(typeof(enumtype)).Cast<enumtype>().Select(x => new SelectListItem { Text = x.ToString(), Value = ((int)x).ToString() }))\n"
},
{
"answer_id": 2511877,
"author": "Ben Hughes",
"author_id": 286796,
"author_profile": "https://Stackoverflow.com/users/286796",
"pm_score": 2,
"selected": false,
"text": "DropDownList1.DataSource = Enum.GetValues(typeof(Response));\nDropDownList1.DataBind();\n Response rIn = Response.Maybe;\nDropDownList1.Text = rIn.ToString();\n Response rOut = (Response) Enum.Parse(typeof(Response), DropDownList1.Text);\n"
},
{
"answer_id": 5120974,
"author": "Diego Mendes",
"author_id": 484222,
"author_profile": "https://Stackoverflow.com/users/484222",
"pm_score": 0,
"selected": false,
"text": "var mylist = Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().ToList<MyEnum>().OrderBy(l => l.ToString());\nforeach (MyEnum item in mylist)\n ddlDivisao.Items.Add(new ListItem(item.ToString(), ((int)item).ToString()));\n"
},
{
"answer_id": 6517806,
"author": "sankalp gurha",
"author_id": 820671,
"author_profile": "https://Stackoverflow.com/users/820671",
"pm_score": 2,
"selected": false,
"text": "public enum Color\n{\n RED,\n GREEN,\n BLUE\n}\n\nddColor.DataSource = Enum.GetNames(typeof(Color));\nddColor.DataBind();\n"
},
{
"answer_id": 7750678,
"author": "Josh Stribling",
"author_id": 464386,
"author_profile": "https://Stackoverflow.com/users/464386",
"pm_score": 0,
"selected": false,
"text": " public static object GetEnumDescriptions(Type enumType)\n {\n var list = new List<KeyValuePair<Enum, string>>();\n foreach (Enum value in Enum.GetValues(enumType))\n {\n string description = value.ToString();\n FieldInfo fieldInfo = value.GetType().GetField(description);\n var attribute = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false).First();\n if (attribute != null)\n {\n description = (attribute as DescriptionAttribute).Description;\n }\n list.Add(new KeyValuePair<Enum, string>(value, description));\n }\n return list;\n }\n enum SampleEnum\n {\n NormalNoSpaces,\n [Description(\"Description With Spaces\")]\n DescriptionWithSpaces,\n [Description(\"50%\")]\n Percent_50,\n }\n m_Combo_Sample.DataSource = GetEnumDescriptions(typeof(SampleEnum));\n m_Combo_Sample.DisplayMember = \"Value\";\n m_Combo_Sample.ValueMember = \"Key\";\n"
},
{
"answer_id": 9900016,
"author": "Trisped",
"author_id": 641833,
"author_profile": "https://Stackoverflow.com/users/641833",
"pm_score": 0,
"selected": false,
"text": "Namespace CustomExtensions\n Public Module ListItemCollectionExtension\n\n <Runtime.CompilerServices.Extension()> _\n Public Sub AddEnum(Of TEnum As Structure)(items As System.Web.UI.WebControls.ListItemCollection)\n Dim enumerationType As System.Type = GetType(TEnum)\n Dim enumUnderType As System.Type = System.Enum.GetUnderlyingType(enumType)\n\n If Not enumerationType.IsEnum Then Throw New ArgumentException(\"Enumeration type is expected.\")\n\n Dim enumTypeNames() As String = System.Enum.GetNames(enumerationType)\n Dim enumTypeValues() As TEnum = System.Enum.GetValues(enumerationType)\n\n For i = 0 To enumTypeNames.Length - 1\n items.Add(New System.Web.UI.WebControls.ListItem(saveResponseTypeNames(i), TryCast(enumTypeValues(i), System.Enum).ToString(\"d\")))\n Next\n End Sub\n End Module\nEnd Namespace\n Imports <projectName>.CustomExtensions.ListItemCollectionExtension\n\n...\n\nyourDropDownList.Items.AddEnum(Of EnumType)()\n namespace CustomExtensions\n{\n public static class ListItemCollectionExtension\n {\n public static void AddEnum<TEnum>(this System.Web.UI.WebControls.ListItemCollection items) where TEnum : struct\n {\n System.Type enumType = typeof(TEnum);\n System.Type enumUnderType = System.Enum.GetUnderlyingType(enumType);\n\n if (!enumType.IsEnum) throw new Exception(\"Enumeration type is expected.\");\n\n string[] enumTypeNames = System.Enum.GetNames(enumType);\n TEnum[] enumTypeValues = (TEnum[])System.Enum.GetValues(enumType);\n\n for (int i = 0; i < enumTypeValues.Length; i++)\n {\n items.add(new System.Web.UI.WebControls.ListItem(enumTypeNames[i], (enumTypeValues[i] as System.Enum).ToString(\"d\")));\n }\n }\n }\n}\n using CustomExtensions.ListItemCollectionExtension;\n\n...\n\nyourDropDownList.Items.AddEnum<EnumType>()\n items.Add(New System.Web.UI.WebControls.ListItem(saveResponseTypeNames(i), saveResponseTypeValues(i).ToString(\"d\")))\n Dim newListItem As System.Web.UI.WebControls.ListItem\nnewListItem = New System.Web.UI.WebControls.ListItem(enumTypeNames(i), Convert.ChangeType(enumTypeValues(i), enumUnderType).ToString())\nnewListItem.Selected = If(EqualityComparer(Of TEnum).Default.Equals(selected, saveResponseTypeValues(i)), True, False)\nitems.Add(newListItem)\n"
},
{
"answer_id": 24769726,
"author": "Amir Chatrbahr",
"author_id": 922713,
"author_profile": "https://Stackoverflow.com/users/922713",
"pm_score": 4,
"selected": false,
"text": "using System.ComponentModel;\npublic enum CompanyType\n{\n [Description(\"\")]\n Null = 1,\n\n [Description(\"Supplier\")]\n Supplier = 2,\n\n [Description(\"Customer\")]\n Customer = 3\n}\n using System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Linq;\nusing System.Web.Mvc;\n\npublic static class EnumExtension\n{\n public static string ToDescription(this System.Enum value)\n {\n var attributes = (DescriptionAttribute[])value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);\n return attributes.Length > 0 ? attributes[0].Description : value.ToString();\n }\n\n public static IEnumerable<SelectListItem> ToSelectList<T>(this System.Enum enumValue)\n {\n return\n System.Enum.GetValues(enumValue.GetType()).Cast<T>()\n .Select(\n x =>\n new SelectListItem\n {\n Text = ((System.Enum)(object) x).ToDescription(),\n Value = x.ToString(),\n Selected = (enumValue.Equals(x))\n });\n }\n}\n public class Company\n{\n public string CompanyName { get; set; }\n public CompanyType Type { get; set; }\n}\n @Html.DropDownListFor(m => m.Type,\[email protected]<CompanyType>())\n @Html.DropDownList(\"type\", \nEnum.GetValues(typeof(CompanyType)).Cast<CompanyType>()\n.Select(x => new SelectListItem {Text = x.ToDescription(), Value = x.ToString()}))\n"
},
{
"answer_id": 27000004,
"author": "bradlis7",
"author_id": 179311,
"author_profile": "https://Stackoverflow.com/users/179311",
"pm_score": 1,
"selected": false,
"text": "@Html.DropDownList(\"response\", EnumHelper.GetSelectList(typeof(Response)))\n // Assuming Model.Response is an instance of Response\[email protected](m => m.Response)\n"
},
{
"answer_id": 33767663,
"author": "KrishnaDhungana",
"author_id": 2330518,
"author_profile": "https://Stackoverflow.com/users/2330518",
"pm_score": 3,
"selected": false,
"text": "var responseTypes= Enum.GetNames(typeof(Response)).Select(x => new { text = x, value = (int)Enum.Parse(typeof(Response), x) });\n DropDownList.DataSource = responseTypes;\n DropDownList.DataTextField = \"text\";\n DropDownList.DataValueField = \"value\";\n DropDownList.DataBind();\n"
},
{
"answer_id": 41553362,
"author": "Pecheneg",
"author_id": 1872210,
"author_profile": "https://Stackoverflow.com/users/1872210",
"pm_score": 0,
"selected": false,
"text": " foreach (string value in Enum.GetNames(typeof(Response)))\n ddlResponse.Items.Add(new ListItem()\n {\n Text = value,\n Value = ((int)Enum.Parse(typeof(Response), value)).ToString()\n });\n"
},
{
"answer_id": 42448307,
"author": "Marie McDonley",
"author_id": 7307726,
"author_profile": "https://Stackoverflow.com/users/7307726",
"pm_score": 2,
"selected": false,
"text": "public class YourEntity\n{\n public int ID { get; set; }\n public string Name{ get; set; }\n public string Description { get; set; }\n public OptionType Types { get; set; }\n}\n\npublic enum OptionType\n{\n Unknown,\n Option1, \n Option2,\n Option3\n}\n @Html.EnumDropDownListFor(model => model.Types, htmlAttributes: new { @class = \"form-control\" })\n"
},
{
"answer_id": 59394848,
"author": "Henkie85",
"author_id": 11846363,
"author_profile": "https://Stackoverflow.com/users/11846363",
"pm_score": 0,
"selected": false,
"text": "public enum Test\n {\n Test1 = 1,\n Test2 = 2,\n Test3 = 3\n }\n class Program\n {\n static void Main(string[] args)\n {\n\n var items = Enum.GetValues(typeof(Test));\n\n foreach (var item in items)\n {\n //Gives you the names\n Console.WriteLine(item);\n }\n\n\n foreach(var item in (Test[])items)\n {\n // Gives you the numbers\n Console.WriteLine((int)item);\n }\n }\n }\n"
},
{
"answer_id": 64668876,
"author": "MaxOvrdrv",
"author_id": 1583649,
"author_profile": "https://Stackoverflow.com/users/1583649",
"pm_score": 0,
"selected": false,
"text": "private void LoadConsciousnessDrop()\n{\n string sel_val = this.drp_Consciousness.SelectedValue;\n this.drp_Consciousness.Items.Clear();\n string[] names = Enum.GetNames(typeof(Consciousness));\n \n for (int i = 0; i < names.Length; i++)\n this.drp_Consciousness.Items.Add(new ListItem(names[i], ((int)((Consciousness)Enum.Parse(typeof(Consciousness), names[i]))).ToString()));\n\n this.drp_Consciousness.SelectedValue = String.IsNullOrWhiteSpace(sel_val) ? null : sel_val;\n}\n"
},
{
"answer_id": 66405336,
"author": "TheRealSheldon",
"author_id": 3037489,
"author_profile": "https://Stackoverflow.com/users/3037489",
"pm_score": 0,
"selected": false,
"text": " private void BuildComboBoxFromEnum(ComboBox box, Type enumType) {\n var dict = new Dictionary<string, int>();\n foreach (var foo in Enum.GetValues(enumType)) {\n dict.Add(foo.ToString(), (int)foo);\n }\n box.DropDownStyle = ComboBoxStyle.DropDownList; // Forces comboBox to ReadOnly\n box.DataSource = new BindingSource(dict, null);\n box.DisplayMember = \"Key\";\n box.ValueMember = \"Value\";\n // Register a callback that prints the Name and Value of the \n // selected enum. This should be removed after initial testing.\n box.SelectedIndexChanged += (o, e) => {\n Console.WriteLine(\"{0} {1}\", box.Text, box.SelectedValue);\n };\n }\n BuildComboBoxFromEnum(comboBox1,typeof(Response));\n"
},
{
"answer_id": 68136328,
"author": "combatc2",
"author_id": 1491388,
"author_profile": "https://Stackoverflow.com/users/1491388",
"pm_score": 0,
"selected": false,
"text": "<select asp-items=\"Html.GetEnumSelectList<GridReportingStatusFilters>()\">\n <option value=\"\"></option>\n</select>\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/61953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] |
61,963 |
<p>I want to import an oracle dump into a different tablespace.</p>
<p>I have a tablespace A used by User A. I've revoked DBA on this user and given him the grants connect and resource. Then I've dumped everything with the command</p>
<blockquote>
<p>exp a/*** owner=a file=oracledump.DMP log=log.log compress=y</p>
</blockquote>
<p>Now I want to import the dump into the tablespace B used by User B. So I've given him the grants on connect and resource (no DBA). Then I've executed the following import:</p>
<blockquote>
<p>imp b/*** file=oracledump.DMP log=import.log fromuser=a touser=b</p>
</blockquote>
<p>The result is a log with lots of errors:</p>
<blockquote>
<p>IMP-00017: following statement failed with ORACLE error 20001: "BEGIN DBMS_STATS.SET_TABLE_STATS
IMP-00003: ORACLE error 20001 encountered
ORA-20001: Invalid or inconsistent input values</p>
</blockquote>
<p>After that, I've tried the same import command but with the option statistics=none. This resulted in the following errors:</p>
<blockquote>
<p>ORA-00959: tablespace 'A_TBLSPACE' does not exist</p>
</blockquote>
<p>How should this be done?</p>
<p>Note: a lot of columns are of type CLOB. It looks like the problems have something to do with that.</p>
<p>Note2: The oracle versions are a mixture of 9.2, 10.1, and 10.1 XE. But I don't think it has to do with versions.</p>
|
[
{
"answer_id": 63823,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "REMAP_TABLESPACE=A_TBLSPACE:NEW_TABLESPACE_GOES_HERE\n"
},
{
"answer_id": 71826,
"author": "Andrew",
"author_id": 5662,
"author_profile": "https://Stackoverflow.com/users/5662",
"pm_score": 6,
"selected": true,
"text": "exp imp ORA-00959: tablespace 'A_TBLSPACE' does not exist USERS imp <xe_username>/<password>@XE file=<filename.dmp> indexfile=index.sql full=y Find: 'REM<space>' Replace: <nothing> Find: '\"<source_tablespace>\"' Replace: '\"USERS\"' Find: '...' Replace: 'REM ...' Find: 'CONNECT' Replace: 'REM CONNECT' sqlplus <xe_username>/<password>@XE @index.sql imp <xe_username>/<password>@XE file=<filename.dmp> fromuser=<original_username> touser=<xe_username> ignore=y"
},
{
"answer_id": 3289277,
"author": "Grebets Kostyantyn",
"author_id": 396705,
"author_profile": "https://Stackoverflow.com/users/396705",
"pm_score": 3,
"selected": false,
"text": "impdp B/B full=Y dumpfile=DUMP.dmp REMAP_TABLESPACE=OLD_TABLESPACE:USERS\n"
},
{
"answer_id": 9619559,
"author": "Dmitry",
"author_id": 1257270,
"author_profile": "https://Stackoverflow.com/users/1257270",
"pm_score": 2,
"selected": false,
"text": "gsar -f -s\"TSDAT_OV101\" -r\"USERS \" rm_schema.dump rm_schema.n.dump\ngsar -f -s\"TABLESPACE \"\"\"USERS \"\"\" ENABLE STORAGE IN ROW CHUNK 8192 RETENTION\" -r\" \" rm_schema.n1.dump rm_schema.n.dump\ngsar -f -s\"TABLESPACE \"\"\"USERS \"\"\" LOGGING\" -r\" \" rm_schema.n1.dump rm_schema.n.dump\ngsar -f -s\"TABLESPACE \"\"\"USERS \"\"\" \" -r\" \" rm_schema.n.dump rm_schema.n1.dump\n"
},
{
"answer_id": 13514792,
"author": "peter",
"author_id": 1845340,
"author_profile": "https://Stackoverflow.com/users/1845340",
"pm_score": 2,
"selected": false,
"text": "CREATE OR REPLACE DIRECTORY tempdump AS '/temp/old_datapump/';\nGRANT READ, WRITE ON DIRECTORY tempdump TO old_user;\n CREATE OR REPLACE DIRECTORY tempdump AS '/temp/new_datapump/';\nGRANT READ, WRITE ON DIRECTORY tempdump TO new_user;\n expdp tables=old_user.table directory=tempdump dumpfile=adump.dmp logfile=adump.log\n impdp directory=tempdump dumpfile=adump_table.dmp logfile=bdump_table.log\nREMAP_TABLESPACE=old_tablespace:new_tablespace REMAP_SCHEMA=old_user:new_user\n"
},
{
"answer_id": 54484926,
"author": "masterxilo",
"author_id": 524504,
"author_profile": "https://Stackoverflow.com/users/524504",
"pm_score": 0,
"selected": false,
"text": "imp exp DATABASE_TABLESPACE USERS -- don't care about the details\nCREATE TABLESPACE DATABASE_TABLESPACE\n DATAFILE 'DATABASE_TABLESPACE.dat' \n SIZE 10M\n REUSE\n AUTOEXTEND ON NEXT 10M MAXSIZE 200M;\n\nALTER DATABASE DEFAULT TABLESPACE DATABASE_TABLESPACE;\n\nCREATE USER username\n IDENTIFIED BY userpassword\n CONTAINER=all;\n\nGRANT create session TO username;\nGRANT create table TO username;\nGRANT create view TO username;\nGRANT create any trigger TO username;\nGRANT create any procedure TO username;\nGRANT create sequence TO username;\nGRANT create synonym TO username;\nGRANT create synonym TO username;\nGRANT UNLIMITED TABLESPACE TO username;\n\n exp imp"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/61963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5043/"
] |
61,967 |
<p>Let's say I have the following simple table variable:</p>
<pre><code>declare @databases table
(
DatabaseID int,
Name varchar(15),
Server varchar(15)
)
-- insert a bunch rows into @databases
</code></pre>
<p>Is declaring and using a cursor my only option if I wanted to iterate through the rows? Is there another way?</p>
|
[
{
"answer_id": 61981,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 2,
"selected": false,
"text": "While (Select Count(*) From #TempTable) > 0\nBegin\n Insert Into @Databases...\n\n Delete From #TempTable Where x = x\nEnd\n"
},
{
"answer_id": 62130,
"author": "Martynnw",
"author_id": 5466,
"author_profile": "https://Stackoverflow.com/users/5466",
"pm_score": 10,
"selected": true,
"text": "SELECT Declare @Id int\n\nWhile (Select Count(*) From ATable Where Processed = 0) > 0\nBegin\n Select Top 1 @Id = Id From ATable Where Processed = 0\n\n --Do some processing here\n\n Update ATable Set Processed = 1 Where Id = @Id \n\nEnd\n Select *\nInto #Temp\nFrom ATable\n\nDeclare @Id int\n\nWhile (Select Count(*) From #Temp) > 0\nBegin\n\n Select Top 1 @Id = Id From #Temp\n\n --Do some processing here\n\n Delete #Temp Where Id = @Id\n\nEnd\n WHILE EXISTS(SELECT * FROM #Temp)\n COUNT EXISTS"
},
{
"answer_id": 63031,
"author": "leoinfo",
"author_id": 6948,
"author_profile": "https://Stackoverflow.com/users/6948",
"pm_score": 4,
"selected": false,
"text": "Select Identity(int, 1,1) AS PK, DatabaseID\nInto #T\nFrom @databases\n\nDeclare @maxPK int;Select @maxPK = MAX(PK) From #T\nDeclare @pk int;Set @pk = 1\n\nWhile @pk <= @maxPK\nBegin\n\n -- Get one record\n Select DatabaseID, Name, Server\n From @databases\n Where DatabaseID = (Select DatabaseID From #T Where PK = @pk)\n\n --Do some processing here\n -- \n\n Select @pk = @pk + 1\nEnd\n declare @databases table\n(\n PK int IDENTITY(1,1), \n DatabaseID int,\n Name varchar(15), \n Server varchar(15)\n)\n-- insert a bunch rows into @databases\n--/*\nINSERT INTO @databases (DatabaseID, Name, Server) SELECT 1,'MainDB', 'MyServer'\nINSERT INTO @databases (DatabaseID, Name, Server) SELECT 1,'MyDB', 'MyServer2'\n--*/\n\nDeclare @maxPK int;Select @maxPK = MAX(PK) From @databases\nDeclare @pk int;Set @pk = 1\n\nWhile @pk <= @maxPK\nBegin\n\n /* Get one record (you can read the values into some variables) */\n Select DatabaseID, Name, Server\n From @databases\n Where PK = @pk\n\n /* Do some processing here */\n /* ... */ \n\n Select @pk = @pk + 1\nEnd\n"
},
{
"answer_id": 63440,
"author": "Tim Lentine",
"author_id": 2833,
"author_profile": "https://Stackoverflow.com/users/2833",
"pm_score": 1,
"selected": false,
"text": "DECLARE @databases TABLE \n( \n DatabaseID int, \n Name varchar(15), \n Server varchar(15), \n fUsed BIT DEFAULT 0 \n) \n\n-- insert a bunch rows into @databases\n\nDECLARE @DBID INT\n\nSELECT TOP 1 @DBID = DatabaseID from @databases where fUsed = 0 \n\nWHILE @@ROWCOUNT <> 0 and @DBID IS NOT NULL \nBEGIN \n -- Perform your processing here \n\n --Update the record to \"used\" \n\n UPDATE @databases SET fUsed = 1 WHERE DatabaseID = @DBID \n\n --Get the next record \n SELECT TOP 1 @DBID = DatabaseID from @databases where fUsed = 0 \nEND\n"
},
{
"answer_id": 65294,
"author": "Josef",
"author_id": 5581,
"author_profile": "https://Stackoverflow.com/users/5581",
"pm_score": 7,
"selected": false,
"text": "While (Select Count(*) From #Temp) > 0\n While EXISTS(SELECT * From #Temp)\n EXISTS"
},
{
"answer_id": 77601,
"author": "Seibar",
"author_id": 357,
"author_profile": "https://Stackoverflow.com/users/357",
"pm_score": 5,
"selected": false,
"text": "declare @databases table\n(\n RowID int not null identity(1,1) primary key,\n DatabaseID int,\n Name varchar(15), \n Server varchar(15)\n)\n\n-- insert a bunch rows into @databases\n declare @i int\nselect @i = min(RowID) from @databases\ndeclare @max int\nselect @max = max(RowID) from @databases\n\nwhile @i <= @max begin\n select DatabaseID, Name, Server from @database where RowID = @i --do some stuff\n set @i = @i + 1\nend\n"
},
{
"answer_id": 680272,
"author": "dance2die",
"author_id": 4035,
"author_profile": "https://Stackoverflow.com/users/4035",
"pm_score": 2,
"selected": false,
"text": "cursor declare @databases table\n(\n DatabaseID int,\n Name varchar(15), \n Server varchar(15)\n)\n\n--; Insert records into @databases...\n\n--; Recurse through @databases\n;with DBs as (\n select * from @databases where DatabaseID = 1\n union all\n select A.* from @databases A \n inner join DBs B on A.DatabaseID = B.DatabaseID + 1\n)\nselect * from DBs\n"
},
{
"answer_id": 2084732,
"author": "Trevor",
"author_id": 253034,
"author_profile": "https://Stackoverflow.com/users/253034",
"pm_score": 6,
"selected": false,
"text": "declare @RowNum int, @CustId nchar(5), @Name1 nchar(25)\n\nselect @CustId=MAX(USERID) FROM UserIDs --start with the highest ID\nSelect @RowNum = Count(*) From UserIDs --get total number of records\nWHILE @RowNum > 0 --loop until no more records\nBEGIN \n select @Name1 = username1 from UserIDs where USERID= @CustID --get other info from that row\n print cast(@RowNum as char(12)) + ' ' + @CustId + ' ' + @Name1 --do whatever\n\n select top 1 @CustId=USERID from UserIDs where USERID < @CustID order by USERID desc--get the next one\n set @RowNum = @RowNum - 1 --decrease count\nEND\n"
},
{
"answer_id": 2135015,
"author": "HLGEM",
"author_id": 9034,
"author_profile": "https://Stackoverflow.com/users/9034",
"pm_score": 2,
"selected": false,
"text": "insert @databases (DatabaseID, Name, Server)\nselect DatabaseID, Name, Server \nFrom ... (Use whatever query you would have used in the loop or cursor)\n"
},
{
"answer_id": 10371631,
"author": "Syed Umar Ahmed",
"author_id": 861216,
"author_profile": "https://Stackoverflow.com/users/861216",
"pm_score": 2,
"selected": false,
"text": "-- [PO_RollBackOnReject] 'FININV10532'\nalter procedure PO_RollBackOnReject\n@CaseID nvarchar(100)\n\nAS\nBegin\nSELECT *\nINTO #tmpTable\nFROM PO_InvoiceItems where CaseID = @CaseID\n\nDeclare @Id int\nDeclare @PO_No int\nDeclare @Current_Balance Money\n\n\nWhile (Select ROW_NUMBER() OVER(ORDER BY PO_LineNo DESC) From #tmpTable) > 0\nBegin\n Select Top 1 @Id = PO_LineNo, @Current_Balance = Current_Balance,\n @PO_No = PO_No\n From #Temp\n update PO_Details\n Set Current_Balance = Current_Balance + @Current_Balance,\n Previous_App_Amount= Previous_App_Amount + @Current_Balance,\n Is_Processed = 0\n Where PO_LineNumber = @Id\n AND PO_No = @PO_No\n update PO_InvoiceItems\n Set IsVisible = 0,\n Is_Processed= 0\n ,Is_InProgress = 0 , \n Is_Active = 0\n Where PO_LineNo = @Id\n AND PO_No = @PO_No\nEnd\nEnd\n"
},
{
"answer_id": 17713828,
"author": "SReiderB",
"author_id": 2571174,
"author_profile": "https://Stackoverflow.com/users/2571174",
"pm_score": 3,
"selected": false,
"text": "DECLARE @rowCount int = 0\n ,@currentRow int = 1\n ,@databaseID int\n ,@name varchar(15)\n ,@server varchar(15);\n\nSELECT @rowCount = COUNT(*)\nFROM @databases;\n\nWHILE (@currentRow <= @rowCount)\nBEGIN\n SELECT TOP 1\n @databaseID = rt.[DatabaseID]\n ,@name = rt.[Name]\n ,@server = rt.[Server]\n FROM (\n SELECT ROW_NUMBER() OVER (\n ORDER BY t.[DatabaseID], t.[Name], t.[Server]\n ) AS [RowNumber]\n ,t.[DatabaseID]\n ,t.[Name]\n ,t.[Server]\n FROM @databases t\n ) rt\n WHERE rt.[RowNumber] = @currentRow;\n\n EXEC [your_stored_procedure] @databaseID, @name, @server;\n\n SET @currentRow = @currentRow + 1;\nEND\n"
},
{
"answer_id": 23432301,
"author": "OrganicCoder",
"author_id": 2611808,
"author_profile": "https://Stackoverflow.com/users/2611808",
"pm_score": 3,
"selected": false,
"text": "declare @Rowcount int \nselect @Rowcount=count(*) from AddressTable;\n\nwhile( @Rowcount>0)\n begin \n select @Rowcount=@Rowcount-1;\n SELECT * FROM AddressTable order by AddressId desc OFFSET @Rowcount ROWS FETCH NEXT 1 ROWS ONLY;\nend \n"
},
{
"answer_id": 23524660,
"author": "howmnsk",
"author_id": 3613336,
"author_profile": "https://Stackoverflow.com/users/3613336",
"pm_score": 0,
"selected": false,
"text": "if object_ID('tempdb..#a')is not NULL drop table #a\n\nselect 'IF EXISTS (SELECT name FROM sysindexes WHERE name ='+CHAR(39)+''+'IDX_'+COLUMN_NAME+'_'+SUBSTRING(table_name,5,len(table_name)-3)+char(39)+')' \n+' begin DROP INDEX [IDX_'+COLUMN_NAME+'_'+SUBSTRING(table_name,5,len(table_name)-3)+'] ON '+table_schema+'.'+table_name+' END Create index IDX_'+COLUMN_NAME+'_'+SUBSTRING(table_name,5,len(table_name)-3)+ ' on '+ table_schema+'.'+table_name+' ('+COLUMN_NAME+') ' 'Field'\n,ROW_NUMBER() over (order by table_NAMe) as 'ROWNMBR'\ninto #a\nfrom INFORMATION_SCHEMA.COLUMNS\nwhere (COLUMN_NAME like '%_SSNO_%' or COLUMN_NAME like'%_EMPR_NO_')\n and TABLE_SCHEMA='dbo'\n\ndeclare @loopcntr int\ndeclare @ROW int\ndeclare @String nvarchar(1000)\nset @loopcntr=(select count(*) from #a)\nset @ROW=1 \n\nwhile (@ROW <= @loopcntr)\n begin\n select top 1 @String=a.Field \n from #A a\n where a.ROWNMBR = @ROW\n execute sp_executesql @String\n set @ROW = @ROW + 1\n end \n"
},
{
"answer_id": 23768656,
"author": "Bob Alley",
"author_id": 3658181,
"author_profile": "https://Stackoverflow.com/users/3658181",
"pm_score": 0,
"selected": false,
"text": "SELECT @pk = @pk + 1\n SET @pk += @pk\n"
},
{
"answer_id": 25618719,
"author": "Srinivas Maale",
"author_id": 3999541,
"author_profile": "https://Stackoverflow.com/users/3999541",
"pm_score": 1,
"selected": false,
"text": "select eno,ename,eaddress,mobno int,row_number() over(order by eno desc) as rno into #tmp_sri from emp \n DECLARE @ROWNUMBER INT\nDECLARE @ename varchar(100)\n SELECT @ROWNUMBER = COUNT(*) FROM #tmp_sri\ndeclare @rno int\n while @rownumber>0\nbegin\n set @rno=@rownumber\n select @ename=ename from #tmp_sri where rno=@rno **// You can take columns data from here as many as you want**\n set @rownumber=@rownumber-1\n print @ename **// instead of printing, you can write insert, update, delete statements**\nend\n"
},
{
"answer_id": 37035265,
"author": "Control Freak",
"author_id": 916535,
"author_profile": "https://Stackoverflow.com/users/916535",
"pm_score": 2,
"selected": false,
"text": "ID Declare @id int = 0, @anything nvarchar(max)\nWHILE(1=1) BEGIN\n Select Top 1 @anything=[Anything],@id=@id+1 FROM Table WHERE ID>@id\n if(@@ROWCOUNT=0) break;\n\n --Process @anything\n\nEND\n"
},
{
"answer_id": 37867029,
"author": "Sean",
"author_id": 240430,
"author_profile": "https://Stackoverflow.com/users/240430",
"pm_score": 1,
"selected": false,
"text": "DECLARE @databases TABLE\n(\n DatabaseID int,\n Name varchar(15), \n Server varchar(15)\n)\n\n-- insert a bunch rows into @databases\n\nDECLARE @CurrID INT\n\nSELECT @CurrID = MIN(DatabaseID)\nFROM @databases\n\nWHILE @CurrID IS NOT NULL\nBEGIN\n\n -- Do stuff for @CurrID\n\n SELECT @CurrID = MIN(DatabaseID)\n FROM @databases\n WHERE DatabaseID > @CurrID\n\nEND\n"
},
{
"answer_id": 40109813,
"author": "Yves A Martin",
"author_id": 1579352,
"author_profile": "https://Stackoverflow.com/users/1579352",
"pm_score": 2,
"selected": false,
"text": "DECLARE @TableVariable (ID int, Name varchar(50));\nDECLARE @RecordCount int;\nSELECT @RecordCount = COUNT(*) FROM @TableVariable;\n\nWHILE @RecordCount > 0\nBEGIN\nSELECT ID, Name FROM @TableVariable ORDER BY ID OFFSET @RecordCount - 1 FETCH NEXT 1 ROW;\nSET @RecordCount = @RecordCount - 1;\nEND\n"
},
{
"answer_id": 42760525,
"author": "Alexandre Pezzutto",
"author_id": 7702229,
"author_profile": "https://Stackoverflow.com/users/7702229",
"pm_score": 2,
"selected": false,
"text": "insert into @tabela values (1, 'verde');\ninsert into @tabela values (2, 'amarelo');\ninsert into @tabela values (3, 'azul');\ninsert into @tabela values (4, 'branco');\n\nreturn;\n DECLARE @cod int, @nome varchar(10);\n\nDECLARE curLoop CURSOR STATIC LOCAL \nFOR\nSELECT \n cod\n ,nome\nFROM \n dbo.f_teste_loop();\n\nOPEN curLoop;\n\nFETCH NEXT FROM curLoop\n INTO @cod, @nome;\n\nWHILE (@@FETCH_STATUS = 0)\nBEGIN\n PRINT @nome;\n\n FETCH NEXT FROM curLoop\n INTO @cod, @nome;\nEND\n\nCLOSE curLoop;\nDEALLOCATE curLoop;\n"
},
{
"answer_id": 43052926,
"author": "Mass Dot Net",
"author_id": 165494,
"author_profile": "https://Stackoverflow.com/users/165494",
"pm_score": 1,
"selected": false,
"text": "BREAK @@ROWCOUNT @databases declare @databases table\n(\n DatabaseID int,\n [Name] varchar(15), \n [Server] varchar(15)\n);\n\n\n-- Populate the [@databases] table with test data.\ninsert into @databases (DatabaseID, [Name], [Server])\nselect X.DatabaseID, X.[Name], X.[Server]\nfrom (values \n (1, 'Roger', 'ServerA'),\n (5, 'Suzy', 'ServerB'),\n (8675309, 'Jenny', 'TommyTutone')\n) X (DatabaseID, [Name], [Server])\n\n\n-- Create an infinite loop & ensure that a break condition is reached in the loop code.\ndeclare @databaseId int;\n\nwhile (1=1)\nbegin\n -- Get the next database ID.\n select top(1) @databaseId = DatabaseId \n from @databases \n where DatabaseId > isnull(@databaseId, 0);\n\n -- If no rows were found by the preceding SQL query, you're done; exit the WHILE loop.\n if (@@ROWCOUNT = 0) break;\n\n -- Otherwise, do whatever you need to do with the current [@databases] table row here.\n print 'Processing @databaseId #' + cast(@databaseId as varchar(50));\nend\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/61967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] |
61,972 |
<p>Best recommendations for accessing and manipulation of sqlite databases from JavaScript.</p>
|
[
{
"answer_id": 11110639,
"author": "Juicy Scripter",
"author_id": 155033,
"author_profile": "https://Stackoverflow.com/users/155033",
"pm_score": 5,
"selected": false,
"text": "sql.js"
},
{
"answer_id": 23878874,
"author": "lovasoa",
"author_id": 3579309,
"author_profile": "https://Stackoverflow.com/users/3579309",
"pm_score": 5,
"selected": false,
"text": "sql.js <script src='js/sql.js'></script>\n<script>\n //Create the database\n var db = new SQL.Database();\n // Run a query without reading the results\n db.run(\"CREATE TABLE test (col1, col2);\");\n // Insert two rows: (1,111) and (2,222)\n db.run(\"INSERT INTO test VALUES (?,?), (?,?)\", [1,111,2,222]);\n\n // Prepare a statement\n var stmt = db.prepare(\"SELECT * FROM test WHERE a BETWEEN $start AND $end\");\n stmt.getAsObject({$start:1, $end:1}); // {col1:1, col2:111}\n\n // Bind new values\n stmt.bind({$start:1, $end:2});\n while(stmt.step()) { //\n var row = stmt.getAsObject();\n // [...] do something with the row of result\n }\n</script>\n var db = openDatabase('mydb', '1.0', 'my first database', 2 * 1024 * 1024);\ndb.transaction(function (tx) {\n tx.executeSql('CREATE TABLE IF NOT EXISTS foo (id unique, text)');\n tx.executeSql('INSERT INTO foo (id, text) VALUES (1, \"synergies\")');\n});\n node-sqlite3 sql.js var sqlite3 = require('sqlite3').verbose();\nvar db = new sqlite3.Database(':memory:');\n\ndb.serialize(function() {\n db.run(\"CREATE TABLE lorem (info TEXT)\");\n\n var stmt = db.prepare(\"INSERT INTO lorem VALUES (?)\");\n for (var i = 0; i < 10; i++) {\n stmt.run(\"Ipsum \" + i);\n }\n stmt.finalize();\n\n db.each(\"SELECT rowid AS id, info FROM lorem\", function(err, row) {\n console.log(row.id + \": \" + row.info);\n });\n});\n\ndb.close();\n sql.js sql.js var fs = require('fs');\nvar SQL = require('sql.js');\nvar filebuffer = fs.readFileSync('test.sqlite');\n\ndb.run(\"INSERT INTO test VALUES (?,?,?)\", [1, 'hello', true]); -- corrected INT to INTO\n\n\nvar data = db.export();\nvar buffer = new Buffer(data);\nfs.writeFileSync(\"filename.sqlite\", buffer);\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/61972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6390/"
] |
61,995 |
<p>Given the following XML:</p>
<pre><code><current>
<login_name>jd</login_name>
</current>
<people>
<person>
<first>John</first>
<last>Doe</last>
<login_name>jd</login_name>
</preson>
<person>
<first>Pierre</first>
<last>Spring</last>
<login_name>ps</login_name>
</preson>
</people>
</code></pre>
<p>How can I get "John Doe" from within the current/login matcher?</p>
<p>I tried the following:</p>
<pre><code><xsl:template match="current/login_name">
<xsl:value-of select="../people/first[login_name = .]"/>
<xsl:text> </xsl:text>
<xsl:value-of select="../people/last[login_name = .]"/>
</xsl:template>
</code></pre>
|
[
{
"answer_id": 62010,
"author": "Kendall Helmstetter Gelner",
"author_id": 6330,
"author_profile": "https://Stackoverflow.com/users/6330",
"pm_score": 0,
"selected": false,
"text": "<xsl:variable name=\"login\" select=\"//current/login_name/text()\"/>\n\n<xsl:template match=\"current/login_name\">\n<xsl:value-of select='concat(../../people/person[login_name=$login]/first,\" \", ../../people/person[login_name=$login]/last)'/>\n\n</xsl:template>\n"
},
{
"answer_id": 62011,
"author": "jelovirt",
"author_id": 2679,
"author_profile": "https://Stackoverflow.com/users/2679",
"pm_score": 2,
"selected": false,
"text": "current() <xsl:template match=\"current/login_name\">\n <xsl:value-of select=\"../../people/person[login_name = current()]/first\"/>\n <xsl:text> </xsl:text>\n <xsl:value-of select=\"../../people/person[login_name = current()]/last\"/>\n</xsl:template>\n <xsl:template match=\"current/login_name\">\n <xsl:for-each select=\"../../people/person[login_name = current()]\">\n <xsl:value-of select=\"first\"/>\n <xsl:text> </xsl:text>\n <xsl:value-of select=\"last\"/>\n </xsl:for-each>\n</xsl:template>\n"
},
{
"answer_id": 62081,
"author": "Matt Large",
"author_id": 2978,
"author_profile": "https://Stackoverflow.com/users/2978",
"pm_score": 0,
"selected": false,
"text": "<xsl:template match=\"login_name[parent::current]\">\n <xsl:variable name=\"login\" select=\"text()\"/>\n <xsl:value-of select='concat(ancestor::people/child::person[login_name=$login]/child::first/text(),\" \",ancestor::people/child::person[login_name=$login]/child::last/text())'/>\n</xsl:template>\n"
},
{
"answer_id": 62429,
"author": "JeniT",
"author_id": 6739,
"author_profile": "https://Stackoverflow.com/users/6739",
"pm_score": 4,
"selected": true,
"text": "<xsl:key name=\"people\" match=\"person\" use=\"login_name\" />\n <person> <login_name> <person> <xsl:template match=\"person\" mode=\"name\">\n <xsl:value-of select=\"concat(first, ' ', last)\" />\n</xsl:template>\n <xsl:template match=\"current/login_name\">\n <xsl:apply-templates select=\"key('people', .)\" mode=\"name\" />\n</xsl:template>\n"
},
{
"answer_id": 77868,
"author": "leekelleher",
"author_id": 12787,
"author_profile": "https://Stackoverflow.com/users/12787",
"pm_score": 1,
"selected": false,
"text": "<xsl:key /> <xsl:template match=\"current/login_name\">\n <xsl:variable name=\"person\" select=\"//people/person[login_name = .]\" />\n <xsl:value-of select=\"concat($person/first, ' ', $person/last)\" />\n</xsl:template>\n <person> concat() <person> </preson>"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/61995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1532/"
] |
62,012 |
<p>I was wondering if anybody knew of a method to configure apache to fall back to returning a static HTML page, should it (Apache) be able to determine that PHP has died? This would provide the developer with a elegant solution to displaying an error page and not (worst case scenario) the source code of the PHP page that should have been executed.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 62748,
"author": "AdamTheHutt",
"author_id": 1103,
"author_profile": "https://Stackoverflow.com/users/1103",
"pm_score": 1,
"selected": false,
"text": "E_FATAL E_PARSE set_error_handler()"
},
{
"answer_id": 65988,
"author": "farzad",
"author_id": 9394,
"author_profile": "https://Stackoverflow.com/users/9394",
"pm_score": 0,
"selected": false,
"text": "1. Install PHP as an Apache module: this way the PHP execution is a thread inside the apache process. So if PHP execution fails, then Apache process fails too. there is no fallback strategy.\n\n2. Install PHP as a CGI script handler: this way Apache will start a new PHP process for each request. If the PHP execution fails, then Apache will know that, and there might be a way to handle the error.\n php.ini"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6085/"
] |
62,013 |
<p>I set up a website to use SqlMembershipProvider as written on <a href="http://msdn.microsoft.com/en-us/library/ms998347.aspx" rel="nofollow noreferrer">this page</a>.</p>
<p>I followed every step. I have the database, I modified the Web.config to use this provider, with the correct connection string, and the authentication mode is set to Forms. Created some users to test with.</p>
<p>I created a Login.aspx and put the Login control on it. Everything works fine until the point that a user can log in. </p>
<p>I call Default.aspx, it gets redirected to Login.aspx, I enter the user and the correct password. No error message, nothing seems to be wrong, but I see again the Login form, to enter the user's login information. However if I check the cookies in the browser, I can see that the cookie with the specified name exists.</p>
<p>I already tried to handle the events by myself and check, what is happening in them, but no success.</p>
<p>I'm using VS2008, Website in filesystem, SQL Express 2005 to store aspnetdb, no role management, tested with K-Meleon, IE7.0 and Chrome.</p>
<p>Any ideas?</p>
<p><strong>Resolution:</strong> After some mailing with Rob we have the ideal solution, which is now the accepted answer.</p>
|
[
{
"answer_id": 62050,
"author": "Leo Moore",
"author_id": 6336,
"author_profile": "https://Stackoverflow.com/users/6336",
"pm_score": 2,
"selected": false,
"text": " <!--Deny all users -->\n <authorization>\n <deny users=\"*\" />\n </authorization>\n <!--Deny all users unless autherticated -->\n <authorization>\n <deny users=\"?\" />\n </authorization>\n <configuration>\n <system.web>\n <authorization>\n <allow roles=\"Admins\"/>\n <deny users=\"*\"/>\n </authorization>\n </system.web>\n</configuration>\n"
},
{
"answer_id": 62084,
"author": "Chris Driver",
"author_id": 5217,
"author_profile": "https://Stackoverflow.com/users/5217",
"pm_score": 0,
"selected": false,
"text": "requireSSL=\"true\""
},
{
"answer_id": 62092,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 3,
"selected": false,
"text": "protected void LoginCtl_Authenticate(object sender, AuthenticateEventArgs e)\n{\n // Check the Credentials against DB\n bool authed = DAL.Authenticate(user, pass);\n e.Authenticated = authed;\n}\n"
},
{
"answer_id": 62104,
"author": "Biri",
"author_id": 968,
"author_profile": "https://Stackoverflow.com/users/968",
"pm_score": 0,
"selected": false,
"text": "<authentication mode=\"Forms\">\n <forms name=\"SqlAuthCookie\" timeout=\"10\" loginUrl=\"Login.aspx\"/>\n</authentication>\n<authorization>\n <deny users=\"?\"/>\n <allow users=\"*\"/>\n</authorization>\n<membership defaultProvider=\"MySqlMembershipProvider\">\n <providers>\n <clear/>\n <add name=\"MySqlMembershipProvider\" connectionStringName=\"MyLocalSQLServer\" applicationName=\"MyAppName\" type=\"System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\"/>\n </providers>\n</membership>\n <connectionStrings>\n <add name=\"MyLocalSQLServer\" connectionString=\"Initial Catalog=aspnetdb;data source=iballanb\\sqlexpress;uid=full;pwd=full;\"/>\n</connectionStrings>\n aspnet_regsql -E -S iballanb\\sqlexpress -A all"
},
{
"answer_id": 65670,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 4,
"selected": true,
"text": "<asp:Login ID=\"Login1\" runat=\"server\" \n MembershipProvider=\"MySqlMembershipProvider\">\n <LayoutTemplate>\n <!-- template code snipped for brevity -->\n </LayoutTemplate>\n</asp:Login>\n <asp:CreateUserWizard ID=\"CreateUserWizard1\" runat=\"server\" \n MembershipProvider=\"MySqlMembershipProvider\">\n <WizardSteps>\n <asp:CreateUserWizardStep runat=\"server\" />\n <asp:CompleteWizardStep runat=\"server\" />\n </WizardSteps>\n </asp:CreateUserWizard>\n"
},
{
"answer_id": 17679617,
"author": "Cabous",
"author_id": 2587849,
"author_profile": "https://Stackoverflow.com/users/2587849",
"pm_score": 0,
"selected": false,
"text": "<forms loginUrl=\"Login.aspx\" protection=\"All\" timeout=\"30\" name=\"AuthTestCookie\"\npath=\"/Authentication\" requireSSL=\"false\" slidingExpiration=\"true\"\ndefaultUrl=\"default.aspx\" cookieless=\"UseCookies\" enableCrossAppRedirects=\"false\"/>\n"
},
{
"answer_id": 33831438,
"author": "Zachary Weber",
"author_id": 2171090,
"author_profile": "https://Stackoverflow.com/users/2171090",
"pm_score": 0,
"selected": false,
"text": "<system.webServer>\n <modules>\n <remove name=\"FormsAuthentication\" />\n </modules>\n</system.webServer>\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/968/"
] |
62,029 |
<p>I use the VS2008 command prompt for builds, TFS access etc. and the cygwin prompt for grep, vi and unix-like tools. Is there any way I can 'import' the vcvars32.bat functionality into the cygwin environment so I can call "tfs checkout" from cygwin itself?</p>
|
[
{
"answer_id": 168447,
"author": "Ted",
"author_id": 8965,
"author_profile": "https://Stackoverflow.com/users/8965",
"pm_score": 3,
"selected": false,
"text": "@echo off\n@REM Select the latest VS Tools\nIF EXIST %VS100COMNTOOLS% (\n CALL \"%VS100COMNTOOLS%\\vsvars32.bat\"\n GOTO :start_term\n)\n\nIF EXIST %VS90COMNTOOLS% (\n CALL \"%VS90COMNTOOLS%\\vsvars32.bat\"\n GOTO :start_term\n)\n\nIF EXIST %VS80COMNTOOLS% (\n CALL \"%VS80COMNTOOLS%\\vsvars32.bat\"\n GOTO :start_term\n)\n\n:start_term\n\nC:\nchdir C:\\cygwin\\bin\nSTART mintty.exe -i /Cygwin-Terminal.ico -\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45603/"
] |
62,034 |
<p>I am trying to write a unit test for an action method which calls the <code>Controller.RedirectToReferrer()</code> method, but am getting a "No referrer available" message.</p>
<p>How can I isolate and mock this method?</p>
|
[
{
"answer_id": 137467,
"author": "James Thigpen",
"author_id": 3285,
"author_profile": "https://Stackoverflow.com/users/3285",
"pm_score": 0,
"selected": false,
"text": "[TestFixture]\npublic class LoginControllerTests : GenericBaseControllerTest<LoginController>\n{\n private string referrer = \"http://www.example.org\";\n protected override IMockRequest BuildRequest()\n {\n var request = new StubRequest(Cookies);\n request.UrlReferrer = referrer;\n\n return request;\n }\n\n protected override IMockResponse BuildResponse(UrlInfo info)\n {\n var response = new StubResponse(info,\n new DefaultUrlBuilder(),\n new StubServerUtility(),\n new RouteMatch(),\n referrer);\n return response;\n }\n RedirectToReferrer"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6413/"
] |
62,038 |
<p>I have a sequence of migrations in a rails app which includes the following steps:</p>
<ol>
<li>Create basic version of the 'user' model</li>
<li>Create an instance of this model - there needs to be at least one initial user in my system so that you can log in and start using it</li>
<li>Update the 'user' model to add a new field / column.</li>
</ol>
<p>Now I'm using "validates_inclusion_of" on this new field/column. This worked fine on my initial development machine, which already had a database with these migrations applied. However, if I go to a fresh machine and run all the migrations, step 2 fails, because validates_inclusion_of fails, because the field from migration 3 hasn't been added to the model class yet.</p>
<p>As a workaround, I can comment out the "validates_..." line, run the migrations, and uncomment it, but that's not nice.</p>
<p>Better would be to re-order my migrations so the user creation (step 2) comes last, after all columns have been added.</p>
<p>I'm a rails newbie though, so I thought I'd ask what the preferred way to handle this situation is :)</p>
|
[
{
"answer_id": 62148,
"author": "Ben Scofield",
"author_id": 6478,
"author_profile": "https://Stackoverflow.com/users/6478",
"pm_score": 4,
"selected": true,
"text": "rake db:schema:load rake db:schema:load"
},
{
"answer_id": 63073,
"author": "Étienne Barrié",
"author_id": 7489,
"author_profile": "https://Stackoverflow.com/users/7489",
"pm_score": 3,
"selected": false,
"text": "class YourMigration < ActiveRecord::Migration\n\n class User < ActiveRecord::Base; end\n\n def self.up\n # User.create(:name => 'admin')\n end\n\nend\n"
},
{
"answer_id": 1463960,
"author": "dznqbit",
"author_id": 44940,
"author_profile": "https://Stackoverflow.com/users/44940",
"pm_score": 0,
"selected": false,
"text": "load(File.join(RAILS_ROOT,\"app/models/user.rb\"))\nclass User < ActiveRecord::Base\n def before_validation; nil; end # clear out the breaking before_validation\n def column1; \"hello\"; end # satisfy validates_inclusion_of :column1\nend\n"
},
{
"answer_id": 62923603,
"author": "Rael Gugelmin Cunha",
"author_id": 1604312,
"author_profile": "https://Stackoverflow.com/users/1604312",
"pm_score": 0,
"selected": false,
"text": "class YourMigration < ActiveRecord::Migration\n\n def up\n user = User.new(name: 'admin')\n user.save(validate: false)\n end\n\nend\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3974/"
] |
62,044 |
<p>I'm trying to construct a find command to process a bunch of files in a directory using two different executables. Unfortunately, <code>-exec</code> on find doesn't allow to use pipe or even <code>\|</code> because the shell interprets that character first. </p>
<p>Here is specifically what I'm trying to do (which doesn't work because pipe ends the find command):</p>
<pre><code>find /path/to/jpgs -type f -exec jhead -v {} | grep 123 \; -print
</code></pre>
|
[
{
"answer_id": 62054,
"author": "Xetius",
"author_id": 274,
"author_profile": "https://Stackoverflow.com/users/274",
"pm_score": 1,
"selected": false,
"text": "find /path/to/jpgs -type f -exec jhead -v {} \\; | grep 123\n find /path/to/jpgs -type f -print -exec jhead -v {} \\; | grep 123\n"
},
{
"answer_id": 62060,
"author": "Martin Marconcini",
"author_id": 2684,
"author_profile": "https://Stackoverflow.com/users/2684",
"pm_score": 8,
"selected": true,
"text": "find /path/to/jpgs -type f -exec sh -c 'jhead -v {} | grep 123' \\; -print\n find -exec some_script {} \\;\n"
},
{
"answer_id": 62066,
"author": "mweerden",
"author_id": 4285,
"author_profile": "https://Stackoverflow.com/users/4285",
"pm_score": 2,
"selected": false,
"text": "-exec sh -c '<shell command>' -exec grep -exec find xargs"
},
{
"answer_id": 62142,
"author": "Palmin",
"author_id": 5949,
"author_profile": "https://Stackoverflow.com/users/5949",
"pm_score": 4,
"selected": false,
"text": "find /path/to/jpgs -type f -print0 | xargs -0 jhead -v | grep 123\n"
},
{
"answer_id": 5131251,
"author": "Dimitar",
"author_id": 636119,
"author_profile": "https://Stackoverflow.com/users/636119",
"pm_score": 2,
"selected": false,
"text": "find for i in dist/*.jar; do echo \">> $i\"; jar -tf \"$i\" | grep BeanException; done\n"
},
{
"answer_id": 48566089,
"author": "linuxgeek",
"author_id": 8906994,
"author_profile": "https://Stackoverflow.com/users/8906994",
"pm_score": 0,
"selected": false,
"text": "root@ifrit findtest # find -type f -exec echo ls $\"|\" cat \\;|sh\nfilename\n root@ifrit findtest # find -type f -exec echo ls $\"|\" cat $\"|\" xargs cat\\;|sh\nh\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3499/"
] |
62,079 |
<p>I am trying to get some accurate runtime comparisons of PHP vs Python (and potentially any other language that I have to include). Timing within a script is not my problem but timing within a script does not account for everything from the moment the request is made to run the script to output.</p>
<blockquote>
<p>1) Is it actually worth taking such things into account?</p>
<p>2) Assuming it is worth taking it into account, how do I do this?</p>
</blockquote>
<p>I'm using a Mac so I've got access to Linux commands and I'm not afraid to compile/create a command to help me, I just don't know how to write such a command.</p>
|
[
{
"answer_id": 62094,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": true,
"text": "$ time script.php\nHI!\n\nreal 0m3.218s\nuser 0m0.080s\nsys 0m0.064s\n"
},
{
"answer_id": 62099,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 1,
"selected": false,
"text": "you@yourmachine:~$ time echo \"hello world\"\nhello world\n\nreal 0m0.000s\nuser 0m0.000s\nsys 0m0.000s\nyou@yourmachine:~$ \n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
] |
62,086 |
<p>I am using Adobe Flex/Air here, but as far as I know this applies to all of JavaScript. I have come across this problem a few times, and there must be an easy solution out there!</p>
<p>Suppose I have the following XML (using e4x):</p>
<pre><code>var xml:XML = <root><example>foo</example></root>
</code></pre>
<p>I can change the contents of the example node using the following code:</p>
<pre><code>xml.example = "bar";
</code></pre>
<p>However, if I have this:</p>
<pre><code>var xml:XML = <root>foo</root>
</code></pre>
<p>How do i change the contents of the root node?</p>
<pre><code>xml = "bar";
</code></pre>
<p>Obviously doesn't work as I'm attempting to assign a string to an XML object.</p>
|
[
{
"answer_id": 62165,
"author": "Loren Segal",
"author_id": 6436,
"author_profile": "https://Stackoverflow.com/users/6436",
"pm_score": 0,
"selected": false,
"text": "var xml = <root>foo</root>; // </fix_syntax_highlighter>\nvar parser = new DOMParser();\nvar serializer = new XMLSerializer();\n\n// Parse xml as DOM document\n// Must inject \"<root></root>\" wrapper because \n// E4X's toString() method doesn't give it to us\n// Not sure if this is expected behaviour.. doesn't seem so to me.\nvar xmlDoc = parser.parseFromString(\"<root>\" + \n xml.toString() + \"</root>\", \"text/xml\");\n\n// Make the change\nxmlDoc.documentElement.firstChild.nodeValue = \"CHANGED\";\n\n// Serialize back to string and then to E4X XML()\nxml = new XML(serializer.serializeToString(xmlDoc));\n"
},
{
"answer_id": 62926,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 4,
"selected": true,
"text": "node = textInput.text;\n node node setChildren XML node.setChildren(textInput.text)\n"
},
{
"answer_id": 63002,
"author": "Grokys",
"author_id": 6448,
"author_profile": "https://Stackoverflow.com/users/6448",
"pm_score": 1,
"selected": false,
"text": "textInput.text = node; \n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6448/"
] |
62,137 |
<p>I've just heard the term covered index in some database discussion - what does it mean?</p>
|
[
{
"answer_id": 62140,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 7,
"selected": true,
"text": "SELECT *\nFROM tablename\nWHERE criteria\n SELECT column1, column2\nFROM tablename\nWHERE criteria\n"
},
{
"answer_id": 62143,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 4,
"selected": false,
"text": "CREATE TABLE MyTable\n(\n ID INT IDENTITY PRIMARY KEY, \n Foo INT\n) \n\nCREATE NONCLUSTERED INDEX index1 ON MyTable(ID, Foo)\n\nSELECT ID, Foo FROM MyTable -- All requested data are covered by index\n"
},
{
"answer_id": 37800438,
"author": "Thomas W",
"author_id": 768795,
"author_profile": "https://Stackoverflow.com/users/768795",
"pm_score": 2,
"selected": false,
"text": "select oi.title, c.name, c.address\nfrom porderitem poi\njoin porder po on po.id = poi.fk_order\njoin customer c on c.id = po.fk_customer\nwhere po.orderdate > ? and po.status = 'SHIPPING';\n\ncreate index porder_custitem on porder (orderdate, id, status, fk_customer);\n"
},
{
"answer_id": 40494784,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "Id (Int), Telephone_Number (Int), Name (VARCHAR), Address (VARCHAR)\n Id SELECT Id FROM mytable WHERE Telephone_Number = '55442233';\n Telephone_Number (Id, Telephone_Number)"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5466/"
] |
62,151 |
<p>I've been wondering what exactly are the principles of how the two properties work. I know the second one is universal and basically doesn't deal with time zones, but can someone explain in detail how they work and which one should be used in what scenario?</p>
|
[
{
"answer_id": 62160,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 10,
"selected": true,
"text": "DateTime.Now DateTime.UtcNow"
},
{
"answer_id": 62164,
"author": "Jeff Atwood",
"author_id": 1,
"author_profile": "https://Stackoverflow.com/users/1",
"pm_score": 7,
"selected": false,
"text": "DateTime.UtcNow"
},
{
"answer_id": 76542,
"author": "Carl Camera",
"author_id": 12804,
"author_profile": "https://Stackoverflow.com/users/12804",
"pm_score": 5,
"selected": false,
"text": "DateTime.Now DateTime.UtcNow DateTime DateTime.UtcNow TimeSpan TimeSpan DateTime.Now() DateTime.UtcNow() TimeSpan String"
},
{
"answer_id": 572968,
"author": "Magnus Krisell",
"author_id": 69311,
"author_profile": "https://Stackoverflow.com/users/69311",
"pm_score": 6,
"selected": false,
"text": "DateTime.UtcNow DateTime.Now DateTime.Now DateTime.Now"
},
{
"answer_id": 30132890,
"author": "Ted Bigham",
"author_id": 868121,
"author_profile": "https://Stackoverflow.com/users/868121",
"pm_score": 5,
"selected": false,
"text": "Kind Now UtcNow Ticks Now UtcNow DateTime.UtcNow Ticks Kind Utc DateTime.Now Ticks Kind Local Kind DateTime DateTime utc = DateTime.UtcNow;\n DateTime now = DateTime.Now;\n Debug.Log (utc + \" \" + utc.Kind); // 05/20/2015 17:19:27 Utc\n Debug.Log (now + \" \" + now.Kind); // 05/20/2015 10:19:27 Local\n\n Debug.Log (utc.Ticks); // 635677391678617830\n Debug.Log (now.Ticks); // 635677139678617840\n\n now = now.AddHours(1);\n TimeSpan diff = utc - now;\n Debug.Log (diff); // 05:59:59.9999990\n\n Debug.Log (utc < now); // false\n Debug.Log (utc == now); // false\n Debug.Log (utc > now); // true\n\n Debug.Log (utc.ToUniversalTime() < now.ToUniversalTime()); // true\n Debug.Log (utc.ToUniversalTime() == now.ToUniversalTime()); // false\n Debug.Log (utc.ToUniversalTime() > now.ToUniversalTime()); // false\n Debug.Log (utc.ToUniversalTime() - now.ToUniversalTime()); // -01:00:00.0000010\n Timespan Kind DateTime Kind=Utc DateTime.UtcNow"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1801/"
] |
62,153 |
<p>Several times now I've been faced with plans from a team that wants to build their own bug tracking system - Not as a product, but as an internal tool.</p>
<p>The arguments I've heard in favous are usually along the lines of :</p>
<ul>
<li>Wanting to 'eat our own dog food' in terms of some internally built web framework</li>
<li>Needing some highly specialised report, or the ability to tweak some feature in some allegedly unique way</li>
<li>Believing that it isn't difficult to build a bug tracking system</li>
</ul>
<p>What arguments might you use to support buying an existing bug tracking system? In particular, what features sound easy but turn out hard to implement, or are difficult and important but often overlooked?</p>
|
[
{
"answer_id": 180008,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 7,
"selected": true,
"text": " Trac: 44 KLoC, 10 Person Years, $577,003\nBugzilla: 54 KLoC, 13 Person Years, $714,437\n Redmine: 171 KLoC, 44 Person Years, $2,400,723\n Mantis: 182 KLoC, 47 Person Years, $2,562,978\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
] |
62,188 |
<p>To commemorate the public launch of Stack Overflow, what's the shortest code to cause a stack overflow? Any language welcome.</p>
<p>ETA: Just to be clear on this question, seeing as I'm an occasional Scheme user: tail-call "recursion" is really iteration, and any solution which can be converted to an iterative solution relatively trivially by a decent compiler won't be counted. :-P</p>
<p>ETA2: I've now selected a “best answer”; see <a href="https://stackoverflow.com/questions/62188/stack-overflow-code-golf/71833#71833">this post</a> for rationale. Thanks to everyone who contributed! :-)</p>
|
[
{
"answer_id": 62189,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 7,
"selected": false,
"text": "push eax\njmp short $-1\n 50 EB FD call $\n E8 FD FF"
},
{
"answer_id": 62191,
"author": "Niyaz",
"author_id": 184,
"author_profile": "https://Stackoverflow.com/users/184",
"pm_score": 0,
"selected": false,
"text": "int overflow(int n)\n{\n return overflow(1);\n}\n"
},
{
"answer_id": 62195,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 6,
"selected": false,
"text": "public int Foo { get { return Foo; } }\n"
},
{
"answer_id": 62205,
"author": "Serafina Brocious",
"author_id": 4977,
"author_profile": "https://Stackoverflow.com/users/4977",
"pm_score": 4,
"selected": false,
"text": "so=lambda:so();so()\n def so():so()\nso()\n o=lambda:map(o,o());o()\n"
},
{
"answer_id": 62209,
"author": "TK.",
"author_id": 1816,
"author_profile": "https://Stackoverflow.com/users/1816",
"pm_score": 2,
"selected": false,
"text": " PUSH \n CALL overflow \n"
},
{
"answer_id": 62213,
"author": "Agnel Kurian",
"author_id": 45603,
"author_profile": "https://Stackoverflow.com/users/45603",
"pm_score": 0,
"selected": false,
"text": "int main(){\n int a = 20;\n return main();\n}\n"
},
{
"answer_id": 62215,
"author": "Huppie",
"author_id": 1830,
"author_profile": "https://Stackoverflow.com/users/1830",
"pm_score": 0,
"selected": false,
"text": "function i(){ i(); }\ni();\n int main(){\n int (*f)() = &main;\n f();\n}\n"
},
{
"answer_id": 62217,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 5,
"selected": false,
"text": "recursion = n. See recursion.\n"
},
{
"answer_id": 62221,
"author": "Agnel Kurian",
"author_id": 45603,
"author_profile": "https://Stackoverflow.com/users/45603",
"pm_score": 1,
"selected": false,
"text": "/* In C/C++ (second attempt) */\n\nint main(){\n int a = main() + 1;\n return a;\n}\n"
},
{
"answer_id": 62231,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 4,
"selected": false,
"text": "void o(){o();o();}\n"
},
{
"answer_id": 62233,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 0,
"selected": false,
"text": "int s(){\n return s();\n}\n"
},
{
"answer_id": 62243,
"author": "Serafina Brocious",
"author_id": 4977,
"author_profile": "https://Stackoverflow.com/users/4977",
"pm_score": 2,
"selected": false,
"text": "loop: ldc.i4.0\nbr loop\n 16 2B FD\n"
},
{
"answer_id": 62244,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 7,
"selected": false,
"text": "throw new StackOverflowException();\n"
},
{
"answer_id": 62318,
"author": "stusmith",
"author_id": 6604,
"author_profile": "https://Stackoverflow.com/users/6604",
"pm_score": 5,
"selected": false,
"text": "10 GOSUB 10\n"
},
{
"answer_id": 62321,
"author": "Serafina Brocious",
"author_id": 4977,
"author_profile": "https://Stackoverflow.com/users/4977",
"pm_score": 7,
"selected": false,
"text": "def o(){[o()]}\n"
},
{
"answer_id": 62323,
"author": "dr_bonzo",
"author_id": 6657,
"author_profile": "https://Stackoverflow.com/users/6657",
"pm_score": 2,
"selected": false,
"text": "def s() s() end; s()\n"
},
{
"answer_id": 62370,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 5,
"selected": false,
"text": "template <int i>\nclass Overflow {\n typedef typename Overflow<i + 1>::type type;\n};\n\ntypedef Overflow<0>::type Kaboom;\n"
},
{
"answer_id": 62379,
"author": "Ozgur Ozcitak",
"author_id": 976,
"author_profile": "https://Stackoverflow.com/users/976",
"pm_score": 2,
"selected": false,
"text": "(defun x() (x)) (x)\n"
},
{
"answer_id": 62399,
"author": "Andrew Johnson",
"author_id": 5109,
"author_profile": "https://Stackoverflow.com/users/5109",
"pm_score": 2,
"selected": false,
"text": "a{return a*a;};\n gcc -D\"a=main()\" so.c\n main() {\n return main()*main();\n}\n"
},
{
"answer_id": 62402,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 1,
"selected": false,
"text": "class Foo { public Foo() {new Foo(); } }\n"
},
{
"answer_id": 62407,
"author": "asksol",
"author_id": 5577,
"author_profile": "https://Stackoverflow.com/users/5577",
"pm_score": 4,
"selected": false,
"text": "$_=sub{&$_};&$_\n i(){ i;};i\n"
},
{
"answer_id": 62412,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 1,
"selected": false,
"text": "program Project1;\n{$APPTYPE CONSOLE}\nuses SysUtils;\n\nbegin\n raise EStackOverflow.Create('Stack Overflow');\nend.\n"
},
{
"answer_id": 62420,
"author": "Sean Cameron",
"author_id": 6692,
"author_profile": "https://Stackoverflow.com/users/6692",
"pm_score": 0,
"selected": false,
"text": "Poke(0)\n"
},
{
"answer_id": 62432,
"author": "Manrico Corazzi",
"author_id": 4690,
"author_profile": "https://Stackoverflow.com/users/4690",
"pm_score": 2,
"selected": false,
"text": "public class SO \n{ \n private void killme()\n {\n killme();\n }\n\n public static void main(String[] args) \n { \n new SO().killme(); \n } \n}\n class SO\n{\n public static void main(String[] a)\n {\n main(null);\n }\n}\n"
},
{
"answer_id": 62468,
"author": "Antti Kissaniemi",
"author_id": 2948,
"author_profile": "https://Stackoverflow.com/users/2948",
"pm_score": 1,
"selected": false,
"text": "main(){main();}\n antti@blah:~$ gcc so.c -o so\nantti@blah:~$ ./so\nSegmentation fault (core dumped)\n"
},
{
"answer_id": 62568,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 0,
"selected": false,
"text": "c(N)->c(N+1)+c(N-1).\nc(0).\n O(n^2) O(n)"
},
{
"answer_id": 62596,
"author": "Leo Lännenmäki",
"author_id": 2451,
"author_profile": "https://Stackoverflow.com/users/2451",
"pm_score": 1,
"selected": false,
"text": "(function i(){ i(); })()\n"
},
{
"answer_id": 62609,
"author": "Kinjal Dixit",
"author_id": 6629,
"author_profile": "https://Stackoverflow.com/users/6629",
"pm_score": 0,
"selected": false,
"text": "a()\n{\n b();\n}\nb()\n{\n a();\n}\n"
},
{
"answer_id": 62733,
"author": "Michal",
"author_id": 7135,
"author_profile": "https://Stackoverflow.com/users/7135",
"pm_score": 1,
"selected": false,
"text": "class X {\npublic static void main(String[] args) {\n main(null);\n}}\n class X{public static void main(String[]a){main(null);}}\n class X{public static void main(String[]a){main(a);}}\n"
},
{
"answer_id": 62809,
"author": "Anders Sandvig",
"author_id": 1709,
"author_profile": "https://Stackoverflow.com/users/1709",
"pm_score": 3,
"selected": false,
"text": " label:\n pusha\n jmp label\n label:\n call label\n"
},
{
"answer_id": 62917,
"author": "JWHEAT",
"author_id": 7079,
"author_profile": "https://Stackoverflow.com/users/7079",
"pm_score": 0,
"selected": false,
"text": "function a() { a(); } a();\n"
},
{
"answer_id": 63020,
"author": "Tim Ring",
"author_id": 3685,
"author_profile": "https://Stackoverflow.com/users/3685",
"pm_score": 2,
"selected": false,
"text": "OK\n10 i=0\n20 print i;\n30 i=i+1\n40 gosub 20\nrun\n 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21\n 22 23 24 25 26 27 28 29 30 31 32 33\nOut of memory in 30\nOk\n"
},
{
"answer_id": 63025,
"author": "bgee",
"author_id": 7003,
"author_profile": "https://Stackoverflow.com/users/7003",
"pm_score": 0,
"selected": false,
"text": "//lang = C++... it's joke, of course\n//Pay attention how \nvoid StackOverflow(){printf(\"StackOverflow!\");}\nint main()\n{\n StackOverflow(); //called StackOverflow, right?\n}\n"
},
{
"answer_id": 63061,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 2,
"selected": false,
"text": "let rec f n =\n f (n)\n let rec f n =\n f (f(n))\n"
},
{
"answer_id": 63116,
"author": "Jesse Millikan",
"author_id": 7526,
"author_profile": "https://Stackoverflow.com/users/7526",
"pm_score": 1,
"selected": false,
"text": "[dx]dx\n"
},
{
"answer_id": 63137,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "def i()i()end;i()\n"
},
{
"answer_id": 63269,
"author": "Evan DeMond",
"author_id": 7695,
"author_profile": "https://Stackoverflow.com/users/7695",
"pm_score": 2,
"selected": false,
"text": "function f()return 1+f()end f()\n"
},
{
"answer_id": 63290,
"author": "tomdemuyt",
"author_id": 7602,
"author_profile": "https://Stackoverflow.com/users/7602",
"pm_score": 2,
"selected": false,
"text": "****** B A T C H R E C U R S I O N exceeds STACK limits ******\nRecursion Count=1240, Stack Usage=90 percent\n****** B A T C H PROCESSING IS A B O R T E D ******\n"
},
{
"answer_id": 63353,
"author": "davidnicol",
"author_id": 7420,
"author_profile": "https://Stackoverflow.com/users/7420",
"pm_score": 0,
"selected": false,
"text": "sub x{&x}x\n"
},
{
"answer_id": 63400,
"author": "davidnicol",
"author_id": 7420,
"author_profile": "https://Stackoverflow.com/users/7420",
"pm_score": 0,
"selected": false,
"text": "copy CON so.bat\nso.bat\n^Z\nso.bat\n"
},
{
"answer_id": 63519,
"author": "Misha",
"author_id": 7557,
"author_profile": "https://Stackoverflow.com/users/7557",
"pm_score": 3,
"selected": false,
"text": "class X{public static void main(String[]a){main(a);}}\n"
},
{
"answer_id": 63529,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 2,
"selected": false,
"text": "(define (x)\n ((x)))\n\n(x)\n"
},
{
"answer_id": 63534,
"author": "Antti Kissaniemi",
"author_id": 2948,
"author_profile": "https://Stackoverflow.com/users/2948",
"pm_score": 1,
"selected": false,
"text": "#!sh\n./so\n antti@blah:~$ ./so\n[disconnected]\n"
},
{
"answer_id": 63812,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 4,
"selected": false,
"text": "#include <stdio.h>\n#include <alloca.h>\n#include <sys/resource.h>\nint main(int argc, char *argv[]) {\n struct rlimit rl = {0};\n getrlimit(RLIMIT_STACK, &rl);\n (void) alloca(rl.rlim_cur);\n printf(\"Goodbye, world\\n\");\n return 0;\n}\n"
},
{
"answer_id": 63848,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 0,
"selected": false,
"text": "Action a = null;\na = () => a();\na();\n"
},
{
"answer_id": 63873,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "xor esp, esp\nret\n"
},
{
"answer_id": 64290,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "\\#!/bin/bash\nof() { of; }\nof\n"
},
{
"answer_id": 64331,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "def a;a;end;a\n"
},
{
"answer_id": 64346,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "sh $0\n"
},
{
"answer_id": 64395,
"author": "Chris Broadfoot",
"author_id": 3947,
"author_profile": "https://Stackoverflow.com/users/3947",
"pm_score": 4,
"selected": false,
"text": "main()\n Caught: java.lang.StackOverflowError\n at stack.main(stack.groovy)\n at stack.run(stack.groovy:1)\n ...\n"
},
{
"answer_id": 64425,
"author": "Jonas Engström",
"author_id": 7634,
"author_profile": "https://Stackoverflow.com/users/7634",
"pm_score": 0,
"selected": false,
"text": "push cs\npush $-1\nret\n"
},
{
"answer_id": 64573,
"author": "botismarius",
"author_id": 4528,
"author_profile": "https://Stackoverflow.com/users/4528",
"pm_score": 1,
"selected": false,
"text": "\ncall $\n \nint main( ) {\n return main( );\n}\n"
},
{
"answer_id": 64707,
"author": "Dennis Munsie",
"author_id": 8728,
"author_profile": "https://Stackoverflow.com/users/8728",
"pm_score": 5,
"selected": false,
"text": "rst 00\n"
},
{
"answer_id": 64830,
"author": "Travis Wilson",
"author_id": 8735,
"author_profile": "https://Stackoverflow.com/users/8735",
"pm_score": 4,
"selected": false,
"text": "eval(i='eval(i)');\n"
},
{
"answer_id": 65046,
"author": "mattiast",
"author_id": 8272,
"author_profile": "https://Stackoverflow.com/users/8272",
"pm_score": 2,
"selected": false,
"text": "let x = x\nprint x\n"
},
{
"answer_id": 65224,
"author": "Joshua Carmody",
"author_id": 8409,
"author_profile": "https://Stackoverflow.com/users/8409",
"pm_score": 2,
"selected": false,
"text": "<cfinclude template=\"#ListLast(CGI.SCRIPT_NAME, \"/\\\")#\">\n"
},
{
"answer_id": 65317,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 0,
"selected": false,
"text": "Function StackOverflow() As Integer\n Return StackOverflow()\nEnd Function\n"
},
{
"answer_id": 65628,
"author": "Joseph Bui",
"author_id": 3275,
"author_profile": "https://Stackoverflow.com/users/3275",
"pm_score": 1,
"selected": false,
"text": "proc a {} a\n proc a {} \"a;a\"\n"
},
{
"answer_id": 66095,
"author": "Alex M",
"author_id": 9652,
"author_profile": "https://Stackoverflow.com/users/9652",
"pm_score": 2,
"selected": false,
"text": ": a 1 recurse ; a\n gforth : a 1 recurse ; a \n*the terminal*:1: Return stack overflow\n: a 1 recurse ; a\n ^\nBacktrace:\n"
},
{
"answer_id": 66370,
"author": "Kemal",
"author_id": 7506,
"author_profile": "https://Stackoverflow.com/users/7506",
"pm_score": 5,
"selected": false,
"text": "<?\nrequire(__FILE__);\n"
},
{
"answer_id": 66392,
"author": "PersistenceOfVision",
"author_id": 6721,
"author_profile": "https://Stackoverflow.com/users/6721",
"pm_score": 0,
"selected": false,
"text": " org $100\nLoop nop\n jsr Loop\n"
},
{
"answer_id": 66483,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "int x[100000000000];\n"
},
{
"answer_id": 66616,
"author": "Thevs",
"author_id": 8559,
"author_profile": "https://Stackoverflow.com/users/8559",
"pm_score": 0,
"selected": false,
"text": "setTimeout(1, function() {while(1) a=1;});\n"
},
{
"answer_id": 66663,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 2,
"selected": false,
"text": "class _{static void Main(){Main();}}\n"
},
{
"answer_id": 66744,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 9,
"selected": true,
"text": "1\n"
},
{
"answer_id": 67634,
"author": "clahey",
"author_id": 8453,
"author_profile": "https://Stackoverflow.com/users/8453",
"pm_score": 2,
"selected": false,
"text": ":\n"
},
{
"answer_id": 68055,
"author": "user4010",
"author_id": 4010,
"author_profile": "https://Stackoverflow.com/users/4010",
"pm_score": 2,
"selected": false,
"text": ":(){ :|:& };:\n"
},
{
"answer_id": 68229,
"author": "RFelix",
"author_id": 10582,
"author_profile": "https://Stackoverflow.com/users/10582",
"pm_score": 0,
"selected": false,
"text": "class Overflow\n def initialize\n Overflow.new\n end\nend\n\nOverflow.new\n"
},
{
"answer_id": 68442,
"author": "Alex M",
"author_id": 9652,
"author_profile": "https://Stackoverflow.com/users/9652",
"pm_score": 5,
"selected": false,
"text": "\\def~{~.}~\n \\end\\end\n"
},
{
"answer_id": 68521,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": -1,
"selected": false,
"text": "enum A{B.values()}\nenum B{A.values()}\n"
},
{
"answer_id": 68586,
"author": "user10178",
"author_id": 10178,
"author_profile": "https://Stackoverflow.com/users/10178",
"pm_score": 1,
"selected": false,
"text": "static void Main(){Main();}\n"
},
{
"answer_id": 68960,
"author": "Ryan Fox",
"author_id": 55,
"author_profile": "https://Stackoverflow.com/users/55",
"pm_score": 4,
"selected": false,
"text": "Person JeffAtwood;\nPerson JoelSpolsky;\nJeffAtwood.TalkTo(JoelSpolsky);\n"
},
{
"answer_id": 69003,
"author": "Jude Allred",
"author_id": 1388,
"author_profile": "https://Stackoverflow.com/users/1388",
"pm_score": 4,
"selected": false,
"text": "call s\n"
},
{
"answer_id": 69369,
"author": "user11039",
"author_id": 11039,
"author_profile": "https://Stackoverflow.com/users/11039",
"pm_score": 0,
"selected": false,
"text": "static void Main()\n{\n Main();\n}\n"
},
{
"answer_id": 69577,
"author": "mike511",
"author_id": 9593,
"author_profile": "https://Stackoverflow.com/users/9593",
"pm_score": 0,
"selected": false,
"text": "mov sp,0\n"
},
{
"answer_id": 69626,
"author": "Mark Nold",
"author_id": 4134,
"author_profile": "https://Stackoverflow.com/users/4134",
"pm_score": 0,
"selected": false,
"text": "%!PS\n/increase {1 add} def\n1 increase\n(so.ps) run\n"
},
{
"answer_id": 70176,
"author": "Wouter Coekaerts",
"author_id": 3432,
"author_profile": "https://Stackoverflow.com/users/3432",
"pm_score": 2,
"selected": false,
"text": "/eval $L\n"
},
{
"answer_id": 70398,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 6,
"selected": false,
"text": "so\n"
},
{
"answer_id": 70950,
"author": "RFelix",
"author_id": 10582,
"author_profile": "https://Stackoverflow.com/users/10582",
"pm_score": 1,
"selected": false,
"text": "(a=lambda{a.call}).call\n"
},
{
"answer_id": 71833,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 3,
"selected": false,
"text": "((Y (lambda (f) (lambda (x) (f (f x))))) #f)\n"
},
{
"answer_id": 71964,
"author": "Leo Lännenmäki",
"author_id": 2451,
"author_profile": "https://Stackoverflow.com/users/2451",
"pm_score": 1,
"selected": false,
"text": "(function() { arguments.callee() })()\n"
},
{
"answer_id": 72993,
"author": "Javier",
"author_id": 12449,
"author_profile": "https://Stackoverflow.com/users/12449",
"pm_score": 1,
"selected": false,
"text": "\nPublic Property Let x(ByVal y As Long)\n x = y\nEnd Property\n\nPrivate Sub Class_Initialize()\n x = 0\nEnd Sub\n"
},
{
"answer_id": 75948,
"author": "squadette",
"author_id": 7754,
"author_profile": "https://Stackoverflow.com/users/7754",
"pm_score": 1,
"selected": false,
"text": "main(){main()}\n"
},
{
"answer_id": 78084,
"author": "defmeta",
"author_id": 10875,
"author_profile": "https://Stackoverflow.com/users/10875",
"pm_score": 0,
"selected": false,
"text": "var i=[];\ni[i.push(i)]=i;\ntrace(i);\n"
},
{
"answer_id": 78911,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "S (K (S I I)) (S (S (K S) K) (K (S I I)))\n"
},
{
"answer_id": 80350,
"author": "matyr",
"author_id": 15066,
"author_profile": "https://Stackoverflow.com/users/15066",
"pm_score": 2,
"selected": false,
"text": "run()\n"
},
{
"answer_id": 90506,
"author": "dsm",
"author_id": 7780,
"author_profile": "https://Stackoverflow.com/users/7780",
"pm_score": 1,
"selected": false,
"text": "`$0`\n $0"
},
{
"answer_id": 570789,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "echo @call b.cmd > b.cmd & b\n"
},
{
"answer_id": 583659,
"author": "Kaarel",
"author_id": 12547,
"author_profile": "https://Stackoverflow.com/users/12547",
"pm_score": 0,
"selected": false,
"text": "p :- p, q.\n:- p.\n"
},
{
"answer_id": 597337,
"author": "Oscar Cabrero",
"author_id": 14440,
"author_profile": "https://Stackoverflow.com/users/14440",
"pm_score": -1,
"selected": false,
"text": "Redmond.Microsoft.Core.Windows.Start()\n"
},
{
"answer_id": 597372,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": 7,
"selected": false,
"text": "overflow\n PUSH\n 0000 0000 0000 0101\n CALL overflow\n 1110 1100 0000 0000\n 0000 0000 0000 0000\n CALL $\n1110 1100 0000 0000\n0000 0000 0000 0000\n RCALL $\n1101 1000 0000 0000\n CALL $\n1001 0000 0000\n CALL $\n0101 0000\n"
},
{
"answer_id": 605938,
"author": "Jonas Kölker",
"author_id": 58668,
"author_profile": "https://Stackoverflow.com/users/58668",
"pm_score": 1,
"selected": false,
"text": "fix (1+)\n λ n → n + 1 fix f = (let x = f(x) in x)\n fix (1+)\n (1+) ((1+) ((1+) ...))\n fix (+1)\n"
},
{
"answer_id": 779109,
"author": "BCS",
"author_id": 1343,
"author_profile": "https://Stackoverflow.com/users/1343",
"pm_score": 0,
"selected": false,
"text": "class C(int i) { C!(i+1) c; }\nC!(1) c;\n"
},
{
"answer_id": 848505,
"author": "Tolgahan Albayrak",
"author_id": 104468,
"author_profile": "https://Stackoverflow.com/users/104468",
"pm_score": 0,
"selected": false,
"text": "_asm t: call t;\n"
},
{
"answer_id": 973947,
"author": "RCIX",
"author_id": 117069,
"author_profile": "https://Stackoverflow.com/users/117069",
"pm_score": 1,
"selected": false,
"text": "function c()c()end;\n"
},
{
"answer_id": 1735693,
"author": "Graphics Noob",
"author_id": 127669,
"author_profile": "https://Stackoverflow.com/users/127669",
"pm_score": 0,
"selected": false,
"text": "let rec f l = f l@l;;\n f # f [0];;\nStack overflow during evaluation (looping recursion?).\n"
},
{
"answer_id": 1738894,
"author": "Graphics Noob",
"author_id": 127669,
"author_profile": "https://Stackoverflow.com/users/127669",
"pm_score": 0,
"selected": false,
"text": "+[>+]\n"
},
{
"answer_id": 1985750,
"author": "Tim Ring",
"author_id": 3685,
"author_profile": "https://Stackoverflow.com/users/3685",
"pm_score": 0,
"selected": false,
"text": ".org 1000\nloop: call loop\n"
},
{
"answer_id": 2101846,
"author": "danielschemmel",
"author_id": 65678,
"author_profile": "https://Stackoverflow.com/users/65678",
"pm_score": 2,
"selected": false,
"text": "class Program\n{\n class StackOverflowExceptionOverflow : System.Exception\n {\n public StackOverflowExceptionOverflow()\n {\n throw new StackOverflowExceptionOverflow();\n }\n }\n\n static void Main(string[] args)\n {\n throw new StackOverflowExceptionOverflow();\n }\n}\n"
},
{
"answer_id": 2173039,
"author": "finnw",
"author_id": 12048,
"author_profile": "https://Stackoverflow.com/users/12048",
"pm_score": 0,
"selected": false,
"text": "def a(x);x.gsub(/./){a$0};end;a\"x\"\n"
},
{
"answer_id": 2216158,
"author": "KirarinSnow",
"author_id": 174376,
"author_profile": "https://Stackoverflow.com/users/174376",
"pm_score": 2,
"selected": false,
"text": "{/}loop\n GS>{/}loop\nError: /stackoverflow in --execute--\nOperand stack:\n --nostringval--\nExecution stack:\n %interp_exit .runexec2 --nostringval-- --nostringval-- --nostringval-- 2 %stopped_push --nostringval-- --nostringval-- %loop_continue 1753 2 3 %oparray_pop --nostringval-- --nostringval-- false 1 %stopped_push .runexec2 --nostringval-- --nostringval-- --nostringval-- 2 %stopped_push --nostringval-- --nostringval-- %loop_continue\nDictionary stack:\n --dict:1150/1684(ro)(G)-- --dict:0/20(G)-- --dict:70/200(L)--\nCurrent allocation mode is local\nLast OS error: 11\nCurrent file position is 8\n [{/[aload 8 1 roll]cvx exec}aload 8 1 roll]cvx exec\n"
},
{
"answer_id": 2343769,
"author": "Carlos Gutiérrez",
"author_id": 237761,
"author_profile": "https://Stackoverflow.com/users/237761",
"pm_score": 0,
"selected": false,
"text": ":a\n@call :a\n"
},
{
"answer_id": 2344985,
"author": "N 1.1",
"author_id": 280730,
"author_profile": "https://Stackoverflow.com/users/280730",
"pm_score": 0,
"selected": false,
"text": "main(){\n main();\n}"
},
{
"answer_id": 2348396,
"author": "Brent Bradburn",
"author_id": 86967,
"author_profile": "https://Stackoverflow.com/users/86967",
"pm_score": 1,
"selected": false,
"text": "a:\n make\n $ make\n b ## ties the winning entry with only one character (does not require end-of-line)\n $ ( PATH=$PATH:. ; b )\n"
},
{
"answer_id": 2348499,
"author": "Draemon",
"author_id": 26334,
"author_profile": "https://Stackoverflow.com/users/26334",
"pm_score": 2,
"selected": false,
"text": "class X{static{new X();}{new X();}}\n static {\n new X();\n}\n {\n new X();\n}\n"
},
{
"answer_id": 2396631,
"author": "F'x",
"author_id": 143495,
"author_profile": "https://Stackoverflow.com/users/143495",
"pm_score": 0,
"selected": false,
"text": "real n(0)\nn(1)=0\nend\n call main\nend\n -fno-underscoring"
},
{
"answer_id": 2679742,
"author": "Juliet",
"author_id": 40516,
"author_profile": "https://Stackoverflow.com/users/40516",
"pm_score": 6,
"selected": false,
"text": "// v___v\nlet rec f o = f(o);(o)\n// ['---']\n// -\"---\"-\n"
},
{
"answer_id": 2904167,
"author": "jkramer",
"author_id": 12523,
"author_profile": "https://Stackoverflow.com/users/12523",
"pm_score": 0,
"selected": false,
"text": "main = print $ x 1 where x y = x y + 1\n"
},
{
"answer_id": 3029226,
"author": "wash",
"author_id": 336878,
"author_profile": "https://Stackoverflow.com/users/336878",
"pm_score": 0,
"selected": false,
"text": "fib←{\n ⍵∊0 1:⍵\n +/∇¨⍵-1 2\n}\n"
},
{
"answer_id": 3029262,
"author": "Daniel Băluţă",
"author_id": 328594,
"author_profile": "https://Stackoverflow.com/users/328594",
"pm_score": 0,
"selected": false,
"text": "int main(void) { return main(); }\n"
},
{
"answer_id": 3230616,
"author": "Artur Gaspar",
"author_id": 286655,
"author_profile": "https://Stackoverflow.com/users/286655",
"pm_score": 0,
"selected": false,
"text": "import sys \nsys.setrecursionlimit(sys.maxint) \ndef so(): \n so() \nso()\n"
},
{
"answer_id": 3272869,
"author": "Ming-Tang",
"author_id": 303939,
"author_profile": "https://Stackoverflow.com/users/303939",
"pm_score": 2,
"selected": false,
"text": "class A{{new A();}static{new A();}}\n Exception in thread \"main\" java.lang.StackOverflowError\n at A.<init>(A.java:1)\n ......\n at A.<init>(A.java:1)\nCould not find the main class: A. Program will exit.\n"
},
{
"answer_id": 3343950,
"author": "st0le",
"author_id": 216517,
"author_profile": "https://Stackoverflow.com/users/216517",
"pm_score": 0,
"selected": false,
"text": "eval(t=\"eval(t)\")\n t=\"Execute(t)\":Execute(t)\n"
},
{
"answer_id": 3605353,
"author": "Ming-Tang",
"author_id": 303939,
"author_profile": "https://Stackoverflow.com/users/303939",
"pm_score": 2,
"selected": false,
"text": "template<int n>struct f{f<n+1>a;};f<0>::a;\n $ g++ test.cpp;\ntest.cpp:1: error: template instantiation depth exceeds maximum of 500 (use -ftemplate-depth-NN to increase the maximum) instantiating ‘struct f<500>’\ntest.cpp:1: instantiated from ‘f<499>’\ntest.cpp:1: instantiated from ‘f<498>’\n......\n main"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13/"
] |
62,201 |
<p>I've got a rails application where users have to log in. Therefore in order for the application to be usable, there must be one initial user in the system for the first person to log in with (they can then create subsequent users). Up to now I've used a migration to add a special user to the database.</p>
<p>After asking <a href="https://stackoverflow.com/questions/62038/rails-model-validators-break-earlier-migrations">this question</a>, it seems that I should be using db:schema:load, rather than running the migrations, to set up fresh databases on new development machines. Unfortunately, this doesn't seem to include the migrations which insert data, only those which set up tables, keys etc.</p>
<p>My question is, what's the best way to handle this situation:</p>
<ol>
<li>Is there a way to get d:s:l to include data-insertion migrations?</li>
<li>Should I not be using migrations at all to insert data this way?</li>
<li>Should I not be pre-populating the database with data at all? Should I update the application code so that it handles the case where there are no users gracefully, and lets an initial user account be created live from within the application?</li>
<li>Any other options? :)</li>
</ol>
|
[
{
"answer_id": 62262,
"author": "Trevor Stow",
"author_id": 75093,
"author_profile": "https://Stackoverflow.com/users/75093",
"pm_score": 2,
"selected": false,
"text": "script/console production\n User.create(:name => \"Whoever\", :password => \"whichever\")\n"
},
{
"answer_id": 62528,
"author": "Aaron Wheeler",
"author_id": 6940,
"author_profile": "https://Stackoverflow.com/users/6940",
"pm_score": 6,
"selected": false,
"text": "\n namespace :bootstrap do\n desc \"Add the default user\"\n task :default_user => :environment do\n User.create( :name => 'default', :password => 'password' )\n end\n\n desc \"Create the default comment\"\n task :default_comment => :environment do\n Comment.create( :title => 'Title', :body => 'First post!' )\n end\n\n desc \"Run all bootstrapping tasks\"\n task :all => [:default_user, :default_comment]\n end\n"
},
{
"answer_id": 64822,
"author": "Jay Stramel",
"author_id": 3547,
"author_profile": "https://Stackoverflow.com/users/3547",
"pm_score": 5,
"selected": false,
"text": "namespace :db do\n desc \"This loads the development data.\"\n task :seed => :environment do\n require 'active_record/fixtures'\n Dir.glob(RAILS_ROOT + '/db/fixtures/*.yml').each do |file|\n base_name = File.basename(file, '.*')\n say \"Loading #{base_name}...\"\n Fixtures.create_fixtures('db/fixtures', base_name)\n end\n end\n\n desc \"This drops the db, builds the db, and seeds the data.\"\n task :reseed => [:environment, 'db:reset', 'db:seed']\nend\n test:\n customer_id: 1\n name: \"Test Guy\"\n email: \"[email protected]\"\n hashed_password: \"656fc0b1c1d1681840816c68e1640f640c6ded12\"\n salt: \"188227600.754087929365988\"\n"
},
{
"answer_id": 14864024,
"author": "Jason Kim",
"author_id": 536890,
"author_profile": "https://Stackoverflow.com/users/536890",
"pm_score": 5,
"selected": false,
"text": "db/seed.rb db/seed.rb User.create(:username => \"moot\", :description => \"king of /b/\") rake db:migrate rake db:seed rake db:setup"
},
{
"answer_id": 21256371,
"author": "frenci",
"author_id": 2273475,
"author_profile": "https://Stackoverflow.com/users/2273475",
"pm_score": 1,
"selected": false,
"text": "db/seed.rb #db/seed.rb\nUser.create( :name => 'default', :password => 'password' )\nComment.create( :title => 'Title', :body => 'First post!' )\n rake db:seed\n [\"bryan\", \"bill\", \"tom\"].each do |name|\n User.create(:name => name, :password => \"password\")\nend\n # ruby encoding: utf-8\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3974/"
] |
62,219 |
<p>As I get more and more namespaces in my solution, the list of using statements at the top of my files grows longer and longer. This is especially the case in my unit tests where for each component that might be called I need to include the using for the interface, the IoC container, and the concrete type. </p>
<p>With upward of 17 lines of usings in my integration test files its just getting downright messy. Does anyone know if theres a way to define a macro for my base using statements? Any other solutions?</p>
|
[
{
"answer_id": 62224,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 3,
"selected": true,
"text": "#region"
},
{
"answer_id": 62453,
"author": "Steve Cooper",
"author_id": 6722,
"author_profile": "https://Stackoverflow.com/users/6722",
"pm_score": 2,
"selected": false,
"text": "using MyCompany.Drawing.Vector.Points;\nusing MyCompany.Drawing.Vector.Shapes;\nusing MyCompany.Drawing.Vector.Transformations;\n MyCompany.Drawing.Vector System.Data System.Drawing System.IO"
},
{
"answer_id": 62717,
"author": "Eugene Katz",
"author_id": 1533,
"author_profile": "https://Stackoverflow.com/users/1533",
"pm_score": 1,
"selected": false,
"text": "using System.Web.UI;\nusing System.Web.Mail;\nusing System.Web.Security;\n... Control ...\n... MailMessage ...\n... Roles ... \n using W = System.Web;\n... W.UI.Control ...\n... W.Mail.MailMessage ...\n... W.Security.Rolse ...\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] |
62,226 |
<p>An instance of class A instantiates a couple of other objects, say for example from class B:</p>
<pre><code>$foo = new B();
</code></pre>
<p>I would like to access A's public class variables from methods within B.</p>
<p>Unless I'm missing something, the only way to do this is to pass the current object to the instances of B:</p>
<pre><code>$foo = new B($this);
</code></pre>
<p>Is this best practice or is there another way to do this?</p>
|
[
{
"answer_id": 76201,
"author": "Peter Bailey",
"author_id": 8815,
"author_profile": "https://Stackoverflow.com/users/8815",
"pm_score": 0,
"selected": false,
"text": "$foo = new B( A::getInstance() );\n"
},
{
"answer_id": 883890,
"author": "Jet",
"author_id": 109480,
"author_profile": "https://Stackoverflow.com/users/109480",
"pm_score": 0,
"selected": false,
"text": "$foo = new B($this);\n $this->squad->battle->getTeam($tid)->getSquad($sqid)->damageCreature(...);\n $obj->toXML($node);\n$this->appendChild($node);\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6260/"
] |
62,230 |
<p>How do I save a jpg image to database and then load it in Delphi using FIBplus and TImage?</p>
|
[
{
"answer_id": 69243,
"author": "Ali",
"author_id": 10989,
"author_profile": "https://Stackoverflow.com/users/10989",
"pm_score": 2,
"selected": false,
"text": "var\n S : TMemoryStream;\nbegin\n S := TMemoryStream.Create;\n try\n TBlobField(AdoQuery1.FieldByName('ImageField')).SaveToStream(S);\n S.Position := 0;\n Image1.Picture.Graphic.LoadFromStream(S);\n finally\n S.Free;\n end;\nend;\n"
},
{
"answer_id": 27692275,
"author": "alper",
"author_id": 4402765,
"author_profile": "https://Stackoverflow.com/users/4402765",
"pm_score": -1,
"selected": false,
"text": "var\n FileStream: TFileStream;\n BlobStream: TStream;\nbegin\n if openpicturedialog1.Execute then\n begin\n Sicil_frm.DBNavigator1.BtnClick(nbEdit);\n image1.Picture.LoadFromFile(openpicturedialog1.FileName);\n try\n BlobStream := dm.sicil.CreateBlobStream(dm.sicil.FieldByName('Resim'),bmWrite);\n FileStream := TFileStream.Create(openpicturedialog1.FileName,fmOpenRead or fmShareDenyNone);\n BlobStream.CopyFrom(FileStream,FileStream.Size);\n FileStream.Free;\n BlobStream.Free;\n Sicil_frm.DBNavigator1.BtnClick(nbPost);\n DM.SicilAfterScroll(dm.sicil);\n except\n dm.sicil.Cancel;\n end;\n end;\nend;\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6155/"
] |
62,241 |
<p>Is there an easy way to avoid dealing with text encoding problems?</p>
|
[
{
"answer_id": 62257,
"author": "Peter",
"author_id": 6094,
"author_profile": "https://Stackoverflow.com/users/6094",
"pm_score": 7,
"selected": true,
"text": "Reader InputStream ReaderInputStream Writer OutputStream WriterOutputStream"
},
{
"answer_id": 1360466,
"author": "Sam Barnum",
"author_id": 14467,
"author_profile": "https://Stackoverflow.com/users/14467",
"pm_score": 2,
"selected": false,
"text": "Reader OutputStream OutputStream OutputStreamWriter char Reader Writer InputStream final Writer writer = new BufferedWriter(new OutputStreamWriter( urlConnection.getOutputStream(), \"UTF-8\" ) );\nint charsRead;\nchar[] cbuf = new char[1024];\nwhile ((charsRead = data.read(cbuf)) != -1) {\n writer.write(cbuf, 0, charsRead);\n}\nwriter.flush();\n// don't forget to close the writer in a finally {} block\n"
},
{
"answer_id": 2373846,
"author": "Phil Harvey",
"author_id": 172157,
"author_profile": "https://Stackoverflow.com/users/172157",
"pm_score": 4,
"selected": false,
"text": "InputStream myInputStream = IOUtils.toInputStream(reportContents, \"UTF-8\");\n"
},
{
"answer_id": 3235846,
"author": "Ritesh Tendulkar",
"author_id": 390304,
"author_profile": "https://Stackoverflow.com/users/390304",
"pm_score": 7,
"selected": false,
"text": "new ByteArrayInputStream(inputString.getBytes(\"UTF-8\"))\n"
},
{
"answer_id": 4268583,
"author": "Bozho",
"author_id": 203907,
"author_profile": "https://Stackoverflow.com/users/203907",
"pm_score": 3,
"selected": false,
"text": "WriterOutputStream"
},
{
"answer_id": 27565648,
"author": "Oliv",
"author_id": 952135,
"author_profile": "https://Stackoverflow.com/users/952135",
"pm_score": 3,
"selected": false,
"text": "new CharSequenceInputStream(html, StandardCharsets.UTF_8);\n String byte[]"
},
{
"answer_id": 27821517,
"author": "Aaron",
"author_id": 7659,
"author_profile": "https://Stackoverflow.com/users/7659",
"pm_score": -1,
"selected": false,
"text": "InputStream s = new BufferedInputStream( new ReaderInputStream( new StringReader(\"a string\")));\n"
},
{
"answer_id": 45535083,
"author": "yegor256",
"author_id": 187141,
"author_profile": "https://Stackoverflow.com/users/187141",
"pm_score": 2,
"selected": false,
"text": "new InputStreamOf(reader) new OutputStreamTo(writer) new ReaderOf(inputStream) new WriterTo(outputStream)"
},
{
"answer_id": 66206820,
"author": "Peter Kriens",
"author_id": 243991,
"author_profile": "https://Stackoverflow.com/users/243991",
"pm_score": 0,
"selected": false,
"text": " // https://www.woolha.com/tutorials/deno-utf-8-encoding-decoding-examples\n public class WriterOutputStream extends OutputStream {\n final Writer writer;\n\n int count = 0;\n int codepoint = 0;\n\n public WriterOutputStream(Writer writer) {\n this.writer = writer;\n }\n\n @Override\n public void write(int b) throws IOException {\n b &= 0xFF;\n switch (b >> 4) {\n case 0b0000:\n case 0b0001:\n case 0b0010:\n case 0b0011:\n case 0b0100:\n case 0b0101:\n case 0b0110:\n case 0b0111:\n count = 1;\n codepoint = b;\n break;\n\n case 0b1000:\n case 0b1001:\n case 0b1010:\n case 0b1011:\n codepoint <<= 6;\n codepoint |= b & 0b0011_1111;\n break;\n\n case 0b1100:\n case 0b1101:\n count = 2;\n codepoint = b & 0b0001_1111;\n break;\n\n case 0b1110:\n count = 3;\n codepoint = b & 0b0000_1111;\n break;\n\n case 0b1111:\n count = 4;\n codepoint = b & 0b0000_0111;\n break;\n }\n if (--count == 0) {\n writer.write(codepoint);\n }\n }\n }\n\n public class ReaderInputStream extends InputStream {\n final Reader reader;\n int count = 0;\n int codepoint;\n\n public ReaderInputStream(Reader reader) {\n this.reader = reader;\n }\n\n @Override\n public int read() throws IOException {\n if (count-- > 0) {\n int r = codepoint >> (count * 6);\n r &= 0b0011_1111;\n r |= 0b1000_0000;\n return r;\n }\n\n codepoint = reader.read();\n if (codepoint < 0)\n return -1;\n if (codepoint > 0xFFFF)\n return 0;\n\n if (codepoint < 0x80)\n return codepoint;\n\n if (codepoint < 0x800) {\n count = 1;\n int v = (codepoint >> 6) | 0b1100_0000;\n return v;\n }\n count = 2;\n int v = (codepoint >> 12) | 0b1110_0000;\n return v;\n }\n }\n @Test\n public void testAll() throws IOException {\n for (char i = 0; i < 0xFFFF; i++) {\n CharArrayReader car = new CharArrayReader(new char[] { i });\n ReaderInputStream rtoi = new ReaderInputStream(car);\n byte[] data = IO.read(rtoi);\n\n CharArrayWriter caw = new CharArrayWriter();\n try (WriterOutputStream wtoo = new WriterOutputStream(caw)) {\n wtoo.write(data);\n char[] translated = caw.toCharArray();\n assertThat(translated.length).isEqualTo(1);\n assertThat((int) translated[0]).isEqualTo(i);\n\n if (!Character.isSurrogate((char) i)) {\n try (InputStream stream = new ByteArrayInputStream(data)) {\n caw = new CharArrayWriter();\n IO.copy(data, caw);\n translated = caw.toCharArray();\n assertThat(translated.length).isEqualTo(1);\n assertThat((int) translated[0]).isEqualTo(i);\n }\n }\n }\n }\n }\n\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3885/"
] |
62,245 |
<p>I am trying to refactor some code I have for software that collects current status of agents in a call queue. Currently, for each of the 6 or so events that I listen to, I check in a Mnesia table if an agent exists and change some values in the row depending on the event or add it as new if the agent doesn't exist. Currently I have this Mnesia transaction in each event and of course that is a bunch of repeated code for checking the existence of agents and so on. </p>
<p>I'm trying to change it so that there is one function like <em>change_agent/2</em> that I call from the events that handles this for me. </p>
<p>My problems are of course records.... I find no way of dynamically creating them or merging 2 of them together or anything. Preferably there would be a function I could call like:</p>
<pre><code>change_agent("001", #agent(id = "001", name = "Steve")).
change_agent("001", #agent(id = "001", paused = 0, talking_to = "None")).
</code></pre>
|
[
{
"answer_id": 62556,
"author": "uwiger",
"author_id": 6834,
"author_profile": "https://Stackoverflow.com/users/6834",
"pm_score": 2,
"selected": false,
"text": "-compile({parse_transform, exprecs}).\n-export_records([...]). % name the records that you want to 'export'\n"
},
{
"answer_id": 62898,
"author": "Adam Lindberg",
"author_id": 2457,
"author_profile": "https://Stackoverflow.com/users/2457",
"pm_score": 3,
"selected": true,
"text": "%%%----------------------------------------------------------------------------\n%%% @spec merge(RecordA, RecordB) -> #my_record{}\n%%% RecordA = #my_record{}\n%%% RecordB = #my_record{}\n%%%\n%%% @doc Merges two #my_record{} instances. The first takes precedence.\n%%% @end\n%%%----------------------------------------------------------------------------\nmerge(RecordA, RecordB) when is_record(RecordA, my_record),\n is_record(RecordB, my_record) ->\n list_to_tuple(\n lists:append([my_record],\n merge(tl(tuple_to_list(RecordA)),\n tl(tuple_to_list(RecordB)),\n tl(tuple_to_list(#my_record{})),\n []))).\n\n%%%----------------------------------------------------------------------------\n%%% @spec merge(A, B, Default, []) -> [term()]\n%%% A = [term()]\n%%% B = [term()]\n%%% Default = [term()]\n%%%\n%%% @doc Merges the lists `A' and `B' into to a new list taking\n%%% default values from `Default'.\n%%%\n%%% Each element of `A' and `B' are compared against the elements in\n%%% `Default'. If they match the default, the default is used. If one\n%%% of them differs from the other and the default value, that element is\n%%% chosen. If both differs, the element from `A' is chosen.\n%%% @end\n%%%----------------------------------------------------------------------------\nmerge([D|ATail], [D|BTail], [D|DTail], To) ->\n merge(ATail, BTail, DTail, [D|To]); % If default, take from D\nmerge([D|ATail], [B|BTail], [D|DTail], To) ->\n merge(ATail, BTail, DTail, [B|To]); % If only A default, take from B\nmerge([A|ATail], [_|BTail], [_|DTail], To) ->\n merge(ATail, BTail, DTail, [A|To]); % Otherwise take from A\nmerge([], [], [], To) ->\n lists:reverse(To).\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5601/"
] |
62,264 |
<p>I recently asked about <a href="https://stackoverflow.com/questions/39742/does-git-have-anything-like-svn-propset-svnkeywords-or-pre-post-commit-hooks">keyword expansion in Git</a> and I'm willing to accept the design not to really support this idea in Git. </p>
<p>For better or worse, the project I'm working on at the moment requires SVN keyword expansion like this:</p>
<pre><code>svn propset svn:keywords "Id" expl3.dtx
</code></pre>
<p>to keep this string up-to-date:</p>
<pre><code>$Id: expl3.dtx 803 2008-09-11 14:01:58Z will $
</code></pre>
<p>But I would quite like to use Git to do my version control. Unfortunately, git-svn doesn't support this, according to the docs:</p>
<blockquote>
<p>"We ignore all SVN properties except svn:executable"</p>
</blockquote>
<p>But it doesn't seem too tricky to have this keyword stuff emulated by a couple of pre/post commit hooks. Am I the first person to want this? Does anyone have some code to do this?</p>
|
[
{
"answer_id": 62288,
"author": "Lily Ballard",
"author_id": 582,
"author_profile": "https://Stackoverflow.com/users/582",
"pm_score": 1,
"selected": false,
"text": "$Id: deadbeefdeadbeefdeadbeefdeadbeefdeadbeef$\n deadbeef... ident"
},
{
"answer_id": 72874,
"author": "emk",
"author_id": 12089,
"author_profile": "https://Stackoverflow.com/users/12089",
"pm_score": 6,
"selected": true,
"text": "git checkout $Date$ git checkout $ git tag v0.5.whatever\n $ git describe --tags\nv0.5.15.1-6-g61cde1d\n g61cde1d *.h $Id$ git archive $Format$ git config filter.rcs-keyword.clean 'perl -pe \"s/\\\\\\$Date[^\\\\\\$]*\\\\\\$/\\\\\\$Date\\\\\\$/\"'\ngit config filter.rcs-keyword.smudge 'perl -pe \"s/\\\\\\$Date[^\\\\\\$]*\\\\\\$/\\\\\\$Date: `date`\\\\\\$/\"'\n\necho '$Date$' > test.html\necho 'test.html filter=rcs-keyword' >> .gitattributes\ngit add test.html .gitattributes\ngit commit -m \"Experimental RCS keyword support for git\"\n\nrm test.html\ngit checkout test.html\ncat test.html\n $Date: Tue Sep 16 10:15:02 EDT 2008$\n smudge clean"
},
{
"answer_id": 1194313,
"author": "Rhialto",
"author_id": 146440,
"author_profile": "https://Stackoverflow.com/users/146440",
"pm_score": 5,
"selected": false,
"text": " $Date$ The date and time the revision was checked in. With -zzone a\n numeric time zone offset is appended; otherwise, the date is\n UTC.\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4161/"
] |
62,268 |
<p>I have a winform app that calls a web service to check for updates. This works in dev and it also works everywhere else I've tried it, just not on the installed copy on my machine (which happens to be the same in dev).</p>
<p>The error is:</p>
<p>Cannot execute a program. The command being executed was "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\csc.exe" /noconfig /fullpaths @"C:\Documents and Settings\Giovanni.DOUBLE-AFSSZ043\Local Settings\Temp\squ8oock.cmdline".</p>
<p>The firewall is disabled and I've looked for "C:\Documents and Settings\Giovanni.DOUBLE-AFSSZ043\Local Settings\Temp\squ8oock.cmdline" and it is not there. Note that every time I try to use the web service the ".cmdline" file is different, for example the second time I ran it it was "dae8rgen.cmdline." No matter what name it has, I can never find the file.</p>
<p>Any suggestions?</p>
|
[
{
"answer_id": 47547430,
"author": "Ivan Chau",
"author_id": 1608670,
"author_profile": "https://Stackoverflow.com/users/1608670",
"pm_score": 0,
"selected": false,
"text": "c:\\windows\\MICROSOFT.NET\\FRAMEWORK\\V2.0.50727\\CSC.EXE c:\\windows\\MICROSOFT.NET\\FRAMEWORK\\V2.0.50727\\CVTRES.EXE"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4050/"
] |
62,289 |
<p>How is it possible to read/write to the Windows registry using Java?</p>
|
[
{
"answer_id": 63231,
"author": "Alex Argo",
"author_id": 5885,
"author_profile": "https://Stackoverflow.com/users/5885",
"pm_score": 5,
"selected": false,
"text": "import java.io.File;\nimport ca.beq.util.win32.registry.RegistryKey;\nimport ca.beq.util.win32.registry.RegistryValue;\nimport ca.beq.util.win32.registry.RootKey;\nimport ca.beq.util.win32.registry.ValueType;\n\n\npublic class FixStuff {\n\nprivate static final String REGEDIT_KEY = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Policies\\\\System\";\nprivate static final String REGEDIT_VALUE = \"DisableRegistryTools\";\nprivate static final String REGISTRY_LIBRARY_PATH = \"\\\\lib\\\\jRegistryKey.dll\";\nprivate static final String FOLDER_OPTIONS_KEY = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Policies\\\\Explorer\";\nprivate static final String FOLDER_OPTIONS_VALUE = \"NoFolderOptions\";\n\npublic static void main(String[] args) {\n //Load JNI library\n RegistryKey.initialize( new File(\".\").getAbsolutePath()+REGISTRY_LIBRARY_PATH );\n\n enableRegistryEditing(true); \n enableShowFolderOptions(true);\n}\n\nprivate static void enableShowFolderOptions(boolean enable) {\n RegistryKey key = new RegistryKey(RootKey.HKEY_CURRENT_USER,FOLDER_OPTIONS_KEY);\n RegistryKey key2 = new RegistryKey(RootKey.HKEY_LOCAL_MACHINE,FOLDER_OPTIONS_KEY);\n RegistryValue value = new RegistryValue();\n value.setName(FOLDER_OPTIONS_VALUE);\n value.setType(ValueType.REG_DWORD_LITTLE_ENDIAN);\n value.setData(enable?0:1);\n\n if(key.hasValue(FOLDER_OPTIONS_VALUE)) {\n key.setValue(value);\n }\n if(key2.hasValue(FOLDER_OPTIONS_VALUE)) {\n key2.setValue(value);\n } \n}\n\nprivate static void enableRegistryEditing(boolean enable) {\n RegistryKey key = new RegistryKey(RootKey.HKEY_CURRENT_USER,REGEDIT_KEY);\n RegistryValue value = new RegistryValue();\n value.setName(REGEDIT_VALUE);\n value.setType(ValueType.REG_DWORD_LITTLE_ENDIAN);\n value.setData(enable?0:1);\n\n if(key.hasValue(REGEDIT_VALUE)) {\n key.setValue(value);\n }\n}\n\n}\n"
},
{
"answer_id": 1982033,
"author": "Oleg Ryaboy",
"author_id": 205711,
"author_profile": "https://Stackoverflow.com/users/205711",
"pm_score": 7,
"selected": false,
"text": "reg /?\n Runtime.getRuntime().exec(\"reg <your parameters here>\");\n import java.io.IOException;\nimport java.io.InputStream;\nimport java.io.StringWriter;\n\n/**\n * @author Oleg Ryaboy, based on work by Miguel Enriquez \n */\npublic class WindowsReqistry {\n\n /**\n * \n * @param location path in the registry\n * @param key registry key\n * @return registry value or null if not found\n */\n public static final String readRegistry(String location, String key){\n try {\n // Run reg query, then read output with StreamReader (internal class)\n Process process = Runtime.getRuntime().exec(\"reg query \" + \n '\"'+ location + \"\\\" /v \" + key);\n\n StreamReader reader = new StreamReader(process.getInputStream());\n reader.start();\n process.waitFor();\n reader.join();\n String output = reader.getResult();\n\n // Output has the following format:\n // \\n<Version information>\\n\\n<key>\\t<registry type>\\t<value>\n if( ! output.contains(\"\\t\")){\n return null;\n }\n\n // Parse out the value\n String[] parsed = output.split(\"\\t\");\n return parsed[parsed.length-1];\n }\n catch (Exception e) {\n return null;\n }\n\n }\n\n static class StreamReader extends Thread {\n private InputStream is;\n private StringWriter sw= new StringWriter();\n\n public StreamReader(InputStream is) {\n this.is = is;\n }\n\n public void run() {\n try {\n int c;\n while ((c = is.read()) != -1)\n sw.write(c);\n }\n catch (IOException e) { \n }\n }\n\n public String getResult() {\n return sw.toString();\n }\n }\n public static void main(String[] args) {\n\n // Sample usage\n String value = WindowsReqistry.readRegistry(\"HKCU\\\\Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\\" \n + \"Explorer\\\\Shell Folders\", \"Personal\");\n System.out.println(value);\n }\n}\n"
},
{
"answer_id": 5902131,
"author": "gousli",
"author_id": 740494,
"author_profile": "https://Stackoverflow.com/users/740494",
"pm_score": 3,
"selected": false,
"text": "public static final String readRegistry(String location, String key)\n{\n try\n {\n // Run reg query, then read output with StreamReader (internal class)\n Process process = Runtime.getRuntime().exec(\"reg query \" + \n '\"'+ location + \"\\\" /v \" + key);\n\n InputStream is = process.getInputStream();\n StringBuilder sw = new StringBuilder();\n\n try\n {\n int c;\n while ((c = is.read()) != -1)\n sw.append((char)c);\n }\n catch (IOException e)\n { \n }\n\n String output = sw.toString();\n\n // Output has the following format:\n // \\n<Version information>\\n\\n<key> <registry type> <value>\\r\\n\\r\\n\n int i = output.indexOf(\"REG_SZ\");\n if (i == -1)\n {\n return null;\n }\n\n sw = new StringBuilder();\n i += 6; // skip REG_SZ\n\n // skip spaces or tabs\n for (;;)\n {\n if (i > output.length())\n break;\n char c = output.charAt(i);\n if (c != ' ' && c != '\\t')\n break;\n ++i;\n }\n\n // take everything until end of line\n for (;;)\n {\n if (i > output.length())\n break;\n char c = output.charAt(i);\n if (c == '\\r' || c == '\\n')\n break;\n sw.append(c);\n ++i;\n }\n\n return sw.toString();\n }\n catch (Exception e)\n {\n return null;\n }\n"
},
{
"answer_id": 6028547,
"author": "Vishal",
"author_id": 390550,
"author_profile": "https://Stackoverflow.com/users/390550",
"pm_score": -1,
"selected": false,
"text": "// Write Operation\nPreferences p = Preferences.userRoot();\np.put(\"key\",\"value\"); \n// also there are various other methods such as putByteArray(), putDouble() etc.\np.flush();\n//Read Operation\nPreferences p = Preferences.userRoot();\nString value = p.get(\"key\");\n"
},
{
"answer_id": 6163701,
"author": "David",
"author_id": 656963,
"author_profile": "https://Stackoverflow.com/users/656963",
"pm_score": 8,
"selected": false,
"text": "java.util.prefs.Preferences String value = WinRegistry.readString (\n WinRegistry.HKEY_LOCAL_MACHINE, //HKEY\n \"SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\", //Key\n \"ProductName\"); //ValueName\n System.out.println(\"Windows Distribution = \" + value); \n import java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.prefs.Preferences;\n\npublic class WinRegistry {\n public static final int HKEY_CURRENT_USER = 0x80000001;\n public static final int HKEY_LOCAL_MACHINE = 0x80000002;\n public static final int REG_SUCCESS = 0;\n public static final int REG_NOTFOUND = 2;\n public static final int REG_ACCESSDENIED = 5;\n\n private static final int KEY_ALL_ACCESS = 0xf003f;\n private static final int KEY_READ = 0x20019;\n private static final Preferences userRoot = Preferences.userRoot();\n private static final Preferences systemRoot = Preferences.systemRoot();\n private static final Class<? extends Preferences> userClass = userRoot.getClass();\n private static final Method regOpenKey;\n private static final Method regCloseKey;\n private static final Method regQueryValueEx;\n private static final Method regEnumValue;\n private static final Method regQueryInfoKey;\n private static final Method regEnumKeyEx;\n private static final Method regCreateKeyEx;\n private static final Method regSetValueEx;\n private static final Method regDeleteKey;\n private static final Method regDeleteValue;\n\n static {\n try {\n regOpenKey = userClass.getDeclaredMethod(\"WindowsRegOpenKey\",\n new Class[] { int.class, byte[].class, int.class });\n regOpenKey.setAccessible(true);\n regCloseKey = userClass.getDeclaredMethod(\"WindowsRegCloseKey\",\n new Class[] { int.class });\n regCloseKey.setAccessible(true);\n regQueryValueEx = userClass.getDeclaredMethod(\"WindowsRegQueryValueEx\",\n new Class[] { int.class, byte[].class });\n regQueryValueEx.setAccessible(true);\n regEnumValue = userClass.getDeclaredMethod(\"WindowsRegEnumValue\",\n new Class[] { int.class, int.class, int.class });\n regEnumValue.setAccessible(true);\n regQueryInfoKey = userClass.getDeclaredMethod(\"WindowsRegQueryInfoKey1\",\n new Class[] { int.class });\n regQueryInfoKey.setAccessible(true);\n regEnumKeyEx = userClass.getDeclaredMethod( \n \"WindowsRegEnumKeyEx\", new Class[] { int.class, int.class, \n int.class }); \n regEnumKeyEx.setAccessible(true);\n regCreateKeyEx = userClass.getDeclaredMethod( \n \"WindowsRegCreateKeyEx\", new Class[] { int.class, \n byte[].class }); \n regCreateKeyEx.setAccessible(true); \n regSetValueEx = userClass.getDeclaredMethod( \n \"WindowsRegSetValueEx\", new Class[] { int.class, \n byte[].class, byte[].class }); \n regSetValueEx.setAccessible(true); \n regDeleteValue = userClass.getDeclaredMethod( \n \"WindowsRegDeleteValue\", new Class[] { int.class, \n byte[].class }); \n regDeleteValue.setAccessible(true); \n regDeleteKey = userClass.getDeclaredMethod( \n \"WindowsRegDeleteKey\", new Class[] { int.class, \n byte[].class }); \n regDeleteKey.setAccessible(true); \n }\n catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n private WinRegistry() { }\n\n /**\n * Read a value from key and value name\n * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n * @param key\n * @param valueName\n * @return the value\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static String readString(int hkey, String key, String valueName) \n throws IllegalArgumentException, IllegalAccessException,\n InvocationTargetException \n {\n if (hkey == HKEY_LOCAL_MACHINE) {\n return readString(systemRoot, hkey, key, valueName);\n }\n else if (hkey == HKEY_CURRENT_USER) {\n return readString(userRoot, hkey, key, valueName);\n }\n else {\n throw new IllegalArgumentException(\"hkey=\" + hkey);\n }\n }\n\n /**\n * Read value(s) and value name(s) form given key \n * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n * @param key\n * @return the value name(s) plus the value(s)\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static Map<String, String> readStringValues(int hkey, String key) \n throws IllegalArgumentException, IllegalAccessException,\n InvocationTargetException \n {\n if (hkey == HKEY_LOCAL_MACHINE) {\n return readStringValues(systemRoot, hkey, key);\n }\n else if (hkey == HKEY_CURRENT_USER) {\n return readStringValues(userRoot, hkey, key);\n }\n else {\n throw new IllegalArgumentException(\"hkey=\" + hkey);\n }\n }\n\n /**\n * Read the value name(s) from a given key\n * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n * @param key\n * @return the value name(s)\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static List<String> readStringSubKeys(int hkey, String key) \n throws IllegalArgumentException, IllegalAccessException,\n InvocationTargetException \n {\n if (hkey == HKEY_LOCAL_MACHINE) {\n return readStringSubKeys(systemRoot, hkey, key);\n }\n else if (hkey == HKEY_CURRENT_USER) {\n return readStringSubKeys(userRoot, hkey, key);\n }\n else {\n throw new IllegalArgumentException(\"hkey=\" + hkey);\n }\n }\n\n /**\n * Create a key\n * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n * @param key\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static void createKey(int hkey, String key) \n throws IllegalArgumentException, IllegalAccessException,\n InvocationTargetException \n {\n int [] ret;\n if (hkey == HKEY_LOCAL_MACHINE) {\n ret = createKey(systemRoot, hkey, key);\n regCloseKey.invoke(systemRoot, new Object[] { new Integer(ret[0]) });\n }\n else if (hkey == HKEY_CURRENT_USER) {\n ret = createKey(userRoot, hkey, key);\n regCloseKey.invoke(userRoot, new Object[] { new Integer(ret[0]) });\n }\n else {\n throw new IllegalArgumentException(\"hkey=\" + hkey);\n }\n if (ret[1] != REG_SUCCESS) {\n throw new IllegalArgumentException(\"rc=\" + ret[1] + \" key=\" + key);\n }\n }\n\n /**\n * Write a value in a given key/value name\n * @param hkey\n * @param key\n * @param valueName\n * @param value\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static void writeStringValue\n (int hkey, String key, String valueName, String value) \n throws IllegalArgumentException, IllegalAccessException,\n InvocationTargetException \n {\n if (hkey == HKEY_LOCAL_MACHINE) {\n writeStringValue(systemRoot, hkey, key, valueName, value);\n }\n else if (hkey == HKEY_CURRENT_USER) {\n writeStringValue(userRoot, hkey, key, valueName, value);\n }\n else {\n throw new IllegalArgumentException(\"hkey=\" + hkey);\n }\n }\n\n /**\n * Delete a given key\n * @param hkey\n * @param key\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static void deleteKey(int hkey, String key) \n throws IllegalArgumentException, IllegalAccessException,\n InvocationTargetException \n {\n int rc = -1;\n if (hkey == HKEY_LOCAL_MACHINE) {\n rc = deleteKey(systemRoot, hkey, key);\n }\n else if (hkey == HKEY_CURRENT_USER) {\n rc = deleteKey(userRoot, hkey, key);\n }\n if (rc != REG_SUCCESS) {\n throw new IllegalArgumentException(\"rc=\" + rc + \" key=\" + key);\n }\n }\n\n /**\n * delete a value from a given key/value name\n * @param hkey\n * @param key\n * @param value\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static void deleteValue(int hkey, String key, String value) \n throws IllegalArgumentException, IllegalAccessException,\n InvocationTargetException \n {\n int rc = -1;\n if (hkey == HKEY_LOCAL_MACHINE) {\n rc = deleteValue(systemRoot, hkey, key, value);\n }\n else if (hkey == HKEY_CURRENT_USER) {\n rc = deleteValue(userRoot, hkey, key, value);\n }\n if (rc != REG_SUCCESS) {\n throw new IllegalArgumentException(\"rc=\" + rc + \" key=\" + key + \" value=\" + value);\n }\n }\n\n // =====================\n\n private static int deleteValue\n (Preferences root, int hkey, String key, String value)\n throws IllegalArgumentException, IllegalAccessException,\n InvocationTargetException \n {\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {\n new Integer(hkey), toCstr(key), new Integer(KEY_ALL_ACCESS) });\n if (handles[1] != REG_SUCCESS) {\n return handles[1]; // can be REG_NOTFOUND, REG_ACCESSDENIED\n }\n int rc =((Integer) regDeleteValue.invoke(root, \n new Object[] { \n new Integer(handles[0]), toCstr(value) \n })).intValue();\n regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });\n return rc;\n }\n\n private static int deleteKey(Preferences root, int hkey, String key) \n throws IllegalArgumentException, IllegalAccessException,\n InvocationTargetException \n {\n int rc =((Integer) regDeleteKey.invoke(root, \n new Object[] { new Integer(hkey), toCstr(key) })).intValue();\n return rc; // can REG_NOTFOUND, REG_ACCESSDENIED, REG_SUCCESS\n }\n\n private static String readString(Preferences root, int hkey, String key, String value)\n throws IllegalArgumentException, IllegalAccessException,\n InvocationTargetException \n {\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {\n new Integer(hkey), toCstr(key), new Integer(KEY_READ) });\n if (handles[1] != REG_SUCCESS) {\n return null; \n }\n byte[] valb = (byte[]) regQueryValueEx.invoke(root, new Object[] {\n new Integer(handles[0]), toCstr(value) });\n regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });\n return (valb != null ? new String(valb).trim() : null);\n }\n\n private static Map<String,String> readStringValues\n (Preferences root, int hkey, String key)\n throws IllegalArgumentException, IllegalAccessException,\n InvocationTargetException \n {\n HashMap<String, String> results = new HashMap<String,String>();\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {\n new Integer(hkey), toCstr(key), new Integer(KEY_READ) });\n if (handles[1] != REG_SUCCESS) {\n return null;\n }\n int[] info = (int[]) regQueryInfoKey.invoke(root,\n new Object[] { new Integer(handles[0]) });\n\n int count = info[0]; // count \n int maxlen = info[3]; // value length max\n for(int index=0; index<count; index++) {\n byte[] name = (byte[]) regEnumValue.invoke(root, new Object[] {\n new Integer\n (handles[0]), new Integer(index), new Integer(maxlen + 1)});\n String value = readString(hkey, key, new String(name));\n results.put(new String(name).trim(), value);\n }\n regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });\n return results;\n }\n\n private static List<String> readStringSubKeys\n (Preferences root, int hkey, String key)\n throws IllegalArgumentException, IllegalAccessException,\n InvocationTargetException \n {\n List<String> results = new ArrayList<String>();\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {\n new Integer(hkey), toCstr(key), new Integer(KEY_READ) \n });\n if (handles[1] != REG_SUCCESS) {\n return null;\n }\n int[] info = (int[]) regQueryInfoKey.invoke(root,\n new Object[] { new Integer(handles[0]) });\n\n int count = info[0]; // Fix: info[2] was being used here with wrong results. Suggested by davenpcj, confirmed by Petrucio\n int maxlen = info[3]; // value length max\n for(int index=0; index<count; index++) {\n byte[] name = (byte[]) regEnumKeyEx.invoke(root, new Object[] {\n new Integer\n (handles[0]), new Integer(index), new Integer(maxlen + 1)\n });\n results.add(new String(name).trim());\n }\n regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });\n return results;\n }\n\n private static int [] createKey(Preferences root, int hkey, String key)\n throws IllegalArgumentException, IllegalAccessException,\n InvocationTargetException \n {\n return (int[]) regCreateKeyEx.invoke(root,\n new Object[] { new Integer(hkey), toCstr(key) });\n }\n\n private static void writeStringValue \n (Preferences root, int hkey, String key, String valueName, String value) \n throws IllegalArgumentException, IllegalAccessException,\n InvocationTargetException \n {\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {\n new Integer(hkey), toCstr(key), new Integer(KEY_ALL_ACCESS) });\n\n regSetValueEx.invoke(root, \n new Object[] { \n new Integer(handles[0]), toCstr(valueName), toCstr(value) \n }); \n regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });\n }\n\n // utility\n private static byte[] toCstr(String str) {\n byte[] result = new byte[str.length() + 1];\n\n for (int i = 0; i < str.length(); i++) {\n result[i] = (byte) str.charAt(i);\n }\n result[str.length()] = 0;\n return result;\n }\n}\n"
},
{
"answer_id": 6287763,
"author": "John McCarthy",
"author_id": 277307,
"author_profile": "https://Stackoverflow.com/users/277307",
"pm_score": 6,
"selected": false,
"text": "import com.sun.jna.platform.win32.Advapi32Util;\nimport com.sun.jna.platform.win32.WinReg;\n\npublic class WindowsRegistrySnippet {\n public static void main(String[] args) {\n // Read a string\n String productName = Advapi32Util.registryGetStringValue(\n WinReg.HKEY_LOCAL_MACHINE, \"SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\", \"ProductName\");\n System.out.printf(\"Product Name: %s\\n\", productName);\n\n // Read an int (& 0xFFFFFFFFL for large unsigned int)\n int timeout = Advapi32Util.registryGetIntValue(\n WinReg.HKEY_LOCAL_MACHINE, \"SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\Windows\", \"ShutdownWarningDialogTimeout\");\n System.out.printf(\"Shutdown Warning Dialog Timeout: %d (%d as unsigned long)\\n\", timeout, timeout & 0xFFFFFFFFL);\n\n // Create a key and write a string\n Advapi32Util.registryCreateKey(WinReg.HKEY_CURRENT_USER, \"SOFTWARE\\\\StackOverflow\");\n Advapi32Util.registrySetStringValue(WinReg.HKEY_CURRENT_USER, \"SOFTWARE\\\\StackOverflow\", \"url\", \"http://stackoverflow.com/a/6287763/277307\");\n\n // Delete a key\n Advapi32Util.registryDeleteKey(WinReg.HKEY_CURRENT_USER, \"SOFTWARE\\\\StackOverflow\");\n }\n}\n"
},
{
"answer_id": 8955801,
"author": "Johnydep",
"author_id": 750965,
"author_profile": "https://Stackoverflow.com/users/750965",
"pm_score": 0,
"selected": false,
"text": "regini Runtime.getRuntime().exec(\"regini <your script file abs path here>\");\n"
},
{
"answer_id": 11854901,
"author": "Petrucio",
"author_id": 828681,
"author_profile": "https://Stackoverflow.com/users/828681",
"pm_score": 5,
"selected": false,
"text": "/**\n * Pure Java Windows Registry access.\n * Modified by petrucio@stackoverflow(828681) to add support for\n * reading (and writing but not creating/deleting keys) the 32-bits\n * registry view from a 64-bits JVM (KEY_WOW64_32KEY)\n * and 64-bits view from a 32-bits JVM (KEY_WOW64_64KEY).\n *****************************************************************************/\n\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.prefs.Preferences;\n\npublic class WinRegistry {\n public static final int HKEY_CURRENT_USER = 0x80000001;\n public static final int HKEY_LOCAL_MACHINE = 0x80000002;\n public static final int REG_SUCCESS = 0;\n public static final int REG_NOTFOUND = 2;\n public static final int REG_ACCESSDENIED = 5;\n\n public static final int KEY_WOW64_32KEY = 0x0200;\n public static final int KEY_WOW64_64KEY = 0x0100;\n\n private static final int KEY_ALL_ACCESS = 0xf003f;\n private static final int KEY_READ = 0x20019;\n private static Preferences userRoot = Preferences.userRoot();\n private static Preferences systemRoot = Preferences.systemRoot();\n private static Class<? extends Preferences> userClass = userRoot.getClass();\n private static Method regOpenKey = null;\n private static Method regCloseKey = null;\n private static Method regQueryValueEx = null;\n private static Method regEnumValue = null;\n private static Method regQueryInfoKey = null;\n private static Method regEnumKeyEx = null;\n private static Method regCreateKeyEx = null;\n private static Method regSetValueEx = null;\n private static Method regDeleteKey = null;\n private static Method regDeleteValue = null;\n\n static {\n try {\n regOpenKey = userClass.getDeclaredMethod(\"WindowsRegOpenKey\", new Class[] { int.class, byte[].class, int.class });\n regOpenKey.setAccessible(true);\n regCloseKey = userClass.getDeclaredMethod(\"WindowsRegCloseKey\", new Class[] { int.class });\n regCloseKey.setAccessible(true);\n regQueryValueEx= userClass.getDeclaredMethod(\"WindowsRegQueryValueEx\",new Class[] { int.class, byte[].class });\n regQueryValueEx.setAccessible(true);\n regEnumValue = userClass.getDeclaredMethod(\"WindowsRegEnumValue\", new Class[] { int.class, int.class, int.class });\n regEnumValue.setAccessible(true);\n regQueryInfoKey=userClass.getDeclaredMethod(\"WindowsRegQueryInfoKey1\",new Class[] { int.class });\n regQueryInfoKey.setAccessible(true);\n regEnumKeyEx = userClass.getDeclaredMethod(\"WindowsRegEnumKeyEx\", new Class[] { int.class, int.class, int.class }); \n regEnumKeyEx.setAccessible(true);\n regCreateKeyEx = userClass.getDeclaredMethod(\"WindowsRegCreateKeyEx\", new Class[] { int.class, byte[].class });\n regCreateKeyEx.setAccessible(true); \n regSetValueEx = userClass.getDeclaredMethod(\"WindowsRegSetValueEx\", new Class[] { int.class, byte[].class, byte[].class }); \n regSetValueEx.setAccessible(true); \n regDeleteValue = userClass.getDeclaredMethod(\"WindowsRegDeleteValue\", new Class[] { int.class, byte[].class }); \n regDeleteValue.setAccessible(true); \n regDeleteKey = userClass.getDeclaredMethod(\"WindowsRegDeleteKey\", new Class[] { int.class, byte[].class }); \n regDeleteKey.setAccessible(true); \n }\n catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n private WinRegistry() { }\n\n /**\n * Read a value from key and value name\n * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n * @param key\n * @param valueName\n * @param wow64 0 for standard registry access (32-bits for 32-bit app, 64-bits for 64-bits app)\n * or KEY_WOW64_32KEY to force access to 32-bit registry view,\n * or KEY_WOW64_64KEY to force access to 64-bit registry view\n * @return the value\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static String readString(int hkey, String key, String valueName, int wow64) \n throws IllegalArgumentException, IllegalAccessException,\n InvocationTargetException \n {\n if (hkey == HKEY_LOCAL_MACHINE) {\n return readString(systemRoot, hkey, key, valueName, wow64);\n }\n else if (hkey == HKEY_CURRENT_USER) {\n return readString(userRoot, hkey, key, valueName, wow64);\n }\n else {\n throw new IllegalArgumentException(\"hkey=\" + hkey);\n }\n }\n\n /**\n * Read value(s) and value name(s) form given key \n * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n * @param key\n * @param wow64 0 for standard registry access (32-bits for 32-bit app, 64-bits for 64-bits app)\n * or KEY_WOW64_32KEY to force access to 32-bit registry view,\n * or KEY_WOW64_64KEY to force access to 64-bit registry view\n * @return the value name(s) plus the value(s)\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static Map<String, String> readStringValues(int hkey, String key, int wow64) \n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n {\n if (hkey == HKEY_LOCAL_MACHINE) {\n return readStringValues(systemRoot, hkey, key, wow64);\n }\n else if (hkey == HKEY_CURRENT_USER) {\n return readStringValues(userRoot, hkey, key, wow64);\n }\n else {\n throw new IllegalArgumentException(\"hkey=\" + hkey);\n }\n }\n\n /**\n * Read the value name(s) from a given key\n * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n * @param key\n * @param wow64 0 for standard registry access (32-bits for 32-bit app, 64-bits for 64-bits app)\n * or KEY_WOW64_32KEY to force access to 32-bit registry view,\n * or KEY_WOW64_64KEY to force access to 64-bit registry view\n * @return the value name(s)\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static List<String> readStringSubKeys(int hkey, String key, int wow64) \n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n {\n if (hkey == HKEY_LOCAL_MACHINE) {\n return readStringSubKeys(systemRoot, hkey, key, wow64);\n }\n else if (hkey == HKEY_CURRENT_USER) {\n return readStringSubKeys(userRoot, hkey, key, wow64);\n }\n else {\n throw new IllegalArgumentException(\"hkey=\" + hkey);\n }\n }\n\n /**\n * Create a key\n * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n * @param key\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static void createKey(int hkey, String key) \n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n {\n int [] ret;\n if (hkey == HKEY_LOCAL_MACHINE) {\n ret = createKey(systemRoot, hkey, key);\n regCloseKey.invoke(systemRoot, new Object[] { new Integer(ret[0]) });\n }\n else if (hkey == HKEY_CURRENT_USER) {\n ret = createKey(userRoot, hkey, key);\n regCloseKey.invoke(userRoot, new Object[] { new Integer(ret[0]) });\n }\n else {\n throw new IllegalArgumentException(\"hkey=\" + hkey);\n }\n if (ret[1] != REG_SUCCESS) {\n throw new IllegalArgumentException(\"rc=\" + ret[1] + \" key=\" + key);\n }\n }\n\n /**\n * Write a value in a given key/value name\n * @param hkey\n * @param key\n * @param valueName\n * @param value\n * @param wow64 0 for standard registry access (32-bits for 32-bit app, 64-bits for 64-bits app)\n * or KEY_WOW64_32KEY to force access to 32-bit registry view,\n * or KEY_WOW64_64KEY to force access to 64-bit registry view\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static void writeStringValue\n (int hkey, String key, String valueName, String value, int wow64) \n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n {\n if (hkey == HKEY_LOCAL_MACHINE) {\n writeStringValue(systemRoot, hkey, key, valueName, value, wow64);\n }\n else if (hkey == HKEY_CURRENT_USER) {\n writeStringValue(userRoot, hkey, key, valueName, value, wow64);\n }\n else {\n throw new IllegalArgumentException(\"hkey=\" + hkey);\n }\n }\n\n /**\n * Delete a given key\n * @param hkey\n * @param key\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static void deleteKey(int hkey, String key) \n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n {\n int rc = -1;\n if (hkey == HKEY_LOCAL_MACHINE) {\n rc = deleteKey(systemRoot, hkey, key);\n }\n else if (hkey == HKEY_CURRENT_USER) {\n rc = deleteKey(userRoot, hkey, key);\n }\n if (rc != REG_SUCCESS) {\n throw new IllegalArgumentException(\"rc=\" + rc + \" key=\" + key);\n }\n }\n\n /**\n * delete a value from a given key/value name\n * @param hkey\n * @param key\n * @param value\n * @param wow64 0 for standard registry access (32-bits for 32-bit app, 64-bits for 64-bits app)\n * or KEY_WOW64_32KEY to force access to 32-bit registry view,\n * or KEY_WOW64_64KEY to force access to 64-bit registry view\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static void deleteValue(int hkey, String key, String value, int wow64) \n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n {\n int rc = -1;\n if (hkey == HKEY_LOCAL_MACHINE) {\n rc = deleteValue(systemRoot, hkey, key, value, wow64);\n }\n else if (hkey == HKEY_CURRENT_USER) {\n rc = deleteValue(userRoot, hkey, key, value, wow64);\n }\n if (rc != REG_SUCCESS) {\n throw new IllegalArgumentException(\"rc=\" + rc + \" key=\" + key + \" value=\" + value);\n }\n }\n\n //========================================================================\n private static int deleteValue(Preferences root, int hkey, String key, String value, int wow64)\n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n {\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {\n new Integer(hkey), toCstr(key), new Integer(KEY_ALL_ACCESS | wow64)\n });\n if (handles[1] != REG_SUCCESS) {\n return handles[1]; // can be REG_NOTFOUND, REG_ACCESSDENIED\n }\n int rc =((Integer) regDeleteValue.invoke(root, new Object[] { \n new Integer(handles[0]), toCstr(value) \n })).intValue();\n regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });\n return rc;\n }\n\n //========================================================================\n private static int deleteKey(Preferences root, int hkey, String key) \n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n {\n int rc =((Integer) regDeleteKey.invoke(root, new Object[] {\n new Integer(hkey), toCstr(key)\n })).intValue();\n return rc; // can REG_NOTFOUND, REG_ACCESSDENIED, REG_SUCCESS\n }\n\n //========================================================================\n private static String readString(Preferences root, int hkey, String key, String value, int wow64)\n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n {\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {\n new Integer(hkey), toCstr(key), new Integer(KEY_READ | wow64)\n });\n if (handles[1] != REG_SUCCESS) {\n return null; \n }\n byte[] valb = (byte[]) regQueryValueEx.invoke(root, new Object[] {\n new Integer(handles[0]), toCstr(value)\n });\n regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });\n return (valb != null ? new String(valb).trim() : null);\n }\n\n //========================================================================\n private static Map<String,String> readStringValues(Preferences root, int hkey, String key, int wow64)\n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n {\n HashMap<String, String> results = new HashMap<String,String>();\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {\n new Integer(hkey), toCstr(key), new Integer(KEY_READ | wow64)\n });\n if (handles[1] != REG_SUCCESS) {\n return null;\n }\n int[] info = (int[]) regQueryInfoKey.invoke(root, new Object[] {\n new Integer(handles[0])\n });\n\n int count = info[2]; // count \n int maxlen = info[3]; // value length max\n for(int index=0; index<count; index++) {\n byte[] name = (byte[]) regEnumValue.invoke(root, new Object[] {\n new Integer(handles[0]), new Integer(index), new Integer(maxlen + 1)\n });\n String value = readString(hkey, key, new String(name), wow64);\n results.put(new String(name).trim(), value);\n }\n regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });\n return results;\n }\n\n //========================================================================\n private static List<String> readStringSubKeys(Preferences root, int hkey, String key, int wow64)\n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n {\n List<String> results = new ArrayList<String>();\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {\n new Integer(hkey), toCstr(key), new Integer(KEY_READ | wow64) \n });\n if (handles[1] != REG_SUCCESS) {\n return null;\n }\n int[] info = (int[]) regQueryInfoKey.invoke(root, new Object[] {\n new Integer(handles[0])\n });\n\n int count = info[0]; // Fix: info[2] was being used here with wrong results. Suggested by davenpcj, confirmed by Petrucio\n int maxlen = info[3]; // value length max\n for(int index=0; index<count; index++) {\n byte[] name = (byte[]) regEnumKeyEx.invoke(root, new Object[] {\n new Integer(handles[0]), new Integer(index), new Integer(maxlen + 1)\n });\n results.add(new String(name).trim());\n }\n regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });\n return results;\n }\n\n //========================================================================\n private static int [] createKey(Preferences root, int hkey, String key)\n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n {\n return (int[]) regCreateKeyEx.invoke(root, new Object[] {\n new Integer(hkey), toCstr(key)\n });\n }\n\n //========================================================================\n private static void writeStringValue(Preferences root, int hkey, String key, String valueName, String value, int wow64)\n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n {\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {\n new Integer(hkey), toCstr(key), new Integer(KEY_ALL_ACCESS | wow64)\n });\n regSetValueEx.invoke(root, new Object[] { \n new Integer(handles[0]), toCstr(valueName), toCstr(value) \n }); \n regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });\n }\n\n //========================================================================\n // utility\n private static byte[] toCstr(String str) {\n byte[] result = new byte[str.length() + 1];\n\n for (int i = 0; i < str.length(); i++) {\n result[i] = (byte) str.charAt(i);\n }\n result[str.length()] = 0;\n return result;\n }\n}\n"
},
{
"answer_id": 17310303,
"author": "kevinarpe",
"author_id": 257299,
"author_profile": "https://Stackoverflow.com/users/257299",
"pm_score": 2,
"selected": false,
"text": "Preferences java.util.prefs.WindowsPreferences"
},
{
"answer_id": 18103763,
"author": "TacB0sS",
"author_id": 348189,
"author_profile": "https://Stackoverflow.com/users/348189",
"pm_score": 0,
"selected": false,
"text": "package com.nu.art.software.utils;\n\n\nimport java.lang.reflect.Method;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.prefs.Preferences;\n\n/**\n *\n * @author TacB0sS\n */\npublic class WinRegistry_TacB0sS {\n\n public static final class RegistryException\n extends Exception {\n\n private static final long serialVersionUID = -8799947496460994651L;\n\n public RegistryException(String message, Throwable e) {\n super(message, e);\n }\n\n public RegistryException(String message) {\n super(message);\n }\n\n\n }\n\n public static final int KEY_WOW64_32KEY = 0x0200;\n\n public static final int KEY_WOW64_64KEY = 0x0100;\n\n public static final int REG_SUCCESS = 0;\n\n public static final int REG_NOTFOUND = 2;\n\n public static final int REG_ACCESSDENIED = 5;\n\n private static final int KEY_ALL_ACCESS = 0xf003f;\n\n private static final int KEY_READ = 0x20019;\n\n public enum WinRegistryKey {\n User(Preferences.userRoot(), 0x80000001), ;\n\n // System(Preferences.systemRoot(), 0x80000002);\n\n private final Preferences preferencesRoot;\n\n private final Integer key;\n\n private WinRegistryKey(Preferences preferencesRoot, int key) {\n this.preferencesRoot = preferencesRoot;\n this.key = key;\n }\n }\n\n private enum WinRegistryMethod {\n OpenKey(\"WindowsRegOpenKey\", int.class, byte[].class, int.class) {\n\n @Override\n protected void verifyReturnValue(Object retValue)\n throws RegistryException {\n int[] retVal = (int[]) retValue;\n if (retVal[1] != REG_SUCCESS)\n throw new RegistryException(\"Action Failed, Return Code: \" + retVal[1]);\n }\n },\n CreateKeyEx(\"WindowsRegCreateKeyEx\", int.class, byte[].class) {\n\n @Override\n protected void verifyReturnValue(Object retValue)\n throws RegistryException {\n int[] retVal = (int[]) retValue;\n if (retVal[1] != REG_SUCCESS)\n throw new RegistryException(\"Action Failed, Return Code: \" + retVal[1]);\n }\n },\n DeleteKey(\"WindowsRegDeleteKey\", int.class, byte[].class) {\n\n @Override\n protected void verifyReturnValue(Object retValue)\n throws RegistryException {\n int retVal = ((Integer) retValue).intValue();\n if (retVal != REG_SUCCESS)\n throw new RegistryException(\"Action Failed, Return Code: \" + retVal);\n }\n },\n DeleteValue(\"WindowsRegDeleteValue\", int.class, byte[].class) {\n\n @Override\n protected void verifyReturnValue(Object retValue)\n throws RegistryException {\n int retVal = ((Integer) retValue).intValue();\n if (retVal != REG_SUCCESS)\n throw new RegistryException(\"Action Failed, Return Code: \" + retVal);\n }\n },\n CloseKey(\"WindowsRegCloseKey\", int.class),\n QueryValueEx(\"WindowsRegQueryValueEx\", int.class, byte[].class),\n EnumKeyEx(\"WindowsRegEnumKeyEx\", int.class, int.class, int.class),\n EnumValue(\"WindowsRegEnumValue\", int.class, int.class, int.class),\n QueryInfoKey(\"WindowsRegQueryInfoKey\", int.class),\n SetValueEx(\"WindowsRegSetValueEx\", int.class, byte[].class, byte[].class);\n\n private Method method;\n\n private WinRegistryMethod(String methodName, Class<?>... classes) {\n // WinRegistryKey.User.preferencesRoot.getClass().getMDeclaredMethods()\n try {\n method = WinRegistryKey.User.preferencesRoot.getClass().getDeclaredMethod(methodName, classes);\n } catch (Exception e) {\n System.err.println(\"Error\");\n System.err.println(e);\n }\n method.setAccessible(true);\n }\n\n public Object invoke(Preferences root, Object... objects)\n throws RegistryException {\n Object retValue;\n try {\n retValue = method.invoke(root, objects);\n verifyReturnValue(retValue);\n } catch (Throwable e) {\n String params = \"\";\n if (objects.length > 0) {\n params = objects[0].toString();\n for (int i = 1; i < objects.length; i++) {\n params += \", \" + objects[i];\n }\n }\n throw new RegistryException(\"Error invoking method: \" + method + \", with params: (\" + params + \")\", e);\n }\n return retValue;\n }\n\n protected void verifyReturnValue(Object retValue)\n throws RegistryException {}\n }\n\n private WinRegistry_TacB0sS() {}\n\n public static String readString(WinRegistryKey regKey, String key, String valueName)\n throws RegistryException {\n int retVal = ((int[]) WinRegistryMethod.OpenKey.invoke(regKey.preferencesRoot, regKey.key, toCstr(key),\n new Integer(KEY_READ)))[0];\n\n byte[] retValue = (byte[]) WinRegistryMethod.QueryValueEx.invoke(regKey.preferencesRoot, retVal,\n toCstr(valueName));\n WinRegistryMethod.CloseKey.invoke(regKey.preferencesRoot, retVal);\n\n /*\n * Should this return an Empty String.\n */\n return (retValue != null ? new String(retValue).trim() : null);\n }\n\n public static Map<String, String> readStringValues(WinRegistryKey regKey, String key)\n throws RegistryException {\n HashMap<String, String> results = new HashMap<String, String>();\n int retVal = ((int[]) WinRegistryMethod.OpenKey.invoke(regKey.preferencesRoot, regKey.key, toCstr(key),\n new Integer(KEY_READ)))[0];\n\n int[] info = (int[]) WinRegistryMethod.QueryInfoKey.invoke(regKey.preferencesRoot, retVal);\n\n int count = info[2]; // count\n int maxlen = info[3]; // value length max\n for (int index = 0; index < count; index++) {\n byte[] name = (byte[]) WinRegistryMethod.EnumValue.invoke(regKey.preferencesRoot, retVal,\n new Integer(index), new Integer(maxlen + 1));\n String value = readString(regKey, key, new String(name));\n results.put(new String(name).trim(), value);\n }\n\n WinRegistryMethod.CloseKey.invoke(regKey.preferencesRoot, retVal);\n return results;\n }\n\n public static List<String> readStringSubKeys(WinRegistryKey regKey, String key)\n throws RegistryException {\n List<String> results = new ArrayList<String>();\n int retVal = ((int[]) WinRegistryMethod.OpenKey.invoke(regKey.preferencesRoot, regKey.key, toCstr(key),\n new Integer(KEY_READ)))[0];\n\n int[] info = (int[]) WinRegistryMethod.QueryInfoKey.invoke(regKey.preferencesRoot, retVal);\n\n int count = info[0]; // Fix: info[2] was being used here with wrong results. Suggested by davenpcj, confirmed by\n // Petrucio\n int maxlen = info[3]; // value length max\n for (int index = 0; index < count; index++) {\n byte[] name = (byte[]) WinRegistryMethod.EnumValue.invoke(regKey.preferencesRoot, retVal,\n new Integer(index), new Integer(maxlen + 1));\n results.add(new String(name).trim());\n }\n\n WinRegistryMethod.CloseKey.invoke(regKey.preferencesRoot, retVal);\n return results;\n }\n\n public static void createKey(WinRegistryKey regKey, String key)\n throws RegistryException {\n int[] retVal = (int[]) WinRegistryMethod.CreateKeyEx.invoke(regKey.preferencesRoot, regKey.key, toCstr(key));\n WinRegistryMethod.CloseKey.invoke(regKey.preferencesRoot, retVal[0]);\n }\n\n public static void writeStringValue(WinRegistryKey regKey, String key, String valueName, String value)\n throws RegistryException {\n int retVal = ((int[]) WinRegistryMethod.OpenKey.invoke(regKey.preferencesRoot, regKey.key, toCstr(key),\n new Integer(KEY_ALL_ACCESS)))[0];\n\n WinRegistryMethod.SetValueEx.invoke(regKey.preferencesRoot, retVal, toCstr(valueName), toCstr(value));\n WinRegistryMethod.CloseKey.invoke(regKey.preferencesRoot, retVal);\n }\n\n public static void deleteKey(WinRegistryKey regKey, String key)\n throws RegistryException {\n WinRegistryMethod.DeleteKey.invoke(regKey.preferencesRoot, regKey.key, toCstr(key));\n }\n\n public static void deleteValue(WinRegistryKey regKey, String key, String value)\n throws RegistryException {\n int retVal = ((int[]) WinRegistryMethod.OpenKey.invoke(regKey.preferencesRoot, regKey.key, toCstr(key),\n new Integer(KEY_ALL_ACCESS)))[0];\n WinRegistryMethod.DeleteValue.invoke(regKey.preferencesRoot, retVal, toCstr(value));\n WinRegistryMethod.CloseKey.invoke(regKey.preferencesRoot, retVal);\n }\n\n // utility\n private static byte[] toCstr(String str) {\n byte[] result = new byte[str.length() + 1];\n\n for (int i = 0; i < str.length(); i++) {\n result[i] = (byte) str.charAt(i);\n }\n result[str.length()] = '\\0';\n return result;\n }\n}\n"
},
{
"answer_id": 22589715,
"author": "Ernestas Gruodis",
"author_id": 2111085,
"author_profile": "https://Stackoverflow.com/users/2111085",
"pm_score": -1,
"selected": false,
"text": "import java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\nimport java.util.prefs.Preferences;\n\npublic class WinRegistry {\n\n public static final int HKEY_CURRENT_USER = 0x80000001,\n HKEY_LOCAL_MACHINE = 0x80000002,\n REG_SUCCESS = 0,\n REG_NOTFOUND = 2,\n REG_ACCESSDENIED = 5,\n KEY_ALL_ACCESS = 0xf003f,\n KEY_READ = 0x20019;\n private static final Preferences userRoot = Preferences.userRoot(),\n systemRoot = Preferences.systemRoot();\n private static final Class<? extends Preferences> userClass = userRoot.getClass();\n private static Method regOpenKey,\n regCloseKey,\n regQueryValueEx,\n regEnumValue,\n regQueryInfoKey,\n regEnumKeyEx,\n regCreateKeyEx,\n regSetValueEx,\n regDeleteKey,\n regDeleteValue;\n\n static {\n try {\n (regOpenKey = userClass.getDeclaredMethod(\"WindowsRegOpenKey\", new Class[]{int.class, byte[].class, int.class})).setAccessible(true);\n (regCloseKey = userClass.getDeclaredMethod(\"WindowsRegCloseKey\", new Class[]{int.class})).setAccessible(true);\n (regQueryValueEx = userClass.getDeclaredMethod(\"WindowsRegQueryValueEx\", new Class[]{int.class, byte[].class})).setAccessible(true);\n (regEnumValue = userClass.getDeclaredMethod(\"WindowsRegEnumValue\", new Class[]{int.class, int.class, int.class})).setAccessible(true);\n (regQueryInfoKey = userClass.getDeclaredMethod(\"WindowsRegQueryInfoKey1\", new Class[]{int.class})).setAccessible(true);\n (regEnumKeyEx = userClass.getDeclaredMethod(\"WindowsRegEnumKeyEx\", new Class[]{int.class, int.class, int.class})).setAccessible(true);\n (regCreateKeyEx = userClass.getDeclaredMethod(\"WindowsRegCreateKeyEx\", new Class[]{int.class, byte[].class})).setAccessible(true);\n (regSetValueEx = userClass.getDeclaredMethod(\"WindowsRegSetValueEx\", new Class[]{int.class, byte[].class, byte[].class})).setAccessible(true);\n (regDeleteValue = userClass.getDeclaredMethod(\"WindowsRegDeleteValue\", new Class[]{int.class, byte[].class})).setAccessible(true);\n (regDeleteKey = userClass.getDeclaredMethod(\"WindowsRegDeleteKey\", new Class[]{int.class, byte[].class})).setAccessible(true);\n } catch (NoSuchMethodException | SecurityException ex) {\n Logger.getLogger(WinRegistry.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n\n /**\n * Read a value from key and value name\n *\n * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n * @param key\n * @param valueName\n * @return the value\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static String readString(int hkey, String key, String valueName) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n switch (hkey) {\n case HKEY_LOCAL_MACHINE:\n return readString(systemRoot, hkey, key, valueName);\n case HKEY_CURRENT_USER:\n return readString(userRoot, hkey, key, valueName);\n default:\n throw new IllegalArgumentException(\"hkey=\" + hkey);\n }\n }\n\n /**\n * Read value(s) and value name(s) form given key\n *\n * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n * @param key\n * @return the value name(s) plus the value(s)\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static Map<String, String> readStringValues(int hkey, String key) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n switch (hkey) {\n case HKEY_LOCAL_MACHINE:\n return readStringValues(systemRoot, hkey, key);\n case HKEY_CURRENT_USER:\n return readStringValues(userRoot, hkey, key);\n default:\n throw new IllegalArgumentException(\"hkey=\" + hkey);\n }\n }\n\n /**\n * Read the value name(s) from a given key\n *\n * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n * @param key\n * @return the value name(s)\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static List<String> readStringSubKeys(int hkey, String key) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n switch (hkey) {\n case HKEY_LOCAL_MACHINE:\n return readStringSubKeys(systemRoot, hkey, key);\n case HKEY_CURRENT_USER:\n return readStringSubKeys(userRoot, hkey, key);\n default:\n throw new IllegalArgumentException(\"hkey=\" + hkey);\n }\n }\n\n /**\n * Create a key\n *\n * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n * @param key\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static void createKey(int hkey, String key) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n int[] ret;\n switch (hkey) {\n case HKEY_LOCAL_MACHINE:\n ret = createKey(systemRoot, hkey, key);\n regCloseKey.invoke(systemRoot, new Object[]{ret[0]});\n break;\n case HKEY_CURRENT_USER:\n ret = createKey(userRoot, hkey, key);\n regCloseKey.invoke(userRoot, new Object[]{ret[0]});\n break;\n default:\n throw new IllegalArgumentException(\"hkey=\" + hkey);\n }\n\n if (ret[1] != REG_SUCCESS) {\n throw new IllegalArgumentException(\"rc=\" + ret[1] + \" key=\" + key);\n }\n }\n\n /**\n * Write a value in a given key/value name\n *\n * @param hkey\n * @param key\n * @param valueName\n * @param value\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static void writeStringValue(int hkey, String key, String valueName, String value) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n switch (hkey) {\n case HKEY_LOCAL_MACHINE:\n writeStringValue(systemRoot, hkey, key, valueName, value);\n break;\n case HKEY_CURRENT_USER:\n writeStringValue(userRoot, hkey, key, valueName, value);\n break;\n default:\n throw new IllegalArgumentException(\"hkey=\" + hkey);\n }\n }\n\n /**\n * Delete a given key\n *\n * @param hkey\n * @param key\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static void deleteKey(int hkey, String key) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n int rc = -1;\n switch (hkey) {\n case HKEY_LOCAL_MACHINE:\n rc = deleteKey(systemRoot, hkey, key);\n break;\n case HKEY_CURRENT_USER:\n rc = deleteKey(userRoot, hkey, key);\n }\n\n if (rc != REG_SUCCESS) {\n throw new IllegalArgumentException(\"rc=\" + rc + \" key=\" + key);\n }\n }\n\n /**\n * delete a value from a given key/value name\n *\n * @param hkey\n * @param key\n * @param value\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static void deleteValue(int hkey, String key, String value) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n int rc = -1;\n switch (hkey) {\n case HKEY_LOCAL_MACHINE:\n rc = deleteValue(systemRoot, hkey, key, value);\n break;\n case HKEY_CURRENT_USER:\n rc = deleteValue(userRoot, hkey, key, value);\n }\n\n if (rc != REG_SUCCESS) {\n throw new IllegalArgumentException(\"rc=\" + rc + \" key=\" + key + \" value=\" + value);\n }\n }\n\n private static int deleteValue(Preferences root, int hkey, String key, String value) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[]{hkey, toCstr(key), KEY_ALL_ACCESS});\n if (handles[1] != REG_SUCCESS) {\n return handles[1];//Can be REG_NOTFOUND, REG_ACCESSDENIED\n }\n int rc = ((Integer) regDeleteValue.invoke(root, new Object[]{handles[0], toCstr(value)}));\n regCloseKey.invoke(root, new Object[]{handles[0]});\n return rc;\n }\n\n private static int deleteKey(Preferences root, int hkey, String key) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n int rc = ((Integer) regDeleteKey.invoke(root, new Object[]{hkey, toCstr(key)}));\n return rc; //Can be REG_NOTFOUND, REG_ACCESSDENIED, REG_SUCCESS\n }\n\n private static String readString(Preferences root, int hkey, String key, String value) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[]{hkey, toCstr(key), KEY_READ});\n if (handles[1] != REG_SUCCESS) {\n return null;\n }\n byte[] valb = (byte[]) regQueryValueEx.invoke(root, new Object[]{handles[0], toCstr(value)});\n regCloseKey.invoke(root, new Object[]{handles[0]});\n return (valb != null ? new String(valb).trim() : null);\n }\n\n private static Map<String, String> readStringValues(Preferences root, int hkey, String key) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n HashMap<String, String> results = new HashMap<>();\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[]{hkey, toCstr(key), KEY_READ});\n if (handles[1] != REG_SUCCESS) {\n return null;\n }\n int[] info = (int[]) regQueryInfoKey.invoke(root, new Object[]{handles[0]});\n\n int count = info[0]; //Count \n int maxlen = info[3]; //Max value length\n for (int index = 0; index < count; index++) {\n byte[] name = (byte[]) regEnumValue.invoke(root, new Object[]{handles[0], index, maxlen + 1});\n String value = readString(hkey, key, new String(name));\n results.put(new String(name).trim(), value);\n }\n regCloseKey.invoke(root, new Object[]{handles[0]});\n return results;\n }\n\n private static List<String> readStringSubKeys(Preferences root, int hkey, String key) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n List<String> results = new ArrayList<>();\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[]{hkey, toCstr(key), KEY_READ});\n if (handles[1] != REG_SUCCESS) {\n return null;\n }\n int[] info = (int[]) regQueryInfoKey.invoke(root, new Object[]{handles[0]});\n\n int count = info[0];//Count\n int maxlen = info[3]; //Max value length\n for (int index = 0; index < count; index++) {\n byte[] name = (byte[]) regEnumKeyEx.invoke(root, new Object[]{handles[0], index, maxlen + 1});\n results.add(new String(name).trim());\n }\n regCloseKey.invoke(root, new Object[]{handles[0]});\n return results;\n }\n\n private static int[] createKey(Preferences root, int hkey, String key) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n return (int[]) regCreateKeyEx.invoke(root, new Object[]{hkey, toCstr(key)});\n }\n\n private static void writeStringValue(Preferences root, int hkey, String key, String valueName, String value) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[]{hkey, toCstr(key), KEY_ALL_ACCESS});\n regSetValueEx.invoke(root, new Object[]{handles[0], toCstr(valueName), toCstr(value)});\n regCloseKey.invoke(root, new Object[]{handles[0]});\n }\n\n private static byte[] toCstr(String str) {\n\n byte[] result = new byte[str.length() + 1];\n for (int i = 0; i < str.length(); i++) {\n result[i] = (byte) str.charAt(i);\n }\n result[str.length()] = 0;\n return result;\n }\n}\n"
},
{
"answer_id": 24877559,
"author": "Boann",
"author_id": 964243,
"author_profile": "https://Stackoverflow.com/users/964243",
"pm_score": 0,
"selected": false,
"text": "import java.util.*;\nimport java.lang.reflect.Method;\n\n/**\n * Simple registry access class implemented using some private APIs\n * in java.util.prefs. It has no other prerequisites.\n */\npublic final class WindowsRegistry {\n /**\n * Tells if the Windows registry functions are available.\n * (They will not be available when not running on Windows, for example.)\n */\n public static boolean isAvailable() {\n return initError == null;\n }\n\n\n\n /** Reads a string value from the given key and value name. */\n public static String readValue(String keyName, String valueName) {\n try (Key key = Key.open(keyName, KEY_READ)) {\n return fromByteArray(invoke(regQueryValueEx, key.handle, toByteArray(valueName)));\n }\n }\n\n\n\n /** Returns a map of all the name-value pairs in the given key. */\n public static Map<String,String> readValues(String keyName) {\n try (Key key = Key.open(keyName, KEY_READ)) {\n int[] info = invoke(regQueryInfoKey, key.handle);\n checkError(info[INFO_ERROR_CODE]);\n int count = info[INFO_COUNT_VALUES];\n int maxlen = info[INFO_MAX_VALUE_LENGTH] + 1;\n Map<String,String> values = new HashMap<>();\n for (int i = 0; i < count; i++) {\n String valueName = fromByteArray(invoke(regEnumValue, key.handle, i, maxlen));\n values.put(valueName, readValue(keyName, valueName));\n }\n return values;\n }\n }\n\n\n\n /** Returns a list of the names of all the subkeys of a key. */\n public static List<String> readSubkeys(String keyName) {\n try (Key key = Key.open(keyName, KEY_READ)) {\n int[] info = invoke(regQueryInfoKey, key.handle);\n checkError(info[INFO_ERROR_CODE]);\n int count = info[INFO_COUNT_KEYS];\n int maxlen = info[INFO_MAX_KEY_LENGTH] + 1;\n List<String> subkeys = new ArrayList<>(count);\n for (int i = 0; i < count; i++) {\n subkeys.add(fromByteArray(invoke(regEnumKeyEx, key.handle, i, maxlen)));\n }\n return subkeys;\n }\n }\n\n\n\n /** Writes a string value with a given key and value name. */\n public static void writeValue(String keyName, String valueName, String value) {\n try (Key key = Key.open(keyName, KEY_WRITE)) {\n checkError(invoke(regSetValueEx, key.handle, toByteArray(valueName), toByteArray(value)));\n }\n }\n\n\n\n /** Deletes a value within a key. */\n public static void deleteValue(String keyName, String valueName) {\n try (Key key = Key.open(keyName, KEY_WRITE)) {\n checkError(invoke(regDeleteValue, key.handle, toByteArray(valueName)));\n }\n }\n\n\n\n /**\n * Deletes a key and all values within it. If the key has subkeys, an\n * \"Access denied\" error will be thrown. Subkeys must be deleted separately.\n */\n public static void deleteKey(String keyName) {\n checkError(invoke(regDeleteKey, keyParts(keyName)));\n }\n\n\n\n /**\n * Creates a key. Parent keys in the path will also be created if necessary.\n * This method returns without error if the key already exists.\n */\n public static void createKey(String keyName) {\n int[] info = invoke(regCreateKeyEx, keyParts(keyName));\n checkError(info[INFO_ERROR_CODE]);\n invoke(regCloseKey, info[INFO_HANDLE]);\n }\n\n\n\n /**\n * The exception type that will be thrown if a registry operation fails.\n */\n public static class RegError extends RuntimeException {\n public RegError(String message, Throwable cause) {\n super(message, cause);\n }\n }\n\n\n\n\n\n // *************\n // PRIVATE STUFF\n // *************\n\n private WindowsRegistry() {}\n\n\n // Map of registry hive names to constants from winreg.h\n private static final Map<String,Integer> hives = new HashMap<>();\n static {\n hives.put(\"HKEY_CLASSES_ROOT\", 0x80000000); hives.put(\"HKCR\", 0x80000000);\n hives.put(\"HKEY_CURRENT_USER\", 0x80000001); hives.put(\"HKCU\", 0x80000001);\n hives.put(\"HKEY_LOCAL_MACHINE\", 0x80000002); hives.put(\"HKLM\", 0x80000002);\n hives.put(\"HKEY_USERS\", 0x80000003); hives.put(\"HKU\", 0x80000003);\n hives.put(\"HKEY_CURRENT_CONFIG\", 0x80000005); hives.put(\"HKCC\", 0x80000005);\n }\n\n\n // Splits a path such as HKEY_LOCAL_MACHINE\\Software\\Microsoft into a pair of\n // values used by the underlying API: An integer hive constant and a byte array\n // of the key path within that hive.\n private static Object[] keyParts(String fullKeyName) {\n int x = fullKeyName.indexOf('\\\\');\n String hiveName = x >= 0 ? fullKeyName.substring(0, x) : fullKeyName;\n String keyName = x >= 0 ? fullKeyName.substring(x + 1) : \"\";\n Integer hkey = hives.get(hiveName);\n if (hkey == null) throw new RegError(\"Unknown registry hive: \" + hiveName, null);\n return new Object[] { hkey, toByteArray(keyName) };\n }\n\n\n // Type encapsulating a native handle to a registry key\n private static class Key implements AutoCloseable {\n final int handle;\n\n private Key(int handle) {\n this.handle = handle;\n }\n\n static Key open(String keyName, int accessMode) {\n Object[] keyParts = keyParts(keyName);\n int[] ret = invoke(regOpenKey, keyParts[0], keyParts[1], accessMode);\n checkError(ret[INFO_ERROR_CODE]);\n return new Key(ret[INFO_HANDLE]);\n }\n\n @Override\n public void close() {\n invoke(regCloseKey, handle);\n }\n }\n\n\n // Array index constants for results of regOpenKey, regCreateKeyEx, and regQueryInfoKey\n private static final int\n INFO_HANDLE = 0,\n INFO_COUNT_KEYS = 0,\n INFO_ERROR_CODE = 1,\n INFO_COUNT_VALUES = 2,\n INFO_MAX_KEY_LENGTH = 3,\n INFO_MAX_VALUE_LENGTH = 4;\n\n\n // Registry access mode constants from winnt.h\n private static final int\n KEY_READ = 0x20019,\n KEY_WRITE = 0x20006;\n\n\n // Error constants from winerror.h\n private static final int\n ERROR_SUCCESS = 0,\n ERROR_FILE_NOT_FOUND = 2,\n ERROR_ACCESS_DENIED = 5;\n\n private static void checkError(int e) {\n if (e == ERROR_SUCCESS) return;\n throw new RegError(\n e == ERROR_FILE_NOT_FOUND ? \"Key not found\" :\n e == ERROR_ACCESS_DENIED ? \"Access denied\" :\n (\"Error number \" + e), null);\n }\n\n\n // Registry access methods in java.util.prefs.WindowsPreferences\n private static final Method\n regOpenKey = getMethod(\"WindowsRegOpenKey\", int.class, byte[].class, int.class),\n regCloseKey = getMethod(\"WindowsRegCloseKey\", int.class),\n regQueryValueEx = getMethod(\"WindowsRegQueryValueEx\", int.class, byte[].class),\n regQueryInfoKey = getMethod(\"WindowsRegQueryInfoKey\", int.class),\n regEnumValue = getMethod(\"WindowsRegEnumValue\", int.class, int.class, int.class),\n regEnumKeyEx = getMethod(\"WindowsRegEnumKeyEx\", int.class, int.class, int.class),\n regSetValueEx = getMethod(\"WindowsRegSetValueEx\", int.class, byte[].class, byte[].class),\n regDeleteValue = getMethod(\"WindowsRegDeleteValue\", int.class, byte[].class),\n regDeleteKey = getMethod(\"WindowsRegDeleteKey\", int.class, byte[].class),\n regCreateKeyEx = getMethod(\"WindowsRegCreateKeyEx\", int.class, byte[].class);\n\n private static Throwable initError;\n\n private static Method getMethod(String methodName, Class<?>... parameterTypes) {\n try {\n Method m = java.util.prefs.Preferences.systemRoot().getClass()\n .getDeclaredMethod(methodName, parameterTypes);\n m.setAccessible(true);\n return m;\n } catch (Throwable t) {\n initError = t;\n return null;\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n private static <T> T invoke(Method method, Object... args) {\n if (initError != null)\n throw new RegError(\"Registry methods are not available\", initError);\n try {\n return (T)method.invoke(null, args);\n } catch (Exception e) {\n throw new RegError(null, e);\n }\n }\n\n\n // Conversion of strings to/from null-terminated byte arrays.\n // There is no support for Unicode; sorry, this is a limitation\n // of the underlying methods that Java makes available.\n private static byte[] toByteArray(String str) {\n byte[] bytes = new byte[str.length() + 1];\n for (int i = 0; i < str.length(); i++)\n bytes[i] = (byte)str.charAt(i);\n return bytes;\n }\n\n private static String fromByteArray(byte[] bytes) {\n if (bytes == null) return null;\n char[] chars = new char[bytes.length - 1];\n for (int i = 0; i < chars.length; i++)\n chars[i] = (char)((int)bytes[i] & 0xFF);\n return new String(chars);\n }\n}\n"
},
{
"answer_id": 26097666,
"author": "Vipul Paralikar",
"author_id": 1677308,
"author_profile": "https://Stackoverflow.com/users/1677308",
"pm_score": 2,
"selected": false,
"text": "java.util.prefs java.util.prefs.Preferences HKCU HKLM import java.util.prefs.Preferences;\n\npublic class RegistryDemo {\n public static final String PREF_KEY = \"org.username\";\n public static void main(String[] args) {\n //\n // Write Preferences information to HKCU (HKEY_CURRENT_USER),\n // HKCU\\Software\\JavaSoft\\Prefs\\org.username\n //\n Preferences userPref = Preferences.userRoot();\n userPref.put(PREF_KEY, \"xyz\");\n\n //\n // Below we read back the value we've written in the code above.\n //\n System.out.println(\"Preferences = \"\n + userPref.get(PREF_KEY, PREF_KEY + \" was not found.\"));\n\n //\n // Write Preferences information to HKLM (HKEY_LOCAL_MACHINE),\n // HKLM\\Software\\JavaSoft\\Prefs\\org.username\n //\n Preferences systemPref = Preferences.systemRoot();\n systemPref.put(PREF_KEY, \"xyz\");\n\n //\n // Read back the value we've written in the code above.\n //\n System.out.println(\"Preferences = \"\n + systemPref.get(PREF_KEY, PREF_KEY + \" was not found.\"));\n }\n}\n"
},
{
"answer_id": 30019357,
"author": "BullyWiiPlaza",
"author_id": 3764804,
"author_profile": "https://Stackoverflow.com/users/3764804",
"pm_score": 3,
"selected": false,
"text": "reg import .reg reg query import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\n\npublic class WindowsRegistry\n{\n public static void importSilently(String regFilePath) throws IOException,\n InterruptedException\n {\n if (!new File(regFilePath).exists())\n {\n throw new FileNotFoundException();\n }\n\n Process importer = Runtime.getRuntime().exec(\"reg import \" + regFilePath);\n\n importer.waitFor();\n }\n\n public static void overwriteValue(String keyPath, String keyName,\n String keyValue) throws IOException, InterruptedException\n {\n Process overwriter = Runtime.getRuntime().exec(\n \"reg add \" + keyPath + \" /t REG_SZ /v \\\"\" + keyName + \"\\\" /d \"\n + keyValue + \" /f\");\n\n overwriter.waitFor();\n }\n\n public static String getValue(String keyPath, String keyName)\n throws IOException, InterruptedException\n {\n Process keyReader = Runtime.getRuntime().exec(\n \"reg query \\\"\" + keyPath + \"\\\" /v \\\"\" + keyName + \"\\\"\");\n\n BufferedReader outputReader;\n String readLine;\n StringBuffer outputBuffer = new StringBuffer();\n\n outputReader = new BufferedReader(new InputStreamReader(\n keyReader.getInputStream()));\n\n while ((readLine = outputReader.readLine()) != null)\n {\n outputBuffer.append(readLine);\n }\n\n String[] outputComponents = outputBuffer.toString().split(\" \");\n\n keyReader.waitFor();\n\n return outputComponents[outputComponents.length - 1];\n }\n}\n"
},
{
"answer_id": 35532028,
"author": "pratapvaibhav19",
"author_id": 4585099,
"author_profile": "https://Stackoverflow.com/users/4585099",
"pm_score": 3,
"selected": false,
"text": "import java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.StringTokenizer;\nimport java.util.prefs.Preferences;\n\npublic class WinRegistry {\n\n private static final int REG_SUCCESS = 0;\n private static final int REG_NOTFOUND = 2;\n private static final int KEY_READ = 0x20019;\n private static final int REG_ACCESSDENIED = 5;\n private static final int KEY_ALL_ACCESS = 0xf003f;\n public static final int HKEY_CLASSES_ROOT = 0x80000000;\n public static final int HKEY_CURRENT_USER = 0x80000001;\n public static final int HKEY_LOCAL_MACHINE = 0x80000002;\n private static final String CLASSES_ROOT = \"HKEY_CLASSES_ROOT\";\n private static final String CURRENT_USER = \"HKEY_CURRENT_USER\";\n private static final String LOCAL_MACHINE = \"HKEY_LOCAL_MACHINE\";\n private static Preferences userRoot = Preferences.userRoot();\n private static Preferences systemRoot = Preferences.systemRoot();\n private static Class<? extends Preferences> userClass = userRoot.getClass();\n private static Method regOpenKey = null;\n private static Method regCloseKey = null;\n private static Method regQueryValueEx = null;\n private static Method regEnumValue = null;\n private static Method regQueryInfoKey = null;\n private static Method regEnumKeyEx = null;\n private static Method regCreateKeyEx = null;\n private static Method regSetValueEx = null;\n private static Method regDeleteKey = null;\n private static Method regDeleteValue = null;\n\n static {\n try {\n regOpenKey = userClass.getDeclaredMethod(\"WindowsRegOpenKey\", new Class[] {int.class, byte[].class, int.class});\n regOpenKey.setAccessible(true);\n regCloseKey = userClass.getDeclaredMethod(\"WindowsRegCloseKey\", new Class[] {int.class});\n regCloseKey.setAccessible(true);\n regQueryValueEx = userClass.getDeclaredMethod(\"WindowsRegQueryValueEx\", new Class[] {int.class, byte[].class});\n regQueryValueEx.setAccessible(true);\n regEnumValue = userClass.getDeclaredMethod(\"WindowsRegEnumValue\", new Class[] {int.class, int.class, int.class});\n regEnumValue.setAccessible(true);\n regQueryInfoKey = userClass.getDeclaredMethod(\"WindowsRegQueryInfoKey1\", new Class[] {int.class});\n regQueryInfoKey.setAccessible(true);\n regEnumKeyEx = userClass.getDeclaredMethod(\"WindowsRegEnumKeyEx\", new Class[] {int.class, int.class, int.class}); \n regEnumKeyEx.setAccessible(true);\n regCreateKeyEx = userClass.getDeclaredMethod(\"WindowsRegCreateKeyEx\", new Class[] {int.class, byte[].class}); \n regCreateKeyEx.setAccessible(true);\n regSetValueEx = userClass.getDeclaredMethod(\"WindowsRegSetValueEx\", new Class[] {int.class, byte[].class, byte[].class}); \n regSetValueEx.setAccessible(true);\n regDeleteValue = userClass.getDeclaredMethod(\"WindowsRegDeleteValue\", new Class[] {int.class, byte[].class}); \n regDeleteValue.setAccessible(true);\n regDeleteKey = userClass.getDeclaredMethod(\"WindowsRegDeleteKey\", new Class[] {int.class, byte[].class}); \n regDeleteKey.setAccessible(true);\n }\n catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n /**\n * Reads value for the key from given path\n * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n * @param path\n * @param key\n * @return the value\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n * @throws IOException \n */\n public static String valueForKey(int hkey, String path, String key) \n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IOException {\n if (hkey == HKEY_LOCAL_MACHINE)\n return valueForKey(systemRoot, hkey, path, key);\n else if (hkey == HKEY_CURRENT_USER)\n return valueForKey(userRoot, hkey, path, key);\n else\n return valueForKey(null, hkey, path, key);\n }\n\n /**\n * Reads all key(s) and value(s) from given path\n * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n * @param path\n * @return the map of key(s) and corresponding value(s)\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n * @throws IOException \n */\n public static Map<String, String> valuesForPath(int hkey, String path) \n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IOException {\n if (hkey == HKEY_LOCAL_MACHINE)\n return valuesForPath(systemRoot, hkey, path);\n else if (hkey == HKEY_CURRENT_USER)\n return valuesForPath(userRoot, hkey, path);\n else\n return valuesForPath(null, hkey, path);\n }\n\n /**\n * Read all the subkey(s) from a given path\n * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n * @param path\n * @return the subkey(s) list\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static List<String> subKeysForPath(int hkey, String path)\n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n if (hkey == HKEY_LOCAL_MACHINE)\n return subKeysForPath(systemRoot, hkey, path);\n else if (hkey == HKEY_CURRENT_USER)\n return subKeysForPath(userRoot, hkey, path);\n else\n return subKeysForPath(null, hkey, path);\n }\n\n /**\n * Create a key\n * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n * @param key\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static void createKey(int hkey, String key) \n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n int [] ret;\n if (hkey == HKEY_LOCAL_MACHINE) {\n ret = createKey(systemRoot, hkey, key);\n regCloseKey.invoke(systemRoot, new Object[] { new Integer(ret[0]) });\n } else if (hkey == HKEY_CURRENT_USER) {\n ret = createKey(userRoot, hkey, key);\n regCloseKey.invoke(userRoot, new Object[] { new Integer(ret[0]) });\n } else\n throw new IllegalArgumentException(\"hkey=\" + hkey);\n if (ret[1] != REG_SUCCESS)\n throw new IllegalArgumentException(\"rc=\" + ret[1] + \" key=\" + key);\n }\n\n /**\n * Write a value in a given key/value name\n * @param hkey\n * @param key\n * @param valueName\n * @param value\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static void writeStringValue(int hkey, String key, String valueName, String value) \n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n if (hkey == HKEY_LOCAL_MACHINE)\n writeStringValue(systemRoot, hkey, key, valueName, value);\n else if (hkey == HKEY_CURRENT_USER)\n writeStringValue(userRoot, hkey, key, valueName, value);\n else\n throw new IllegalArgumentException(\"hkey=\" + hkey);\n }\n\n /**\n * Delete a given key\n * @param hkey\n * @param key\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static void deleteKey(int hkey, String key) \n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n int rc = -1;\n if (hkey == HKEY_LOCAL_MACHINE)\n rc = deleteKey(systemRoot, hkey, key);\n else if (hkey == HKEY_CURRENT_USER)\n rc = deleteKey(userRoot, hkey, key);\n if (rc != REG_SUCCESS)\n throw new IllegalArgumentException(\"rc=\" + rc + \" key=\" + key);\n }\n\n /**\n * delete a value from a given key/value name\n * @param hkey\n * @param key\n * @param value\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static void deleteValue(int hkey, String key, String value) \n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n int rc = -1;\n if (hkey == HKEY_LOCAL_MACHINE)\n rc = deleteValue(systemRoot, hkey, key, value);\n else if (hkey == HKEY_CURRENT_USER)\n rc = deleteValue(userRoot, hkey, key, value);\n if (rc != REG_SUCCESS)\n throw new IllegalArgumentException(\"rc=\" + rc + \" key=\" + key + \" value=\" + value);\n }\n\n // =====================\n\n private static int deleteValue(Preferences root, int hkey, String key, String value)\n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {new Integer(hkey), toCstr(key), new Integer(KEY_ALL_ACCESS)});\n if (handles[1] != REG_SUCCESS)\n return handles[1]; // can be REG_NOTFOUND, REG_ACCESSDENIED\n int rc =((Integer) regDeleteValue.invoke(root, new Object[] {new Integer(handles[0]), toCstr(value)})).intValue();\n regCloseKey.invoke(root, new Object[] { new Integer(handles[0])});\n return rc;\n }\n\n private static int deleteKey(Preferences root, int hkey, String key) \n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n int rc =((Integer) regDeleteKey.invoke(root, new Object[] {new Integer(hkey), toCstr(key)})).intValue();\n return rc; // can REG_NOTFOUND, REG_ACCESSDENIED, REG_SUCCESS\n }\n\n private static String valueForKey(Preferences root, int hkey, String path, String key)\n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IOException {\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {new Integer(hkey), toCstr(path), new Integer(KEY_READ)});\n if (handles[1] != REG_SUCCESS)\n throw new IllegalArgumentException(\"The system can not find the specified path: '\"+getParentKey(hkey)+\"\\\\\"+path+\"'\");\n byte[] valb = (byte[]) regQueryValueEx.invoke(root, new Object[] {new Integer(handles[0]), toCstr(key)});\n regCloseKey.invoke(root, new Object[] {new Integer(handles[0])});\n return (valb != null ? parseValue(valb) : queryValueForKey(hkey, path, key));\n }\n\n private static String queryValueForKey(int hkey, String path, String key) throws IOException {\n return queryValuesForPath(hkey, path).get(key);\n }\n\n private static Map<String,String> valuesForPath(Preferences root, int hkey, String path)\n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IOException {\n HashMap<String, String> results = new HashMap<String,String>();\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {new Integer(hkey), toCstr(path), new Integer(KEY_READ)});\n if (handles[1] != REG_SUCCESS)\n throw new IllegalArgumentException(\"The system can not find the specified path: '\"+getParentKey(hkey)+\"\\\\\"+path+\"'\");\n int[] info = (int[]) regQueryInfoKey.invoke(root, new Object[] {new Integer(handles[0])});\n int count = info[2]; // Fixed: info[0] was being used here\n int maxlen = info[4]; // while info[3] was being used here, causing wrong results\n for(int index=0; index<count; index++) {\n byte[] valb = (byte[]) regEnumValue.invoke(root, new Object[] {new Integer(handles[0]), new Integer(index), new Integer(maxlen + 1)});\n String vald = parseValue(valb);\n if(valb == null || vald.isEmpty())\n return queryValuesForPath(hkey, path);\n results.put(vald, valueForKey(root, hkey, path, vald));\n }\n regCloseKey.invoke(root, new Object[] {new Integer(handles[0])});\n return results;\n }\n\n /**\n * Searches recursively into the path to find the value for key. This method gives \n * only first occurrence value of the key. If required to get all values in the path \n * recursively for this key, then {@link #valuesForKeyPath(int hkey, String path, String key)} \n * should be used.\n * @param hkey\n * @param path\n * @param key\n * @param list\n * @return the value of given key obtained recursively\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n * @throws IOException\n */\n public static String valueForKeyPath(int hkey, String path, String key)\n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IOException {\n String val;\n try {\n val = valuesForKeyPath(hkey, path, key).get(0);\n } catch(IndexOutOfBoundsException e) {\n throw new IllegalArgumentException(\"The system can not find the key: '\"+key+\"' after \"\n + \"searching the specified path: '\"+getParentKey(hkey)+\"\\\\\"+path+\"'\");\n }\n return val;\n }\n\n /**\n * Searches recursively into given path for particular key and stores obtained value in list\n * @param hkey\n * @param path\n * @param key\n * @param list\n * @return list containing values for given key obtained recursively\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n * @throws IOException\n */\n public static List<String> valuesForKeyPath(int hkey, String path, String key)\n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IOException {\n List<String> list = new ArrayList<String>();\n if (hkey == HKEY_LOCAL_MACHINE)\n return valuesForKeyPath(systemRoot, hkey, path, key, list);\n else if (hkey == HKEY_CURRENT_USER)\n return valuesForKeyPath(userRoot, hkey, path, key, list);\n else\n return valuesForKeyPath(null, hkey, path, key, list);\n }\n\n private static List<String> valuesForKeyPath(Preferences root, int hkey, String path, String key, List<String> list)\n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IOException {\n if(!isDirectory(root, hkey, path)) {\n takeValueInListForKey(hkey, path, key, list);\n } else {\n List<String> subKeys = subKeysForPath(root, hkey, path);\n for(String subkey: subKeys) {\n String newPath = path+\"\\\\\"+subkey;\n if(isDirectory(root, hkey, newPath))\n valuesForKeyPath(root, hkey, newPath, key, list);\n takeValueInListForKey(hkey, newPath, key, list);\n }\n }\n return list;\n }\n\n /**\n * Takes value for key in list\n * @param hkey\n * @param path\n * @param key\n * @param list\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n * @throws IOException\n */\n private static void takeValueInListForKey(int hkey, String path, String key, List<String> list)\n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IOException {\n String value = valueForKey(hkey, path, key);\n if(value != null)\n list.add(value);\n }\n\n /**\n * Checks if the path has more subkeys or not\n * @param root\n * @param hkey\n * @param path\n * @return true if path has subkeys otherwise false\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n private static boolean isDirectory(Preferences root, int hkey, String path)\n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n return !subKeysForPath(root, hkey, path).isEmpty();\n }\n\n private static List<String> subKeysForPath(Preferences root, int hkey, String path)\n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n List<String> results = new ArrayList<String>();\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {new Integer(hkey), toCstr(path), new Integer(KEY_READ)});\n if (handles[1] != REG_SUCCESS)\n throw new IllegalArgumentException(\"The system can not find the specified path: '\"+getParentKey(hkey)+\"\\\\\"+path+\"'\");\n int[] info = (int[]) regQueryInfoKey.invoke(root, new Object[] {new Integer(handles[0])});\n int count = info[0]; // Fix: info[2] was being used here with wrong results. Suggested by davenpcj, confirmed by Petrucio\n int maxlen = info[3]; // value length max\n for(int index=0; index<count; index++) {\n byte[] valb = (byte[]) regEnumKeyEx.invoke(root, new Object[] {new Integer(handles[0]), new Integer(index), new Integer(maxlen + 1)});\n results.add(parseValue(valb));\n }\n regCloseKey.invoke(root, new Object[] {new Integer(handles[0])});\n return results;\n }\n\n private static int [] createKey(Preferences root, int hkey, String key)\n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n return (int[]) regCreateKeyEx.invoke(root, new Object[] {new Integer(hkey), toCstr(key)});\n }\n\n private static void writeStringValue(Preferences root, int hkey, String key, String valueName, String value) \n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {new Integer(hkey), toCstr(key), new Integer(KEY_ALL_ACCESS)});\n regSetValueEx.invoke(root, new Object[] {new Integer(handles[0]), toCstr(valueName), toCstr(value)}); \n regCloseKey.invoke(root, new Object[] {new Integer(handles[0])});\n }\n\n /**\n * Makes cmd query for the given hkey and path then executes the query\n * @param hkey\n * @param path\n * @return the map containing all results in form of key(s) and value(s) obtained by executing query\n * @throws IOException\n */\n private static Map<String, String> queryValuesForPath(int hkey, String path) throws IOException {\n String line;\n StringBuilder builder = new StringBuilder();\n Map<String, String> map = new HashMap<String, String>();\n Process process = Runtime.getRuntime().exec(\"reg query \\\"\"+getParentKey(hkey)+\"\\\\\" + path + \"\\\"\");\n BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));\n while((line = reader.readLine()) != null) {\n if(!line.contains(\"REG_\"))\n continue;\n StringTokenizer tokenizer = new StringTokenizer(line, \" \\t\");\n while(tokenizer.hasMoreTokens()) {\n String token = tokenizer.nextToken();\n if(token.startsWith(\"REG_\"))\n builder.append(\"\\t \");\n else\n builder.append(token).append(\" \");\n }\n String[] arr = builder.toString().split(\"\\t\");\n map.put(arr[0].trim(), arr[1].trim());\n builder.setLength(0);\n }\n return map;\n }\n\n /**\n * Determines the string equivalent of hkey\n * @param hkey\n * @return string equivalent of hkey\n */\n private static String getParentKey(int hkey) {\n if(hkey == HKEY_CLASSES_ROOT)\n return CLASSES_ROOT;\n else if(hkey == HKEY_CURRENT_USER)\n return CURRENT_USER;\n else if(hkey == HKEY_LOCAL_MACHINE)\n return LOCAL_MACHINE;\n return null;\n }\n\n /**\n *Intern method which adds the trailing \\0 for the handle with java.dll\n * @param str String\n * @return byte[] \n */\n private static byte[] toCstr(String str) {\n if(str == null)\n str = \"\";\n return (str += \"\\0\").getBytes();\n }\n\n /**\n * Method removes the trailing \\0 which is returned from the java.dll (just if the last sign is a \\0)\n * @param buf the byte[] buffer which every read method returns\n * @return String a parsed string without the trailing \\0\n */\n private static String parseValue(byte buf[]) {\n if(buf == null)\n return null;\n String ret = new String(buf);\n if(ret.charAt(ret.length()-1) == '\\0')\n return ret.substring(0, ret.length()-1);\n return ret;\n }\n} \n String hex = WinRegistry.valueForKey(WinRegistry.HKEY_LOCAL_MACHINE, \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\WindowsUpdate\\\\Auto Update\", \"AUOptions\");\n Map<String, String> map = WinRegistry.valuesForPath(WinRegistry.HKEY_LOCAL_MACHINE, \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\WSMAN\");\n String val = WinRegistry.valueForKeyPath(WinRegistry.HKEY_LOCAL_MACHINE, \"System\", \"TypeID\");\n List<String> list = WinRegistry.valuesForKeyPath(\n WinRegistry.HKEY_LOCAL_MACHINE, //HKEY \"SOFTWARE\\\\Wow6432Node\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall\", //path \"DisplayName\" //Key\n );\n List<String> list3 = WinRegistry.subKeysForPath(WinRegistry.HKEY_CURRENT_USER, \"Software\");\n"
},
{
"answer_id": 73575038,
"author": "Gon Juarez",
"author_id": 9296473,
"author_profile": "https://Stackoverflow.com/users/9296473",
"pm_score": 0,
"selected": false,
"text": " public class Registry {\n\n public static enum key {\n HKEY_CURRENT_USER, HKEY_USERS, HKEY_LOCAL_MACHINE, HKEY_CURRENT_CONFIG;\n };\n\n public static enum dataType {\n REG_BINARY, REG_DWORD, REG_EXPAND_SZ, REG_MULTI_SZ, REG_SZ, REG_RESOURCE_LIST, REG_RESOURCE_REQUIREMENTS_LIST, REG_FULL_RESOURCE_DESCRIPTOR, REG_NONE, REG_LINK, REG_QWORD;\n }\n\n public static enum userKey {\n AppEvents, Console, Control_Panel, Enviroment, EUDC, Keyboard_Layout, Microsoft, Network, Printers, Software, System, Uninstall, Volatile_Enviroment;\n }\n\n public static void overWriteSoftwareInt(String key, String userKey, String path, String valueKey, String datatype, int value) {\n try {\n Process process = Runtime.getRuntime().exec(\"reg add \" + key + \"\\\\\" + userKey + \"\\\\\" + path + \" /t \" + datatype + \" /v \\\"\" + valueKey + \"\\\" /d \" + value);\n process.waitFor();\n } catch (IOException ex) {\n // Logger.getLogger(Registry.class.getName()).log(Level.SEVERE, null, ex);\n } catch (InterruptedException ex) {\n Logger.getLogger(Registry.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n \n public static void overWriteSoftwareString(String key, String userKey, String path, String valueKey, String datatype, int value) {\n try {\n Process process = Runtime.getRuntime().exec(\"reg add \" + key + \"\\\\\" + userKey + \"\\\\\" + path + \" /t \" + datatype + \" /v \\\"\" + valueKey + \"\\\" /d \\\"\" + value+\"\\\"\");\n process.waitFor();\n } catch (IOException ex) {\n // Logger.getLogger(Registry.class.getName()).log(Level.SEVERE, null, ex);\n } catch (InterruptedException ex) {\n Logger.getLogger(Registry.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n\n public static void deleteValue(String key, String userKey, String path, String valueKey) {\n try {\n Process process = Runtime.getRuntime().exec(\"reg delete \" + key + \"\\\\\" + userKey + \"\\\\\" + path + \" /v \\\"\" + valueKey + \"\\\" /f\");\n process.waitFor();\n } catch (IOException ex) {\n // Logger.getLogger(Registry.class.getName()).log(Level.SEVERE, null, ex);\n } catch (InterruptedException ex) {\n Logger.getLogger(Registry.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n}\n Registry.deleteValue(Registry.key.HKEY_CURRENT_USER.name(), Registry.userKey.Software.name(), \"path\", \"valueName\");\n Registry.overWriteSoftwareInt(Registry.key.HKEY_CURRENT_USER.name(), Registry.userKey.Software.name(), \"path\", \"valueName\", Registry.dataType.REG_DWORD.name(), 0);\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
62,294 |
<p>The default check-in action for a work-item is "resolve". I'd like to set it to "associate" so that this work item isn't automaticaly closed if I check-in stuff too fast. How can I do that?</p>
|
[
{
"answer_id": 44068378,
"author": "maf-soft",
"author_id": 1855801,
"author_profile": "https://Stackoverflow.com/users/1855801",
"pm_score": 0,
"selected": false,
"text": "HKEY_CURRENT_USER\\Software\\Microsoft\\VisualStudio\\14.0\\TeamFoundation\\SourceControl\\Behavior\n ResolveAsDefaultCheckinAction True False"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6555/"
] |
62,317 |
<p>In PHP, how can I replicate the expand/contract feature for Tinyurls as on search.twitter.com?</p>
|
[
{
"answer_id": 62367,
"author": "Paul Dixon",
"author_id": 6521,
"author_profile": "https://Stackoverflow.com/users/6521",
"pm_score": 4,
"selected": true,
"text": "GET /dmsfm HTTP/1.0\nHost: tinyurl.com\n HTTP/1.0 301 Moved Permanently\nConnection: close\nX-Powered-By: PHP/5.2.6\nLocation: http://en.wikipedia.org/wiki/TinyURL\nContent-type: text/html\nContent-Length: 0\nDate: Mon, 15 Sep 2008 12:29:04 GMT\nServer: TinyURL/1.6\n <?php\n$tinyurl=\"dmsfm\";\n\n$fp = fsockopen(\"tinyurl.com\", 80, $errno, $errstr, 30);\nif (!$fp) {\n echo \"$errstr ($errno)<br />\\n\";\n} else {\n $out = \"GET /$tinyurl HTTP/1.0\\r\\n\";\n $out .= \"Host: tinyurl.com\\r\\n\";\n $out .= \"Connection: Close\\r\\n\\r\\n\";\n\n $response=\"\";\n\n fwrite($fp, $out);\n while (!feof($fp)) {\n $response.=fgets($fp, 128);\n }\n fclose($fp);\n\n //now parse the Location: header out of the response\n\n}\n?>\n"
},
{
"answer_id": 62597,
"author": "Udo",
"author_id": 6907,
"author_profile": "https://Stackoverflow.com/users/6907",
"pm_score": 2,
"selected": false,
"text": "function make_tinyurl($longurl)\n{\n return(implode('', file(\n 'http://tinyurl.com/api-create.php?url='.urlencode($longurl))));\n}\n\n// make an example call\nprint(make_tinyurl('http://www.joelonsoftware.com/items/2008/09/15.html'));\n"
},
{
"answer_id": 63072,
"author": "barredo",
"author_id": 7398,
"author_profile": "https://Stackoverflow.com/users/7398",
"pm_score": 0,
"selected": false,
"text": "<?php\nfunction getTinyUrl($url) {\nreturn file_get_contents('http://tinyurl.com/api-create.php?url='.$url);\n}\n?>\n"
},
{
"answer_id": 63091,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 2,
"selected": false,
"text": "/api/resolve_tinyurl/http://tinyurl.com/abcd def resolve_tinyurl(url):\n key = md5( url.lower_case() )\n if cache.has_key(key)\n return cache[md5]\n else:\n resolved = query_tinyurl(url)\n cache[key] = resolved\n return resolved\n cache"
},
{
"answer_id": 1735913,
"author": "GZipp",
"author_id": 153350,
"author_profile": "https://Stackoverflow.com/users/153350",
"pm_score": 0,
"selected": false,
"text": "$tinyurl = 'http://tinyurl.com/3fvbx8';\n$context = stream_context_create(array('http' => array('method' => 'HEAD')));\n$response = file_get_contents($tinyurl, null, $context);\n\n$location = '';\nforeach ($http_response_header as $header) {\n if (strpos($header, 'Location:') === 0) {\n $location = trim(strrchr($header, ' '));\n break;\n }\n}\necho $location;\n// http://www.pingdom.com/reports/vb1395a6sww3/check_overview/?name=twitter.com%2Fhome\n"
},
{
"answer_id": 1975639,
"author": "Pons",
"author_id": 231676,
"author_profile": "https://Stackoverflow.com/users/231676",
"pm_score": 1,
"selected": false,
"text": "function doShortURLDecode($url) {\n $ch = @curl_init($url);\n @curl_setopt($ch, CURLOPT_HEADER, TRUE);\n @curl_setopt($ch, CURLOPT_NOBODY, TRUE);\n @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);\n @curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);\n $response = @curl_exec($ch);\n preg_match('/Location: (.*)\\n/', $response, $a);\n if (!isset($a[1])) return $url;\n return $a[1];\n}\n"
},
{
"answer_id": 57036749,
"author": "rubo77",
"author_id": 1069083,
"author_profile": "https://Stackoverflow.com/users/1069083",
"pm_score": 0,
"selected": false,
"text": "https://stackoverflow.com/q/62317 public function doShortURLDecode($url) {\n $ch = @curl_init($url);\n @curl_setopt($ch, CURLOPT_HEADER, TRUE);\n @curl_setopt($ch, CURLOPT_NOBODY, TRUE);\n @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);\n @curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);\n $response = @curl_exec($ch);\n $cleanresponse= preg_replace('/[^A-Za-z0-9\\- _,.:\\n\\/]/', '', $response);\n preg_match('/Location: (.*)[\\n\\r]/', $cleanresponse, $a);\n if (!isset($a[1])) return $url;\n return parse_url($url, PHP_URL_SCHEME).'://'.parse_url($url, PHP_URL_HOST).$a[1];\n}\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
62,340 |
<pre><code>std::vector<int> ints;
// ... fill ints with random values
for(std::vector<int>::iterator it = ints.begin(); it != ints.end(); )
{
if(*it < 10)
{
*it = ints.back();
ints.pop_back();
continue;
}
it++;
}
</code></pre>
<p>This code is not working because when <code>pop_back()</code> is called, <code>it</code> is invalidated. But I don't find any doc talking about invalidation of iterators in <code>std::vector::pop_back()</code>.</p>
<p>Do you have some links about that?</p>
|
[
{
"answer_id": 62522,
"author": "Ben",
"author_id": 6930,
"author_profile": "https://Stackoverflow.com/users/6930",
"pm_score": 5,
"selected": true,
"text": "pop_back() pop_back()"
},
{
"answer_id": 62878,
"author": "Pieter",
"author_id": 5822,
"author_profile": "https://Stackoverflow.com/users/5822",
"pm_score": 3,
"selected": false,
"text": "{ iterator tmp = a.end(); \n--tmp; \na.erase(tmp); } \n"
},
{
"answer_id": 63135,
"author": "NeARAZ",
"author_id": 6799,
"author_profile": "https://Stackoverflow.com/users/6799",
"pm_score": 1,
"selected": false,
"text": "pop_back() it"
},
{
"answer_id": 415847,
"author": "CB Bailey",
"author_id": 19563,
"author_profile": "https://Stackoverflow.com/users/19563",
"pm_score": 0,
"selected": false,
"text": "for(std::vector<int>::iterator it = ints.begin(); it != ints.end(); )\n{\n if(*it < 10)\n it = ints.erase( it );\n else\n ++it;\n}\n std::remove_if struct LessThanTen { bool operator()( int n ) { return n < 10; } };\n\nints.erase( std::remove_if( ints.begin(), ints.end(), LessThanTen() ), ints.end() );\n std::remove_if"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6605/"
] |
62,353 |
<p>I have a solution with multiple project. I am trying to optimize AssemblyInfo.cs files by linking one solution wide assembly info file. What are the best practices for doing this? Which attributes should be in solution wide file and which are project/assembly specific?</p>
<hr>
<p><em>Edit: If you are interested there is a follow up question <a href="https://stackoverflow.com/questions/64602/what-are-differences-between-assemblyversion-assemblyfileversion-and-assemblyin">What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?</a></em></p>
|
[
{
"answer_id": 62631,
"author": "SaguiItay",
"author_id": 6980,
"author_profile": "https://Stackoverflow.com/users/6980",
"pm_score": 0,
"selected": false,
"text": "AssemblyTitle AssemblyVersion targets"
},
{
"answer_id": 62637,
"author": "JRoppert",
"author_id": 6777,
"author_profile": "https://Stackoverflow.com/users/6777",
"pm_score": 9,
"selected": true,
"text": " [assembly: AssemblyProduct(\"Your Product Name\")]\n\n [assembly: AssemblyCompany(\"Your Company\")]\n [assembly: AssemblyCopyright(\"Copyright © 2008 ...\")]\n [assembly: AssemblyTrademark(\"Your Trademark - if applicable\")]\n\n #if DEBUG\n [assembly: AssemblyConfiguration(\"Debug\")]\n #else\n [assembly: AssemblyConfiguration(\"Release\")]\n #endif\n\n [assembly: AssemblyVersion(\"This is set by build process\")]\n [assembly: AssemblyFileVersion(\"This is set by build process\")]\n [assembly: AssemblyTitle(\"Your assembly title\")]\n [assembly: AssemblyDescription(\"Your assembly description\")]\n [assembly: AssemblyCulture(\"The culture - if not neutral\")]\n\n [assembly: ComVisible(true/false)]\n\n // unique id per assembly\n [assembly: Guid(\"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\")]\n"
},
{
"answer_id": 62739,
"author": "Krishna",
"author_id": 6995,
"author_profile": "https://Stackoverflow.com/users/6995",
"pm_score": 4,
"selected": false,
"text": "[assembly: AssemblyCompany(\"Company\")]\n[assembly: AssemblyProduct(\"Product Name\")]\n[assembly: AssemblyCopyright(\"Copyright © 2007 Company\")]\n[assembly: AssemblyTrademark(\"Company\")]\n\n//This shows up as Product Version in Windows Explorer\n//We make this the same for all files in a particular product version. And increment it globally for all projects.\n//We then use this as the Product Version in installers as well (for example built using Wix).\n[assembly: AssemblyInformationalVersion(\"0.9.2.0\")]\n"
},
{
"answer_id": 63132,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 4,
"selected": false,
"text": "#if DEBUG\n[assembly: AssemblyConfiguration(\"Debug\")]\n#else\n[assembly: AssemblyConfiguration(\"Release\")]\n#endif\n[assembly: AssemblyVersion(\"This is set by build process\")]\n[assembly: AssemblyFileVersion(\"This is set by build process\")]\n[assembly: CLSCompliant(true)]\n [assembly: AssemblyInformationalVersion(\"0.9.2.0\")]\n"
},
{
"answer_id": 25117433,
"author": "Jack Ukleja",
"author_id": 61714,
"author_profile": "https://Stackoverflow.com/users/61714",
"pm_score": 3,
"selected": false,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"UpdateAssemblyInfo\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n\n <ItemGroup>\n <AllAssemblyInfoFiles Include=\"..\\**\\AssemblyInfo.cs\" />\n </ItemGroup>\n\n <Import Project=\"MSBuild.ExtensionPack.tasks\" />\n\n <Target Name=\"UpdateAssemblyInfo\">\n <Message Text=\"%(AllAssemblyInfoFiles.FullPath)\" />\n <MSBuild.ExtensionPack.Framework.AssemblyInfo \n AssemblyInfoFiles=\"@(AllAssemblyInfoFiles)\"\n AssemblyCompany=\"Company\"\n AssemblyProduct=\"Product\"\n AssemblyCopyright=\"Copyright\"\n ... etc ...\n />\n </Target>\n\n</Project>\n"
},
{
"answer_id": 39352322,
"author": "John Denniston",
"author_id": 4511145,
"author_profile": "https://Stackoverflow.com/users/4511145",
"pm_score": 1,
"selected": false,
"text": "SubWCRev.exe AssemblyInfo.wcrev AssemblyInfo.cs [assembly: AssemblyVersion(\"2.3.$WCREV$.$WCMODS?1:0$$WCUNVER?1:0$\")]\n AssemblyInfo.wcrev AssemblyInfo.cs"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2361/"
] |
62,365 |
<p>Say I have an ASMX web service, MyService. The service has a method, MyMethod. I could execute MyMethod on the server side as follows:</p>
<pre><code>MyService service = new MyService();
service.MyMethod();
</code></pre>
<p>I need to do similar, with service and method not known until runtime. </p>
<p>I'm assuming that reflection is the way to go about that. Unfortunately, I'm having a hard time making it work. When I execute this code:</p>
<pre><code>Type.GetType("MyService", true);
</code></pre>
<p>It throws this error:</p>
<blockquote>
<p>Could not load type 'MyService' from assembly 'App_Web__ktsp_r0, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.</p>
</blockquote>
<p>Any guidance would be appreciated.</p>
|
[
{
"answer_id": 62381,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 3,
"selected": true,
"text": "Dim HTTPRequest As HttpWebRequest\nDim HTTPResponse As HttpWebResponse\nDim ResponseReader As StreamReader\nDim URL AS String\nDim ResponseText As String\n\nURL = \"http://www.example.com/MyWebSerivce/MyMethod?arg1=A&arg2=B\"\n\nHTTPRequest = HttpWebRequest.Create(URL)\nHTTPRequest.Method = \"GET\"\n\nHTTPResponse = HTTPRequest.GetResponse()\n\nResponseReader = New StreamReader(HTTPResponse.GetResponseStream())\nResponseText = ResponseReader.ReadToEnd()\n"
},
{
"answer_id": 62461,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 1,
"selected": false,
"text": "[WebService]"
},
{
"answer_id": 62687,
"author": "Radu094",
"author_id": 3263,
"author_profile": "https://Stackoverflow.com/users/3263",
"pm_score": 0,
"selected": false,
"text": " [WebService(Namespace = \"http://tempuri.org/\")]\n [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]\n [ToolboxItem(false)]\n public class WebService1 : System.Web.Services.WebService\n {\n ...\n }\n WebService1 ws = new WebService1 ();\nws.SomeMethod();\n"
},
{
"answer_id": 62794,
"author": "Steve Eisner",
"author_id": 7104,
"author_profile": "https://Stackoverflow.com/users/7104",
"pm_score": 1,
"selected": false,
"text": "public class MyService : SoapHttpClientProtocol\n{\n public MyService(string url)\n {\n this.Url = url;\n // plus set credentials, etc.\n }\n\n [SoapDocumentMethod(\"{service url}\", RequestNamespace=\"{namespace}\", ResponseNamespace=\"{namespace}\", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]\n public int MyMethod(string arg1)\n {\n object[] results = this.Invoke(\"MyMethod\", new object[] { arg1 });\n return ((int)(results[0]));\n }\n}\n"
},
{
"answer_id": 87636,
"author": "Steve Eisner",
"author_id": 7104,
"author_profile": "https://Stackoverflow.com/users/7104",
"pm_score": 0,
"selected": false,
"text": "System.Web.Compilation.BuildManager.GetType(\"MyService\", true)\n"
},
{
"answer_id": 730158,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": " Type t = System.Web.Compilation.BuildManager.GetType(\"MyServiceClass\", true);\n object act = Activator.CreateInstance(t); \n object o = t.GetMethod(\"hello\").Invoke(act, null);\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/60/"
] |
62,389 |
<p>What are the advantages/disadvantages between MS VS C++ 6.0 and MSVS C++ 2008? </p>
<p>The main reason for asking such a question is that there are still many decent programmers that prefer using the older version instead of the newest version.</p>
<p>Is there any reason the might prefer the older over the new?</p>
|
[
{
"answer_id": 379446,
"author": "FryGuy",
"author_id": 28776,
"author_profile": "https://Stackoverflow.com/users/28776",
"pm_score": 0,
"selected": false,
"text": "sometemplate<othertemplate<t>> sometemplate< othertemplate<t>"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6619/"
] |
62,406 |
<p>I am overriding a lot of SAP's Portal functionality in my current project. I have to create a custom fixed width framework, custom iView trays, custom KM API functionality, and more.</p>
<p>With all of these custom parts, I will not be using a lot of the style functionality implemented by SAP's Theme editor. What I would like to do is create an external CSS, store it outside of the Portal and reference it. Storing externally will allow for easier updates rather than storing the CSS within a portal application. It would also allow for all custom pieces to have their styles in once place.</p>
<p>Unfortunately, I've not found a way to gain access to the HEAD portion of the page that allows me to insert an external stylesheet. Portal Applications can do so using the IResource object to gain access to internal references, but not items on another server.</p>
<p>I'm looking for any ideas that would allow me to gain this functionality. I have <a href="https://www.sdn.sap.com/irj/sdn/thread?threadID=1046064&tstart=0" rel="nofollow noreferrer">x-posted on SAP's SDN</a>, but I suspect I'll get a better answer here.</p>
|
[
{
"answer_id": 66035,
"author": "Mike Cornell",
"author_id": 419788,
"author_profile": "https://Stackoverflow.com/users/419788",
"pm_score": 0,
"selected": false,
"text": "IPortalNode node = request.getNode().getPortalNode();\nIPortalResponse resp = (IPortalResponse) node.getValue(IPortalResponse.class.getName());\nif (resp instanceof PortalHtmlResponse) {\n PortalHtmlResponse htmlResp = (PortalHtmlResponse) resp;\n HtmlDocument doc = htmlResp.getHtmlDocument();\n HtmlHead myHead = doc.getHead();\n HtmlLink cssLink = new HtmlLink(\"http://myserver.com/css/mycss.css\");\n cssLink.setType(\"text/css\");\n cssLink.setRel(\"stylesheet\");\n myHead.addElement(cssLink);\n}\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/419788/"
] |
62,418 |
<p>When a java based application starts to misbehave on a windows machine, you want to be able to kill the process in the task manager if you can't quit the application normally. Most of the time, there's more than one java based application running on my machine. Is there a better way than just randomly killing java.exe processes in hope that you'll hit the correct application eventually?</p>
<p><strong>EDIT:</strong> Thank you to all the people who pointed me to Sysinternal's Process Explorer - Exactly what I'm looking for!</p>
|
[
{
"answer_id": 63655,
"author": "Misha",
"author_id": 7557,
"author_profile": "https://Stackoverflow.com/users/7557",
"pm_score": 6,
"selected": false,
"text": "jps -lv taskkill /PID <pid>\n"
},
{
"answer_id": 63659,
"author": "Bill Michell",
"author_id": 7938,
"author_profile": "https://Stackoverflow.com/users/7938",
"pm_score": 3,
"selected": false,
"text": "jvisualvm"
},
{
"answer_id": 3504584,
"author": "Jesse",
"author_id": 423045,
"author_profile": "https://Stackoverflow.com/users/423045",
"pm_score": 5,
"selected": false,
"text": "wmic PROCESS get Processid,Caption,Commandline\n wmic PROCESS where \"name like '%java%'\" get Processid,Caption,Commandline\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6094/"
] |
62,430 |
<p>Is is possible to construct a regular expression that rejects all input strings?</p>
|
[
{
"answer_id": 62473,
"author": "Jan Hančič",
"author_id": 185527,
"author_profile": "https://Stackoverflow.com/users/185527",
"pm_score": 1,
"selected": false,
"text": "if ( inputString != \"\" )\n doSomething ()\n"
},
{
"answer_id": 62475,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 4,
"selected": true,
"text": "[^\\w\\W]\n $.^\n (?#it's just a comment inside of empty regex)\n (?<!)\n"
},
{
"answer_id": 62508,
"author": "Fernando Barrocal",
"author_id": 2274,
"author_profile": "https://Stackoverflow.com/users/2274",
"pm_score": -1,
"selected": false,
"text": "^$ [^\\w\\s]"
},
{
"answer_id": 62561,
"author": "Henrik N",
"author_id": 6962,
"author_profile": "https://Stackoverflow.com/users/6962",
"pm_score": 2,
"selected": false,
"text": "(?=not)possible\n"
},
{
"answer_id": 62758,
"author": "asksol",
"author_id": 5577,
"author_profile": "https://Stackoverflow.com/users/5577",
"pm_score": 1,
"selected": false,
"text": "if (! str.match( /./ ))\n if (!foo)\n"
},
{
"answer_id": 70015,
"author": "David Arno",
"author_id": 7122,
"author_profile": "https://Stackoverflow.com/users/7122",
"pm_score": 0,
"selected": false,
"text": "[^]+"
},
{
"answer_id": 79286,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 3,
"selected": false,
"text": ".^\n $.\n ^ $ ^ $"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4984/"
] |
62,433 |
<p>I have looked in vain for a good example or starting point to write a java based facebook application... I was hoping that someone here would know of one. As well, I hear that facebook will no longer support their java API is this true and if yes does that mean that we should no longer use java to write facebook apps??</p>
|
[
{
"answer_id": 7411318,
"author": "stickfigure",
"author_id": 635982,
"author_profile": "https://Stackoverflow.com/users/635982",
"pm_score": 1,
"selected": false,
"text": "/** You write your own Jackson user mapping for the pieces you care about */\npublic class User {\n long uid;\n @JsonProperty(\"first_name\") String firstName;\n String pic_square;\n String timezone;\n}\n\nBatcher batcher = new FacebookBatcher(accessToken);\n\nLater<User> me = batcher.graph(\"me\", User.class);\nLater<User> mark = batcher.graph(\"markzuckerberg\", User.class);\nLater<List<User>> myFriends = batcher.query(\n \"SELECT uid, first_name, pic_square FROM user WHERE uid IN\" +\n \"(SELECT uid2 FROM friend WHERE uid1 = \" + myId + \")\", User.class);\nLater<User> bob = batcher.queryFirst(\"SELECT timezone FROM user WHERE uid = \" + bobsId, User.class);\nPagedLater<Post> feed = batcher.paged(\"me/feed\", Post.class);\n\n// No calls to Facebook have been made yet. The following get() will execute the\n// whole batch as a single Facebook call.\nString timezone = bob.get().timezone;\n\n// You can just get simple values forcing immediate execution of the batch at any time.\nUser ivan = batcher.graph(\"ivan\", User.class).get();\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6788/"
] |
62,436 |
<p>I am having a problem with the speed of accessing an association property with a large number of records.</p>
<p>I have an XAF app with a parent class called <code>MyParent</code>.</p>
<p>There are 230 records in <code>MyParent</code>.</p>
<p><code>MyParent</code> has a child class called <code>MyChild</code>.</p>
<p>There are 49,000 records in <code>MyChild</code>.</p>
<p>I have an association defined between <code>MyParent</code> and <code>MyChild</code> in the standard way:</p>
<p>In <code>MyChild</code>:</p>
<pre><code>// MyChild (many) and MyParent (one)
[Association("MyChild-MyParent")]
public MyParent MyParent;
</code></pre>
<p>And in <code>MyParent</code>:</p>
<pre><code>[Association("MyChild-MyParent", typeof(MyChild))]
public XPCollection<MyCHild> MyCHildren
{
get { return GetCollection<MyCHild>("MyCHildren"); }
}
</code></pre>
<p>There's a specific <code>MyParent</code> record called <code>MyParent1</code>.</p>
<p>For <code>MyParent1</code>, there are 630 <code>MyChild</code> records.</p>
<p>I have a DetailView for a class called <code>MyUI</code>.</p>
<p>The user chooses an item in one drop-down in the <code>MyUI</code> DetailView, and my code has to fill another drop-down with <code>MyChild</code> objects.</p>
<p>The user chooses <code>MyParent1</code> in the first drop-down.</p>
<p>I created a property in <code>MyUI</code> to return the collection of <code>MyChild</code> objects for the selected value in the first drop-down.</p>
<p>Here is the code for the property:</p>
<pre><code>[NonPersistent]
public XPCollection<MyChild> DisplayedValues
{
get
{
Session theSession;
MyParent theParentValue;
XPCollection<MyCHild> theChildren;
theParentValue = this.DropDownOne;
// get the parent value
if theValue == null)
{
// if none
return null;
// return null
}
theChildren = theParentValue.MyChildren;
// get the child values for the parent
return theChildren;
// return it
}
</code></pre>
<p>I marked the <code>DisplayedValues</code> property as <code>NonPersistent</code> because it is only needed for the UI of the DetailVIew. I don't think that persisting it will speed up the creation of the collection the first time, and after it's used to fill the drop-down, I don't need it, so I don't want to spend time storing it.</p>
<p>The problem is that it takes 45 seconds to call <code>theParentValue = this.DropDownOne</code>.</p>
<p>Specs:</p>
<ul>
<li>Vista Business</li>
<li>8 GB of RAM</li>
<li>2.33 GHz E6550 processor</li>
<li>SQL Server Express 2005</li>
</ul>
<p>This is too long for users to wait for one of many drop-downs in the DetailView.</p>
<p>I took the time to sketch out the business case because I have two questions:</p>
<ol>
<li><p>How can I make the associated values load faster?</p></li>
<li><p>Is there another (simple) way to program the drop-downs and DetailView that runs much faster?</p></li>
</ol>
<p>Yes, you can say that 630 is too many items to display in a drop-down, but this code is taking so long I suspect that the speed is proportional to the 49,000 and not to the 630. 100 items in the drop-down would not be too many for my app.</p>
<p>I need quite a few of these drop-downs in my app, so it's not appropriate to force the user to enter more complicated filtering criteria for each one. The user needs to pick one value and see the related values.</p>
<p>I would understand if finding a large number of records was slow, but finding a few hundred shouldn't take that long.</p>
|
[
{
"answer_id": 1169654,
"author": "Steven Evers",
"author_id": 48553,
"author_profile": "https://Stackoverflow.com/users/48553",
"pm_score": 1,
"selected": false,
"text": "public class A : XPObject\n{\n [Association(\"a<b\", typeof(b))]\n public XPCollection<b> bs { get { GetCollection(\"bs\"); } }\n}\n\npublic class B : XPObject\n{\n [Association(\"a<b\") Persistent(\"Aid\")]\n public A a { get; set; }\n}\n A myA = GetSomeParticularA();\nlupAsBs.Properties.DataSource = myA.Bs;\nlupAsBs.Properties.DisplayMember = \"WhateverPropertyName\";\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6783/"
] |
62,437 |
<p>I load some XML from a servlet from my Flex application like this:</p>
<pre><code>_loader = new URLLoader();
_loader.load(new URLRequest(_servletURL+"?do=load&id="+_id));
</code></pre>
<p>As you can imagine <code>_servletURL</code> is something like <a href="http://foo.bar/path/to/servlet" rel="nofollow noreferrer">http://foo.bar/path/to/servlet</a></p>
<p>In some cases, this URL contains accented characters (long story). I pass the <code>unescaped</code> string to <code>URLRequest</code>, but it seems that flash escapes it and calls the escaped URL, which is invalid. Ideas?</p>
|
[
{
"answer_id": 62519,
"author": "grapefrukt",
"author_id": 914,
"author_profile": "https://Stackoverflow.com/users/914",
"pm_score": 2,
"selected": false,
"text": "var request:URLRequest = new URLRequest(_servletURL)\nrequest.method = URLRequestMethod.GET;\nvar reqData:Object = new Object();\n\nreqData.do = \"load\";\nreqData.id = _id;\nrequest.data = reqData;\n\n_loader = new URLLoader(request); \n"
},
{
"answer_id": 62994,
"author": "Ryan Guill",
"author_id": 7186,
"author_profile": "https://Stackoverflow.com/users/7186",
"pm_score": 0,
"selected": false,
"text": "System.useCodePage = false"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1199623/"
] |
62,447 |
<p>Tomcat fails to start even if i remove all my applications from the WEBAPPS directory leaving everything just like after the OS installation.</p>
<p>The log (catalina.out) says:</p>
<pre><code>Using CATALINA_BASE: /usr/share/tomcat5
Using CATALINA_HOME: /usr/share/tomcat5
Using CATALINA_TMPDIR: /usr/share/tomcat5/temp
Using JRE_HOME:
Created MBeanServer with ID: -dpv07y:fl4s82vl.0:hydrogenium.timberlinecolorado.com:1
java.lang.NoClassDefFoundError: org.apache.catalina.core.StandardService
at java.lang.Class.initializeClass(libgcj.so.7rh)
at java.lang.Class.initializeClass(libgcj.so.7rh)
at java.lang.Class.initializeClass(libgcj.so.7rh)
at java.lang.Class.newInstance(libgcj.so.7rh)
at org.apache.catalina.startup.Bootstrap.init(bootstrap.jar.so)
at org.apache.catalina.startup.Bootstrap.main(bootstrap.jar.so)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.modeler.Registry not found in org.apache.catalina.loader.StandardClassLoader{urls=[file:/var/lib/tomcat5/server/classes/,file:/usr/share/java/tomcat5/catalina-cluster-5.5.23.jar,file:/usr/share/java/tomcat5/catalina-storeconfig-5.5.23.jar,file:/usr/share/java/tomcat5/catalina-optional-5.5.23.jar,file:/usr/share/java/tomcat5/tomcat-coyote-5.5.23.jar,file:/usr/share/java/tomcat5/tomcat-jkstatus-ant-5.5.23.jar,file:/usr/share/java/tomcat5/tomcat-ajp-5.5.23.jar,file:/usr/share/java/tomcat5/servlets-default-5.5.23.jar,file:/usr/share/java/tomcat5/servlets-invoker-5.5.23.jar,file:/usr/share/java/tomcat5/catalina-ant-jmx-5.5.23.jar,file:/usr/share/java/tomcat5/tomcat-http-5.5.23.jar,file:/usr/share/java/tomcat5/tomcat-util-5.5.23.jar,file:/usr/share/java/tomcat5/tomcat-apr-5.5.23.jar,file:/usr/share/eclipse/plugins/org.eclipse.jdt.core_3.2.1.v_677_R32x.jar,file:/usr/share/java/tomcat5/servlets-webdav-5.5.23.jar,file:/usr/share/java/tomcat5/catalina-5.5.23.jar], parent=org.apache.catalina.loader.StandardClassLoader{urls=[file:/var/lib/tomcat5/common/classes/,file:/var/lib/tomcat5/common/i18n/tomcat-i18n-ja.jar,file:/var/lib/tomcat5/common/i18n/tomcat-i18n-fr.jar,file:/var/lib/tomcat5/common/i18n/tomcat-i18n-en.jar,file:/var/lib/tomcat5/common/i18n/tomcat-i18n-es.jar,file:/usr/share/java/tomcat5/naming-resources-5.5.23.jar,file:/usr/share/eclipse/plugins/org.eclipse.jdt.core_3.2.1.v_677_R32x.jar,file:/usr/share/java/tomcat5/naming-factory-5.5.23.jar], parent=gnu.gcj.runtime.SystemClassLoader{urls=[file:/usr/lib/jvm/java/lib/tools.jar,file:/usr/share/tomcat5/bin/bootstrap.jar,file:/usr/share/tomcat5/bin/commons-logging-api.jar,file:/usr/share/java/mx4j/mx4j-impl.jar,file:/usr/share/java/mx4j/mx4j-jmx.jar], parent=gnu.gcj.runtime.ExtensionClassLoader{urls=[], parent=null}}}}
at java.net.URLClassLoader.findClass(libgcj.so.7rh)
at java.lang.ClassLoader.loadClass(libgcj.so.7rh)
at java.lang.ClassLoader.loadClass(libgcj.so.7rh)
at java.lang.Class.initializeClass(libgcj.so.7rh)
...5 more
</code></pre>
|
[
{
"answer_id": 62559,
"author": "tbond",
"author_id": 6197,
"author_profile": "https://Stackoverflow.com/users/6197",
"pm_score": 0,
"selected": false,
"text": "JAVA_HOME/JRE_HOME"
},
{
"answer_id": 64862,
"author": "Alexandre Brasil",
"author_id": 8841,
"author_profile": "https://Stackoverflow.com/users/8841",
"pm_score": 1,
"selected": false,
"text": "ClassNotFoundException org.apache.commons.modeler.Registry"
},
{
"answer_id": 358763,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "$CATALINA_HOME/common/lib"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
62,449 |
<p>When using the Net.Sockets.TcpListener, what is the best way to handle incoming connections (.AcceptSocket) in seperate threads?</p>
<p>The idea is to start a new thread when a new incoming connection is accepted, while the tcplistener then stays available for further incoming connections (and for every new incoming connection a new thread is created). All communication and termination with the client that originated the connection will be handled in the thread.</p>
<p>Example C# of VB.NET code is appreciated.</p>
|
[
{
"answer_id": 62547,
"author": "x0n",
"author_id": 6920,
"author_profile": "https://Stackoverflow.com/users/6920",
"pm_score": 1,
"selected": false,
"text": "http://examples.oreilly.com/9780596516109/CSharp3_0CookbookCodeRTM.zip"
},
{
"answer_id": 247108,
"author": "Anton",
"author_id": 341413,
"author_profile": "https://Stackoverflow.com/users/341413",
"pm_score": 5,
"selected": true,
"text": "class Server\n{\n private AutoResetEvent connectionWaitHandle = new AutoResetEvent(false);\n\n public void Start()\n {\n TcpListener listener = new TcpListener(IPAddress.Any, 5555);\n listener.Start();\n\n while(true)\n {\n IAsyncResult result = listener.BeginAcceptTcpClient(HandleAsyncConnection, listener);\n connectionWaitHandle.WaitOne(); // Wait until a client has begun handling an event\n connectionWaitHandle.Reset(); // Reset wait handle or the loop goes as fast as it can (after first request)\n }\n }\n\n\n private void HandleAsyncConnection(IAsyncResult result)\n {\n TcpListener listener = (TcpListener)result.AsyncState;\n TcpClient client = listener.EndAcceptTcpClient(result);\n connectionWaitHandle.Set(); //Inform the main thread this connection is now handled\n\n //... Use your TcpClient here\n\n client.Close();\n }\n}\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1271/"
] |
62,490 |
<p>I am receiving SOAP requests from a client that uses the Axis 1.4 libraries. The requests have the following form:</p>
<pre><code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<PlaceOrderRequest xmlns="http://example.com/schema/order/request">
<order>
<ns1:requestParameter xmlns:ns1="http://example.com/schema/common/request">
<ns1:orderingSystemWithDomain>
<ns1:orderingSystem>Internet</ns1:orderingSystem>
<ns1:domainSign>2</ns1:domainSign>
</ns1:orderingSystemWithDomain>
</ns1:requestParameter>
<ns2:directDeliveryAddress ns2:addressType="0" ns2:index="1"
xmlns:ns2="http://example.com/schema/order/request">
<ns3:address xmlns:ns3="http://example.com/schema/common/request">
<ns4:zipcode xmlns:ns4="http://example.com/schema/common">12345</ns4:zipcode>
<ns5:city xmlns:ns5="http://example.com/schema/common">City</ns5:city>
<ns6:street xmlns:ns6="http://example.com/schema/common">Street</ns6:street>
<ns7:houseNum xmlns:ns7="http://example.com/schema/common">1</ns7:houseNum>
<ns8:country xmlns:ns8="http://example.com/schema/common">XX</ns8:country>
</ns3:address>
[...]
</code></pre>
<p>As you can see, several prefixes are defined for the same namespace, e.g. the namespace <a href="http://example.com/schema/common" rel="noreferrer">http://example.com/schema/common</a> has the prefixes ns4, ns5, ns6, ns7 and ns8. Some long requests define several hundred prefixes for the same namespace.</p>
<p>This causes a problem with the <a href="http://saxon.sourceforge.net/" rel="noreferrer">Saxon</a> XSLT processor, that I use to transform the requests. Saxon limits the the number of different prefixes for the same namespace to 255 and throws an exception when you define more prefixes.</p>
<p>Can Axis 1.4 be configured to define smarter prefixes, so that there is only one prefix for each namespace?</p>
|
[
{
"answer_id": 179495,
"author": "Ian McLaird",
"author_id": 18796,
"author_profile": "https://Stackoverflow.com/users/18796",
"pm_score": 2,
"selected": false,
"text": "public class XMLManipulationHandler extends BasicHandler {\n private static Log log = LogFactory.getLog(XMLManipulationHandler.class);\n private static List processingHandlers;\n\n public static void setProcessingHandlers(List handlers) {\n processingHandlers = handlers;\n }\n\n protected Document process(Document doc) {\n if (processingHandlers == null) {\n processingHandlers = new ArrayList();\n processingHandlers.add(new EmptyProcessingHandler());\n }\n log.trace(processingHandlers);\n treeWalk(doc.getRootElement());\n return doc;\n }\n\n protected void treeWalk(Element element) {\n for (int i = 0, size = element.nodeCount(); i < size; i++) {\n Node node = element.node(i);\n for (int handlerIndex = 0; handlerIndex < processingHandlers.size(); handlerIndex++) {\n ProcessingHandler handler = (ProcessingHandler) processingHandlers.get(handlerIndex);\n handler.process(node);\n }\n if (node instanceof Element) {\n treeWalk((Element) node);\n }\n }\n }\n\n public void invoke(MessageContext context) throws AxisFault {\n if (!context.getPastPivot()) {\n SOAPMessage message = context.getMessage();\n SOAPPart soapPart = message.getSOAPPart();\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n\n try {\n message.writeTo(baos);\n baos.flush();\n baos.close();\n\n ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());\n SAXReader saxReader = new SAXReader();\n Document doc = saxReader.read(bais);\n doc = process(doc);\n DocumentSource ds = new DocumentSource(doc);\n soapPart.setContent(ds);\n message.saveChanges();\n } catch (Exception e) {\n throw new AxisFault(\"Error Caught processing document in XMLManipulationHandler\", e);\n }\n }\n }\n}\n public interface ProcessingHandler {\n public Node process(Node node);\n}\n public class NamespaceRemovalHandler implements ProcessingHandler {\n private static Log log = LogFactory.getLog(NamespaceRemovalHandler.class);\n private Namespace namespace;\n private String targetElement;\n private Set ignoreElements;\n\n public NamespaceRemovalHandler() {\n ignoreElements = new HashSet();\n }\n\n public Node process(Node node) {\n if (node instanceof Element) {\n Element element = (Element) node;\n if (element.isRootElement()) {\n // Evidently, we never actually see the root node when we're called from\n // SOAP...\n } else {\n if (element.getName().equals(targetElement)) {\n log.trace(\"Found the target Element. Adding requested namespace\");\n Namespace already = element.getNamespaceForURI(namespace.getURI());\n if (already == null) {\n element.add(namespace);\n }\n } else if (!ignoreElements.contains(element.getName())) {\n Namespace target = element.getNamespaceForURI(namespace.getURI());\n if (target != null) {\n element.remove(target);\n element.setQName(new QName(element.getName(), namespace));\n }\n }\n\n Attribute type = element.attribute(\"type\");\n if (type != null) {\n log.trace(\"Replacing type information: \" + type.getText());\n String typeText = type.getText();\n typeText = typeText.replaceAll(\"ns[0-9]+\", namespace.getPrefix());\n type.setText(typeText);\n }\n }\n }\n\n return node;\n }\n\n public Namespace getNamespace() {\n return namespace;\n }\n\n public void setNamespace(Namespace namespace) {\n this.namespace = namespace;\n }\n\n /**\n * @return the targetElement\n */\n public String getTargetElement() {\n return targetElement;\n }\n\n /**\n * @param targetElement the targetElement to set\n */\n public void setTargetElement(String targetElement) {\n this.targetElement = targetElement;\n }\n\n /**\n * @return the ignoreElements\n */\n public Set getIgnoreElements() {\n return ignoreElements;\n }\n\n /**\n * @param ignoreElements the ignoreElements to set\n */\n public void setIgnoreElements(Set ignoreElements) {\n this.ignoreElements = ignoreElements;\n }\n\n public void addIgnoreElement(String element) {\n this.ignoreElements.add(element);\n }\n}\n"
},
{
"answer_id": 185432,
"author": "Stephen Denne",
"author_id": 11721,
"author_profile": "https://Stackoverflow.com/users/11721",
"pm_score": 1,
"selected": false,
"text": "enableNamespacePrefixOptimization true <globalConfiguration >\n <parameter name=\"enableNamespacePrefixOptimization\" value=\"true\"/>\n"
},
{
"answer_id": 5649242,
"author": "Pica Creations",
"author_id": 706035,
"author_profile": "https://Stackoverflow.com/users/706035",
"pm_score": 2,
"selected": false,
"text": "String endpoint = \"http://localhost:5555/yourService\";\n\n// Parameter to be send\nInteger secuencial = new Integer(11); // 0011\n\n// Make the call\nService service = new Service();\n\nCall call = (Call) service.createCall();\n\n// Disable sending Multirefs\ncall.setOption( org.apache.axis.AxisEngine.PROP_DOMULTIREFS, new java.lang.Boolean( false) ); \n\n// Disable sending xsi:type\ncall.setOption(org.apache.axis.AxisEngine.PROP_SEND_XSI, new java.lang.Boolean( false)); \n\n// XML with new line\ncall.setOption(org.apache.axis.AxisEngine.PROP_DISABLE_PRETTY_XML, new java.lang.Boolean( false)); \n\n// Other Options. You will not need them\ncall.setOption(org.apache.axis.AxisEngine.PROP_ENABLE_NAMESPACE_PREFIX_OPTIMIZATION, new java.lang.Boolean( true)); \ncall.setOption(org.apache.axis.AxisEngine.PROP_DOTNET_SOAPENC_FIX, new java.lang.Boolean( true));\n\ncall.setTargetEndpointAddress(new java.net.URL(endpoint));\ncall.setSOAPActionURI(\"http://YourActionUrl\");//Optional\n\n// Opertion Name\n//call.setOperationName( \"YourMethod\" );\ncall.setOperationName(new javax.xml.namespace.QName(\"http://yourUrl\", \"YourMethod\")); \n\n// Do not send encoding style\ncall.setEncodingStyle(null);\n\n// Do not send xmlns in the xml nodes\ncall.setProperty(org.apache.axis.client.Call.SEND_TYPE_ATTR, Boolean.FALSE);\n\n/////// Configuration of namespaces\norg.apache.axis.description.OperationDesc oper;\norg.apache.axis.description.ParameterDesc param;\noper = new org.apache.axis.description.OperationDesc();\noper.setName(\"InsertaTran\");\nparam = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName(\"http://yourUrl\", \"secuencial\"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName(\"http://www.w3.org/2001/XMLSchema\", \"int\"), int.class, false, false);\noper.addParameter(param);\n\noper.setReturnType(new javax.xml.namespace.QName(\"http://www.w3.org/2001/XMLSchema\", \"int\"));\noper.setReturnClass(int.class);\noper.setReturnQName(new javax.xml.namespace.QName(\"http://yourUrl\", \"yourReturnMethod\"));\noper.setStyle(org.apache.axis.constants.Style.WRAPPED);\noper.setUse(org.apache.axis.constants.Use.LITERAL);\n\ncall.setOperation(oper);\n\nInteger ret = (Integer) call.invoke( new java.lang.Object [] \n { secuencial });\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5035/"
] |
62,491 |
<p>Nokia has stopped offering its Developer's Suite, relying on other IDEs, including Eclipse. Meanwhile, Nokia changed its own development tools again and EclipseMe has also changed. This leaves most documentation irrelevant. </p>
<p>I want to know what does it take to make a simple Hello-World?</p>
<p>(I already found out myself, so this is a Q&A for other people to use)</p>
|
[
{
"answer_id": 63574,
"author": "Brad Richards",
"author_id": 7732,
"author_profile": "https://Stackoverflow.com/users/7732",
"pm_score": 3,
"selected": false,
"text": "public HelloWorld() {\n super();\n myForm = new Form(\"Hello World!\");\n myForm.append( new StringItem(null, \"Hello, world!\"));\n myForm.addCommand(new Command(\"Exit\", Command.EXIT, 0));\n myForm.setCommandListener(this);\n}\n\nprotected void startApp() throws MIDletStateChangeException {\n Display.getDisplay(this).setCurrent(myForm);\n}\n\nprotected void pauseApp() {}\n\nprotected void destroyApp(boolean arg0) throws MIDletStateChangeException {}\n\npublic void commandAction(Command arg0, Displayable arg1) {\n notifyDestroyed();\n}\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6827/"
] |
62,503 |
<p>In C#, <code>int</code> and <code>Int32</code> are the same thing, but I've read a number of times that <code>int</code> is preferred over <code>Int32</code> with no reason given. Is there a reason, and should I care?</p>
|
[
{
"answer_id": 62555,
"author": "James Sutherland",
"author_id": 6779,
"author_profile": "https://Stackoverflow.com/users/6779",
"pm_score": 8,
"selected": false,
"text": "int Int32 int Int32 int Int32"
},
{
"answer_id": 62557,
"author": "Simon Steele",
"author_id": 4591,
"author_profile": "https://Stackoverflow.com/users/4591",
"pm_score": 3,
"selected": false,
"text": "int Int32 int string String"
},
{
"answer_id": 62558,
"author": "Jesper Kihlberg",
"author_id": 6976,
"author_profile": "https://Stackoverflow.com/users/6976",
"pm_score": 2,
"selected": false,
"text": "int Int32 int Int32"
},
{
"answer_id": 62585,
"author": "spoulson",
"author_id": 3347,
"author_profile": "https://Stackoverflow.com/users/3347",
"pm_score": 4,
"selected": false,
"text": "int Int32 int.MinValue int.MaxValue int Int64"
},
{
"answer_id": 62612,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "int total = Int32.Parse(\"1009\");\n"
},
{
"answer_id": 62738,
"author": "HasaniH",
"author_id": 7141,
"author_profile": "https://Stackoverflow.com/users/7141",
"pm_score": 8,
"selected": true,
"text": "int System.Int32"
},
{
"answer_id": 62800,
"author": "raven",
"author_id": 4228,
"author_profile": "https://Stackoverflow.com/users/4228",
"pm_score": 7,
"selected": false,
"text": "public enum MyEnum : Int32\n{\n member1 = 0\n}\n public enum MyEnum : int\n{\n member1 = 0\n}\n"
},
{
"answer_id": 63128,
"author": "HidekiAI",
"author_id": 7234,
"author_profile": "https://Stackoverflow.com/users/7234",
"pm_score": 4,
"selected": false,
"text": "i32 u32"
},
{
"answer_id": 63143,
"author": "Jim T",
"author_id": 7298,
"author_profile": "https://Stackoverflow.com/users/7298",
"pm_score": 1,
"selected": false,
"text": "int System.Int32"
},
{
"answer_id": 63395,
"author": "Michael Meadows",
"author_id": 7643,
"author_profile": "https://Stackoverflow.com/users/7643",
"pm_score": 0,
"selected": false,
"text": "Int32 System System.Int32 int"
},
{
"answer_id": 63860,
"author": "Remi Despres-Smyth",
"author_id": 8169,
"author_profile": "https://Stackoverflow.com/users/8169",
"pm_score": 6,
"selected": false,
"text": "Int32 int long long BinaryReader br = new BinaryReader( /* ... */ );\nfloat val = br.ReadSingle(); // OK, but it looks a little odd...\nSingle val = br.ReadSingle(); // OK, and is easier to read\n"
},
{
"answer_id": 64031,
"author": "yhdezalvarez",
"author_id": 8013,
"author_profile": "https://Stackoverflow.com/users/8013",
"pm_score": 2,
"selected": false,
"text": "int int System.Int32 struct int32 using System;"
},
{
"answer_id": 64342,
"author": "Schmuli",
"author_id": 8363,
"author_profile": "https://Stackoverflow.com/users/8363",
"pm_score": 0,
"selected": false,
"text": "public enum MyEnum : Int32\n{\n AEnum = 0\n}\n public enum MyEnum : int\n{\n AEnum = 0\n}\n"
},
{
"answer_id": 66648,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "int lMax = Int32.MaxValue Int32 lMax = Int32.MaxValue public enum MyEnum : Int32\n{\n AEnum = 0\n}\n public enum MyEnum : int\n{\n AEnum = 0\n}\n"
},
{
"answer_id": 146672,
"author": "Mark A. Nicolosi",
"author_id": 1103052,
"author_profile": "https://Stackoverflow.com/users/1103052",
"pm_score": 3,
"selected": false,
"text": "int x, y;\n...\nString.Format (\"{0}x{1}\", x, y);\n"
},
{
"answer_id": 17448373,
"author": "Selim",
"author_id": 2546603,
"author_profile": "https://Stackoverflow.com/users/2546603",
"pm_score": 0,
"selected": false,
"text": "sizeof(int)\n4\nsizeof(Int32)\n4\nsizeof(Int64)\n8\nInt32\nint\n base {System.ValueType}: System.ValueType\n MaxValue: 2147483647\n MinValue: -2147483648\nInt64\nlong\n base {System.ValueType}: System.ValueType\n MaxValue: 9223372036854775807\n MinValue: -9223372036854775808\nint\nint\n base {System.ValueType}: System.ValueType\n MaxValue: 2147483647\n MinValue: -2147483648\n"
},
{
"answer_id": 69175392,
"author": "Karl Stephen",
"author_id": 2410892,
"author_profile": "https://Stackoverflow.com/users/2410892",
"pm_score": 0,
"selected": false,
"text": "Int32 int int long db dw dd C# 43.0 256-bits Int32 int int WORD DWORD int ushort UInt16 Decimal short int Int32 int Int32 var Pointers IntPtr (Int32*) int32Ptr = (Int32*) int64Ptr; IfTest address address 16-bits 32-bits IfTestMethod(...) IfTestMethodInt() IfTestMethod32() IfTestMethodShort() IfTestMethod16() Int32 val; var val; // 32-bits int Int32 Int32 Int64"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1826/"
] |
62,504 |
<p>I am using MS Access 2003. I want to run a lot of insert SQL statements in what is called 'Query' in MS Access. Is there any easy(or indeed any way) to do it?</p>
|
[
{
"answer_id": 62583,
"author": "Jonathan",
"author_id": 6910,
"author_profile": "https://Stackoverflow.com/users/6910",
"pm_score": 2,
"selected": false,
"text": "Sub InsertLots ()\n Dim SqlConn as Connection\n SqlConn.Connect(\"your connection string\")\n SqlConn.Execute(\"INSERT <tablename> (column1, column2) VALUES (1, 2)\")\n SqlConn.Execute(\"INSERT <tablename> (column1, column2) VALUES (2, 3)\")\n SqlConn.Close()\nEnd Sub\n"
},
{
"answer_id": 65027,
"author": "BIBD",
"author_id": 685,
"author_profile": "https://Stackoverflow.com/users/685",
"pm_score": 6,
"selected": true,
"text": "insert into foo (c1, c2, c3)\nvalues (\"v1a\", \"v2a\", \"v3a\"),\n (\"v1b\", \"v2b\", \"v3b\"),\n (\"v1c\", \"v2c\", \"v3c\")\n insert into foo (c1, c2, c3)\n select (v1, v2, v3) from bar\n INSERT INTO foo (f1, f2, f3)\n SELECT *\n FROM (select top 1 \"b1a\" AS f1, \"b2a\" AS f2, \"b3a\" AS f3 from onerow\n union all\n select top 1 \"b1b\" AS f1, \"b2b\" AS f2, \"b3b\" AS f3 from onerow\n union all \n select top 1 \"b1c\" AS f1, \"b2c\" AS f2, \"b3c\" AS f3 from onerow)\n"
},
{
"answer_id": 148584,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": 1,
"selected": false,
"text": "INSERT INTO foo (f1, f2, f3)\n SELECT *\n FROM (select top 1 \"b1a\" AS f1, \"b2a\" AS f2, \"b3a\" AS f3 from onerow\n union all\n select top 1 \"b1b\" AS f1, \"b2b\" AS f2, \"b3b\" AS f3 from onerow\n union all \n select top 1 \"b1c\" AS f1, \"b2c\" AS f2, \"b3c\" AS f3 from onerow)\n ALTER TABLE foo ADD\n CONSTRAINT max_two_foo_rows\n CHECK (2 >= (SELECT COUNT(*) FROM foo AS T2));\n INSERT INTO..SELECT.. INSERT CHECK"
},
{
"answer_id": 16428930,
"author": "Mark",
"author_id": 2360066,
"author_profile": "https://Stackoverflow.com/users/2360066",
"pm_score": 1,
"selected": false,
"text": "From this:\nINSERT INTO CLASS VALUES('10012','ACCT-211','1','MWF 8:00-8:50 a.m.','BUS311','105');\nINSERT INTO CLASS VALUES('10013','ACCT-211','2','MWF 9:00-9:50 a.m.','BUS200','105');\nINSERT INTO CLASS VALUES('10014','ACCT-211','3','TTh 2:30-3:45 p.m.','BUS252','342');\nTo this:\n10012,ACCT-211,1,MWF 8:00-8:50 a.m.,BUS311,105\n10013,ACCT-211,2,MWF 9:00-9:50 a.m.,BUS200,105\n10014,ACCT-211,3,TTh 2:30-3:45 p.m.,BUS252,342\n"
},
{
"answer_id": 65726799,
"author": "John Bentley",
"author_id": 872154,
"author_profile": "https://Stackoverflow.com/users/872154",
"pm_score": 0,
"selected": false,
"text": "Public Sub InsertMinimalData()\n CurrentDb.Execute \"INSERT INTO FinancialYear (FinancialYearID) VALUES ('FY2019/2020');\"\n CurrentDb.Execute \"INSERT INTO FinancialYear (FinancialYearID) VALUES ('FY2020/2021');\"\nEnd Sub\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6613/"
] |
62,505 |
<p>I wish Subversion had a better way of moving tags. The only way that I know to move a tag is to remove the file from the tag and then copy it again. Revision tree browsers don't seem to handle that very well. This also requires keeping the directory structure under the trunk and tag in sync.</p>
<p>Use case: We have thousands of "maps" and we want to tag which version of each map is the "production" version. We need to be able to easily get the production version of all maps.</p>
<p>Can anyone suggest a better way to address our use case?
I have considered properties also but then we can't get the prod version of all files easily. Merging to the tag doesn't appear to be very easy either.
(Originally posted to <a href="http://jamesjava.blogspot.com/2007/12/subversion-moving-tags.html" rel="nofollow noreferrer">http://jamesjava.blogspot.com/2007/12/subversion-moving-tags.html</a>)</p>
|
[
{
"answer_id": 62656,
"author": "Anarchofascist",
"author_id": 6740,
"author_profile": "https://Stackoverflow.com/users/6740",
"pm_score": 1,
"selected": false,
"text": "/svn/tags/production/2008/09/15/mapproject\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6770/"
] |
62,512 |
<p>I would like to find out safe ways of implementing three dimensional arrays of integers in C++, using pointer arithmetic / dynamic memory allocation, or, alternatively using <code>STL</code> techniques such as vectors.</p>
<p>Essentially I want my integer array dimensions to look like:</p>
<pre><code>[ x ][ y ][ z ]
</code></pre>
<p>x and y are in the range 20-6000
z is known and equals 4.</p>
|
[
{
"answer_id": 62532,
"author": "ChrisN",
"author_id": 3853,
"author_profile": "https://Stackoverflow.com/users/3853",
"pm_score": 5,
"selected": true,
"text": "#include \"boost/multi_array.hpp\"\n\nint main() {\n // Create a 3D array that is 20 x 30 x 4\n int x = 20;\n int y = 30;\n int z = 4;\n\n typedef boost::multi_array<int, 3> array_type;\n typedef array_type::index index;\n array_type my_array(boost::extents[x][y][z]);\n\n // Assign values to the elements\n int values = 0;\n for (index i = 0; i != x; ++i) {\n for (index j = 0; j != y; ++j) {\n for (index k = 0; k != z; ++k) {\n my_array[i][j][k] = values++;\n }\n }\n }\n}\n"
},
{
"answer_id": 62601,
"author": "Zooba",
"author_id": 891,
"author_profile": "https://Stackoverflow.com/users/891",
"pm_score": 3,
"selected": false,
"text": "x = myArray[4];\nx = *(myArray+4);\n x = myArray[2][7];\nx = *((*(myArray+2))+7);\n int*** myArray = (some allocation method, keep reading);\n//\n// All in one line:\nint value = myArray[x][y][z];\n//\n// Separated to multiple steps:\nint** deref1 = myArray[x];\nint* deref2 = deref1[y];\nint value = deref2[z];\n // Start by allocating an array for array of arrays\nint*** myArray = new int**[X_MAXIMUM];\n\n// Allocate an array for each element of the first array\nfor(int x = 0; x < X_MAXIMUM; ++x)\n{\n myArray[x] = new int*[Y_MAXIMUM];\n\n // Allocate an array of integers for each element of this array\n for(int y = 0; y < Y_MAXIMUM; ++y)\n {\n myArray[x][y] = new int[Z_MAXIMUM];\n\n // Specify an initial value (if desired)\n for(int z = 0; z < Z_MAXIMUM; ++z)\n {\n myArray[x][y][z] = -1;\n }\n }\n}\n for(int x = 0; x < X_MAXIMUM; ++x)\n{\n for(int y = 0; y < Y_MAXIMUM; ++y)\n {\n delete[] myArray[x][y];\n }\n\n delete[] myArray[x];\n}\n\ndelete[] myArray;\n"
},
{
"answer_id": 62674,
"author": "Pieter",
"author_id": 5822,
"author_profile": "https://Stackoverflow.com/users/5822",
"pm_score": 2,
"selected": false,
"text": "std::vector< std::vector< std::vector< int > > > array3d;\n"
},
{
"answer_id": 62915,
"author": "Paul Troon",
"author_id": 6649,
"author_profile": "https://Stackoverflow.com/users/6649",
"pm_score": 1,
"selected": false,
"text": "// a class that does something in 3 dimensions\n\nclass MySimpleClass\n{\npublic:\n\n MySimpleClass(const size_t inWidth, const size_t inHeight, const size_t inDepth) :\n mWidth(inWidth), mHeight(inHeight), mDepth(inDepth)\n {\n mArray.resize(mWidth * mHeight * mDepth);\n }\n\n\n // inline for speed\n int Get(const size_t inX, const size_t inY, const size_t inZ) {\n return mArray[(inZ * mWidth * mHeight) + (mY * mWidth) + mX];\n }\n\n void Set(const size_t inX, const size_t inY, const size_t inZ, const int inVal) {\n return mArray[(inZ * mWidth * mHeight) + (mY * mWidth) + mX];\n }\n\n // doing something uniform with the data is easier if it's not a vector of vectors\n void DoSomething()\n {\n std::transform(mArray.begin(), mArray.end(), mArray.begin(), MyUnaryFunc);\n }\n\nprivate:\n\n // dimensions of data\n size_t mWidth;\n size_t mHeight;\n size_t mDepth;\n\n // data buffer\n std::vector< int > mArray;\n};\n"
},
{
"answer_id": 4466150,
"author": "kriss",
"author_id": 168465,
"author_profile": "https://Stackoverflow.com/users/168465",
"pm_score": 3,
"selected": false,
"text": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(){\n\n {\n // C Style Static 3D Arrays\n int a[10][20][30];\n a[9][19][29] = 10;\n printf(\"a[9][19][29]=%d\\n\", a[9][19][29]);\n }\n\n {\n // C Style dynamic 3D Arrays\n int (*a)[20][30];\n a = (int (*)[20][30])malloc(10*20*30*sizeof(int));\n a[9][19][29] = 10;\n printf(\"a[9][19][29]=%d\\n\", a[9][19][29]);\n free(a);\n }\n\n {\n // C++ Style dynamic 3D Arrays\n int (*a)[20][30];\n a = new int[10][20][30];\n a[9][19][29] = 10;\n printf(\"a[9][19][29]=%d\\n\", a[9][19][29]);\n delete [] a;\n }\n\n}\n int x = 100;\n int y = 200;\n int z = 30;\n\n {\n // C Style Static 3D Arrays \n int a[x][y][z];\n a[99][199][29] = 10;\n printf(\"a[99][199][29]=%d\\n\", a[99][199][29]);\n }\n\n {\n // C Style dynamic 3D Arrays\n int (*a)[y][z];\n a = (int (*)[y][z])malloc(x*y*z*sizeof(int));\n a[99][199][29] = 10;\n printf(\"a[99][199][29]=%d\\n\", a[99][199][29]);\n free(a);\n }\n {\n class ThreeDArray {\n class InnerTwoDArray {\n int * data;\n size_t y;\n size_t z;\n public:\n InnerTwoDArray(int * data, size_t y, size_t z)\n : data(data), y(y), z(z) {}\n\n public:\n int * operator [](size_t y){ return data + y*z; }\n };\n\n int * data;\n size_t x;\n size_t y;\n size_t z;\n public:\n ThreeDArray(size_t x, size_t y, size_t z) : x(x), y(y), z(z) {\n data = (int*)malloc(x*y*z*sizeof data);\n }\n\n ~ThreeDArray(){ free(data); }\n\n InnerTwoDArray operator [](size_t x){\n return InnerTwoDArray(data + x*y*z, y, z);\n }\n };\n\n ThreeDArray a(x, y, z);\n a[99][199][29] = 10;\n printf(\"a[99][199][29]=%d\\n\", a[99][199][29]);\n }\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6795/"
] |
62,529 |
<p>The RoR tutorials posit one model per table for the ORM to work.
My DB schema has some 70 tables divided conceptually into 5 groups of functionality
(eg, any given table lives in one and only one functional group, and relations between tables of different groups are minimised.)
So: should I design a model per conceptual group, or should I simply have 70 Rails models and leave the grouping 'conceptual'?
Thanks!</p>
|
[
{
"answer_id": 62743,
"author": "Ben",
"author_id": 6998,
"author_profile": "https://Stackoverflow.com/users/6998",
"pm_score": 3,
"selected": false,
"text": "app/models/admin/user.rb\napp/models/admin/group.rb\n app/models/publishing/article.rb\napp/models/publishing/comment.rb\n"
},
{
"answer_id": 63689,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 1,
"selected": false,
"text": "app/models/admin/base.rb - module Admin::Base, included by all other Admin::xxx\napp/models/admin/user.rb - class Admin::User, includes Admin::Base\napp/models/admin/group.rb - class Admin::Group, includes Admin::Base\n"
},
{
"answer_id": 99671,
"author": "Dan Harper",
"author_id": 14530,
"author_profile": "https://Stackoverflow.com/users/14530",
"pm_score": 4,
"selected": true,
"text": "events\nevent_types\nevent_groups\nevent_attendees\netc...\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6941/"
] |
62,534 |
<p>Need to parse some basic XML (one root element, 3-4 subelements, 1-3 attributes each) from a ksh script (ideally stick to ksh, given the script already exists and it's just trying to read some extra configuration created in XML by another program).</p>
<p>I know I can use sed and do pattern matching, but it's not foolproof given that the input XML could change and attributes could be duplicated on the various subelements (or new subelements).</p>
<p>So far, I'm thinking of using an XSLT against the XML to extract the few attributes (for specific elements) that the ksh script cares about as individual fields. I can use Oracle for this given we are a DB-driven product, and Oracle would always be installed on our systems, but that seems a bit heavy handed. </p>
<p>Any other safe approach to extract specific attributes from the input XML in a cross-platform manner that doesn't require access to 3rd-party parser/transformer?</p>
|
[
{
"answer_id": 194282,
"author": "Zed",
"author_id": 19202,
"author_profile": "https://Stackoverflow.com/users/19202",
"pm_score": 1,
"selected": false,
"text": "--text_only"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
62,539 |
<p>What is the dependency inversion principle and why is it important?</p>
|
[
{
"answer_id": 62594,
"author": "Marc Hughes",
"author_id": 6791,
"author_profile": "https://Stackoverflow.com/users/6791",
"pm_score": 1,
"selected": false,
"text": "public class MyClass\n{\n public Service myService = ServiceLocator.service;\n}\n public class MyClass\n{\n public IService myService;\n}\n"
},
{
"answer_id": 62613,
"author": "Staale",
"author_id": 3355,
"author_profile": "https://Stackoverflow.com/users/3355",
"pm_score": 2,
"selected": false,
"text": "class Service {\n Database database;\n init() {\n database = FrameworkSingleton.getService(\"database\");\n }\n}\n class Service {\n Database database;\n init(database) {\n this.database = database;\n }\n}\n"
},
{
"answer_id": 35355975,
"author": "xurxodev",
"author_id": 3537539,
"author_profile": "https://Stackoverflow.com/users/3537539",
"pm_score": 4,
"selected": false,
"text": "// DataAccessLayer.dll\npublic class ProductDAO {\n\n}\n // BusinessLogicLayer.dll\nusing DataAccessLayer;\npublic class ProductBO { \n private ProductDAO productDAO;\n}\n // DataAccessLayer.dll\npublic interface IProductDAO\npublic class ProductDAO : IProductDAO{\n\n}\n // BusinessLogicLayer.dll\nusing DataAccessLayer;\npublic class ProductBO { \n private IProductDAO productDAO;\n}\n // Domain.dll\npublic interface IProductRepository;\n\nusing DataAccessLayer;\npublic class ProductBO { \n private IProductRepository productRepository;\n}\n // Persistence.dll\npublic class ProductDAO : IProductRepository{\n\n}\n"
},
{
"answer_id": 37283098,
"author": "mattvonb",
"author_id": 1170736,
"author_profile": "https://Stackoverflow.com/users/1170736",
"pm_score": 3,
"selected": false,
"text": "Logic class Dependency { ... }\nclass Logic {\n private Dependency dep;\n int doSomething() {\n // Business logic using dep here\n }\n}\n class Dependency { ... }\ninterface Data { ... }\nclass DataFromDependency implements Data {\n private Dependency dep;\n ...\n}\nclass Logic {\n int doSomething(Data data) {\n // compute something with data\n }\n}\n Data DataFromDependency Logic Dependency Dependency Logic Logic Logic Data"
},
{
"answer_id": 54944762,
"author": "Rejwanul Reja",
"author_id": 4259851,
"author_profile": "https://Stackoverflow.com/users/4259851",
"pm_score": -1,
"selected": false,
"text": " public interface ICustomer\n {\n string GetCustomerNameById(int id);\n }\n\n public class Customer : ICustomer\n {\n //ctor\n public Customer(){}\n\n public string GetCustomerNameById(int id)\n {\n return \"Dummy Customer Name\";\n }\n }\n\n public class CustomerFactory\n {\n public static ICustomer GetCustomerData()\n {\n return new Customer();\n }\n }\n\n public class CustomerBLL\n {\n ICustomer _customer;\n public CustomerBLL()\n {\n _customer = CustomerFactory.GetCustomerData();\n }\n\n public string GetCustomerNameById(int id)\n {\n return _customer.GetCustomerNameById(id);\n }\n }\n\n public class Program\n {\n static void Main()\n {\n CustomerBLL customerBLL = new CustomerBLL();\n int customerId = 25;\n string customerName = customerBLL.GetCustomerNameById(customerId);\n\n\n Console.WriteLine(customerName);\n Console.ReadKey();\n }\n }\n"
},
{
"answer_id": 56630214,
"author": "John Silence",
"author_id": 1812300,
"author_profile": "https://Stackoverflow.com/users/1812300",
"pm_score": -1,
"selected": false,
"text": "class Program\n{\n static void Main(string[] args)\n {\n /*\n * BadEncoder: High-level class *contains* low-level I/O functionality.\n * Hence, you'll have to fiddle with BadEncoder whenever you want to change\n * the I/O mode or details. Not good. A good encoder should be I/O-agnostic --\n * problems with I/O shouldn't break the encoder!\n */\n BadEncoder.Run(); \n }\n}\n\npublic static class BadEncoder\n{\n public static void Run()\n {\n Console.WriteLine(Convert.ToBase64String(Encoding.UTF8.GetBytes(Console.ReadLine())));\n }\n} \n class Program\n{\n static void Main(string[] args)\n { \n /* Demo of the Dependency Inversion Principle (= \"High-level functionality\n * should not depend upon low-level implementations\"): \n * You can easily implement new I/O methods like\n * ConsoleReader, ConsoleWriter without ever touching the high-level\n * Encoder class!!!\n */ \n GoodEncoder.Run(new ConsoleReader(), new ConsoleWriter()); }\n}\n\npublic static class GoodEncoder\n{\n public static void Run(IReadable input, IWriteable output)\n {\n output.WriteOutput(Convert.ToBase64String(Encoding.ASCII.GetBytes(input.ReadInput())));\n }\n}\n\npublic interface IReadable\n{\n string ReadInput();\n}\n\npublic interface IWriteable\n{\n void WriteOutput(string txt);\n}\n\npublic class ConsoleReader : IReadable\n{\n public string ReadInput()\n {\n return Console.ReadLine();\n }\n}\n\npublic class ConsoleWriter : IWriteable\n{\n public void WriteOutput(string txt)\n {\n Console.WriteLine(txt);\n }\n}\n GoodEncoder IReadable IWriteable"
},
{
"answer_id": 61267123,
"author": "Sumanth Varada",
"author_id": 4044987,
"author_profile": "https://Stackoverflow.com/users/4044987",
"pm_score": -1,
"selected": false,
"text": " class Student {\n private Address address;\n\n public Student() {\n this.address = new Address();\n }\n}\nclass Address{\n private String perminentAddress;\n private String currentAdrress;\n\n public Address() {\n }\n} \n class Student{\n private Address address;\n\n public Student(Address address) {\n this.address = address;\n }\n //or\n public void setAddress(Address address) {\n this.address = address;\n }\n}\n"
},
{
"answer_id": 66808672,
"author": "yoAlex5",
"author_id": 4770877,
"author_profile": "https://Stackoverflow.com/users/4770877",
"pm_score": 2,
"selected": false,
"text": "//A -> B\nclass A {\n B b\n\n func foo() {\n b = B();\n }\n}\n //A -> IB <|- B\n//client[A -> IB] <|- B is the Inversion \nclass A {\n IB ib // An abstraction between High level module A and low level module B\n\n func foo() {\n ib = B()\n }\n}\n A B A IB B IB"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3012/"
] |
62,567 |
<p>What is the easiest way to compare strings in Python, ignoring case?</p>
<p>Of course one can do (str1.lower() <= str2.lower()), etc., but this created two additional temporary strings (with the obvious alloc/g-c overheads).</p>
<p>I guess I'm looking for an equivalent to C's stricmp().</p>
<p>[Some more context requested, so I'll demonstrate with a trivial example:]</p>
<p>Suppose you want to sort a looong list of strings. You simply do theList.sort().
This is O(n * log(n)) string comparisons and no memory management (since all
strings and list elements are some sort of smart pointers). You are happy.</p>
<p>Now, you want to do the same, but ignore the case (let's simplify and say
all strings are ascii, so locale issues can be ignored).
You can do theList.sort(key=lambda s: s.lower()), but then you cause two new
allocations per comparison, plus burden the garbage-collector with the duplicated
(lowered) strings.
Each such memory-management noise is orders-of-magnitude slower than simple string comparison.</p>
<p>Now, with an in-place stricmp()-like function, you do: theList.sort(cmp=stricmp)
and it is as fast and as memory-friendly as theList.sort(). You are happy again.</p>
<p>The problem is any Python-based case-insensitive comparison involves implicit string
duplications, so I was expecting to find a C-based comparisons (maybe in module string).</p>
<p>Could not find anything like that, hence the question here.
(Hope this clarifies the question).</p>
|
[
{
"answer_id": 62647,
"author": "Moses Ting",
"author_id": 7056,
"author_profile": "https://Stackoverflow.com/users/7056",
"pm_score": 1,
"selected": false,
"text": "import re\np = re.compile('^hello$', re.I)\np.match('Hello')\np.match('hello')\np.match('HELLO')\n"
},
{
"answer_id": 62652,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": -1,
"selected": false,
"text": "str"
},
{
"answer_id": 63007,
"author": "Ricardo Reyes",
"author_id": 3399,
"author_profile": "https://Stackoverflow.com/users/3399",
"pm_score": 2,
"selected": false,
"text": "str1.lower() == str2.lower()\n"
},
{
"answer_id": 63071,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 3,
"selected": false,
"text": "from timeit import Timer\n\ns1 = \"1234567890\" * 100000 + \"a\"\ns2 = \"1234567890\" * 100000 + \"B\"\n\ncode = \"s1.lower() < s2.lower()\"\ntime = Timer(code, \"from __main__ import s1, s2\").timeit(1000)\nprint time / 1000 # 0.00920499992371 on my machine\n"
},
{
"answer_id": 66547,
"author": "patrickyoung",
"author_id": 3701,
"author_profile": "https://Stackoverflow.com/users/3701",
"pm_score": -1,
"selected": true,
"text": "from ctypes import *\nlibc = CDLL(\"libc.so.6\") // see link above for Win32 help\nlibc.strcasecmp(\"THIS\", \"this\") // returns 0\nlibc.strcasecmp(\"THIS\", \"THAT\") // returns 8\n"
},
{
"answer_id": 67388,
"author": "Antoine P.",
"author_id": 10194,
"author_profile": "https://Stackoverflow.com/users/10194",
"pm_score": 1,
"selected": false,
"text": ">>> original_list = ['a', 'b', 'A', 'B']\n>>> decorated = [(s.lower(), s) for s in original_list]\n>>> decorated.sort()\n>>> sorted_list = [s[1] for s in decorated]\n>>> sorted_list\n['A', 'a', 'B', 'b']\n >>> sorted_list = [s[1] for s in sorted((s.lower(), s) for s in original_list)]\n>>> sorted_list\n['A', 'a', 'B', 'b']\n"
},
{
"answer_id": 67583,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 3,
"selected": false,
"text": "Python 2.5.2 (r252:60911, Aug 22 2008, 02:34:17)\n[GCC 4.3.1] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import locale\n>>> locale.setlocale(locale.LC_COLLATE, \"en_US\")\n'en_US'\n>>> sorted(\"ABCabc\", key=locale.strxfrm)\n['a', 'A', 'b', 'B', 'c', 'C']\n>>> sorted(\"ABCabc\", cmp=locale.strcoll)\n['a', 'A', 'b', 'B', 'c', 'C']\n"
},
{
"answer_id": 121364,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "str.lower libc.strcasecmp #!/usr/bin/env python2.7\nimport random\nimport timeit\n\nfrom ctypes import *\nlibc = CDLL('libc.dylib') # change to 'libc.so.6' on linux\n\nwith open('/usr/share/dict/words', 'r') as wordlist:\n words = wordlist.read().splitlines()\nrandom.shuffle(words)\nprint '%i words in list' % len(words)\n\nsetup = 'from __main__ import words, libc; gc.enable()'\nstmts = [\n ('simple sort', 'sorted(words)'),\n ('sort with key=str.lower', 'sorted(words, key=str.lower)'),\n ('sort with cmp=libc.strcasecmp', 'sorted(words, cmp=libc.strcasecmp)'),\n]\n\nfor (comment, stmt) in stmts:\n t = timeit.Timer(stmt=stmt, setup=setup)\n print '%s: %.2f msec/pass' % (comment, (1000*t.timeit(10)/10))\n 235886 words in list\nsimple sort: 483.59 msec/pass\nsort with key=str.lower: 1064.70 msec/pass\nsort with cmp=libc.strcasecmp: 5487.86 msec/pass\n str.lower lower()"
},
{
"answer_id": 193863,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 0,
"selected": false,
"text": "str().lower()"
},
{
"answer_id": 2711031,
"author": "Benjamin Atkin",
"author_id": 3461,
"author_profile": "https://Stackoverflow.com/users/3461",
"pm_score": 2,
"selected": false,
"text": "def equals_ignore_case(str1, str2):\n import re\n return re.match(re.escape(str1) + r'\\Z', str2, re.I) is not None\n"
},
{
"answer_id": 7239139,
"author": "trevorcroft",
"author_id": 919044,
"author_profile": "https://Stackoverflow.com/users/919044",
"pm_score": 2,
"selected": false,
"text": "def strincmp(str1, str2, numchars=None):\n result = 0\n len1 = len(str1)\n len2 = len(str2)\n if numchars is not None:\n minlen = min(len1,len2,numchars)\n else:\n minlen = min(len1,len2)\n #end if\n orda = ord('a')\n ordz = ord('z')\n\n i = 0\n while i < minlen and 0 == result:\n ord1 = ord(str1[i])\n ord2 = ord(str2[i])\n if ord1 >= orda and ord1 <= ordz:\n ord1 = ord1-32\n #end if\n if ord2 >= orda and ord2 <= ordz:\n ord2 = ord2-32\n #end if\n result = cmp(ord1, ord2)\n i += 1\n #end while\n\n if 0 == result and minlen != numchars:\n if len1 < len2:\n result = -1\n elif len2 < len1:\n result = 1\n #end if\n #end if\n\n return result\n#end def\n"
},
{
"answer_id": 22249049,
"author": "Venkatesh Bachu",
"author_id": 1008603,
"author_profile": "https://Stackoverflow.com/users/1008603",
"pm_score": 0,
"selected": false,
"text": "import re\nif re.match('tEXT', 'text', re.IGNORECASE):\n # is True\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6984/"
] |
62,570 |
<p>I would like to move a file or folder from one place to another within the same repository without having to use Repo Browser to do it, and without creating two independent add/delete operations. Using Repo Browser works fine except that your code will be hanging in a broken state until you get any supporting changes checked in afterwards (like the .csproj file for example).</p>
<p>Update: People have suggested "move" from the command line. Is there a TortoiseSVN equivalent?</p>
|
[
{
"answer_id": 62591,
"author": "Clinton Dreisbach",
"author_id": 6262,
"author_profile": "https://Stackoverflow.com/users/6262",
"pm_score": 2,
"selected": false,
"text": "svn mv path1 path2"
},
{
"answer_id": 62595,
"author": "acemtp",
"author_id": 6605,
"author_profile": "https://Stackoverflow.com/users/6605",
"pm_score": 0,
"selected": false,
"text": "svn move"
},
{
"answer_id": 62598,
"author": "StocksR",
"author_id": 6892,
"author_profile": "https://Stackoverflow.com/users/6892",
"pm_score": 6,
"selected": false,
"text": "svn move"
},
{
"answer_id": 62642,
"author": "Mark Embling",
"author_id": 6844,
"author_profile": "https://Stackoverflow.com/users/6844",
"pm_score": 10,
"selected": true,
"text": "Tortoise SVN SVN move versioned files here SVN move versioned files here"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1436/"
] |
62,588 |
<p>I have some ASP.NET web services which all share a common helper class they only need to instantiate one instance of <em>per server</em>. It's used for simple translation of data, but does spend some time during start-up loading things from the web.config file, etc. <em>The helper class is 100% thread-safe. Think of it as a simple library of utility calls. I'd make all the methods shared on the class, but I want to load the initial configuration from web.config.</em> We've deployed the web services to IIS 6.0 and using an Application Pool, with a Web Garden of 15 workers.</p>
<p>I declared the helper class as a Private Shared variable in Global.asax, and added a lazy load Shared ReadOnly property like this:</p>
<pre><code>Private Shared _helper As MyHelperClass
Public Shared ReadOnly Property Helper() As MyHelperClass
Get
If _helper Is Nothing Then
_helper = New MyHelperClass()
End If
Return _helper
End Get
End Property
</code></pre>
<p>I have logging code in the constructor for <code>MyHelperClass()</code>, and it shows the constructor running for each request, even on the same thread. I'm sure I'm just missing some key detail of ASP.NET but MSDN hasn't been very helpful.</p>
<p>I've tried doing similar things using both <code>Application("Helper")</code> and <code>Cache("Helper")</code> and I still saw the constructor run with each request.</p>
|
[
{
"answer_id": 62924,
"author": "JRoppert",
"author_id": 6777,
"author_profile": "https://Stackoverflow.com/users/6777",
"pm_score": 2,
"selected": false,
"text": " void Application_Start(object sender, EventArgs e)\n {\n Application.Add(\"MyHelper\", new MyHelperClass());\n }\n MyHelperClass helper = (MyHelperClass)HttpContext.Current.Application[\"MyHelper\"];\n helper.Foo();\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6897/"
] |
62,599 |
<p>How do you define your UserControls as being in a namespace below the project namespace, ie. [RootNameSpace].[SubSectionOfProgram].Controls?</p>
<p><strong>Edit due to camainc's answer:</strong> I also have a constraint that I have to have all the code in a single project.</p>
<p><strong>Edit to finalise question:</strong> As I suspected it isn't possible to do what I required so camainc's answer is the nearest solution.</p>
|
[
{
"answer_id": 62817,
"author": "camainc",
"author_id": 7232,
"author_profile": "https://Stackoverflow.com/users/7232",
"pm_score": 2,
"selected": true,
"text": "[CompanyName].[SolutionName].[ProjectName]\n OurCompany.ThisSolution.Controls\n OurCompany.Common.Controls\n Imports OurCompany\nImports OurCompany.Common\nImports OurCompany.Common.Controls\n"
},
{
"answer_id": 62957,
"author": "Keithius",
"author_id": 5956,
"author_profile": "https://Stackoverflow.com/users/5956",
"pm_score": 0,
"selected": false,
"text": "[ProjectNamespace].[YourSpecialNamespace].Controls [ProjectNamespace].Controls Controls Namespace [YourSpecialNamespace] Public Class Form1 [...] End Class End Namespace Controls"
},
{
"answer_id": 3904409,
"author": "Cody Gray",
"author_id": 366904,
"author_profile": "https://Stackoverflow.com/users/366904",
"pm_score": 1,
"selected": false,
"text": "Imports System.ComponentModel\n\nNamespace Controls\n Friend Class FloatingSearchForm\n\n 'Your code goes here...\n\n End Class\nEnd Namespace\n Namespace Controls\n <Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _\n Partial Class FloatingSearchForm\n\n 'Designer generated code\n\n End Class\nEnd Namespace\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6369/"
] |
62,606 |
<p>I'm using <code>int</code> as an example, but this applies to any value type in .Net</p>
<p>In .Net 1 the following would throw a compiler exception:</p>
<pre><code>int i = SomeFunctionThatReturnsInt();
if( i == null ) //compiler exception here
</code></pre>
<p>Now (in .Net 2 or 3.5) that exception has gone.</p>
<p>I know why this is:</p>
<pre><code>int? j = null; //nullable int
if( i == j ) //this shouldn't throw an exception
</code></pre>
<p>The problem is that because <code>int?</code> is nullable and <code>int</code> now has a implicit cast to <code>int?</code>. The syntax above is compiler magic. Really we're doing:</p>
<pre><code>Nullable<int> j = null; //nullable int
//compiler is smart enough to do this
if( (Nullable<int>) i == j)
//and not this
if( i == (int) j)
</code></pre>
<p>So now, when we do <code>i == null</code> we get:</p>
<pre><code>if( (Nullable<int>) i == null )
</code></pre>
<p>Given that C# is doing compiler logic to calculate this anyway why can't it be smart enough to not do it when dealing with absolute values like <code>null</code>?</p>
|
[
{
"answer_id": 62747,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 2,
"selected": false,
"text": "static int F()\n{\n return 42;\n}\n\nstatic void Main(string[] args)\n{\n int i = F();\n\n if (i == null)\n {\n }\n}\n warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?'\n L_0001: call int32 ConsoleApplication1.Program::F()\nL_0006: stloc.0 \nL_0007: ldc.i4.0 \nL_0008: ldc.i4.0 \nL_0009: ceq \nL_000b: stloc.1 \nL_000c: br.s L_000e\n"
},
{
"answer_id": 62775,
"author": "Steve Cooper",
"author_id": 6722,
"author_profile": "https://Stackoverflow.com/users/6722",
"pm_score": 3,
"selected": true,
"text": "bool oneIsNull = 1 == null;\n The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type '<null>'"
},
{
"answer_id": 63027,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 0,
"selected": false,
"text": "1 == 2 1==2 1==null"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905/"
] |
62,618 |
<p>I've got many, many mp3 files that I would like to merge into a single file. I've used the command line method</p>
<pre><code>copy /b 1.mp3+2.mp3 3.mp3
</code></pre>
<p>but it's a pain when there's a lot of them and their namings are inconsistent. The time never seems to come out right either.</p>
|
[
{
"answer_id": 574439,
"author": "joelhardi",
"author_id": 11438,
"author_profile": "https://Stackoverflow.com/users/11438",
"pm_score": 2,
"selected": false,
"text": "id3cp original.mp3 new.mp3\n"
},
{
"answer_id": 1479701,
"author": "bmurphy1976",
"author_id": 1931,
"author_profile": "https://Stackoverflow.com/users/1931",
"pm_score": 4,
"selected": false,
"text": "ffmpeg -i originalA.mp3 -f mp3 -ab 128kb -ar 44100 -ac 2 intermediateA.mp3 \nffmpeg -i originalB.mp3 -f mp3 -ab 128kb -ar 44100 -ac 2 intermediateB.mp3\n cat intermediateA.mp3 intermediateB.mp3 > output.mp3\n mp3val output.mp3 -f -nb\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4230/"
] |
62,625 |
<p>Using C#, I need a class called <code>User</code> that has a username, password, active flag, first name, last name, full name, etc. </p>
<p>There should be methods to <em>authenticate</em> and <em>save</em> a user. Do I just write a test for the methods? And do I even need to worry about testing the properties since they are .Net's getter and setters?</p>
|
[
{
"answer_id": 62682,
"author": "Tim Howland",
"author_id": 4276,
"author_profile": "https://Stackoverflow.com/users/4276",
"pm_score": 6,
"selected": false,
"text": "Integer i = new Integer(7);\nassert (i.instanceOf(integer));\n instanceof"
},
{
"answer_id": 62698,
"author": "Steve Cooper",
"author_id": 6722,
"author_profile": "https://Stackoverflow.com/users/6722",
"pm_score": 4,
"selected": false,
"text": "public class User\n{\n public string Username { get; set; }\n public string Password { get; set; }\n}\n"
},
{
"answer_id": 62825,
"author": "Dean Poulin",
"author_id": 5462,
"author_profile": "https://Stackoverflow.com/users/5462",
"pm_score": 1,
"selected": false,
"text": " public class AccountService\n {\n public void DebitAccount(int accountNumber, double amount)\n {\n\n }\n\n public void CreditAccount(int accountNumber, double amount)\n {\n\n }\n\n public void CloseAccount(int accountNumber)\n {\n\n }\n }\n [TestFixture]\n public class AccountServiceTests\n {\n [Test]\n public void DebitAccountTest()\n {\n\n }\n\n [Test]\n public void CreditAccountTest()\n {\n\n }\n\n [Test]\n public void CloseAccountTest()\n {\n\n }\n }\n"
},
{
"answer_id": 69259,
"author": "eroijen",
"author_id": 10829,
"author_profile": "https://Stackoverflow.com/users/10829",
"pm_score": 5,
"selected": false,
"text": "public class TestPayments\n{\n InvoiceDiaryHeader invoiceHeader = null;\n InvoiceDiaryDetail invoiceDetail = null;\n BankCashDiaryHeader bankHeader = null;\n BankCashDiaryDetail bankDetail = null;\n\n\n\n public InvoiceDiaryHeader CreateSales(string amountIncVat, bool sales, int invoiceNumber, string date)\n {\n ......\n ......\n }\n\n public BankCashDiaryHeader CreateMultiplePayments(IList<InvoiceDiaryHeader> invoices, int headerNumber, decimal amount, decimal discount)\n {\n ......\n ......\n ......\n }\n\n\n [TestMethod]\n public void TestSingleSalesPaymentNoDiscount()\n {\n IList<InvoiceDiaryHeader> list = new List<InvoiceDiaryHeader>();\n list.Add(CreateSales(\"119\", true, 1, \"01-09-2008\"));\n bankHeader = CreateMultiplePayments(list, 1, 119.00M, 0);\n bankHeader.Save();\n\n Assert.AreEqual(1, bankHeader.BankCashDetails.Count);\n Assert.AreEqual(1, bankHeader.BankCashDetails[0].Payments.Count);\n Assert.AreEqual(119M, bankHeader.BankCashDetails[0].Payments[0].PaymentAmount);\n Assert.AreEqual(0M, bankHeader.BankCashDetails[0].Payments[0].PaymentDiscount);\n Assert.AreEqual(0, bankHeader.BankCashDetails[0].Payments[0].InvoiceHeader.Balance);\n }\n\n [TestMethod]\n public void TestSingleSalesPaymentDiscount()\n {\n IList<InvoiceDiaryHeader> list = new List<InvoiceDiaryHeader>();\n list.Add(CreateSales(\"119\", true, 2, \"01-09-2008\"));\n bankHeader = CreateMultiplePayments(list, 2, 118.00M, 1M);\n bankHeader.Save();\n\n Assert.AreEqual(1, bankHeader.BankCashDetails.Count);\n Assert.AreEqual(1, bankHeader.BankCashDetails[0].Payments.Count);\n Assert.AreEqual(118M, bankHeader.BankCashDetails[0].Payments[0].PaymentAmount);\n Assert.AreEqual(1M, bankHeader.BankCashDetails[0].Payments[0].PaymentDiscount);\n Assert.AreEqual(0, bankHeader.BankCashDetails[0].Payments[0].InvoiceHeader.Balance);\n }\n\n [TestMethod]\n [ExpectedException(typeof(ApplicationException))]\n public void TestDuplicateInvoiceNumber()\n {\n IList<InvoiceDiaryHeader> list = new List<InvoiceDiaryHeader>();\n list.Add(CreateSales(\"100\", true, 2, \"01-09-2008\"));\n list.Add(CreateSales(\"200\", true, 2, \"01-09-2008\"));\n\n bankHeader = CreateMultiplePayments(list, 3, 300, 0);\n bankHeader.Save();\n Assert.Fail(\"expected an ApplicationException\");\n }\n\n [TestMethod]\n public void TestMultipleSalesPaymentWithPaymentDiscount()\n {\n IList<InvoiceDiaryHeader> list = new List<InvoiceDiaryHeader>();\n list.Add(CreateSales(\"119\", true, 11, \"01-09-2008\"));\n list.Add(CreateSales(\"400\", true, 12, \"02-09-2008\"));\n list.Add(CreateSales(\"600\", true, 13, \"03-09-2008\"));\n list.Add(CreateSales(\"25,40\", true, 14, \"04-09-2008\"));\n\n bankHeader = CreateMultiplePayments(list, 5, 1144.00M, 0.40M);\n bankHeader.Save();\n\n Assert.AreEqual(1, bankHeader.BankCashDetails.Count);\n Assert.AreEqual(4, bankHeader.BankCashDetails[0].Payments.Count);\n Assert.AreEqual(118.60M, bankHeader.BankCashDetails[0].Payments[0].PaymentAmount);\n Assert.AreEqual(400, bankHeader.BankCashDetails[0].Payments[1].PaymentAmount);\n Assert.AreEqual(600, bankHeader.BankCashDetails[0].Payments[2].PaymentAmount);\n Assert.AreEqual(25.40M, bankHeader.BankCashDetails[0].Payments[3].PaymentAmount);\n\n Assert.AreEqual(0.40M, bankHeader.BankCashDetails[0].Payments[0].PaymentDiscount);\n Assert.AreEqual(0, bankHeader.BankCashDetails[0].Payments[1].PaymentDiscount);\n Assert.AreEqual(0, bankHeader.BankCashDetails[0].Payments[2].PaymentDiscount);\n Assert.AreEqual(0, bankHeader.BankCashDetails[0].Payments[3].PaymentDiscount);\n\n Assert.AreEqual(0, bankHeader.BankCashDetails[0].Payments[0].InvoiceHeader.Balance);\n Assert.AreEqual(0, bankHeader.BankCashDetails[0].Payments[1].InvoiceHeader.Balance);\n Assert.AreEqual(0, bankHeader.BankCashDetails[0].Payments[2].InvoiceHeader.Balance);\n Assert.AreEqual(0, bankHeader.BankCashDetails[0].Payments[3].InvoiceHeader.Balance);\n }\n\n [TestMethod]\n public void TestSettlement()\n {\n IList<InvoiceDiaryHeader> list = new List<InvoiceDiaryHeader>();\n list.Add(CreateSales(\"300\", true, 43, \"01-09-2008\")); //Sales\n list.Add(CreateSales(\"100\", false, 6453, \"02-09-2008\")); //Purchase\n\n bankHeader = CreateMultiplePayments(list, 22, 200, 0);\n bankHeader.Save();\n\n Assert.AreEqual(1, bankHeader.BankCashDetails.Count);\n Assert.AreEqual(2, bankHeader.BankCashDetails[0].Payments.Count);\n Assert.AreEqual(300, bankHeader.BankCashDetails[0].Payments[0].PaymentAmount);\n Assert.AreEqual(-100, bankHeader.BankCashDetails[0].Payments[1].PaymentAmount);\n Assert.AreEqual(0, bankHeader.BankCashDetails[0].Payments[0].InvoiceHeader.Balance);\n Assert.AreEqual(0, bankHeader.BankCashDetails[0].Payments[1].InvoiceHeader.Balance);\n }\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9938/"
] |
62,629 |
<p>I need to determine when my Qt 4.4.1 application receives focus.</p>
<p>I have come up with 2 possible solutions, but they both don’t work exactly as I would like.</p>
<p>In the first possible solution, I connect the focusChanged() signal from qApp to a SLOT. In the slot I check the ‘old’ pointer. If it ‘0’, then I know we’ve switched to this application, and I do what I want. This seems to be the most reliable method of getting the application to detect focus in of the two solutions presented here, but suffers from the problem described below. </p>
<p>In the second possible solution, I overrode the ‘focusInEvent()’ routine, and do what I want if the reason is ‘ActiveWindowFocusReason’.</p>
<p>In both of these solutions, the code is executed at times when I don’t want it to be.</p>
<p>For example, I have this code that overrides the focusInEvent() routine:</p>
<pre><code>void
ApplicationWindow::focusInEvent( QFocusEvent* p_event )
{
Qt::FocusReason reason = p_event->reason();
if( reason == Qt::ActiveWindowFocusReason &&
hasNewUpstreamData() )
{
switch( QMessageBox::warning( this, "New Upstream Data Found!",
"New upstream data exists!\n"
"Do you want to refresh this simulation?",
"&Yes", "&No", 0, 0, 1 ) )
{
case 0: // Yes
refreshSimulation();
break;
case 1: // No
break;
}
}
}
</code></pre>
<p>When this gets executed, the QMessageBox dialog appears. However, when the dialog is dismissed by pressing either ‘yes’ or ‘no’, this function immediately gets called again because I suppose the focus changed back to the application window at that point with the ActiveWindowFocusReason. Obviously I don’t want this to happen.</p>
<p>Likewise, if the user is using the application opening & closing dialogs and windows etc, I don’t want this routine to activate. NOTE: I’m not sure of the circumstances when this routine is activated though since I’ve tried a bit, and it doesn’t happen for all windows & dialogs, though it does happen at least for the one shown in the sample code.</p>
<p>I only want it to activate if the application is focussed on from outside of this application, not when the main window is focussed in from other dialog windows.</p>
<p>Is this possible? How can this be done?</p>
<p>Thanks for any information, since this is very important for our application to do.</p>
<p>Raymond.</p>
|
[
{
"answer_id": 358253,
"author": "Michael Bishop",
"author_id": 45114,
"author_profile": "https://Stackoverflow.com/users/45114",
"pm_score": 3,
"selected": false,
"text": "bool\nApplicationWindow::eventFilter( QObject * watched, QEvent * event )\n{\n if ( watched != qApp )\n goto finished;\n\n if ( event->type() != QEvent::ApplicationActivate )\n goto finished;\n\n // Invariant: we are now looking at an application activate event for\n // the application object\n if ( !hasNewUpstreamData() )\n goto finished;\n\n QMessageBox::StandardButton response =\n QMessageBox::warning( this, \"New Upstream Data Found!\",\n \"New upstream data exists!\\n\"\n \"Do you want to refresh this simulation?\",\n QMessageBox::Yes | QMessageBox::No) );\n\n if ( response == QMessageBox::Yes )\n refreshSimulation();\n\nfinished:\n return <The-Superclass-here>::eventFilter( watched, event );\n}\n\nApplicationWindow::ApplicationWindow(...)\n{\n if (qApp)\n qApp->installEventFilter( this );\n ...\n}\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/460958/"
] |
62,650 |
<p>What's the simplest-to-use techonlogy available to save an arbitrary Java object graph as an XML file (and to be able to rehydrate the objects later)?</p>
|
[
{
"answer_id": 63256,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 2,
"selected": false,
"text": "java.beans.XMLEncoder"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
62,658 |
<p>I'm trying to install <a href="http://laconi.ca/" rel="noreferrer">Laconica</a>, an open-source Microblogging application on my Windows development server using XAMPP as per the <a href="http://laconi.ca/trac/wiki/InstallationWindows" rel="noreferrer">instructions provided</a>.</p>
<p>The website cannot find PEAR, and throws the below errors:</p>
<blockquote>
<p>Warning: require_once(PEAR.php) [function.require-once]: failed to open stream: No such file or directory in C:\xampplite\htdocs\laconica\lib\common.php on line 31</p>
<p>Fatal error: require_once() [function.require]: Failed opening required 'PEAR.php' (include_path='.;\xampplite\php\pear\PEAR') in C:\xampplite\htdocs\laconica\lib\common.php on line 31</p>
</blockquote>
<ol>
<li>PEAR is located in <code>C:\xampplite\php\pear</code></li>
<li><code>phpinfo()</code> shows me that the include path is <code>.;\xampplite\php\pear</code></li>
</ol>
<p>What am I doing wrong? Why isn't the PEAR folder being included?</p>
|
[
{
"answer_id": 62755,
"author": "Sietse",
"author_id": 6400,
"author_profile": "https://Stackoverflow.com/users/6400",
"pm_score": 0,
"selected": false,
"text": "include_path='.;c:\\xampplite\\php\\pear\\PEAR'\n include_path='.;c:\\xampplite\\php'\n"
},
{
"answer_id": 62829,
"author": "user7075",
"author_id": 7075,
"author_profile": "https://Stackoverflow.com/users/7075",
"pm_score": 6,
"selected": true,
"text": "include_path php.ini include_path = ... phpinfo() \\xampplite\\php\\pear\\PEAR C:\\xampplite\\php\\pear"
},
{
"answer_id": 12060371,
"author": "Reid Johnson",
"author_id": 1429777,
"author_profile": "https://Stackoverflow.com/users/1429777",
"pm_score": 3,
"selected": false,
"text": "pear config-set doc_dir :\\xampp\\php\\docs\\PEAR\npear config-set cfg_dir :\\xampp\\php\\cfg\npear config-set data_dir :\\xampp\\php\\data\\PEAR\npear config-set test_dir :\\xampp\\php\\tests\npear config-set www_dir :\\xampp\\php\\www\n"
},
{
"answer_id": 31203967,
"author": "Alex Rapso",
"author_id": 3679696,
"author_profile": "https://Stackoverflow.com/users/3679696",
"pm_score": 2,
"selected": false,
"text": "if (!defined('PEAR_INSTALL_DIR') || !PEAR_INSTALL_DIR) {\n $PEAR_INSTALL_DIR = PHP_LIBDIR . DIRECTORY_SEPARATOR . 'pear';\n} \nelse {\n $PEAR_INSTALL_DIR = PEAR_INSTALL_DIR;\n}\n $PEAR_INSTALL_DIR = \"C:\\\\xampp\\\\php\\\\pear\";\n pear config-all \n"
},
{
"answer_id": 41975155,
"author": "mpalencia",
"author_id": 1191830,
"author_profile": "https://Stackoverflow.com/users/1191830",
"pm_score": 1,
"selected": false,
"text": "cd php\\pear\n pear\n"
},
{
"answer_id": 55215386,
"author": "Musab ibnu Siraj",
"author_id": 10579938,
"author_profile": "https://Stackoverflow.com/users/10579938",
"pm_score": 2,
"selected": false,
"text": "<?php\n\n/**\n * Laravel - A PHP Framework For Web Artisans\n *\n * @package Laravel\n * @author Taylor Otwell <[email protected]>\n */\n\n$uri = urldecode(\n parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)\n);\n\n// This file allows us to emulate Apache's \"mod_rewrite\" functionality from the\n// built-in PHP web server. This provides a convenient way to test a Laravel\n// application without having installed a \"real\" web server software here.\nif ($uri !== '/' && file_exists(__DIR__.'/public'.$uri)) {\n return false;\n}\n\nrequire_once __DIR__.'/public/index.php';"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6939/"
] |
62,661 |
<p>What Direct3D render states should be used to implement Java's Porter-Duff compositing rules (CLEAR, SRC, SRCOVER, etc.)?</p>
|
[
{
"answer_id": 67873,
"author": "Corey Ross",
"author_id": 5927,
"author_profile": "https://Stackoverflow.com/users/5927",
"pm_score": 2,
"selected": false,
"text": "SourceBlend = Zero\nDestinationBlend = Zero\n SourceBlend = One\nDestinationBlend = Zero\n SourceBlend = Zero\nDestinationBlend = One\n SourceBlend = One\nDestinationBlend = InvSourceAlpha\n SourceBlend = InvDestinationAlpha\nDestinationBlend = One\n SourceBlend = DestinationAlpha\nDestinationBlend = One\n SourceBlend = Zero\nDestinationBlend = SourceAlpha\n SourceBlend = InvDestinationAlpha\nDestinationBlend = Zero\n SourceBlend = Zero\nDestinationBlend = InvSourceAlpha\n SourceBlend = DestinationAlpha\nDestinationBlend = InvSourceAlpha\n SourceBlend = InvDestinationAlpha\nDestinationBlend = SourceAlpha\n SourceBlend = InvDestinationAlpha\nDestinationBlend = InvSourceAlpha\n"
},
{
"answer_id": 69665,
"author": "Corey Ross",
"author_id": 5927,
"author_profile": "https://Stackoverflow.com/users/5927",
"pm_score": 0,
"selected": false,
"text": "AlphaTestEnable = false\n"
},
{
"answer_id": 8620911,
"author": "benbuck",
"author_id": 716058,
"author_profile": "https://Stackoverflow.com/users/716058",
"pm_score": 1,
"selected": false,
"text": "SourceBlend = DestinationAlpha\nDestinationBlend = Zero\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7071/"
] |
62,689 |
<p>I'm trying to implement a data compression idea I've had, and since I'm imagining running it against a large corpus of test data, I had thought to code it in C (I mostly have experience in scripting languages like Ruby and Tcl.) </p>
<p>Looking through the O'Reilly 'cow' books on C, I realize that I can't simply index the bits of a simple 'char' or 'int' type variable as I'd like to to do bitwise comparisons and operators. </p>
<p>Am I correct in this perception? Is it reasonable for me to use an enumerated type for representing a bit (and make an array of these, and writing functions to convert to and from char)? If so, is such a type and functions defined in a standard library already somewhere? Are there other (better?) approaches? Is there some example code somewhere that someone could point me to?</p>
<p>Thanks - </p>
|
[
{
"answer_id": 62723,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 3,
"selected": false,
"text": "x |= (1 << 5); // sets the 5th-from right\n x &= ~(1 << 5); // clears 5th-from-right\n x ^= (1 << 5); // flips 5th-from-right\n (x & (1 << 5)) >> 5 // gets the value (0 or 1) of the 5th-from-right\n"
},
{
"answer_id": 62757,
"author": "TK.",
"author_id": 1816,
"author_profile": "https://Stackoverflow.com/users/1816",
"pm_score": 0,
"selected": false,
"text": "bit = (char & 0xF0) >> 7;\n bit = char & 0xF0;\n #define BIT_0 0x1 // or 1 << 0\n#define BIT_1 0x2 // or 1 << 1\n#define BIT_2 0x4 // or 1 << 2\n#define BIT_3 0x8 // or 1 << 3\n bit = char & BIT_1;\n char |= BIT_2;\n char &= ~BIT_3\n char ^= BIT_4\n"
},
{
"answer_id": 62783,
"author": "Mladen Janković",
"author_id": 6300,
"author_profile": "https://Stackoverflow.com/users/6300",
"pm_score": 1,
"selected": false,
"text": "int index_state = variable & ( 1 << bit_index );\n varabile |= 1 << bit_index;\n variable &= ~( 1 << bit_index );\n"
},
{
"answer_id": 63037,
"author": "Microserf",
"author_id": 7474,
"author_profile": "https://Stackoverflow.com/users/7474",
"pm_score": 2,
"selected": false,
"text": "1101\n0100\n---- AND\n0100\n 1101\n0010\n---- OR\n1111\n unsigned char myVal = 0x65; /* in hex; this is 01100101 in binary. */\n\n/* Q: is the 3-rd least significant bit set (again, the LSB is the 0th bit)? */\nunsigned char pattern = 1;\npattern <<= 3; /* Shift pattern left by three places.*/\n\nif(myVal && (char)(1<<3)) {printf(\"Yes!\\n\");} /* Perform the test. */\n\n/* Set the most significant bit. */\nmyVal |= (char)(1<<7);\n"
},
{
"answer_id": 63041,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 4,
"selected": true,
"text": "#define GetBit(var, bit) ((var & (1 << bit)) != 0) // Returns true / false if bit is set\n#define SetBit(var, bit) (var |= (1 << bit))\n#define FlipBit(var, bit) (var ^= (1 << bit))\n int myVar = 0;\nSetBit(myVar, 5);\nif (GetBit(myVar, 5))\n{\n // Do something\n}\n"
},
{
"answer_id": 63087,
"author": "Mark D",
"author_id": 7452,
"author_profile": "https://Stackoverflow.com/users/7452",
"pm_score": 0,
"selected": false,
"text": "struct\n{\n unsigned bit0 : 1;\n unsigned bit1 : 1;\n unsigned bit2 : 1;\n unsigned bit3 : 1;\n unsigned reserved : 28;\n} bitPattern; \n CopyMemory( &input, &value, sizeof(value) );\n int state = bitPattern.bit2;\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
62,713 |
<p>In a flow definition, I am trying to access a bean that has a dot in its ID</p>
<p>(example: <code><evaluate expression="bus.MyServiceFacade.someAction()" /></code></p>
<p>However, it does not work. SWF tries to find a bean "bus" instead.</p>
<p>Initially, I got over it by using a helper bean to load the required bean, but the solution is inelegant and uncomfortable. The use of alias'es is also out of the question since the beans are part of a large system and I cannot tamper with them.</p>
<p>In a nutshell, none of the solution allowed me to refernce the bean directly by using its original name. Is that even possible in the current SWF release?</p>
|
[
{
"answer_id": 65920,
"author": "Owen",
"author_id": 2109,
"author_profile": "https://Stackoverflow.com/users/2109",
"pm_score": -1,
"selected": false,
"text": "bus getServiceFacade getServiceFacade getSomeAction"
},
{
"answer_id": 14408583,
"author": "Ryan Ransford",
"author_id": 12604,
"author_profile": "https://Stackoverflow.com/users/12604",
"pm_score": 3,
"selected": false,
"text": "@ #{@'bus.MyServiceFacade'.someAction()}"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6871/"
] |
62,716 |
<p>SVN externals allow you to make an SVN folder appear as if it's at another location. A good use for this is having a common folder shared across all of your projects in SVN.</p>
<p>I have a /trunk/common folder in SVN that I share via several different project.</p>
<p>Example:</p>
<ul>
<li>Project1 : /trunk/project1/depends</li>
<li>Project2 : /trunk/project2/depends</li>
<li>Project3 : /trunk/project3/depends</li>
<li>Project4 : /trunk/project4/depends</li>
</ul>
<p>Each of these depends folders are empty, but have an svn:external defined to point to my /trunk/common folder. </p>
<p>The problem is when I view log within any of the projects: /trunk/projectX/ it does not show changes from the svn:externals. I am using tortoise SVN as my SVN client. </p>
<p>Does anyone know how to change this behavior? I would like for the show log of /trunk/projectX to include any changes to any defined svn:externals as well.</p>
|
[
{
"answer_id": 63106,
"author": "Romain Verdier",
"author_id": 4687,
"author_profile": "https://Stackoverflow.com/users/4687",
"pm_score": 0,
"selected": false,
"text": "repo\n myfirstproject\n trunk\n mysecondproject\n trunk\n mycommonlib\n trunk\n mysecondproject\\trunk svn://mysrv/repo/mysharedlib@2451 sharedlib\n secondproject Folder (refers mysecondproject/trunk)\n sharedlib Folder (refers mycommonlib/trunk @ revision #2451)\n"
},
{
"answer_id": 14500112,
"author": "Lazy Badger",
"author_id": 960558,
"author_profile": "https://Stackoverflow.com/users/960558",
"pm_score": 0,
"selected": false,
"text": ">dir /B /S /AD\nz:\\subversion-troubleshoot-b\\.svn\n...\nz:\\subversion-troubleshoot-b\\trunk\nz:\\subversion-troubleshoot-b\\tags\nz:\\subversion-troubleshoot-b\\trunk\\lib\nz:\\subversion-troubleshoot-b\\trunk\\lib\\.svn\n...\nz:\\subversion-troubleshoot-b\\tags\\1.0.0\nz:\\subversion-troubleshoot-b\\tags\\1.0.1\nz:\\subversion-troubleshoot-b\\tags\\1.0.1\\lib\nz:\\subversion-troubleshoot-b\\tags\\1.0.1\\lib\\.svn\n...\n >svn ls -R\nreadme.textile\ntags/\ntags/1.0.0/\ntags/1.0.0/core_mod.txt\ntags/1.0.1/\ntags/1.0.1/core_mod.txt\ntrunk/\ntrunk/core_mod.txt\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
] |
62,720 |
<p>I am working on an ASP.NET web application, it seems to be working properly when I try to debug it in Visual Studio. However when I emulate heavy load, IIS crashes without any trace -- log entry in the system journal is very generic, "The World Wide Web Publishing service terminated unexpectedly. It has done this 4 time(s)."
How is it possible to get more information from IIS to troubleshoot this problem?</p>
|
[
{
"answer_id": 65553,
"author": "sachaa",
"author_id": 1152057,
"author_profile": "https://Stackoverflow.com/users/1152057",
"pm_score": 2,
"selected": false,
"text": "cscript adplus.vbs -crash -pn w3wp.exe\n .loadby sos mscorwks\n !clrstack\n kpn 200\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6954/"
] |
62,742 |
<p>Is there a way to draw a line along a curved path with a gradient that varies in a direction perpendicular to the direction of the line? I am using the GDI+ framework for my graphics.</p>
|
[
{
"answer_id": 780628,
"author": "TK.",
"author_id": 1816,
"author_profile": "https://Stackoverflow.com/users/1816",
"pm_score": 0,
"selected": false,
"text": "GraphicsPath gp = new GraphicsPath();\n\ngp.AddArc(); // etc...\n\ngraphics.SetClip( gp );\n\ngraphics.FillRectangle( myLinearGradientBrush, gp.GetBounds());\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7040/"
] |
62,771 |
<p>I want to include a batch file rename functionality in my application. A user can type a destination filename pattern and (after replacing some wildcards in the pattern) I need to check if it's going to be a legal filename under Windows. I've tried to use regular expression like <code>[a-zA-Z0-9_]+</code> but it doesn't include many national-specific characters from various languages (e.g. umlauts and so on). What is the best way to do such a check?</p>
|
[
{
"answer_id": 62805,
"author": "Eugene Katz",
"author_id": 1533,
"author_profile": "https://Stackoverflow.com/users/1533",
"pm_score": 8,
"selected": true,
"text": "Path.GetInvalidPathChars GetInvalidFileNameChars"
},
{
"answer_id": 62828,
"author": "Justin Poliey",
"author_id": 6967,
"author_profile": "https://Stackoverflow.com/users/6967",
"pm_score": 0,
"selected": false,
"text": "\\ / : * ? \" < > |\n"
},
{
"answer_id": 62855,
"author": "Steve Cooper",
"author_id": 6722,
"author_profile": "https://Stackoverflow.com/users/6722",
"pm_score": 6,
"selected": false,
"text": "System.IO.Path.InvalidPathChars bool IsValidFilename(string testName)\n{\n Regex containsABadCharacter = new Regex(\"[\" \n + Regex.Escape(System.IO.Path.InvalidPathChars) + \"]\");\n if (containsABadCharacter.IsMatch(testName)) { return false; };\n\n // other checks for UNC, drive-path format, etc\n\n return true;\n}\n System.IO.Path.GetInvalidPathChars() bool IsValidFilename(string testName)\n{\n Regex containsABadCharacter = new Regex(\"[\"\n + Regex.Escape(new string(System.IO.Path.GetInvalidPathChars())) + \"]\");\n if (containsABadCharacter.IsMatch(testName)) { return false; };\n\n // other checks for UNC, drive-path format, etc\n\n return true;\n}\n c:\\my\\drive \\\\server\\share\\dir\\file.ext"
},
{
"answer_id": 62888,
"author": "user7116",
"author_id": 7116,
"author_profile": "https://Stackoverflow.com/users/7116",
"pm_score": 7,
"selected": false,
"text": "< > : \" / \\ | ? * \\?\\ \\?\\"
},
{
"answer_id": 63235,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 5,
"selected": false,
"text": " public static bool IsValidFileName(this string expression, bool platformIndependent)\n {\n string sPattern = @\"^(?!^(PRN|AUX|CLOCK\\$|NUL|CON|COM\\d|LPT\\d|\\..*)(\\..+)?$)[^\\x00-\\x1f\\\\?*:\\\"\";|/]+$\";\n if (platformIndependent)\n {\n sPattern = @\"^(([a-zA-Z]:|\\\\)\\\\)?(((\\.)|(\\.\\.)|([^\\\\/:\\*\\?\"\"\\|<>\\. ](([^\\\\/:\\*\\?\"\"\\|<>\\. ])|([^\\\\/:\\*\\?\"\"\\|<>]*[^\\\\/:\\*\\?\"\"\\|<>\\. ]))?))\\\\)*[^\\\\/:\\*\\?\"\"\\|<>\\. ](([^\\\\/:\\*\\?\"\"\\|<>\\. ])|([^\\\\/:\\*\\?\"\"\\|<>]*[^\\\\/:\\*\\?\"\"\\|<>\\. ]))?$\";\n }\n return (Regex.IsMatch(expression, sPattern, RegexOptions.CultureInvariant));\n }\n"
},
{
"answer_id": 64807,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "String.IndexOfAny() Path.GetInvalidPathChars() Path.GetInvalidFileNameChars() Path.GetInvalidXXX()"
},
{
"answer_id": 101706,
"author": "Jon Schneider",
"author_id": 12484,
"author_profile": "https://Stackoverflow.com/users/12484",
"pm_score": 4,
"selected": false,
"text": "\"file.txt\"\n\" file.txt\"\n\" file.txt\"\n"
},
{
"answer_id": 3425681,
"author": "Steve Cooper",
"author_id": 6722,
"author_profile": "https://Stackoverflow.com/users/6722",
"pm_score": 5,
"selected": false,
"text": "var myCleanPath = PathSanitizer.SanitizeFilename(myBadPath, ' ');\n /// <summary>\n/// Cleans paths of invalid characters.\n/// </summary>\npublic static class PathSanitizer\n{\n /// <summary>\n /// The set of invalid filename characters, kept sorted for fast binary search\n /// </summary>\n private readonly static char[] invalidFilenameChars;\n /// <summary>\n /// The set of invalid path characters, kept sorted for fast binary search\n /// </summary>\n private readonly static char[] invalidPathChars;\n\n static PathSanitizer()\n {\n // set up the two arrays -- sorted once for speed.\n invalidFilenameChars = System.IO.Path.GetInvalidFileNameChars();\n invalidPathChars = System.IO.Path.GetInvalidPathChars();\n Array.Sort(invalidFilenameChars);\n Array.Sort(invalidPathChars);\n\n }\n\n /// <summary>\n /// Cleans a filename of invalid characters\n /// </summary>\n /// <param name=\"input\">the string to clean</param>\n /// <param name=\"errorChar\">the character which replaces bad characters</param>\n /// <returns></returns>\n public static string SanitizeFilename(string input, char errorChar)\n {\n return Sanitize(input, invalidFilenameChars, errorChar);\n }\n\n /// <summary>\n /// Cleans a path of invalid characters\n /// </summary>\n /// <param name=\"input\">the string to clean</param>\n /// <param name=\"errorChar\">the character which replaces bad characters</param>\n /// <returns></returns>\n public static string SanitizePath(string input, char errorChar)\n {\n return Sanitize(input, invalidPathChars, errorChar);\n }\n\n /// <summary>\n /// Cleans a string of invalid characters.\n /// </summary>\n /// <param name=\"input\"></param>\n /// <param name=\"invalidChars\"></param>\n /// <param name=\"errorChar\"></param>\n /// <returns></returns>\n private static string Sanitize(string input, char[] invalidChars, char errorChar)\n {\n // null always sanitizes to null\n if (input == null) { return null; }\n StringBuilder result = new StringBuilder();\n foreach (var characterToTest in input)\n {\n // we binary search for the character in the invalid set. This should be lightning fast.\n if (Array.BinarySearch(invalidChars, characterToTest) >= 0)\n {\n // we found the character in the array of \n result.Append(errorChar);\n }\n else\n {\n // the character was not found in invalid, so it is valid.\n result.Append(characterToTest);\n }\n }\n\n // we're done.\n return result.ToString();\n }\n\n}\n"
},
{
"answer_id": 14105459,
"author": "JerKimball",
"author_id": 48692,
"author_profile": "https://Stackoverflow.com/users/48692",
"pm_score": 2,
"selected": false,
"text": "public static bool IsLegalFilename(string name)\n{\n try \n {\n var fileInfo = new FileInfo(name);\n return true;\n }\n catch\n {\n return false;\n }\n}\n"
},
{
"answer_id": 15072694,
"author": "JoelFan",
"author_id": 16012,
"author_profile": "https://Stackoverflow.com/users/16012",
"pm_score": 3,
"selected": false,
"text": "private static readonly Regex InvalidFileRegex = new Regex(\n string.Format(\"[{0}]\", Regex.Escape(@\"<>:\"\"/\\|?*\")));\n\npublic static string SanitizeFileName(string fileName)\n{\n return InvalidFileRegex.Replace(fileName, string.Empty);\n}\n"
},
{
"answer_id": 41563828,
"author": "Tony Sun",
"author_id": 6633541,
"author_profile": "https://Stackoverflow.com/users/6633541",
"pm_score": 0,
"selected": false,
"text": "string tagetFileFullNameToBeChecked;\ntry\n{\n Path.GetFullPath(tagetFileFullNameToBeChecked)\n}\ncatch(AugumentException ex)\n{\n // invalid chars found\n}\n"
},
{
"answer_id": 42589487,
"author": "tmt",
"author_id": 1475183,
"author_profile": "https://Stackoverflow.com/users/1475183",
"pm_score": 3,
"selected": false,
"text": "bool IsFileNameCorrect(string fileName){\n return !fileName.Any(f=>Path.GetInvalidFileNameChars().Contains(f))\n}\n bool IsFileNameCorrect(string fileName){\n return fileName.All(f=>!Path.GetInvalidFileNameChars().Contains(f))\n}\n"
},
{
"answer_id": 42777899,
"author": "Brent",
"author_id": 1022710,
"author_profile": "https://Stackoverflow.com/users/1022710",
"pm_score": 1,
"selected": false,
"text": "public class ValidFileNameAttribute : ValidationAttribute\n{\n public ValidFileNameAttribute()\n {\n RequireExtension = true;\n ErrorMessage = \"{0} is an Invalid Filename\";\n MaxLength = 255; //superseeded in modern windows environments\n }\n public override bool IsValid(object value)\n {\n //http://stackoverflow.com/questions/422090/in-c-sharp-check-that-filename-is-possibly-valid-not-that-it-exists\n var fileName = (string)value;\n if (string.IsNullOrEmpty(fileName)) { return true; }\n if (fileName.IndexOfAny(Path.GetInvalidFileNameChars()) > -1 ||\n (!AllowHidden && fileName[0] == '.') ||\n fileName[fileName.Length - 1]== '.' ||\n fileName.Length > MaxLength)\n {\n return false;\n }\n string extension = Path.GetExtension(fileName);\n return (!RequireExtension || extension != string.Empty)\n && (ExtensionList==null || ExtensionList.Contains(extension));\n }\n private const string _sepChar = \",\";\n private IEnumerable<string> ExtensionList { get; set; }\n public bool AllowHidden { get; set; }\n public bool RequireExtension { get; set; }\n public int MaxLength { get; set; }\n public string AllowedExtensions {\n get { return string.Join(_sepChar, ExtensionList); } \n set {\n if (string.IsNullOrEmpty(value))\n { ExtensionList = null; }\n else {\n ExtensionList = value.Split(new char[] { _sepChar[0] })\n .Select(s => s[0] == '.' ? s : ('.' + s))\n .ToList();\n }\n } }\n\n public override bool RequiresValidationContext => false;\n}\n [TestMethod]\npublic void TestFilenameAttribute()\n{\n var rxa = new ValidFileNameAttribute();\n Assert.IsFalse(rxa.IsValid(\"pptx.\"));\n Assert.IsFalse(rxa.IsValid(\"pp.tx.\"));\n Assert.IsFalse(rxa.IsValid(\".\"));\n Assert.IsFalse(rxa.IsValid(\".pp.tx\"));\n Assert.IsFalse(rxa.IsValid(\".pptx\"));\n Assert.IsFalse(rxa.IsValid(\"pptx\"));\n Assert.IsFalse(rxa.IsValid(\"a/abc.pptx\"));\n Assert.IsFalse(rxa.IsValid(\"a\\\\abc.pptx\"));\n Assert.IsFalse(rxa.IsValid(\"c:abc.pptx\"));\n Assert.IsFalse(rxa.IsValid(\"c<abc.pptx\"));\n Assert.IsTrue(rxa.IsValid(\"abc.pptx\"));\n rxa = new ValidFileNameAttribute { AllowedExtensions = \".pptx\" };\n Assert.IsFalse(rxa.IsValid(\"abc.docx\"));\n Assert.IsTrue(rxa.IsValid(\"abc.pptx\"));\n}\n"
},
{
"answer_id": 45887757,
"author": "Nick Albrecht",
"author_id": 466224,
"author_profile": "https://Stackoverflow.com/users/466224",
"pm_score": 1,
"selected": false,
"text": "Split() var nameToTest = \"Best file name \\\"ever\\\".txt\";\nbool isInvalidName = nameToTest.Split(System.IO.Path.GetInvalidFileNameChars()).Length > 1;\n\nvar pathToTest = \"C:\\\\My Folder <secrets>\\\\\";\nbool isInvalidPath = pathToTest.Split(System.IO.Path.GetInvalidPathChars()).Length > 1;\n Split() Regex(\"[\" + Regex.Escape(new string(System.IO.Path.GetInvalidPathChars())) + \"]\") Path"
},
{
"answer_id": 46503080,
"author": "Maxence",
"author_id": 200443,
"author_profile": "https://Stackoverflow.com/users/200443",
"pm_score": 0,
"selected": false,
"text": "using System.IO;\n\nstatic class PathUtils\n{\n public static string IsValidFullPath([NotNull] string fullPath)\n {\n if (string.IsNullOrWhiteSpace(fullPath))\n return \"Path is null, empty or white space.\";\n\n bool pathContainsInvalidChars = fullPath.IndexOfAny(Path.GetInvalidPathChars()) != -1;\n if (pathContainsInvalidChars)\n return \"Path contains invalid characters.\";\n\n string fileName = Path.GetFileName(fullPath);\n if (fileName == \"\")\n return \"Path must contain a file name.\";\n\n bool fileNameContainsInvalidChars = fileName.IndexOfAny(Path.GetInvalidFileNameChars()) != -1;\n if (fileNameContainsInvalidChars)\n return \"File name contains invalid characters.\";\n\n if (!Path.IsPathRooted(fullPath))\n return \"The path must be absolute.\";\n\n return \"\";\n }\n}\n Path.GetInvalidPathChars public static bool TestIfFileCanBeCreated([NotNull] string fullPath)\n{\n if (string.IsNullOrWhiteSpace(fullPath))\n throw new ArgumentException(\"Value cannot be null or whitespace.\", \"fullPath\");\n\n string directoryName = Path.GetDirectoryName(fullPath);\n if (directoryName != null) Directory.CreateDirectory(directoryName);\n try\n {\n using (new FileStream(fullPath, FileMode.CreateNew)) { }\n File.Delete(fullPath);\n return true;\n }\n catch (IOException)\n {\n return false;\n }\n}\n"
},
{
"answer_id": 46517818,
"author": "KenR",
"author_id": 8705832,
"author_profile": "https://Stackoverflow.com/users/8705832",
"pm_score": 1,
"selected": false,
"text": "public bool IsPathFileNameGood(string fname)\n{\n bool rc = Constants.Fail;\n try\n {\n this._stream = new StreamWriter(fname, true);\n rc = Constants.Pass;\n }\n catch (Exception ex)\n {\n MessageBox.Show(ex.Message, \"Problem opening file\");\n rc = Constants.Fail;\n }\n return rc;\n}\n"
},
{
"answer_id": 49301029,
"author": "Vlad",
"author_id": 276994,
"author_profile": "https://Stackoverflow.com/users/276994",
"pm_score": 0,
"selected": false,
"text": "static bool IsValidFileName(string name)\n{\n return\n !string.IsNullOrWhiteSpace(name) &&\n name.IndexOfAny(Path.GetInvalidFileNameChars()) < 0 &&\n !Path.GetFullPath(name).StartsWith(@\"\\\\.\\\");\n}\n <>:\"/\\|?* CON NUL COMx Path.GetFullPath"
},
{
"answer_id": 53576616,
"author": "Zananok",
"author_id": 1612470,
"author_profile": "https://Stackoverflow.com/users/1612470",
"pm_score": -1,
"selected": false,
"text": "public static bool IsValidFilename(string testName) => !Regex.IsMatch(testName, \"[\" + Regex.Escape(new string(System.IO.Path.InvalidPathChars)) + \"]\");\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7162/"
] |
62,776 |
<p>How do I implement a Copy menu item in a Windows application written in C#/.NET 2.0?</p>
<p>I want to let the user to mark some text in a control and then select the Copy menu item from an Edit menu in the menubar of the application and then do a Paste in for example Excel. </p>
<p>What makes my head spin is how to first determine which child form is active and then how to find the control that contains the marked text that should be copied to the clipboard. </p>
<p>Help, please.</p>
|
[
{
"answer_id": 62833,
"author": "GEOCHET",
"author_id": 5640,
"author_profile": "https://Stackoverflow.com/users/5640",
"pm_score": -1,
"selected": false,
"text": "MessageBox.Show(\"I copied your datas!\");"
},
{
"answer_id": 63004,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "((FormFoo)this.ActiveMDIChild).GetCopiedData();\n Form f = this.ActiveMDIChild;\nif(f is FormGrid)\n{\n ((FormGrid)f).GetGridCopiedData();\n} else if(f is FormText) {\n ((FormText)f).GetTextCopiedData();\n}\n"
},
{
"answer_id": 63470,
"author": "Petteri",
"author_id": 7174,
"author_profile": "https://Stackoverflow.com/users/7174",
"pm_score": 4,
"selected": true,
"text": " /// <summary>\n /// Recursively traverse a tree of controls to find the control that has focus, if any\n /// </summary>\n /// <param name=\"c\">The control to search, might be a control container</param>\n /// <returns>The control that either has focus or contains the control that has focus</returns>\n private Control FindFocus(Control c) \n {\n foreach (Control k in c.Controls)\n {\n if (k.Focused)\n {\n return k;\n }\n else if (k.ContainsFocus)\n {\n return FindFocus(k);\n }\n }\n\n return null;\n }\n\n private void copyToolStripMenuItem_Click(object sender, EventArgs e)\n {\n Form f = this.ActiveMdiChild;\n\n // Find the control that has focus\n Control focusedControl = FindFocus(f.ActiveControl);\n\n // See if focusedControl is of a type that can select text/data\n if (focusedControl is TextBox)\n {\n TextBox tb = focusedControl as TextBox;\n Clipboard.SetDataObject(tb.SelectedText);\n }\n else if (focusedControl is DataGridView)\n {\n DataGridView dgv = focusedControl as DataGridView;\n Clipboard.SetDataObject(dgv.GetClipboardContent());\n }\n else if (...more?...)\n {\n }\n }\n"
},
{
"answer_id": 1207426,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": " if (e.Button == MouseButtons.Right)\n {\n dataGridView.Focus();\n\n dataGridView.CurrentCell = dataGridView[e.ColumnIndex, e.RowIndex];\n }\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7174/"
] |
62,784 |
<p>It's fall of 2008, and I still hear developers say that you should not design a site that requires JavaScript.</p>
<p>I understand that you should develop sites that degrade gracefully when JS is not present/on. But at what point do you not include funcitonality that can only be powered by JS? </p>
<p>I guess the question comes down to demographics. Are there numbers out there of how many folks are browsing without JS? </p>
|
[
{
"answer_id": 68158,
"author": "HFLW",
"author_id": 252822,
"author_profile": "https://Stackoverflow.com/users/252822",
"pm_score": 1,
"selected": false,
"text": "<noscript> <div dojoType=\"dojox.Rating\" stars=\"5\" value=\"4\"></div>\n<noscript>4/5</noscript>\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6957/"
] |
62,804 |
<p>Is there a standard library method that converts a string that has duration in the standard ISO 8601 Duration (also used in XSD for its <code>duration</code> type) format into the .NET TimeSpan object?</p>
<p>For example, P0DT1H0M0S which represents a duration of one hour, is converted into New TimeSpan(0,1,0,0,0).</p>
<p>A Reverse converter does exist which works as follows:
Xml.XmlConvert.ToString(New TimeSpan(0,1,0,0,0))
The above expression will return P0DT1H0M0S.</p>
|
[
{
"answer_id": 63219,
"author": "user7658",
"author_id": 7658,
"author_profile": "https://Stackoverflow.com/users/7658",
"pm_score": 6,
"selected": true,
"text": "System.Xml.XmlConvert.ToTimeSpan(\"P0DT1H0M0S\")\n"
},
{
"answer_id": 5760821,
"author": "Paul Williams",
"author_id": 420400,
"author_profile": "https://Stackoverflow.com/users/420400",
"pm_score": 4,
"selected": false,
"text": "PS C:\\Users\\troll> [Reflection.Assembly]::LoadWithPartialName(\"System.Xml\")\n\nGAC Version Location\n--- ------- --------\nTrue v2.0.50727 C:\\Windows\\assembly\\GAC_MSIL\\System.Xml\\2.0.0.0__b77a5c561934e089\\System.Xml.dll\n\n\nPS C:\\Users\\troll> [System.Xml.XmlConvert]::ToTimeSpan(\"P1M\")\n\n\nDays : 30\nHours : 0\nMinutes : 0\nSeconds : 0\nMilliseconds : 0\nTicks : 25920000000000\nTotalDays : 30\nTotalHours : 720\nTotalMinutes : 43200\nTotalSeconds : 2592000\nTotalMilliseconds : 2592000000\n\n\n\nPS C:\\Users\\troll> [System.Xml.XmlConvert]::ToTimeSpan(\"P1Y\")\n\n\nDays : 365\nHours : 0\nMinutes : 0\nSeconds : 0\nMilliseconds : 0\nTicks : 315360000000000\nTotalDays : 365\nTotalHours : 8760\nTotalMinutes : 525600\nTotalSeconds : 31536000\nTotalMilliseconds : 31536000000\n\n\n\nPS C:\\Users\\troll>\n"
},
{
"answer_id": 11923534,
"author": "revington",
"author_id": 344911,
"author_profile": "https://Stackoverflow.com/users/344911",
"pm_score": 0,
"selected": false,
"text": "TimeSpan ts = System.Xml.XmlConvert.ToTimeSpan(\"P5Y\");\nDateTime now = new DateTime(2008,2,29);\nConsole.WriteLine(now + ts); // 27/02/2013 0:00:00\n DateTime now = new DateTime (2008, 2, 29);\nstring duration = \"P1Y\";\nRegex expr = \n new Regex (@\"(-?)P((\\d{1,4})Y)?((\\d{1,4})M)?((\\d{1,4})D)?(T((\\d{1,4})H)?((\\d{1,4})M)?((\\d{1,4}(\\.\\d{1,3})?)S)?)?\", RegexOptions.Compiled | RegexOptions.CultureInvariant);\nbool positiveDuration = false == (input [0] == '-');\n\nMatchCollection matches = expr.Matches (duration);\nvar g = matches [0];\nFunc<int,int> getNumber = x => {\n if (g.Groups.Count < x || string.IsNullOrEmpty (g.Groups [x].ToString ())) {\n return 0;\n }\n\n int a = int.Parse (g.Groups [x].ToString ());\n\n return PositiveDuration ? a : a * -1;\n\n};\nnow.AddYears (getNumber (3));\nnow.AddMonths (getNumber (5));\nnow.AddDays (getNumber (7));\nnow.AddHours (getNumber (10));\nnow.AddMinutes (getNumber (12));\nnow.AddSeconds (getNumber (14));\nConsole.WriteLine (now); // 28/02/2012 0:00:00\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7105/"
] |
62,810 |
<p>I use RCF with boost.serialization (why use RCF's copy when we already use the original?) It works OK, but when an exception is thrown in the server, it's not passed correctly to the client. Instead, I get an RCF::SerializationException quoting an <code>archive_exception</code> saying "class name too long". When I change the protocol to BsText, the exceptions is "unregistered class". When I change the protocol to SfBinary, it works.
I've registered RemoteException on both server and client like this:</p>
<pre><code>BOOST_CLASS_VERSION(RCF::RemoteException, 0)
BOOST_CLASS_EXPORT(RCF::RemoteException)
</code></pre>
<p>I even tried serializing and deserializing a <code>boost::shared_ptr<RCF::RemoteException></code> in the same test, and it works.</p>
<p>So how can I make RCF pass exceptions correctly without resorting to SF?</p>
|
[
{
"answer_id": 132553,
"author": "Lev",
"author_id": 7224,
"author_profile": "https://Stackoverflow.com/users/7224",
"pm_score": 3,
"selected": true,
"text": "void serialize(SerializationProtocolOut & out, const RemoteException & e)\n{\n serialize(out, std::auto_ptr<RemoteException>(new RemoteException(e)));\n}\n ar & boost::serialization::make_nvp(\"Dummy\", apt.get());\n T *pt = apt.get();\nar & boost::serialization::make_nvp(\"Dummy\", pt);\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7224/"
] |
62,814 |
<p>Is there any difference between a binary semaphore and mutex or are they essentially the same?</p>
|
[
{
"answer_id": 63084,
"author": "Casey Barker",
"author_id": 7046,
"author_profile": "https://Stackoverflow.com/users/7046",
"pm_score": 1,
"selected": false,
"text": "{\n mutexGet(); // Other threads can no longer get the mutex.\n\n // Make changes to the protected object.\n // ...\n\n objectModify(); // Also gets/puts the mutex. Only allowed from this thread context.\n\n // Make more changes to the protected object.\n // ...\n\n mutexPut(); // Finally allows other threads to get the mutex.\n}\n"
},
{
"answer_id": 86021,
"author": "Benoit",
"author_id": 10703,
"author_profile": "https://Stackoverflow.com/users/10703",
"pm_score": 10,
"selected": false,
"text": "\n Task A Task B\n ... Take BinSemaphore <== wait for something\n Do Something Noteworthy\n Give BinSemaphore do something <== unblocks\n"
},
{
"answer_id": 311648,
"author": "ConcernedOfTunbridgeWells",
"author_id": 15401,
"author_profile": "https://Stackoverflow.com/users/15401",
"pm_score": 5,
"selected": false,
"text": "Count down from 5000:\n i. Execute the test-and-set instruction\n ii. If the mutex is clear, we have acquired it in the previous instruction \n so we can exit the loop\n iii. When we get to zero, give up our time slice.\n (somewhere in the program startup)\nInitialise the semaphore to its start-up value.\n\nAcquiring a semaphore\n i. (synchronised) Attempt to decrement the semaphore value\n ii. If the value would be less than zero, put the task on the tail of the list of tasks waiting on the semaphore and give up the time slice.\n\nPosting a semaphore\n i. (synchronised) Increment the semaphore value\n ii. If the value is greater or equal to the amount requested in the post at the front of the queue, take that task off the queue and make it runnable. \n iii. Repeat (ii) for all tasks until the posted value is exhausted or there are no more tasks waiting.\n"
},
{
"answer_id": 13559646,
"author": "user1852497",
"author_id": 1852497,
"author_profile": "https://Stackoverflow.com/users/1852497",
"pm_score": 3,
"selected": false,
"text": "Mutex Semaphore"
},
{
"answer_id": 13824078,
"author": "paxi",
"author_id": 1895252,
"author_profile": "https://Stackoverflow.com/users/1895252",
"pm_score": 3,
"selected": false,
"text": "lock() lock()"
},
{
"answer_id": 18200546,
"author": "Raghav Navada",
"author_id": 612581,
"author_profile": "https://Stackoverflow.com/users/612581",
"pm_score": 2,
"selected": false,
"text": "#include <stdio.h>\n#include <windows.h>\n#define xUSE_MUTEX 1\n#define MAX_SEM_COUNT 1\n\nDWORD WINAPI Thread_no_1( LPVOID lpParam );\nDWORD WINAPI Thread_no_2( LPVOID lpParam );\n\nHANDLE Handle_Of_Thread_1 = 0;\nHANDLE Handle_Of_Thread_2 = 0;\nint Data_Of_Thread_1 = 1;\nint Data_Of_Thread_2 = 2;\nHANDLE ghMutex = NULL;\nHANDLE ghSemaphore = NULL;\n\n\nint main(void)\n{\n\n#ifdef USE_MUTEX\n ghMutex = CreateMutex( NULL, FALSE, NULL);\n if (ghMutex == NULL) \n {\n printf(\"CreateMutex error: %d\\n\", GetLastError());\n return 1;\n }\n#else\n // Create a semaphore with initial and max counts of MAX_SEM_COUNT\n ghSemaphore = CreateSemaphore(NULL,MAX_SEM_COUNT,MAX_SEM_COUNT,NULL);\n if (ghSemaphore == NULL) \n {\n printf(\"CreateSemaphore error: %d\\n\", GetLastError());\n return 1;\n }\n#endif\n // Create thread 1.\n Handle_Of_Thread_1 = CreateThread( NULL, 0,Thread_no_1, &Data_Of_Thread_1, 0, NULL); \n if ( Handle_Of_Thread_1 == NULL)\n {\n printf(\"Create first thread problem \\n\");\n return 1;\n }\n\n /* sleep for 5 seconds **/\n Sleep(5 * 1000);\n\n /*Create thread 2 */\n Handle_Of_Thread_2 = CreateThread( NULL, 0,Thread_no_2, &Data_Of_Thread_2, 0, NULL); \n if ( Handle_Of_Thread_2 == NULL)\n {\n printf(\"Create second thread problem \\n\");\n return 1;\n }\n\n // Sleep for 20 seconds\n Sleep(20 * 1000);\n\n printf(\"Out of the program \\n\");\n return 0;\n}\n\n\nint my_critical_section_code(HANDLE thread_handle)\n{\n\n#ifdef USE_MUTEX\n if(thread_handle == Handle_Of_Thread_1)\n {\n /* get the lock */\n WaitForSingleObject(ghMutex, INFINITE);\n printf(\"Thread 1 holding the mutex \\n\");\n }\n#else\n /* get the semaphore */\n if(thread_handle == Handle_Of_Thread_1)\n {\n WaitForSingleObject(ghSemaphore, INFINITE);\n printf(\"Thread 1 holding semaphore \\n\");\n }\n#endif\n\n if(thread_handle == Handle_Of_Thread_1)\n {\n /* sleep for 10 seconds */\n Sleep(10 * 1000);\n#ifdef USE_MUTEX\n printf(\"Thread 1 about to release mutex \\n\");\n#else\n printf(\"Thread 1 about to release semaphore \\n\");\n#endif\n }\n else\n {\n /* sleep for 3 secconds */\n Sleep(3 * 1000);\n }\n\n#ifdef USE_MUTEX\n /* release the lock*/\n if(!ReleaseMutex(ghMutex))\n {\n printf(\"Release Mutex error in thread %d: error # %d\\n\", (thread_handle == Handle_Of_Thread_1 ? 1:2),GetLastError());\n }\n#else\n if (!ReleaseSemaphore(ghSemaphore,1,NULL) ) \n {\n printf(\"ReleaseSemaphore error in thread %d: error # %d\\n\",(thread_handle == Handle_Of_Thread_1 ? 1:2), GetLastError());\n }\n#endif\n\n return 0;\n}\n\nDWORD WINAPI Thread_no_1( LPVOID lpParam ) \n{ \n my_critical_section_code(Handle_Of_Thread_1);\n return 0;\n}\n\n\nDWORD WINAPI Thread_no_2( LPVOID lpParam ) \n{\n my_critical_section_code(Handle_Of_Thread_2);\n return 0;\n}\n"
},
{
"answer_id": 34494207,
"author": "Rahul Yadav",
"author_id": 4037532,
"author_profile": "https://Stackoverflow.com/users/4037532",
"pm_score": -1,
"selected": false,
"text": "initial value of SemaVar=0\n\nProducer Consumer\n--- SemaWait()->decrement SemaVar \nproduce data\n---\nSemaSignal SemaVar or SemaVar++ --->consumer unblocks as SemVar is 1 now.\n"
},
{
"answer_id": 38391937,
"author": "Adi06411",
"author_id": 6521452,
"author_profile": "https://Stackoverflow.com/users/6521452",
"pm_score": 2,
"selected": false,
"text": "EDEADLK EPERM pthread_mutex_t mutex;\npthread_mutexattr_t attr;\npthread_mutexattr_init (&attr);\npthread_mutexattr_settype (&attr, PTHREAD_MUTEX_ERRORCHECK_NP);\npthread_mutex_init (&mutex, &attr);\n if(pthread_mutex_unlock(&mutex)==EPERM)\n printf(\"Unlock failed:Mutex not owned by this thread\\n\");\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7086/"
] |
62,832 |
<p>I would like to monitor a log file that is being written to by an application. I want to process the file line by line as, or shortly after, it is written. I have not found a way of detecting that a file has been extended after reaching eof.</p>
<p>The code needs to work on Mac and PC, and can be in any language, though I am most familiar with C++ and Perl.</p>
<p>Does anybody have a suggestion for the best way to do it?</p>
|
[
{
"answer_id": 63446,
"author": "Bruno De Fraine",
"author_id": 6918,
"author_profile": "https://Stackoverflow.com/users/6918",
"pm_score": 2,
"selected": false,
"text": "tail -f open IN, $file;\nwhile(1) {\n my $line = <IN>;\n if($line) {\n #process line...\n } else {\n sleep(1);\n seek(IN,0,1);\n }\n}\nclose IN;\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/259/"
] |
62,892 |
<p>I'm looking for advice on how to dynamically create content in flash based on a database. Initially I was thinking that we would export the database to an XML file and use the built in Actionscript XML parser to take care of that, however the size of the XML file may prove prohibitive. </p>
<p>I have read about using an intermediary step (PHP, ASP) to retrieve information and pass it back as something that Actionscript can read, but I would prefer not to do that if possible. Has anyone worked with the <a href="http://code.google.com/p/assql/" rel="nofollow noreferrer">asSQL</a> libraries before? Or is there something else that I am missing?</p>
|
[
{
"answer_id": 69947200,
"author": "gonewiththewhind",
"author_id": 17144628,
"author_profile": "https://Stackoverflow.com/users/17144628",
"pm_score": -1,
"selected": false,
"text": "sudo mkdir actionpackt;\nauto-config -con yes;\ntouch actionpackt/config.gar\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4753/"
] |
62,906 |
<p>In VB.NET is there a library of template dialogs I can use? It's easy to create a custom dialog and inherit from that, but it seems like there would be some templates for that sort of thing.</p>
<p>I just need something simple like Save/Cancel, Yes/No, etc. </p>
<p>Edit: MessageBox is not quite enough, because I want to add drop-down menus, listboxes, grids, etc. If I had a dialog form where I could ask for some pre-defined buttons, each of which returned a modal result and closed the form, then I could add those controls and the buttons would already be there.</p>
|
[
{
"answer_id": 62928,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": 2,
"selected": false,
"text": "MsgBox(\"Do you want to see this message?\", MsgBoxStyle.OkCancel + MsgBoxStyle.Information, \"Respond\")\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672/"
] |
62,916 |
<p>I have installed and setup RubyCAS-Server and RubyCAS-Client on my machine. Login works perfectly but when I try to logout I get this error message from the RubyCAS-Server:</p>
<pre><code>Camping Problem!
CASServer::Controllers::Logout.GET
ActiveRecord::StatementInvalid Mysql::Error: Unknown column 'username' in 'where clause': SELECT * FROM `casserver_pgt` WHERE (username = 'lgs') :
</code></pre>
<p>I am using version 0.6 of the gem. Looking at the migrations in the RubyCAS-Server it looks like there shouldn't be a username column in that table at all.</p>
<p>Does anyone know why this is happening and what I can do about it?</p>
|
[
{
"answer_id": 62928,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": 2,
"selected": false,
"text": "MsgBox(\"Do you want to see this message?\", MsgBoxStyle.OkCancel + MsgBoxStyle.Information, \"Respond\")\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3842/"
] |
62,923 |
<p>Developer looking for best method to identify a deadlock on a specific transaction inside a specific thread. We are getting deadlock errors but these are very general in FB 2.0</p>
<p>Deadlocks happening and they are leading to breakdowns in the DB connection between client and the DB. </p>
<ul>
<li>We send live ( once a second) data to the DB. </li>
<li>We open a thread pool of around 30 threads and use them to ingest the data ( about 1-2 kB each second). </li>
<li>Sometimes the DB can only take so much that we use the next thread in the pool to keep the stream current as possible. </li>
</ul>
<p>On occasion this produces a deadlock in addition to reaching the max thread count and breaking the connection. </p>
<p>So we really need opinions on if this is the best method to ingest this amount of data every second. We have up to 100 on these clients hitting the DB at the same time.<br>
Average transactions are about 1.5 to 1.8 million per day.</p>
|
[
{
"answer_id": 63518,
"author": "Harriv",
"author_id": 7735,
"author_profile": "https://Stackoverflow.com/users/7735",
"pm_score": 1,
"selected": false,
"text": "SELECT ATT.MON$USER, ATT.MON$REMOTE_ADDRESS, STMT.MON$SQL_TEXT, STMT.MON$TIMESTAMP\nFROM MON$ATTACHMENTS ATT \nJOIN MON$STATEMENTS STMT ON ATT.MON$ATTACHMENT_ID = STMT.MON$ATTACHMENT_ID\nWHERE ATT.MON$ATTACHMENT_ID <> CURRENT_CONNECTION AND STMT.MON$STATE = 1\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
62,929 |
<p>I am getting the following error trying to read from a socket. I'm doing a <code>readInt()</code> on that <code>InputStream</code>, and I am getting this error. Perusing the documentation this suggests that the client part of the connection closed the connection. In this scenario, I am the server.</p>
<p>I have access to the client log files and it is not closing the connection, and in fact its log files suggest I am closing the connection. So does anybody have an idea why this is happening? What else to check for? Does this arise when there are local resources that are perhaps reaching thresholds?</p>
<hr>
<p>I do note that I have the following line:</p>
<pre><code>socket.setSoTimeout(10000);
</code></pre>
<p>just prior to the <code>readInt()</code>. There is a reason for this (long story), but just curious, are there circumstances under which this might lead to the indicated error? I have the server running in my IDE, and I happened to leave my IDE stuck on a breakpoint, and I then noticed the exact same errors begin appearing in my own logs in my IDE.</p>
<p>Anyway, just mentioning it, hopefully not a red herring. :-(</p>
|
[
{
"answer_id": 63155,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 6,
"selected": false,
"text": "SocketTimeoutException setSoTimeout() read()"
},
{
"answer_id": 31741436,
"author": "Davut Gürbüz",
"author_id": 413032,
"author_profile": "https://Stackoverflow.com/users/413032",
"pm_score": 4,
"selected": false,
"text": "java.net.SocketException: Connection reset Socket Socket clientSocket = ServerSocket.accept();\nis = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));\nint readed = is.read(); // WHERE ERROR STARTS !!!\n for my JAVA Socket ServerSocket is.read() while(true)\n{\n Receive();\n}\n java.net.SocketException: Socket is closed\n at java.net.ServerSocket.accept(ServerSocket.java:494)\n String Receive() throws Exception\n{\ntry { \n int readed = is.read();\n ....\n}catch(Exception e)\n{\n tryReConnect();\n logit(); //etc\n}\n\n\n//...\n}\n private void tryReConnect()\n {\n try\n {\n ServerSocket.close();\n //empty my old lost connection and let it get by garbage col. immediately \n clientSocket=null;\n System.gc();\n //Wait a new client Socket connection and address this to my local variable\n clientSocket= ServerSocket.accept(); // Waiting for another Connection\n System.out.println(\"Connection established...\");\n }catch (Exception e) {\n String message=\"ReConnect not successful \"+e.getMessage();\n logit();//etc...\n }\n }\n try and catch Connection reset"
},
{
"answer_id": 57515659,
"author": "Sumiya",
"author_id": 2473061,
"author_profile": "https://Stackoverflow.com/users/2473061",
"pm_score": 2,
"selected": false,
"text": "-Djavax.net.debug=ssl:handshake:verbose:keymanager:trustmanager -Djava.security.debug=access:stack"
},
{
"answer_id": 68480666,
"author": "tsotzolas",
"author_id": 3832031,
"author_profile": "https://Stackoverflow.com/users/3832031",
"pm_score": 1,
"selected": false,
"text": "DNS problem host file"
},
{
"answer_id": 71227340,
"author": "Djek-Grif",
"author_id": 2471275,
"author_profile": "https://Stackoverflow.com/users/2471275",
"pm_score": 0,
"selected": false,
"text": "OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();\n List<ConnectionSpec> connectionSpecs = new ArrayList<>();\n connectionSpecs.add(ConnectionSpec.COMPATIBLE_TLS);\n // clientBuilder.connectionSpecs(connectionSpecs);\n"
},
{
"answer_id": 73825492,
"author": "MaVRoSCy",
"author_id": 1387157,
"author_profile": "https://Stackoverflow.com/users/1387157",
"pm_score": 0,
"selected": false,
"text": " <Connector port=\"8443\" protocol=\"HTTP/1.1\" SSLEnabled=\"true\"\n maxThreads=\"150\" scheme=\"https\" secure=\"true\"\n clientAuth=\"false\" sslProtocol=\"TLS\" keystorePass=\"changeit\" />\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
62,936 |
<p>For example: <code>man(1)</code>, <code>find(3)</code>, <code>updatedb(2)</code>? </p>
<p>What do the numbers in parentheses (Brit. "brackets") mean?</p>
|
[
{
"answer_id": 62943,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 7,
"selected": false,
"text": "man 1 man\nman 3 find\n"
},
{
"answer_id": 62972,
"author": "Ian G",
"author_id": 5764,
"author_profile": "https://Stackoverflow.com/users/5764",
"pm_score": 10,
"selected": true,
"text": "man 5 foo\n"
},
{
"answer_id": 63098,
"author": "TREE",
"author_id": 6973,
"author_profile": "https://Stackoverflow.com/users/6973",
"pm_score": 4,
"selected": false,
"text": "man -s 1 man\n"
},
{
"answer_id": 58496243,
"author": "Gabriel Staples",
"author_id": 4561887,
"author_profile": "https://Stackoverflow.com/users/4561887",
"pm_score": 5,
"selected": false,
"text": "man man man DESCRIPTION\n man is the system's manual pager. Each page argument given\n to man is normally the name of a program, utility or func‐\n tion. The manual page associated with each of these argu‐\n ments is then found and displayed. A section, if provided,\n will direct man to look only in that section of the manual.\n The default action is to search in all of the available sec‐\n tions following a pre-defined order (\"1 n l 8 3 2 3posix 3pm\n 3perl 5 4 9 6 7\" by default, unless overridden by the SEC‐\n TION directive in /etc/manpath.config), and to show only the\n first page found, even if page exists in several sections.\n\n The table below shows the section numbers of the manual fol‐\n lowed by the types of pages they contain.\n\n 1 Executable programs or shell commands\n 2 System calls (functions provided by the kernel)\n 3 Library calls (functions within program libraries)\n 4 Special files (usually found in /dev)\n 5 File formats and conventions eg /etc/passwd\n 6 Games\n 7 Miscellaneous (including macro packages and conven‐\n tions), e.g. man(7), groff(7)\n 8 System administration commands (usually only for root)\n 9 Kernel routines [Non standard]\n\n A manual page consists of several sections.\n\n\n man <section_num> <cmd> OPEN(2) man 2 open FOPEN(3) man 3 fopen man <section_num> intro man <section_num> intro man 1 intro man 2 intro man 7 intro man -a intro --Man-- next: intro(8) [ view (return) | skip (Ctrl-D) | quit (Ctrl-C) ]\n man -a intro man man The default action is to search in all of the available sections follow‐\ning a pre-defined order (\"1 n l 8 3 2 3posix 3pm 3perl 5 4 9 6 7\" by default, unless overrid‐\nden by the SECTION directive in /etc/manpath.config)\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7370/"
] |
62,940 |
<p>Need to show a credits screen where I want to acknowledge the many contributors to my application. </p>
<p>Want it to be an automatically scrolling box, much like the credits roll at the end of the film.</p>
|
[
{
"answer_id": 62998,
"author": "Anheledir",
"author_id": 5703,
"author_profile": "https://Stackoverflow.com/users/5703",
"pm_score": 2,
"selected": false,
"text": "textbox1.SelectionStart = textbox1.Text.Length;\ntextbox1.ScrollToCaret();\ntextbox1.Refresh();\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
62,963 |
<p>Last year, Scott Guthrie <a href="http://weblogs.asp.net/scottgu/archive/2007/07/31/linq-to-sql-debug-visualizer.aspx" rel="noreferrer">stated</a> “You can actually override the raw SQL that LINQ to SQL uses if you want absolute control over the SQL executed”, but I can’t find documentation describing an extensibility method.</p>
<p>I would like to modify the following LINQ to SQL query:</p>
<pre>using (NorthwindContext northwind = new NorthwindContext ()) {
var q = from row in northwind.Customers
let orderCount = row.Orders.Count ()
select new {
row.ContactName,
orderCount
};
}</pre>
<p>Which results in the following TSQL:</p>
<pre>SELECT [t0].[ContactName], (
SELECT COUNT(*)
FROM [dbo].[Orders] AS [t1]
WHERE [t1].[CustomerID] = [t0].[CustomerID]
) AS [orderCount]
FROM [dbo].[Customers] AS [t0]</pre>
<p>To:</p>
<pre>using (NorthwindContext northwind = new NorthwindContext ()) {
var q = from row in northwind.Customers.With (
TableHint.NoLock, TableHint.Index (0))
let orderCount = row.Orders.With (
TableHint.HoldLock).Count ()
select new {
row.ContactName,
orderCount
};
}</pre>
<p>Which <em>would</em> result in the following TSQL:</p>
<pre>SELECT [t0].[ContactName], (
SELECT COUNT(*)
FROM [dbo].[Orders] AS [t1] WITH (HOLDLOCK)
WHERE [t1].[CustomerID] = [t0].[CustomerID]
) AS [orderCount]
FROM [dbo].[Customers] AS [t0] WITH (NOLOCK, INDEX(0))</pre>
<p>Using:</p>
<pre>public static Table<TEntity> With<TEntity> (
this Table<TEntity> table,
params TableHint[] args) where TEntity : class {
//TODO: implement
return table;
}
public static EntitySet<TEntity> With<TEntity> (
this EntitySet<TEntity> entitySet,
params TableHint[] args) where TEntity : class {
//TODO: implement
return entitySet;
}</pre>
<p>And</p>
<pre>
public class TableHint {
//TODO: implement
public static TableHint NoLock;
public static TableHint HoldLock;
public static TableHint Index (int id) {
return null;
}
public static TableHint Index (string name) {
return null;
}
}</pre>
<p>Using some type of LINQ to SQL extensibility, other than <a href="http://blogs.msdn.com/mattwar/archive/2008/05/04/mocks-nix-an-extensible-linq-to-sql-datacontext.aspx" rel="noreferrer">this one</a>. Any ideas?</p>
|
[
{
"answer_id": 64612,
"author": "user8456",
"author_id": 8456,
"author_profile": "https://Stackoverflow.com/users/8456",
"pm_score": -1,
"selected": false,
"text": "DataContext x = new DataContext var a = x.Where().with()"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5869/"
] |
62,987 |
<p>A project I'm working on at the moment involves refactoring a C# Com Object which serves as a database access layer to some Sql 2005 databases.</p>
<p>The author of the existent code has built all the sql queries manually using a string and many if-statements to construct the fairly complex sql statement (~10 joins, >10 sub selects, ~15-25 where conditions and GroupBy's). The base table is always the same one, but the structure of joins, conditions and groupings depend on a set of parameters that are passed into my class/method.</p>
<p>Constructing the sql query like this does work but it obviously isn't a very elegant solution (and rather hard to read/understand and maintain as well)... I could just write a simple "querybuilder" myself but I am pretty sure that I am not the first one with this kind of problem, hence my questions:</p>
<ul>
<li>How do <em>you</em> construct your database queries?</li>
<li>Does C# offer an easy way to dynamically build queries?</li>
</ul>
|
[
{
"answer_id": 63725,
"author": "sgwill",
"author_id": 1204,
"author_profile": "https://Stackoverflow.com/users/1204",
"pm_score": 4,
"selected": true,
"text": "IQueryable<Log> matches = m_Locator.Logs;\n\n// Users filter\nif (usersFilter)\n matches = matches.Where(l => l.UserName == comboBoxUsers.Text);\n\n // Severity filter\n if (severityFilter)\n matches = matches.Where(l => l.Severity == comboBoxSeverity.Text);\n\n Logs = (from log in matches\n orderby log.EventTime descending\n select log).ToList();\n"
},
{
"answer_id": 63802,
"author": "Esteban Araya",
"author_id": 781,
"author_profile": "https://Stackoverflow.com/users/781",
"pm_score": 1,
"selected": false,
"text": "public IQueryable<ClientEntity> GetClients(Expression<Func<ClientModel, bool>> criteria)\n {\n return (\n from model in Context.Client.AsExpandable()\n where criteria.Invoke(model)\n select new Ibfx.AppServer.Imsdb.Entities.Client.ClientEntity()\n {\n Id = model.Id,\n ClientNumber = model.ClientNumber,\n NameFirst = model.NameFirst,\n //more propertie here\n\n }\n );\n }\n public IQueryable<ClientEntity> GetClientsWithWebAccountId(int webAccountId)\n {\n var criteria = PredicateBuilder.True<ClientModel>();\n criteria = criteria.And(c => c.ClientWebAccount.WebAccountId.Equals(webAccountId));\n return GetClients(criteria);\n }\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5005/"
] |
62,995 |
<p>I am currently building in Version 3.5 of the .Net framework and I have a resource (.resx) file that I am trying to access in a web application. I have exposed the .resx properties as public access modifiers and am able to access these properties in the controller files or other .cs files in the web app. My question is this: Is it possible to access the name/value pairs within my view page? I'd like to do something like this...</p>
<pre><code>text="<%$ Resources: Namespace.ResourceFileName, NAME %>"
</code></pre>
<p>or some other similar method in the view page.</p>
|
[
{
"answer_id": 63083,
"author": "Mike Becatti",
"author_id": 6617,
"author_profile": "https://Stackoverflow.com/users/6617",
"pm_score": 4,
"selected": true,
"text": "<%= Resources.<ResourceName>.<Property> %>\n"
},
{
"answer_id": 63328,
"author": "HectorMac",
"author_id": 1400,
"author_profile": "https://Stackoverflow.com/users/1400",
"pm_score": 1,
"selected": false,
"text": "text = Resources.YourResourceFilename.YourProperty;\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7215/"
] |
62,999 |
<p>I’ve been trying to install Ms SQL Server 2005 for over two weeks now, and I’ve finally gotten to the point where the prerequisites all seem to be in place. Unfortunately, every time I try to install SQL Server itself, I get the following message:</p>
<p>“The SQL Server service failed to start. For more information, see the SQL Server Books Online topics, "How to: View SQL Server 2005 Setup Log Files" and "Starting SQL Server Manually."”</p>
<p>The installer then “rolls back” the install and I’m left with three uninstalled products in the Setup list: “SQL Server Database Services,” “Reporting Services,” and “Workstation Components, Books Online…”.</p>
<p>Does anyone have any thoughts? I can’t check the SQL Server Books Online topics because they don’t install, either; and I can’t make sense of the log files without them.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 15960858,
"author": "Tilesh Khatri",
"author_id": 2272474,
"author_profile": "https://Stackoverflow.com/users/2272474",
"pm_score": 3,
"selected": false,
"text": "SQL server failed to start"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/62999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
63,008 |
<p>I'm writing a C# application which downloads a compressed database backup via FTP. The application then needs to extract the backup and restore it to the default database location.</p>
<p>I will not know which version of SQL Server will be installed on the machine where the application runs. Therefore, I need to find the default location based on the instance name (which is in the config file).</p>
<p>The examples I found all had a registry key which they read, but this will not work, since this assumes that only one instance of SQL is installed.</p>
<p>Another example I found created a database, read that database's file properties, the deleting the database once it was done. That's just cumbersome.</p>
<p>I did find something in the .NET framework which should work, ie:</p>
<p><pre><code>Microsoft.SqlServer.Management.Smo.Server(ServerName).Settings.DefaultFile</code></pre></p>
<p>The problem is that this is returning empty strings, which does not help.</p>
<p>I also need to find out the NT account under which the SQL service is running, so that I can grant read access to that user on the backup file once I have the it extracted.</p>
|
[
{
"answer_id": 63273,
"author": "Chris Miller",
"author_id": 206,
"author_profile": "https://Stackoverflow.com/users/206",
"pm_score": 2,
"selected": false,
"text": "select filename from master.dbo.sysdatabases where name = 'master'\n"
},
{
"answer_id": 119735,
"author": "Richard C",
"author_id": 6389,
"author_profile": "https://Stackoverflow.com/users/6389",
"pm_score": 4,
"selected": true,
"text": "Microsoft.SqlServer.Management.Smo.Server(ServerName).Settings.DefaultFile\n Microsoft.SqlServer.Management.Smo.Server(ServerName).Information.RootDirectory + \"\\\\DATA\\\\\"\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/63008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6389/"
] |
63,011 |
<p>I'm displaying a set of images as an overlay using Google Maps. Displaying these images should be in an endless loop but most most browsers detect this, and display a warning. </p>
<p>Is there a way to make a endless loop in JavaScript so that it isn't stopped or warned against by the browser?</p>
|
[
{
"answer_id": 63039,
"author": "Erik",
"author_id": 6733,
"author_profile": "https://Stackoverflow.com/users/6733",
"pm_score": 4,
"selected": true,
"text": "(show = (o) => setTimeout(() => {\n\n console.log(o)\n show(++o)\n\n}, 1000))(1); .as-console-wrapper { max-height: 100% !important; top: 0; }"
},
{
"answer_id": 63050,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 2,
"selected": false,
"text": "setTimeout() var c = 0\nvar t;\n\nfunction timedCount() {\n document.getElementById('txt').value = c;\n c = c + 1;\n t = setTimeout(\"timedCount()\", 1000);\n} <form>\n <input type=\"button\" value=\"Start count!\" onClick=\"timedCount()\">\n <input type=\"text\" id=\"txt\">\n</form>"
},
{
"answer_id": 63080,
"author": "Wyatt",
"author_id": 6886,
"author_profile": "https://Stackoverflow.com/users/6886",
"pm_score": 0,
"selected": false,
"text": "function foo() {\n alert('hi');\n setTimeout(foo, 5000);\n}\n"
},
{
"answer_id": 63096,
"author": "Marius",
"author_id": 1585,
"author_profile": "https://Stackoverflow.com/users/1585",
"pm_score": 2,
"selected": false,
"text": "function setImage(){\n var Static = arguments.callee;\n Static.currentImage = (Static.currentImage || 0);\n var elm = document.getElementById(\"imageContainer\");\n elm.src = imageArray[Static.currentImage++];\n}\nimageInterval = setInterval(setImage, 1000);\n"
},
{
"answer_id": 64520,
"author": "Thevs",
"author_id": 8559,
"author_profile": "https://Stackoverflow.com/users/8559",
"pm_score": 0,
"selected": false,
"text": "var i = 0;\n\nwhile (i < 1) {\n do something...\n\n if (i < 1) i = 0;\n else i = fooling_function(i); // must return 0\n}\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/63011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7417/"
] |
63,038 |
<p>Sorry for the subject line sounding like an even nerdier Harry Potter title.</p>
<p>I'm trying to use AS3's Socket class to write a simple FTP program to export as an AIR app in Flex Builder 3. I'm using an FTP server on my local network to test the program. I can successfully connect to the server (the easy part) but I can't send any commands. I'm pretty sure that you have to use the ByteArray class to send these commands but there's some crucial piece of information that I'm missing apparently. Does anyone know how to do this? Thanks!
Dave</p>
|
[
{
"answer_id": 289252,
"author": "seanalltogether",
"author_id": 26986,
"author_profile": "https://Stackoverflow.com/users/26986",
"pm_score": 0,
"selected": false,
"text": "socket.writeUTFBytes(\"USER \"+user+\"\\n\"); socket.flush();\n var response:String = mySocket.readUTFBytes(mySocket.bytesAvailable);\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/63038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7478/"
] |
63,043 |
<p>Has anybody got this to actually work? Documentation is non existent on how to enable this feature and I get missing attribute exceptions despite having a 3.5 SP1 project. </p>
|
[
{
"answer_id": 63788,
"author": "Doanair",
"author_id": 4774,
"author_profile": "https://Stackoverflow.com/users/4774",
"pm_score": 1,
"selected": false,
"text": "[ServiceContract]\npublic interface IService1\n{\n\n [OperationContract]\n CompositeType GetData(int value);\n\n}\n\n\npublic class CompositeType\n{\n bool boolValue = true;\n string stringValue = \"Hello \";\n\n public bool BoolValue\n {\n get { return boolValue; }\n set { boolValue = value; }\n }\n\n public string StringValue\n {\n get { return stringValue; }\n set { stringValue = value; }\n }\n}\n public class Service1 : IService1\n{\n public CompositeType GetData(int value)\n {\n return new CompositeType()\n {\n BoolValue = true,\n StringValue = value.ToString()\n };\n }\n\n}\n"
},
{
"answer_id": 472236,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": true,
"text": "internal static bool IsNonAttributedTypeValidForSerialization(Type type)\n{\n if (type.IsArray)\n {\n return false;\n }\n if (type.IsEnum)\n {\n return false;\n }\n if (type.IsGenericParameter)\n {\n return false;\n }\n if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type))\n {\n return false;\n }\n if (type.IsPointer)\n {\n return false;\n }\n if (type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false))\n {\n return false;\n }\n foreach (Type type2 in type.GetInterfaces())\n {\n if (CollectionDataContract.IsCollectionInterface(type2))\n {\n return false;\n }\n }\n if (type.IsSerializable)\n {\n return false;\n }\n if (Globals.TypeOfISerializable.IsAssignableFrom(type))\n {\n return false;\n }\n if (type.IsDefined(Globals.TypeOfDataContractAttribute, false))\n {\n return false;\n }\n if (type == Globals.TypeOfExtensionDataObject)\n {\n return false;\n }\n if (type.IsValueType)\n {\n return type.IsVisible;\n }\n return (type.IsVisible && (type.GetConstructor(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, Globals.EmptyTypeArray, null) != null));\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/63043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7375/"
] |
63,081 |
<p>I'm looking to hear others experiences with SVG + Javascript Frameworks. </p>
<p>Things that I'd like the framework to handle - DOM creation, event handling and minimal size.</p>
<p>Jquery SVG plugin - <a href="http://keith-wood.name/svg.html" rel="noreferrer">http://keith-wood.name/svg.html</a> seems to be the only one I can find. </p>
|
[
{
"answer_id": 2303709,
"author": "Volodymyr Frolov",
"author_id": 276773,
"author_profile": "https://Stackoverflow.com/users/276773",
"pm_score": 2,
"selected": false,
"text": "jQueryInitialize jQueryInitialize(window); svg:onload"
},
{
"answer_id": 22842771,
"author": "ncubica",
"author_id": 196038,
"author_profile": "https://Stackoverflow.com/users/196038",
"pm_score": 2,
"selected": false,
"text": "http://snapsvg.io/"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/63081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
63,086 |
<p>I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?</p>
<p>I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting?</p>
|
[
{
"answer_id": 63124,
"author": "Justin Standard",
"author_id": 92,
"author_profile": "https://Stackoverflow.com/users/92",
"pm_score": 2,
"selected": false,
"text": "; \\"
},
{
"answer_id": 68052,
"author": "Ryan",
"author_id": 8819,
"author_profile": "https://Stackoverflow.com/users/8819",
"pm_score": 1,
"selected": false,
"text": "def foobar(a, b):\nif a == b:\na = a+1\nelif a < b:\nb = b-1\nif b > a: a = a-1\nend if\nelse:\nprint 'oops!'\nend if\nend def foobar\n def foobar(a, b):\n if a == b:\n a = a+1\n elif a < b:\n b = b-1\n if b > a: a = a-1\n # end if\n else:\n print 'oops!'\n # end if\n# end def foobar\n"
},
{
"answer_id": 68702,
"author": "Chris Calloway",
"author_id": 10769,
"author_profile": "https://Stackoverflow.com/users/10769",
"pm_score": 6,
"selected": false,
"text": "from __future__ import braces\n"
},
{
"answer_id": 118216,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 1,
"selected": false,
"text": ">>> from __future__ import braces\n File \"<stdin>\", line 1\nSyntaxError: not a chance\n"
},
{
"answer_id": 1515244,
"author": "Gzorg",
"author_id": 183258,
"author_profile": "https://Stackoverflow.com/users/183258",
"pm_score": 0,
"selected": false,
"text": "return pass if continue while if"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/63086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1231/"
] |
63,090 |
<p>Here we go again, the old argument still arises... </p>
<p>Would we better have a business key as a primary key, or would we rather have a surrogate id (i.e. an SQL Server identity) with a unique constraint on the business key field? </p>
<p>Please, provide examples or proof to support your theory.</p>
|
[
{
"answer_id": 541602,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 6,
"selected": false,
"text": "select sum(t.hours)\nfrom timesheets t\nwhere t.dept_code = 'HR'\nand t.status = 'VALID'\nand t.project_code = 'MYPROJECT'\nand t.task = 'BUILD';\n select sum(t.hours)\nfrom timesheets t\n join departents d on d.dept_id = t.dept_id\n join timesheet_statuses s on s.status_id = t.status_id\n join projects p on p.project_id = t.project_id\n join tasks k on k.task_id = t.task_id\nwhere d.dept_code = 'HR'\nand s.status = 'VALID'\nand p.project_code = 'MYPROJECT'\nand k.task_code = 'BUILD';\n select sum(t.hours)\nfrom timesheets t\nwhere t.dept_id = 34394\nand t.status_id = 89 \nand t.project_id = 1253\nand t.task_id = 77;\n"
},
{
"answer_id": 13049552,
"author": "Stefanos Kargas",
"author_id": 350061,
"author_profile": "https://Stackoverflow.com/users/350061",
"pm_score": 3,
"selected": false,
"text": "Table: JOB with 50 records\nCODE (primary key) NAME DESCRIPTION\nPRG PROGRAMMER A programmer is writing code\nMNG MANAGER A manager is doing whatever\nCLN CLEANER A cleaner cleans\n...............\njoined with\nTable: PEOPLE with 100000 inserts\n\nforeign key JOBCODE in table PEOPLE\nlooks at\nprimary key CODE in table JOB\n Table: ASSIGNMENT with 1000000 records\njoined with\nTable: PEOPLE with 100000 records\n\nforeign key PEOPLEID in table ASSIGNMENT\nlooks at\nprimary key ID in table PEOPLE (autoincrement)\n PEOPLE JOB SELECT * FROM PEOPLE WHERE JOBCODE = 'PRG'"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/63090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4690/"
] |
63,104 |
<p>When a previous Vim session crashed, you are greeted with the "Swap file ... already exists!" for each and every file that was open in the previous session.</p>
<p>Can you make this Vim recovery prompt smarter? (Without switching off recovery!) Specifically, I'm thinking of:</p>
<ul>
<li>If the swapped version does not contain unsaved changes and the editing process is no longer running, can you make Vim automatically delete the swap file?</li>
<li>Can you automate the suggested process of saving the recovered file under a new name, merging it with file on disk and then deleting the old swap file, so that minimal interaction is required? Especially when the swap version and the disk version are the same, everything should be automatic.</li>
</ul>
<p>I discovered the <code>SwapExists</code> autocommand but I don't know if it can help with these tasks.</p>
|
[
{
"answer_id": 63341,
"author": "Chouser",
"author_id": 7624,
"author_profile": "https://Stackoverflow.com/users/7624",
"pm_score": 6,
"selected": true,
"text": "set directory=~/.vim/swap,.\n cleanswap TMPDIR=$(mktemp -d) || exit 1\nRECTXT=\"$TMPDIR/vim.recovery.$USER.txt\"\nRECFN=\"$TMPDIR/vim.recovery.$USER.fn\"\ntrap 'rm -f \"$RECTXT\" \"$RECFN\"; rmdir \"$TMPDIR\"' 0 1 2 3 15\nfor q in ~/.vim/swap/.*sw? ~/.vim/swap/*; do\n [[ -f $q ]] || continue\n rm -f \"$RECTXT\" \"$RECFN\"\n vim -X -r \"$q\" \\\n -c \"w! $RECTXT\" \\\n -c \"let fn=expand('%')\" \\\n -c \"new $RECFN\" \\\n -c \"exec setline( 1, fn )\" \\\n -c w\\! \\\n -c \"qa\"\n if [[ ! -f $RECFN ]]; then\n echo \"nothing to recover from $q\"\n rm -f \"$q\"\n continue\n fi\n CRNT=\"$(cat $RECFN)\"\n if diff --strip-trailing-cr --brief \"$CRNT\" \"$RECTXT\"; then\n echo \"removing redundant $q\"\n echo \" for $CRNT\"\n rm -f \"$q\"\n else\n echo $q contains changes\n vim -n -d \"$CRNT\" \"$RECTXT\"\n rm -i \"$q\" || exit\n fi\ndone\n"
},
{
"answer_id": 220543,
"author": "Jack Senechal",
"author_id": 29833,
"author_profile": "https://Stackoverflow.com/users/29833",
"pm_score": 5,
"selected": false,
"text": " command DiffOrig vert new | set bt=nofile | r # | 0d_ | diffthis\n \\ | wincmd p | diffthis\n"
},
{
"answer_id": 784372,
"author": "Mark Grimes",
"author_id": 13233,
"author_profile": "https://Stackoverflow.com/users/13233",
"pm_score": 2,
"selected": false,
"text": "#!/bin/bash\n\nswap_files=`find . -name \"*.swp\"`\n\nfor s in $swap_files ; do\n orig_file=`echo $s | perl -pe 's!/\\.([^/]*).swp$!/$1!' `\n echo \"Editing $orig_file\"\n sleep 1\n vim -r $orig_file -c \"DiffOrig\"\n echo -n \" Ok to delete swap file? [y/n] \"\n read resp\n if [ \"$resp\" == \"y\" ] ; then\n echo \" Deleting $s\"\n rm $s\n fi\ndone\n"
},
{
"answer_id": 5826793,
"author": "coppit",
"author_id": 730300,
"author_profile": "https://Stackoverflow.com/users/730300",
"pm_score": 4,
"selected": false,
"text": "#!/bin/bash\n\nSWAP_FILE_DIR=~/temp/vim_swp\nIFS=$'\\n'\n\nTMPDIR=$(mktemp -d) || exit 1\nRECTXT=\"$TMPDIR/vim.recovery.$USER.txt\"\nRECFN=\"$TMPDIR/vim.recovery.$USER.fn\"\ntrap 'rm -f \"$RECTXT\" \"$RECFN\"; rmdir \"$TMPDIR\"' 0 1 2 3 15\nfor q in $SWAP_FILE_DIR/.*sw? $SWAP_FILE_DIR/*; do\n echo $q\n [[ -f $q ]] || continue\n rm -f \"$RECTXT\" \"$RECFN\"\n vim -X -r \"$q\" \\\n -c \"w! $RECTXT\" \\\n -c \"let fn=expand('%')\" \\\n -c \"new $RECFN\" \\\n -c \"exec setline( 1, fn )\" \\\n -c w\\! \\\n -c \"qa\"\n if [[ ! -f $RECFN ]]; then\n echo \"nothing to recover from $q\"\n rm -f \"$q\"\n continue\n fi\n CRNT=\"$(cat $RECFN)\"\n if [ \"$CRNT\" = \"$RECTXT\" ]; then\n echo \"Can't find original file. Press enter to open vim so you can save the file. The swap file will be deleted afterward!\"\n read\n vim \"$CRNT\"\n rm -f \"$q\"\n else if diff --strip-trailing-cr --brief \"$CRNT\" \"$RECTXT\"; then\n echo \"Removing redundant $q\"\n echo \" for $CRNT\"\n rm -f \"$q\"\n else\n echo $q contains changes, or there may be no original saved file\n vim -n -d \"$CRNT\" \"$RECTXT\"\n rm -i \"$q\" || exit\n fi\n fi\ndone\n"
},
{
"answer_id": 16742978,
"author": "Mario Aguilera",
"author_id": 289870,
"author_profile": "https://Stackoverflow.com/users/289870",
"pm_score": 0,
"selected": false,
"text": "#!/bin/bash\n\nif [[ \"$1\" == \"-h\" ]] || [[ \"$1\" == \"--help\" ]]; then\n echo \"Moves VIM swap files under <base-path> to ~/.vim/swap and reconciles differences\"\n echo \"usage: $0 <base-path>\"\n exit 0\nfi\n\nif [ -z \"$1\" ] || [ ! -d \"$1\" ]; then\n echo \"directory path not provided or invalid, see $0 -h\"\n exit 1\nfi\n\necho looking for duplicate file names in hierarchy\nswaps=\"$(find $1 -name '.*.swp' | while read file; do echo $(basename $file); done | sort | uniq -c | egrep -v \"^[[:space:]]*1\")\"\nif [ -z \"$swaps\" ]; then\n echo no duplicates found\n files=$(find $1 -name '.*.swp')\n if [ ! -d ~/.vim/swap ]; then mkdir ~/.vim/swap; fi\n echo \"moving files to swap space ~./vim/swap\"\n mv $files ~/.vim/swap\n echo \"executing reconciliation\"\n TMPDIR=$(mktemp -d) || exit 1\n RECTXT=\"$TMPDIR/vim.recovery.$USER.txt\"\n RECFN=\"$TMPDIR/vim.recovery.$USER.fn\"\n trap 'rm -f \"$RECTXT\" \"$RECFN\"; rmdir \"$TMPDIR\"' 0 1 2 3 15\n for q in ~/.vim/swap/.*sw? ~/.vim/swap/*; do\n [[ -f $q ]] || continue\n rm -f \"$RECTXT\" \"$RECFN\"\n vim -X -r \"$q\" \\\n -c \"w! $RECTXT\" \\\n -c \"let fn=expand('%')\" \\\n -c \"new $RECFN\" \\\n -c \"exec setline( 1, fn )\" \\\n -c w\\! \\\n -c \"qa\"\n if [[ ! -f $RECFN ]]; then\n echo \"nothing to recover from $q\"\n rm -f \"$q\"\n continue\n fi\n CRNT=\"$(cat $RECFN)\"\n if diff --strip-trailing-cr --brief \"$CRNT\" \"$RECTXT\"; then\n echo \"removing redundant $q\"\n echo \" for $CRNT\"\n rm -f \"$q\"\n else\n echo $q contains changes\n vim -n -d \"$CRNT\" \"$RECTXT\"\n rm -i \"$q\" || exit\n fi\n done\nelse\n echo duplicates found, please address their swap reconciliation manually:\n find $1 -name '.*.swp' | while read file; do echo $(basename $file); done | sort | uniq -c | egrep '^[[:space:]]*[2-9][0-9]*.*'\nfi\n"
},
{
"answer_id": 23016290,
"author": "Miguel",
"author_id": 2773308,
"author_profile": "https://Stackoverflow.com/users/2773308",
"pm_score": 0,
"selected": false,
"text": "mswpclean(){\n\nfor i in `find -L -name '*swp'`\ndo\n swpf=$i\n aux=${swpf//\"/.\"/\"/\"}\n orif=${aux//.swp/}\n bakf=${aux//.swp/.sbak}\n\n vim -r $swpf -c \":wq! $bakf\" && rm $swpf\n if cmp \"$bakf\" \"$orif\" -s\n then rm $bakf && echo \"Swap file was not different: Deleted\" $swpf\n else vimdiff $bakf $orif\n fi\ndone\n\nfor i in `find -L -name '*sbak'`\ndo\n bakf=$i\n orif=${bakf//.sbak/}\n if test $orif -nt $bakf\n then rm $bakf && echo \"Backup file deleted:\" $bakf\n else echo \"Backup file kept as:\" $bakf\n fi\ndone }\n else echo \"Backup file kept as:\" $bakf\n else vim $bakf -c \":wq! $orif\" && echo \"Backup file kept and saved as:\" $orif\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/63104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6918/"
] |
63,125 |
<p>I'm trying to find the best design for the following scenario - an application to store results of dance competitions. </p>
<p>An event contains multiple rounds, each round contains a number of performances (one per dance). Each performance is judged by many judges, who return a scoresheet.</p>
<p>There are two types of rounds, a final round (containing 6 or less dance couples) or a normal round (containing more than 6 dance couples). Each requires slightly different behaviour and data. </p>
<p>In the case of a final round, each scoresheet contains an ordered list of the 6 couples in the final showing which couple the judge placed 1st, 2nd etc. I call these placings "a scoresheet contains 6 placings". A placing contains a couple number, and what place that couple is</p>
<p>In the case of a normal round, each scoresheet contains a non-ordered set of M couples (M < the number of couples entered into the round - exact value determined by the competition organiser). I call these recalls: "a score sheet as M recalls". A recall does not contain a score or a ranking</p>
<p>for example
In a final</p>
<ul>
<li>1st place: couple 56 </li>
<li>2nd place: couple 234 </li>
<li>3rd place: couple 198 </li>
<li>4th place: couple 98 </li>
<li>5th place: couple 3</li>
<li>6th place: couple 125</li>
</ul>
<p>For a normal round
The following couples are recalled
54,67,201,104,187,209,8,56,79,35,167,98</p>
<p>My naive-version of this is implemented as</p>
<p>Event - has_one final_round, has_many rounds</p>
<p>final_round - has_many final_performances
final_performance - has_many final_scoresheets
final_scoresheet - has_many placings</p>
<p>round - has_many perforomances
performance has_many scoresheets
scoresheet has_many recalls</p>
<p>However I do not like the duplication that this requires, and I have several parallel hierarchies (for round, performance and scoresheet) which is going to be a pain to maintain.</p>
|
[
{
"answer_id": 321177,
"author": "DJClayworth",
"author_id": 19276,
"author_profile": "https://Stackoverflow.com/users/19276",
"pm_score": 0,
"selected": false,
"text": "round.getScoresheet(couple,dance)\n round.getPerformance(couple,dance).getScoresheet()\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/63125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7473/"
] |
63,130 |
<p>I would like to add a DataGridViewTextBoxCell cell to a DataGridViewCell control, but as well as being able to type in the text cell as normal it must also contain a '...' button that once clicks brings up the OpenFileDialog window to allow the user to select a file. Once selected, the text cell will be populated with the full file path.</p>
<p>What is the best way to go about this?</p>
<p>Thanks</p>
|
[
{
"answer_id": 63228,
"author": "Cameron MacFarland",
"author_id": 3820,
"author_profile": "https://Stackoverflow.com/users/3820",
"pm_score": 2,
"selected": true,
"text": "DataGridView UserControl DataGridView"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/63130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7585/"
] |
63,150 |
<p>While working in a Java app, I recently needed to assemble a comma-delimited list of values to pass to another web service without knowing how many elements there would be in advance. The best I could come up with off the top of my head was something like this:</p>
<pre><code>public String appendWithDelimiter( String original, String addition, String delimiter ) {
if ( original.equals( "" ) ) {
return addition;
} else {
return original + delimiter + addition;
}
}
String parameterString = "";
if ( condition ) parameterString = appendWithDelimiter( parameterString, "elementName", "," );
if ( anotherCondition ) parameterString = appendWithDelimiter( parameterString, "anotherElementName", "," );
</code></pre>
<p>I realize this isn't particularly efficient, since there are strings being created all over the place, but I was going for clarity more than optimization.</p>
<p>In Ruby, I can do something like this instead, which feels much more elegant:</p>
<pre><code>parameterArray = [];
parameterArray << "elementName" if condition;
parameterArray << "anotherElementName" if anotherCondition;
parameterString = parameterArray.join(",");
</code></pre>
<p>But since Java lacks a join command, I couldn't figure out anything equivalent.</p>
<p>So, what's the best way to do this in Java?</p>
|
[
{
"answer_id": 63173,
"author": "Stu Thompson",
"author_id": 2961,
"author_profile": "https://Stackoverflow.com/users/2961",
"pm_score": 4,
"selected": false,
"text": "java.lang.StringBuilder StringBuilder StringBuilder StringBuffer StringBuilder"
},
{
"answer_id": 63186,
"author": "Kent Boogaart",
"author_id": 5380,
"author_profile": "https://Stackoverflow.com/users/5380",
"pm_score": 2,
"selected": false,
"text": "StringBuilder StringBuffer"
},
{
"answer_id": 63201,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 4,
"selected": false,
"text": "public static String join(Iterable<? extends CharSequence> s, String delimiter) {\n Iterator<? extends CharSequence> iter = s.iterator();\n if (!iter.hasNext()) return \"\";\n StringBuilder buffer = new StringBuilder(iter.next());\n while (iter.hasNext()) buffer.append(delimiter).append(iter.next());\n return buffer.toString();\n}\n"
},
{
"answer_id": 63217,
"author": "martinatime",
"author_id": 1353,
"author_profile": "https://Stackoverflow.com/users/1353",
"pm_score": 0,
"selected": false,
"text": "StringBuilder sb = new StringBuilder();\nif (condition) { sb.append(\"elementName\").append(\",\"); }\nif (anotherCondition) { sb.append(\"anotherElementName\").append(\",\"); }\nString parameterString = sb.toString();\n"
},
{
"answer_id": 63218,
"author": "izb",
"author_id": 974,
"author_profile": "https://Stackoverflow.com/users/974",
"pm_score": -1,
"selected": false,
"text": "public static String join(String[] strings, char del)\n{\n StringBuffer sb = new StringBuffer();\n int len = strings.length;\n boolean appended = false;\n for (int i = 0; i < len; i++)\n {\n if (appended)\n {\n sb.append(del);\n }\n sb.append(\"\"+strings[i]);\n appended = true;\n }\n return sb.toString();\n}\n"
},
{
"answer_id": 63226,
"author": "newdayrising",
"author_id": 3126,
"author_profile": "https://Stackoverflow.com/users/3126",
"pm_score": 1,
"selected": false,
"text": "StringBuilder append"
},
{
"answer_id": 63229,
"author": "agnul",
"author_id": 6069,
"author_profile": "https://Stackoverflow.com/users/6069",
"pm_score": 1,
"selected": false,
"text": "ArrayList<String> parms = new ArrayList<String>();\nif (someCondition) parms.add(\"someString\");\nif (anotherCondition) parms.add(\"someOtherString\");\n// ...\nString sep = \"\"; StringBuffer b = new StringBuffer();\nfor (String p: parms) {\n b.append(sep);\n b.append(p);\n sep = \"yourDelimiter\";\n}\n"
},
{
"answer_id": 63258,
"author": "Martin Gladdish",
"author_id": 7686,
"author_profile": "https://Stackoverflow.com/users/7686",
"pm_score": 10,
"selected": true,
"text": "StringUtils.join(java.lang.Iterable,char) StringJoiner String.join() StringJoiner StringJoiner joiner = new StringJoiner(\",\");\njoiner.add(\"01\").add(\"02\").add(\"03\");\nString joinedString = joiner.toString(); // \"01,02,03\"\n String.join(CharSequence delimiter, CharSequence... elements)) String joinedString = String.join(\" - \", \"04\", \"05\", \"06\"); // \"04 - 05 - 06\"\n String.join(CharSequence delimiter, Iterable<? extends CharSequence> elements) List<String> strings = new LinkedList<>();\nstrings.add(\"Java\");strings.add(\"is\");\nstrings.add(\"cool\");\nString message = String.join(\" \", strings);\n//message returned is: \"Java is cool\"\n"
},
{
"answer_id": 63274,
"author": "Rob Dickerson",
"author_id": 7530,
"author_profile": "https://Stackoverflow.com/users/7530",
"pm_score": 6,
"selected": false,
"text": "public static String join(List<String> list, String delim) {\n\n StringBuilder sb = new StringBuilder();\n\n String loopDelim = \"\";\n\n for(String s : list) {\n\n sb.append(loopDelim);\n sb.append(s); \n\n loopDelim = delim;\n }\n\n return sb.toString();\n}\n List<String> list = new ArrayList<String>();\n\n if( condition ) list.add(\"elementName\");\n if( anotherCondition ) list.add(\"anotherElementName\");\n\n join(list, \",\");\n"
},
{
"answer_id": 63282,
"author": "killdash10",
"author_id": 7621,
"author_profile": "https://Stackoverflow.com/users/7621",
"pm_score": 0,
"selected": false,
"text": "public static String appendWithDelimiter(String original, String addition, String delimiter) {\n\nif (original.equals(\"\")) {\n return addition;\n} else {\n StringBuilder sb = new StringBuilder(original.length() + addition.length() + delimiter.length());\n sb.append(original);\n sb.append(delimiter);\n sb.append(addition);\n return sb.toString();\n }\n}\n"
},
{
"answer_id": 63306,
"author": "Mikezx6r",
"author_id": 5382,
"author_profile": "https://Stackoverflow.com/users/5382",
"pm_score": 0,
"selected": false,
"text": "// Answers real question\npublic String appendWithDelimiters(String delimiter, String original, String addition) {\n StringBuilder sb = new StringBuilder(original);\n if(sb.length()!=0) {\n sb.append(delimiter).append(addition);\n } else {\n sb.append(addition);\n }\n return sb.toString();\n}\n\n\n// A more generic case.\n// ... means a list of indeterminate length of Strings.\npublic String appendWithDelimitersGeneric(String delimiter, String... strings) {\n StringBuilder sb = new StringBuilder();\n for (String string : strings) {\n if(sb.length()!=0) {\n sb.append(delimiter).append(string);\n } else {\n sb.append(string);\n }\n }\n\n return sb.toString();\n}\n\npublic void testAppendWithDelimiters() {\n String string = appendWithDelimitersGeneric(\",\", \"string1\", \"string2\", \"string3\");\n}\n"
},
{
"answer_id": 63324,
"author": "Yaba",
"author_id": 7524,
"author_profile": "https://Stackoverflow.com/users/7524",
"pm_score": 0,
"selected": false,
"text": "public StringBuffer appendWithDelimiter( StringBuffer original, String addition, String delimiter ) {\n if ( original == null ) {\n StringBuffer buffer = new StringBuffer();\n buffer.append(addition);\n return buffer;\n } else {\n buffer.append(delimiter);\n buffer.append(addition);\n return original;\n }\n}\n"
},
{
"answer_id": 63351,
"author": "Eric Normand",
"author_id": 7492,
"author_profile": "https://Stackoverflow.com/users/7492",
"pm_score": 3,
"selected": false,
"text": "package util;\n\nimport java.util.ArrayList;\nimport java.util.Iterable;\nimport java.util.Collections;\nimport java.util.Iterator;\n\npublic class Utils {\n // accept a collection of objects, since all objects have toString()\n public static String join(String delimiter, Iterable<? extends Object> objs) {\n if (objs.isEmpty()) {\n return \"\";\n }\n Iterator<? extends Object> iter = objs.iterator();\n StringBuilder buffer = new StringBuilder();\n buffer.append(iter.next());\n while (iter.hasNext()) {\n buffer.append(delimiter).append(iter.next());\n }\n return buffer.toString();\n }\n\n // for convenience\n public static String join(String delimiter, Object... objs) {\n ArrayList<Object> list = new ArrayList<Object>();\n Collections.addAll(list, objs);\n return join(delimiter, list);\n }\n}\n"
},
{
"answer_id": 63418,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "String parameterString = \"\";\nif ( condition ) parameterString = appendWithDelimiter( parameterString, \"elementName\", \",\" );\nif ( anotherCondition ) parameterString = appendWithDelimiter( parameterString, \"anotherElementName\", \",\" );\n StringBuilder parameterString = new StringBuilder();\nif (condition) parameterString.append(\"elementName\").append(\",\");\nif (anotherCondition) parameterString.append(\"anotherElementName\").append(\",\");\n...\n if (parameterString.length() > 0) \n parameterString.deleteCharAt(parameterString.length() - 1);\n parameterString.toString();\n"
},
{
"answer_id": 63840,
"author": "MetroidFan2002",
"author_id": 8026,
"author_profile": "https://Stackoverflow.com/users/8026",
"pm_score": 0,
"selected": false,
"text": "//Note: if you have access to Java5+, \n//use StringBuilder in preference to StringBuffer. \n//All that has to be replaced is the class name. \n//StringBuffer will work in Java 1.4, though.\n\nappendWithDelimiter( StringBuffer buffer, String addition, \n String delimiter ) {\n if ( buffer.length() == 0) {\n buffer.append(addition);\n } else {\n buffer.append(delimiter);\n buffer.append(addition);\n }\n}\n\n\nStringBuffer parameterBuffer = new StringBuffer();\nif ( condition ) { \n appendWithDelimiter(parameterBuffer, \"elementName\", \",\" );\n}\nif ( anotherCondition ) {\n appendWithDelimiter(parameterBuffer, \"anotherElementName\", \",\" );\n}\n\n//Finally, to return a string representation, call toString() when returning.\nreturn parameterBuffer.toString(); \n"
},
{
"answer_id": 76070,
"author": "Mark B",
"author_id": 13070,
"author_profile": "https://Stackoverflow.com/users/13070",
"pm_score": 1,
"selected": false,
"text": "import junit.framework.Assert;\nimport org.junit.Test;\n\npublic class StringUtil\n{\n public static String join(String delim, String... strings)\n {\n StringBuilder builder = new StringBuilder();\n\n if (strings != null)\n {\n for (String str : strings)\n {\n if (builder.length() > 0)\n {\n builder.append(delim).append(\" \");\n }\n builder.append(str);\n }\n } \n return builder.toString();\n }\n @Test\n public void joinTest()\n {\n Assert.assertEquals(\"\", StringUtil.join(\",\", null));\n Assert.assertEquals(\"\", StringUtil.join(\",\", \"\"));\n Assert.assertEquals(\"\", StringUtil.join(\",\", new String[0]));\n Assert.assertEquals(\"test\", StringUtil.join(\",\", \"test\"));\n Assert.assertEquals(\"foo, bar\", StringUtil.join(\",\", \"foo\", \"bar\"));\n Assert.assertEquals(\"foo, bar, x\", StringUtil.join(\",\", \"foo\", \"bar\", \"x\"));\n }\n}\n"
},
{
"answer_id": 297128,
"author": "akuhn",
"author_id": 24468,
"author_profile": "https://Stackoverflow.com/users/24468",
"pm_score": 2,
"selected": false,
"text": "Separator StringBuilder buf = new StringBuilder();\nSeparator sep = new Separator(\", \");\nfor (String each : list) {\n buf.append(sep).append(each);\n}\n toString Separator public class Separator {\n\n private boolean skipFirst;\n private final String value;\n\n public Separator() {\n this(\", \");\n }\n\n public Separator(String value) {\n this.value = value;\n this.skipFirst = true;\n }\n\n public void reset() {\n skipFirst = true;\n }\n\n public String toString() {\n String sep = skipFirst ? \"\" : value;\n skipFirst = false;\n return sep;\n }\n\n}\n"
},
{
"answer_id": 2179425,
"author": "dfa",
"author_id": 89266,
"author_profile": "https://Stackoverflow.com/users/89266",
"pm_score": 0,
"selected": false,
"text": "String joined = $(aCollection).join(\",\");\n @Override\npublic String join(String separator) {\n Separator sep = new Separator(separator);\n StringBuilder sb = new StringBuilder();\n\n for (T item : iterable) {\n sb.append(sep).append(item);\n }\n\n return sb.toString();\n}\n Separator class Separator {\n\n private final String separator;\n private boolean wasCalled;\n\n public Separator(String separator) {\n this.separator = separator;\n this.wasCalled = false;\n }\n\n @Override\n public String toString() {\n if (!wasCalled) {\n wasCalled = true;\n return \"\";\n } else {\n return separator;\n }\n }\n}\n"
},
{
"answer_id": 3338199,
"author": "java al",
"author_id": 402658,
"author_profile": "https://Stackoverflow.com/users/402658",
"pm_score": 0,
"selected": false,
"text": "public static String join(String[] strings, char del)\n{\n StringBuilder sb = new StringBuilder();\n int len = strings.length;\n\n if(len > 1) \n {\n len -= 1;\n }else\n {\n return strings[0];\n }\n\n for (int i = 0; i < len; i++)\n {\n sb.append(strings[i]).append(del);\n }\n\n sb.append(strings[i]);\n\n return sb.toString();\n}\n"
},
{
"answer_id": 6011632,
"author": "Kevin",
"author_id": 357951,
"author_profile": "https://Stackoverflow.com/users/357951",
"pm_score": 6,
"selected": false,
"text": "android.text.TextUtils.join(CharSequence delimiter, Iterable tokens)\n"
},
{
"answer_id": 12471817,
"author": "Alex K",
"author_id": 876298,
"author_profile": "https://Stackoverflow.com/users/876298",
"pm_score": 5,
"selected": false,
"text": "\"My pets are: \" + Joiner.on(\", \").join(Arrays.asList(\"rabbit\", \"parrot\", \"dog\")); \n// returns \"My pets are: rabbit, parrot, dog\"\n\nJoiner.on(\" AND \").join(Arrays.asList(\"field1=1\" , \"field2=2\", \"field3=3\"));\n// returns \"field1=1 AND field2=2 AND field3=3\"\n\nJoiner.on(\",\").skipNulls().join(Arrays.asList(\"London\", \"Moscow\", null, \"New York\", null, \"Paris\"));\n// returns \"London,Moscow,New York,Paris\"\n\nJoiner.on(\", \").useForNull(\"Team held a draw\").join(Arrays.asList(\"FC Barcelona\", \"FC Bayern\", null, null, \"Chelsea FC\", \"AC Milan\"));\n// returns \"FC Barcelona, FC Bayern, Team held a draw, Team held a draw, Chelsea FC, AC Milan\"\n"
},
{
"answer_id": 20013838,
"author": "Craig P. Motlin",
"author_id": 23572,
"author_profile": "https://Stackoverflow.com/users/23572",
"pm_score": 2,
"selected": false,
"text": "makeString() appendString() makeString() String toString() makeString(start, separator, end) makeString(separator) makeString() \", \" MutableList<Integer> list = FastList.newListWith(1, 2, 3);\nassertEquals(\"[1/2/3]\", list.makeString(\"[\", \"/\", \"]\"));\nassertEquals(\"1/2/3\", list.makeString(\"/\"));\nassertEquals(\"1, 2, 3\", list.makeString());\nassertEquals(list.toString(), list.makeString(\"[\", \", \", \"]\"));\n appendString() makeString() Appendable StringBuilder void MutableList<Integer> list = FastList.newListWith(1, 2, 3);\nAppendable appendable = new StringBuilder();\nlist.appendString(appendable, \"[\", \"/\", \"]\");\nassertEquals(\"[1/2/3]\", appendable.toString());\n List<Object> list = ...;\nListAdapter.adapt(list).makeString(\",\");\n"
},
{
"answer_id": 22577623,
"author": "micha",
"author_id": 1115554,
"author_profile": "https://Stackoverflow.com/users/1115554",
"pm_score": 5,
"selected": false,
"text": "String.join() List<String> list = Arrays.asList(\"foo\", \"bar\", \"baz\");\nString joined = String.join(\" and \", list); // \"foo and bar and baz\"\n"
},
{
"answer_id": 22659416,
"author": "Thamme Gowda",
"author_id": 1506477,
"author_profile": "https://Stackoverflow.com/users/1506477",
"pm_score": 2,
"selected": false,
"text": "/**\n *\n * @param delim : String that should be kept in between the parts\n * @param parts : parts that needs to be joined\n * @return a String that's formed by joining the parts\n */\nprivate static final String join(String delim, String... parts) {\n StringBuilder builder = new StringBuilder();\n for (int i = 0; i < parts.length - 1; i++) {\n builder.append(parts[i]).append(delim);\n }\n if(parts.length > 0){\n builder.append(parts[parts.length - 1]);\n }\n return builder.toString();\n}\n"
},
{
"answer_id": 27599779,
"author": "gladiator",
"author_id": 1072826,
"author_profile": "https://Stackoverflow.com/users/1072826",
"pm_score": 5,
"selected": false,
"text": "list.stream().map(Object::toString)\n .collect(Collectors.joining(delimiter));\n list.stream().map(String::valueOf)\n .collect(Collectors.joining(delimiter))\n list.stream().map(String::valueOf)\n .collect(Collectors.joining(delimiter, prefix, suffix));\n"
},
{
"answer_id": 28063943,
"author": "рüффп",
"author_id": 628006,
"author_profile": "https://Stackoverflow.com/users/628006",
"pm_score": 1,
"selected": false,
"text": "// Encoding Set<String> to String delimited \nString asString = org.springframework.util.StringUtils.collectionToDelimitedString(codes, \";\");\n\n// Decoding String delimited to Set\nSet<String> collection = org.springframework.util.StringUtils.commaDelimitedListToSet(asString);\n"
},
{
"answer_id": 29135746,
"author": "maXp",
"author_id": 3094065,
"author_profile": "https://Stackoverflow.com/users/3094065",
"pm_score": 0,
"selected": false,
"text": "public static String join(String delimiter, String... values)\n{\n StringBuilder stringBuilder = new StringBuilder();\n\n for (String value : values)\n {\n stringBuilder.append(value);\n stringBuilder.append(delimiter);\n }\n\n String result = stringBuilder.toString();\n\n return result.isEmpty() ? result : result.substring(0, result.length() - 1);\n}\n"
},
{
"answer_id": 33451093,
"author": "gstackoverflow",
"author_id": 2674303,
"author_profile": "https://Stackoverflow.com/users/2674303",
"pm_score": 3,
"selected": false,
"text": "stringCollection.stream().collect(Collectors.joining(\", \"));\n"
},
{
"answer_id": 36839833,
"author": "Ankit Lalan",
"author_id": 6251178,
"author_profile": "https://Stackoverflow.com/users/6251178",
"pm_score": 2,
"selected": false,
"text": "import org.springframework.util.StringUtils;\n\nList<String> groupIds = new List<String>; \ngroupIds.add(\"a\"); \ngroupIds.add(\"b\"); \ngroupIds.add(\"c\");\n\nString csv = StringUtils.arrayToCommaDelimitedString(groupIds.toArray());\n a,b,c"
},
{
"answer_id": 39067118,
"author": "Philipp Grigoryev",
"author_id": 3281886,
"author_profile": "https://Stackoverflow.com/users/3281886",
"pm_score": 0,
"selected": false,
"text": "List lst = Arrays.asList(\"ab\", \"bc\", \"cd\");\nString str = lst.toString().replaceAll(\"[\\\\[\\\\]]\", \"\");\n"
},
{
"answer_id": 49860671,
"author": "Luis Aguilar",
"author_id": 9572533,
"author_profile": "https://Stackoverflow.com/users/9572533",
"pm_score": 3,
"selected": false,
"text": "List<Integer> example;\nexample.add(1);\nexample.add(2);\nexample.add(3);\n...\nexample.stream().collect(Collectors.joining(\",\"));\n List<Person> person;\n...\nperson.stream().map(Person::getAge).collect(Collectors.joining(\",\"));\n"
},
{
"answer_id": 73844686,
"author": "VIVek",
"author_id": 12591119,
"author_profile": "https://Stackoverflow.com/users/12591119",
"pm_score": 0,
"selected": false,
"text": " List<String> tags= emp.getTags();\n String tagTxt=\"\";\n for (String s : tags) {\n if (tagTxt.isEmpty()){\n tagTxt=s;\n }else\n tagTxt= tagTxt+\", \"+s;\n } \n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/63150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2041950/"
] |
63,166 |
<p>I once had the task of determining the following performance parameters from inside a running application:</p>
<ul>
<li>Total virtual memory available</li>
<li>Virtual memory currently used</li>
<li>Virtual memory currently used by my process<hr></li>
<li>Total RAM available</li>
<li>RAM currently used</li>
<li>RAM currently used by my process<hr></li>
<li>% CPU currently used</li>
<li>% CPU currently used by my process</li>
</ul>
<p>The code had to run on Windows and Linux. Even though this seems to be a standard task, finding the necessary information in the manuals (WIN32 API, GNU docs) as well as on the Internet took me several days, because there's so much incomplete/incorrect/outdated information on this topic to be found out there.</p>
<p>In order to save others from going through the same trouble, I thought it would be a good idea to collect all the scattered information plus what I found by trial and error here in one place.</p>
|
[
{
"answer_id": 64166,
"author": "Lanzelot",
"author_id": 7381,
"author_profile": "https://Stackoverflow.com/users/7381",
"pm_score": 10,
"selected": false,
"text": "#include \"windows.h\"\n\nMEMORYSTATUSEX memInfo;\nmemInfo.dwLength = sizeof(MEMORYSTATUSEX);\nGlobalMemoryStatusEx(&memInfo);\nDWORDLONG totalVirtualMem = memInfo.ullTotalPageFile;\n DWORDLONG virtualMemUsed = memInfo.ullTotalPageFile - memInfo.ullAvailPageFile;\n #include \"windows.h\"\n#include \"psapi.h\"\n\nPROCESS_MEMORY_COUNTERS_EX pmc;\nGetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS*)&pmc, sizeof(pmc));\nSIZE_T virtualMemUsedByMe = pmc.PrivateUsage;\n DWORDLONG totalPhysMem = memInfo.ullTotalPhys;\n DWORDLONG physMemUsed = memInfo.ullTotalPhys - memInfo.ullAvailPhys;\n SIZE_T physMemUsedByMe = pmc.WorkingSetSize;\n #include \"TCHAR.h\"\n#include \"pdh.h\"\n\nstatic PDH_HQUERY cpuQuery;\nstatic PDH_HCOUNTER cpuTotal;\n\nvoid init(){\n PdhOpenQuery(NULL, NULL, &cpuQuery);\n // You can also use L\"\\\\Processor(*)\\\\% Processor Time\" and get individual CPU values with PdhGetFormattedCounterArray()\n PdhAddEnglishCounter(cpuQuery, L\"\\\\Processor(_Total)\\\\% Processor Time\", NULL, &cpuTotal);\n PdhCollectQueryData(cpuQuery);\n}\n\ndouble getCurrentValue(){\n PDH_FMT_COUNTERVALUE counterVal;\n\n PdhCollectQueryData(cpuQuery);\n PdhGetFormattedCounterValue(cpuTotal, PDH_FMT_DOUBLE, NULL, &counterVal);\n return counterVal.doubleValue;\n}\n #include \"windows.h\"\n\nstatic ULARGE_INTEGER lastCPU, lastSysCPU, lastUserCPU;\nstatic int numProcessors;\nstatic HANDLE self;\n\nvoid init(){\n SYSTEM_INFO sysInfo;\n FILETIME ftime, fsys, fuser;\n\n GetSystemInfo(&sysInfo);\n numProcessors = sysInfo.dwNumberOfProcessors;\n\n GetSystemTimeAsFileTime(&ftime);\n memcpy(&lastCPU, &ftime, sizeof(FILETIME));\n\n self = GetCurrentProcess();\n GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser);\n memcpy(&lastSysCPU, &fsys, sizeof(FILETIME));\n memcpy(&lastUserCPU, &fuser, sizeof(FILETIME));\n}\n\ndouble getCurrentValue(){\n FILETIME ftime, fsys, fuser;\n ULARGE_INTEGER now, sys, user;\n double percent;\n\n GetSystemTimeAsFileTime(&ftime);\n memcpy(&now, &ftime, sizeof(FILETIME));\n\n GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser);\n memcpy(&sys, &fsys, sizeof(FILETIME));\n memcpy(&user, &fuser, sizeof(FILETIME));\n percent = (sys.QuadPart - lastSysCPU.QuadPart) +\n (user.QuadPart - lastUserCPU.QuadPart);\n percent /= (now.QuadPart - lastCPU.QuadPart);\n percent /= numProcessors;\n lastCPU = now;\n lastUserCPU = user;\n lastSysCPU = sys;\n\n return percent * 100;\n}\n getrusage() /proc #include \"sys/types.h\"\n#include \"sys/sysinfo.h\"\n\nstruct sysinfo memInfo;\n\nsysinfo (&memInfo);\nlong long totalVirtualMem = memInfo.totalram;\n//Add other values in next statement to avoid int overflow on right hand side...\ntotalVirtualMem += memInfo.totalswap;\ntotalVirtualMem *= memInfo.mem_unit;\n long long virtualMemUsed = memInfo.totalram - memInfo.freeram;\n//Add other values in next statement to avoid int overflow on right hand side...\nvirtualMemUsed += memInfo.totalswap - memInfo.freeswap;\nvirtualMemUsed *= memInfo.mem_unit;\n #include \"stdlib.h\"\n#include \"stdio.h\"\n#include \"string.h\"\n\nint parseLine(char* line){\n // This assumes that a digit will be found and the line ends in \" Kb\".\n int i = strlen(line);\n const char* p = line;\n while (*p <'0' || *p > '9') p++;\n line[i-3] = '\\0';\n i = atoi(p);\n return i;\n}\n\nint getValue(){ //Note: this value is in KB!\n FILE* file = fopen(\"/proc/self/status\", \"r\");\n int result = -1;\n char line[128];\n\n while (fgets(line, 128, file) != NULL){\n if (strncmp(line, \"VmSize:\", 7) == 0){\n result = parseLine(line);\n break;\n }\n }\n fclose(file);\n return result;\n}\n long long totalPhysMem = memInfo.totalram;\n//Multiply in next statement to avoid int overflow on right hand side...\ntotalPhysMem *= memInfo.mem_unit;\n long long physMemUsed = memInfo.totalram - memInfo.freeram;\n//Multiply in next statement to avoid int overflow on right hand side...\nphysMemUsed *= memInfo.mem_unit;\n int getValue(){ //Note: this value is in KB!\n FILE* file = fopen(\"/proc/self/status\", \"r\");\n int result = -1;\n char line[128];\n\n while (fgets(line, 128, file) != NULL){\n if (strncmp(line, \"VmRSS:\", 6) == 0){\n result = parseLine(line);\n break;\n }\n }\n fclose(file);\n return result;\n}\n #include \"stdlib.h\"\n#include \"stdio.h\"\n#include \"string.h\"\n\nstatic unsigned long long lastTotalUser, lastTotalUserLow, lastTotalSys, lastTotalIdle;\n\nvoid init(){\n FILE* file = fopen(\"/proc/stat\", \"r\");\n fscanf(file, \"cpu %llu %llu %llu %llu\", &lastTotalUser, &lastTotalUserLow,\n &lastTotalSys, &lastTotalIdle);\n fclose(file);\n}\n\ndouble getCurrentValue(){\n double percent;\n FILE* file;\n unsigned long long totalUser, totalUserLow, totalSys, totalIdle, total;\n\n file = fopen(\"/proc/stat\", \"r\");\n fscanf(file, \"cpu %llu %llu %llu %llu\", &totalUser, &totalUserLow,\n &totalSys, &totalIdle);\n fclose(file);\n\n if (totalUser < lastTotalUser || totalUserLow < lastTotalUserLow ||\n totalSys < lastTotalSys || totalIdle < lastTotalIdle){\n //Overflow detection. Just skip this value.\n percent = -1.0;\n }\n else{\n total = (totalUser - lastTotalUser) + (totalUserLow - lastTotalUserLow) +\n (totalSys - lastTotalSys);\n percent = total;\n total += (totalIdle - lastTotalIdle);\n percent /= total;\n percent *= 100;\n }\n\n lastTotalUser = totalUser;\n lastTotalUserLow = totalUserLow;\n lastTotalSys = totalSys;\n lastTotalIdle = totalIdle;\n\n return percent;\n}\n #include \"stdlib.h\"\n#include \"stdio.h\"\n#include \"string.h\"\n#include \"sys/times.h\"\n#include \"sys/vtimes.h\"\n\nstatic clock_t lastCPU, lastSysCPU, lastUserCPU;\nstatic int numProcessors;\n\nvoid init(){\n FILE* file;\n struct tms timeSample;\n char line[128];\n\n lastCPU = times(&timeSample);\n lastSysCPU = timeSample.tms_stime;\n lastUserCPU = timeSample.tms_utime;\n\n file = fopen(\"/proc/cpuinfo\", \"r\");\n numProcessors = 0;\n while(fgets(line, 128, file) != NULL){\n if (strncmp(line, \"processor\", 9) == 0) numProcessors++;\n }\n fclose(file);\n}\n\ndouble getCurrentValue(){\n struct tms timeSample;\n clock_t now;\n double percent;\n\n now = times(&timeSample);\n if (now <= lastCPU || timeSample.tms_stime < lastSysCPU ||\n timeSample.tms_utime < lastUserCPU){\n //Overflow detection. Just skip this value.\n percent = -1.0;\n }\n else{\n percent = (timeSample.tms_stime - lastSysCPU) +\n (timeSample.tms_utime - lastUserCPU);\n percent /= (now - lastCPU);\n percent /= numProcessors;\n percent *= 100;\n }\n lastCPU = now;\n lastSysCPU = timeSample.tms_stime;\n lastUserCPU = timeSample.tms_utime;\n\n return percent;\n}\n getrusage()"
},
{
"answer_id": 64422,
"author": "Martin Del Vecchio",
"author_id": 5397,
"author_profile": "https://Stackoverflow.com/users/5397",
"pm_score": 6,
"selected": false,
"text": "Anderson cxc # more /proc/meminfo\nMemTotal: 4083948 kB\nMemFree: 2198520 kB\nBuffers: 82080 kB\nCached: 1141460 kB\nSwapCached: 0 kB\nActive: 1137960 kB\nInactive: 608588 kB\nHighTotal: 3276672 kB\nHighFree: 1607744 kB\nLowTotal: 807276 kB\nLowFree: 590776 kB\nSwapTotal: 2096440 kB\nSwapFree: 2096440 kB\nDirty: 32 kB\nWriteback: 0 kB\nAnonPages: 523252 kB\nMapped: 93560 kB\nSlab: 52880 kB\nSReclaimable: 24652 kB\nSUnreclaim: 28228 kB\nPageTables: 2284 kB\nNFS_Unstable: 0 kB\nBounce: 0 kB\nCommitLimit: 4138412 kB\nCommitted_AS: 1845072 kB\nVmallocTotal: 118776 kB\nVmallocUsed: 3964 kB\nVmallocChunk: 112860 kB\nHugePages_Total: 0\nHugePages_Free: 0\nHugePages_Rsvd: 0\nHugepagesize: 2048 kB\n Anderson cxc # more /proc/stat\ncpu 2329889 0 2364567 1063530460 9034 9463 96111 0\ncpu0 572526 0 636532 265864398 2928 1621 6899 0\ncpu1 590441 0 531079 265949732 4763 351 8522 0\ncpu2 562983 0 645163 265796890 682 7490 71650 0\ncpu3 603938 0 551790 265919440 660 0 9040 0\nintr 37124247\nctxt 50795173133\nbtime 1218807985\nprocesses 116889\nprocs_running 1\nprocs_blocked 0\n cpu 2330047 0 2365006 1063853632 9035 9463 96114 0\n cpu 2330047 0 2365007 1063854028 9035 9463 96114 0\n 19340 (whatever) S 19115 19115 3084 34816 19115 4202752 118200 607 0 0 770 384 2\n 7 20 0 77 0 266764385 692477952 105074 4294967295 134512640 146462952 321468364\n8 3214683328 4294960144 0 2147221247 268439552 1276 4294967295 0 0 17 0 0 0 0\n Name: whatever\nState: S (sleeping)\nTgid: 19340\nPid: 19340\nPPid: 19115\nTracerPid: 0\nUid: 0 0 0 0\nGid: 0 0 0 0\nFDSize: 256\nGroups: 0 1 2 3 4 6 10 11 20 26 27\nVmPeak: 676252 kB\nVmSize: 651352 kB\nVmLck: 0 kB\nVmHWM: 420300 kB\nVmRSS: 420296 kB\nVmData: 581028 kB\nVmStk: 112 kB\nVmExe: 11672 kB\nVmLib: 76608 kB\nVmPTE: 1244 kB\nThreads: 77\nSigQ: 0/36864\nSigPnd: 0000000000000000\nShdPnd: 0000000000000000\nSigBlk: fffffffe7ffbfeff\nSigIgn: 0000000010001000\nSigCgt: 20000001800004fc\nCapInh: 0000000000000000\nCapPrm: 00000000ffffffff\nCapEff: 00000000fffffeff\nCpus_allowed: 0f\nMems_allowed: 1\nvoluntary_ctxt_switches: 6518\nnonvoluntary_ctxt_switches: 6598\n"
},
{
"answer_id": 1911863,
"author": "Michael Taylor",
"author_id": 172534,
"author_profile": "https://Stackoverflow.com/users/172534",
"pm_score": 7,
"selected": false,
"text": "struct statfs stats;\nif (0 == statfs(\"/\", &stats))\n{\n myFreeSwap = (uint64_t)stats.f_bsize * stats.f_bfree;\n}\n sysctl -n vm.swapusage\nvm.swapusage: total = 3072.00M used = 2511.78M free = 560.22M (encrypted)\n xsw_usage vmusage = {0};\nsize_t size = sizeof(vmusage);\nif( sysctlbyname(\"vm.swapusage\", &vmusage, &size, NULL, 0)!=0 )\n{\n perror( \"unable to get swap usage by calling sysctlbyname(\\\"vm.swapusage\\\",...)\" );\n}\n task_info #include<mach/mach.h>\n\nstruct task_basic_info t_info;\nmach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;\n\nif (KERN_SUCCESS != task_info(mach_task_self(),\n TASK_BASIC_INFO, (task_info_t)&t_info,\n &t_info_count))\n{\n return -1;\n}\n// resident size is in t_info.resident_size;\n// virtual size is in t_info.virtual_size;\n sysctl #include <sys/types.h>\n#include <sys/sysctl.h>\n...\nint mib[2];\nint64_t physical_memory;\nmib[0] = CTL_HW;\nmib[1] = HW_MEMSIZE;\nlength = sizeof(int64_t);\nsysctl(mib, 2, &physical_memory, &length, NULL, 0);\n host_statistics #include <mach/vm_statistics.h>\n#include <mach/mach_types.h>\n#include <mach/mach_init.h>\n#include <mach/mach_host.h>\n\nint main(int argc, const char * argv[]) {\n vm_size_t page_size;\n mach_port_t mach_port;\n mach_msg_type_number_t count;\n vm_statistics64_data_t vm_stats;\n\n mach_port = mach_host_self();\n count = sizeof(vm_stats) / sizeof(natural_t);\n if (KERN_SUCCESS == host_page_size(mach_port, &page_size) &&\n KERN_SUCCESS == host_statistics64(mach_port, HOST_VM_INFO,\n (host_info64_t)&vm_stats, &count))\n {\n long long free_memory = (int64_t)vm_stats.free_count * (int64_t)page_size;\n\n long long used_memory = ((int64_t)vm_stats.active_count +\n (int64_t)vm_stats.inactive_count +\n (int64_t)vm_stats.wire_count) * (int64_t)page_size;\n printf(\"free memory: %lld\\nused memory: %lld\\n\", free_memory, used_memory);\n }\n\n return 0;\n}\n"
},
{
"answer_id": 13947253,
"author": "Mohsen Zahraee",
"author_id": 1907986,
"author_profile": "https://Stackoverflow.com/users/1907986",
"pm_score": 4,
"selected": false,
"text": "#include <windows.h>\n#include <stdio.h>\n\n//------------------------------------------------------------------------------------------------------------------\n// Prototype(s)...\n//------------------------------------------------------------------------------------------------------------------\nCHAR cpuusage(void);\n\n//-----------------------------------------------------\ntypedef BOOL ( __stdcall * pfnGetSystemTimes)( LPFILETIME lpIdleTime, LPFILETIME lpKernelTime, LPFILETIME lpUserTime );\nstatic pfnGetSystemTimes s_pfnGetSystemTimes = NULL;\n\nstatic HMODULE s_hKernel = NULL;\n//-----------------------------------------------------\nvoid GetSystemTimesAddress()\n{\n if(s_hKernel == NULL)\n {\n s_hKernel = LoadLibrary(L\"Kernel32.dll\");\n if(s_hKernel != NULL)\n {\n s_pfnGetSystemTimes = (pfnGetSystemTimes)GetProcAddress(s_hKernel, \"GetSystemTimes\");\n if(s_pfnGetSystemTimes == NULL)\n {\n FreeLibrary(s_hKernel);\n s_hKernel = NULL;\n }\n }\n }\n}\n//----------------------------------------------------------------------------------------------------------------\n\n//----------------------------------------------------------------------------------------------------------------\n// cpuusage(void)\n// ==============\n// Return a CHAR value in the range 0 - 100 representing actual CPU usage in percent.\n//----------------------------------------------------------------------------------------------------------------\nCHAR cpuusage()\n{\n FILETIME ft_sys_idle;\n FILETIME ft_sys_kernel;\n FILETIME ft_sys_user;\n\n ULARGE_INTEGER ul_sys_idle;\n ULARGE_INTEGER ul_sys_kernel;\n ULARGE_INTEGER ul_sys_user;\n\n static ULARGE_INTEGER ul_sys_idle_old;\n static ULARGE_INTEGER ul_sys_kernel_old;\n static ULARGE_INTEGER ul_sys_user_old;\n\n CHAR usage = 0;\n\n // We cannot directly use GetSystemTimes in the C language\n /* Add this line :: pfnGetSystemTimes */\n s_pfnGetSystemTimes(&ft_sys_idle, /* System idle time */\n &ft_sys_kernel, /* system kernel time */\n &ft_sys_user); /* System user time */\n\n CopyMemory(&ul_sys_idle , &ft_sys_idle , sizeof(FILETIME)); // Could been optimized away...\n CopyMemory(&ul_sys_kernel, &ft_sys_kernel, sizeof(FILETIME)); // Could been optimized away...\n CopyMemory(&ul_sys_user , &ft_sys_user , sizeof(FILETIME)); // Could been optimized away...\n\n usage =\n (\n (\n (\n (\n (ul_sys_kernel.QuadPart - ul_sys_kernel_old.QuadPart)+\n (ul_sys_user.QuadPart - ul_sys_user_old.QuadPart)\n )\n -\n (ul_sys_idle.QuadPart-ul_sys_idle_old.QuadPart)\n )\n *\n (100)\n )\n /\n (\n (ul_sys_kernel.QuadPart - ul_sys_kernel_old.QuadPart)+\n (ul_sys_user.QuadPart - ul_sys_user_old.QuadPart)\n )\n );\n\n ul_sys_idle_old.QuadPart = ul_sys_idle.QuadPart;\n ul_sys_user_old.QuadPart = ul_sys_user.QuadPart;\n ul_sys_kernel_old.QuadPart = ul_sys_kernel.QuadPart;\n\n return usage;\n}\n\n\n//------------------------------------------------------------------------------------------------------------------\n// Entry point\n//------------------------------------------------------------------------------------------------------------------\nint main(void)\n{\n int n;\n GetSystemTimesAddress();\n for(n=0; n<20; n++)\n {\n printf(\"CPU Usage: %3d%%\\r\", cpuusage());\n Sleep(2000);\n }\n printf(\"\\n\");\n return 0;\n}\n"
},
{
"answer_id": 30452461,
"author": "Boernii",
"author_id": 4894793,
"author_profile": "https://Stackoverflow.com/users/4894793",
"pm_score": 2,
"selected": false,
"text": "#include <atomic.h>\n#include <libc.h>\n#include <pthread.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/iofunc.h>\n#include <sys/neutrino.h>\n#include <sys/resmgr.h>\n#include <sys/syspage.h>\n#include <unistd.h>\n#include <inttypes.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys/types.h>\n#include <sys/debug.h>\n#include <sys/procfs.h>\n#include <sys/syspage.h>\n#include <sys/neutrino.h>\n#include <sys/time.h>\n#include <time.h>\n#include <fcntl.h>\n#include <devctl.h>\n#include <errno.h>\n\n#define MAX_CPUS 32\n\nstatic float Loads[MAX_CPUS];\nstatic _uint64 LastSutime[MAX_CPUS];\nstatic _uint64 LastNsec[MAX_CPUS];\nstatic int ProcFd = -1;\nstatic int NumCpus = 0;\n\n\nint find_ncpus(void) {\n return NumCpus;\n}\n\nint get_cpu(int cpu) {\n int ret;\n ret = (int)Loads[ cpu % MAX_CPUS ];\n ret = max(0,ret);\n ret = min(100,ret);\n return( ret );\n}\n\nstatic _uint64 nanoseconds( void ) {\n _uint64 sec, usec;\n struct timeval tval;\n gettimeofday( &tval, NULL );\n sec = tval.tv_sec;\n usec = tval.tv_usec;\n return( ( ( sec * 1000000 ) + usec ) * 1000 );\n}\n\nint sample_cpus( void ) {\n int i;\n debug_thread_t debug_data;\n _uint64 current_nsec, sutime_delta, time_delta;\n memset( &debug_data, 0, sizeof( debug_data ) );\n \n for( i=0; i<NumCpus; i++ ) {\n /* Get the sutime of the idle thread #i+1 */\n debug_data.tid = i + 1;\n devctl( ProcFd, DCMD_PROC_TIDSTATUS,\n &debug_data, sizeof( debug_data ), NULL );\n /* Get the current time */\n current_nsec = nanoseconds();\n /* Get the deltas between now and the last samples */\n sutime_delta = debug_data.sutime - LastSutime[i];\n time_delta = current_nsec - LastNsec[i];\n /* Figure out the load */\n Loads[i] = 100.0 - ( (float)( sutime_delta * 100 ) / (float)time_delta );\n /* Flat out strange rounding issues. */\n if( Loads[i] < 0 ) {\n Loads[i] = 0;\n }\n /* Keep these for reference in the next cycle */\n LastNsec[i] = current_nsec;\n LastSutime[i] = debug_data.sutime;\n }\n return EOK;\n}\n\nint init_cpu( void ) {\n int i;\n debug_thread_t debug_data;\n memset( &debug_data, 0, sizeof( debug_data ) );\n/* Open a connection to proc to talk over.*/\n ProcFd = open( \"/proc/1/as\", O_RDONLY );\n if( ProcFd == -1 ) {\n fprintf( stderr, \"pload: Unable to access procnto: %s\\n\",strerror( errno ) );\n fflush( stderr );\n return -1;\n }\n i = fcntl(ProcFd,F_GETFD);\n if(i != -1){\n i |= FD_CLOEXEC;\n if(fcntl(ProcFd,F_SETFD,i) != -1){\n /* Grab this value */\n NumCpus = _syspage_ptr->num_cpu;\n /* Get a starting point for the comparisons */\n for( i=0; i<NumCpus; i++ ) {\n /*\n * the sutime of idle thread is how much\n * time that thread has been using, we can compare this\n * against how much time has passed to get an idea of the\n * load on the system.\n */\n debug_data.tid = i + 1;\n devctl( ProcFd, DCMD_PROC_TIDSTATUS, &debug_data, sizeof( debug_data ), NULL );\n LastSutime[i] = debug_data.sutime;\n LastNsec[i] = nanoseconds();\n }\n return(EOK);\n }\n }\n close(ProcFd);\n return(-1);\n}\n\nvoid close_cpu(void){\n if(ProcFd != -1){\n close(ProcFd);\n ProcFd = -1;\n }\n}\n\nint main(int argc, char* argv[]){\n int i,j;\n init_cpu();\n printf(\"System has: %d CPUs\\n\", NumCpus);\n for(i=0; i<20; i++) {\n sample_cpus();\n for(j=0; j<NumCpus;j++)\n printf(\"CPU #%d: %f\\n\", j, Loads[j]);\n sleep(1);\n }\n close_cpu();\n}\n #include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <err.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n\nint main( int argc, char *argv[] ){\n struct stat statbuf;\n paddr_t freemem;\n stat( \"/proc\", &statbuf );\n freemem = (paddr_t)statbuf.st_size;\n printf( \"Free memory: %d bytes\\n\", freemem );\n printf( \"Free memory: %d KB\\n\", freemem / 1024 );\n printf( \"Free memory: %d MB\\n\", freemem / ( 1024 * 1024 ) );\n return 0;\n} \n"
},
{
"answer_id": 31464645,
"author": "Mark Lakata",
"author_id": 364818,
"author_profile": "https://Stackoverflow.com/users/364818",
"pm_score": 4,
"selected": false,
"text": "sysinfo #include <sys/sysinfo.h>\n\n int sysinfo(struct sysinfo *info);\n Until Linux 2.3.16, sysinfo() used to return information in the\n following structure:\n\n struct sysinfo {\n long uptime; /* Seconds since boot */\n unsigned long loads[3]; /* 1, 5, and 15 minute load averages */\n unsigned long totalram; /* Total usable main memory size */\n unsigned long freeram; /* Available memory size */\n unsigned long sharedram; /* Amount of shared memory */\n unsigned long bufferram; /* Memory used by buffers */\n unsigned long totalswap; /* Total swap space size */\n unsigned long freeswap; /* swap space still available */\n unsigned short procs; /* Number of current processes */\n char _f[22]; /* Pads structure to 64 bytes */\n };\n\n and the sizes were given in bytes.\n\n Since Linux 2.3.23 (i386), 2.3.48 (all architectures) the structure\n is:\n\n struct sysinfo {\n long uptime; /* Seconds since boot */\n unsigned long loads[3]; /* 1, 5, and 15 minute load averages */\n unsigned long totalram; /* Total usable main memory size */\n unsigned long freeram; /* Available memory size */\n unsigned long sharedram; /* Amount of shared memory */\n unsigned long bufferram; /* Memory used by buffers */\n unsigned long totalswap; /* Total swap space size */\n unsigned long freeswap; /* swap space still available */\n unsigned short procs; /* Number of current processes */\n unsigned long totalhigh; /* Total high memory size */\n unsigned long freehigh; /* Available high memory size */\n unsigned int mem_unit; /* Memory unit size in bytes */\n char _f[20-2*sizeof(long)-sizeof(int)]; /* Padding to 64 bytes */\n };\n\n and the sizes are given as multiples of mem_unit bytes.\n"
},
{
"answer_id": 40268513,
"author": "Salman Ghaffar",
"author_id": 7037557,
"author_profile": "https://Stackoverflow.com/users/7037557",
"pm_score": 0,
"selected": false,
"text": "static HANDLE self;\nstatic int numProcessors;\nSYSTEM_INFO sysInfo;\n\ndouble percent;\n\nnumProcessors = sysInfo.dwNumberOfProcessors;\n\n//Getting system times information\nFILETIME SysidleTime;\nFILETIME SyskernelTime; \nFILETIME SysuserTime; \nULARGE_INTEGER SyskernelTimeInt, SysuserTimeInt;\nGetSystemTimes(&SysidleTime, &SyskernelTime, &SysuserTime);\nmemcpy(&SyskernelTimeInt, &SyskernelTime, sizeof(FILETIME));\nmemcpy(&SysuserTimeInt, &SysuserTime, sizeof(FILETIME));\n__int64 denomenator = SysuserTimeInt.QuadPart + SyskernelTimeInt.QuadPart; \n\n//Getting process times information\nFILETIME ProccreationTime, ProcexitTime, ProcKernelTime, ProcUserTime;\nULARGE_INTEGER ProccreationTimeInt, ProcexitTimeInt, ProcKernelTimeInt, ProcUserTimeInt;\nGetProcessTimes(self, &ProccreationTime, &ProcexitTime, &ProcKernelTime, &ProcUserTime);\nmemcpy(&ProcKernelTimeInt, &ProcKernelTime, sizeof(FILETIME));\nmemcpy(&ProcUserTimeInt, &ProcUserTime, sizeof(FILETIME));\n__int64 numerator = ProcUserTimeInt.QuadPart + ProcKernelTimeInt.QuadPart;\n//QuadPart represents a 64-bit signed integer (ULARGE_INTEGER)\n\npercent = 100*(numerator/denomenator);\n"
},
{
"answer_id": 42925322,
"author": "Steven Warner",
"author_id": 4721690,
"author_profile": "https://Stackoverflow.com/users/4721690",
"pm_score": 2,
"selected": false,
"text": "/proc/[pid]/statm\n\n Provides information about memory usage, measured in pages.\n The columns are:\n\n size (1) total program size\n (same as VmSize in /proc/[pid]/status)\n resident (2) resident set size\n (same as VmRSS in /proc/[pid]/status)\n shared (3) number of resident shared pages (i.e., backed by a file)\n (same as RssFile+RssShmem in /proc/[pid]/status)\n text (4) text (code)\n lib (5) library (unused since Linux 2.6; always 0)\n data (6) data + stack\n dt (7) dirty pages (unused since Linux 2.6; always 0)\n"
},
{
"answer_id": 49996245,
"author": "souch",
"author_id": 4964856,
"author_profile": "https://Stackoverflow.com/users/4964856",
"pm_score": 2,
"selected": false,
"text": "#include <mach/mach_init.h>\n#include <mach/mach_error.h>\n#include <mach/mach_host.h>\n#include <mach/vm_map.h>\n\nstatic unsigned long long _previousTotalTicks = 0;\nstatic unsigned long long _previousIdleTicks = 0;\n\n// Returns 1.0f for \"CPU fully pinned\", 0.0f for \"CPU idle\", or somewhere in between\n// You'll need to call this at regular intervals, since it measures the load between\n// the previous call and the current one.\nfloat GetCPULoad()\n{\n host_cpu_load_info_data_t cpuinfo;\n mach_msg_type_number_t count = HOST_CPU_LOAD_INFO_COUNT;\n if (host_statistics(mach_host_self(), HOST_CPU_LOAD_INFO, (host_info_t)&cpuinfo, &count) == KERN_SUCCESS)\n {\n unsigned long long totalTicks = 0;\n for(int i=0; i<CPU_STATE_MAX; i++) totalTicks += cpuinfo.cpu_ticks[i];\n return CalculateCPULoad(cpuinfo.cpu_ticks[CPU_STATE_IDLE], totalTicks);\n }\n else return -1.0f;\n}\n\nfloat CalculateCPULoad(unsigned long long idleTicks, unsigned long long totalTicks)\n{\n unsigned long long totalTicksSinceLastTime = totalTicks-_previousTotalTicks;\n unsigned long long idleTicksSinceLastTime = idleTicks-_previousIdleTicks;\n float ret = 1.0f-((totalTicksSinceLastTime > 0) ? ((float)idleTicksSinceLastTime)/totalTicksSinceLastTime : 0);\n _previousTotalTicks = totalTicks;\n _previousIdleTicks = idleTicks;\n return ret;\n}\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/63166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7381/"
] |
63,181 |
<p>In Flex, I have an xml document such as the following:</p>
<pre><code>var xml:XML = <root><node>value1</node><node>value2</node><node>value3</node></root>
</code></pre>
<p>At runtime, I want to create a TextInput control for each node under root, and have the values bound to the values in the XML. As far as I can tell I can't use BindingUtils to bind to e4x nodes at runtime (please tell me if I'm wrong here!), so I'm trying to do this by hand:</p>
<pre><code>for each (var node:XML in xml.node)
{
var textInput:TextInput = new TextInput();
var handler:Function = function(event:Event):void
{
node.setChildren(event.target.text);
};
textInput.text = node.text();
textInput.addEventListener(Event.CHANGE, handler);
this.addChild(pileHeightEditor);
}
</code></pre>
<p>My problem is that when the user edits one of the TextInputs, the node getting assigned to is always the last one encountered in the for loop. I am used to this pattern from C#, where each time an anonymous function is created, a "snapshot" of the values of the used values is taken, so "node" would be different in each handler function.</p>
<p>How do I "take a snapshot" of the current value of node to use in the handler? Or should I be using a different pattern in Flex?</p>
|
[
{
"answer_id": 64166,
"author": "Lanzelot",
"author_id": 7381,
"author_profile": "https://Stackoverflow.com/users/7381",
"pm_score": 10,
"selected": false,
"text": "#include \"windows.h\"\n\nMEMORYSTATUSEX memInfo;\nmemInfo.dwLength = sizeof(MEMORYSTATUSEX);\nGlobalMemoryStatusEx(&memInfo);\nDWORDLONG totalVirtualMem = memInfo.ullTotalPageFile;\n DWORDLONG virtualMemUsed = memInfo.ullTotalPageFile - memInfo.ullAvailPageFile;\n #include \"windows.h\"\n#include \"psapi.h\"\n\nPROCESS_MEMORY_COUNTERS_EX pmc;\nGetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS*)&pmc, sizeof(pmc));\nSIZE_T virtualMemUsedByMe = pmc.PrivateUsage;\n DWORDLONG totalPhysMem = memInfo.ullTotalPhys;\n DWORDLONG physMemUsed = memInfo.ullTotalPhys - memInfo.ullAvailPhys;\n SIZE_T physMemUsedByMe = pmc.WorkingSetSize;\n #include \"TCHAR.h\"\n#include \"pdh.h\"\n\nstatic PDH_HQUERY cpuQuery;\nstatic PDH_HCOUNTER cpuTotal;\n\nvoid init(){\n PdhOpenQuery(NULL, NULL, &cpuQuery);\n // You can also use L\"\\\\Processor(*)\\\\% Processor Time\" and get individual CPU values with PdhGetFormattedCounterArray()\n PdhAddEnglishCounter(cpuQuery, L\"\\\\Processor(_Total)\\\\% Processor Time\", NULL, &cpuTotal);\n PdhCollectQueryData(cpuQuery);\n}\n\ndouble getCurrentValue(){\n PDH_FMT_COUNTERVALUE counterVal;\n\n PdhCollectQueryData(cpuQuery);\n PdhGetFormattedCounterValue(cpuTotal, PDH_FMT_DOUBLE, NULL, &counterVal);\n return counterVal.doubleValue;\n}\n #include \"windows.h\"\n\nstatic ULARGE_INTEGER lastCPU, lastSysCPU, lastUserCPU;\nstatic int numProcessors;\nstatic HANDLE self;\n\nvoid init(){\n SYSTEM_INFO sysInfo;\n FILETIME ftime, fsys, fuser;\n\n GetSystemInfo(&sysInfo);\n numProcessors = sysInfo.dwNumberOfProcessors;\n\n GetSystemTimeAsFileTime(&ftime);\n memcpy(&lastCPU, &ftime, sizeof(FILETIME));\n\n self = GetCurrentProcess();\n GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser);\n memcpy(&lastSysCPU, &fsys, sizeof(FILETIME));\n memcpy(&lastUserCPU, &fuser, sizeof(FILETIME));\n}\n\ndouble getCurrentValue(){\n FILETIME ftime, fsys, fuser;\n ULARGE_INTEGER now, sys, user;\n double percent;\n\n GetSystemTimeAsFileTime(&ftime);\n memcpy(&now, &ftime, sizeof(FILETIME));\n\n GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser);\n memcpy(&sys, &fsys, sizeof(FILETIME));\n memcpy(&user, &fuser, sizeof(FILETIME));\n percent = (sys.QuadPart - lastSysCPU.QuadPart) +\n (user.QuadPart - lastUserCPU.QuadPart);\n percent /= (now.QuadPart - lastCPU.QuadPart);\n percent /= numProcessors;\n lastCPU = now;\n lastUserCPU = user;\n lastSysCPU = sys;\n\n return percent * 100;\n}\n getrusage() /proc #include \"sys/types.h\"\n#include \"sys/sysinfo.h\"\n\nstruct sysinfo memInfo;\n\nsysinfo (&memInfo);\nlong long totalVirtualMem = memInfo.totalram;\n//Add other values in next statement to avoid int overflow on right hand side...\ntotalVirtualMem += memInfo.totalswap;\ntotalVirtualMem *= memInfo.mem_unit;\n long long virtualMemUsed = memInfo.totalram - memInfo.freeram;\n//Add other values in next statement to avoid int overflow on right hand side...\nvirtualMemUsed += memInfo.totalswap - memInfo.freeswap;\nvirtualMemUsed *= memInfo.mem_unit;\n #include \"stdlib.h\"\n#include \"stdio.h\"\n#include \"string.h\"\n\nint parseLine(char* line){\n // This assumes that a digit will be found and the line ends in \" Kb\".\n int i = strlen(line);\n const char* p = line;\n while (*p <'0' || *p > '9') p++;\n line[i-3] = '\\0';\n i = atoi(p);\n return i;\n}\n\nint getValue(){ //Note: this value is in KB!\n FILE* file = fopen(\"/proc/self/status\", \"r\");\n int result = -1;\n char line[128];\n\n while (fgets(line, 128, file) != NULL){\n if (strncmp(line, \"VmSize:\", 7) == 0){\n result = parseLine(line);\n break;\n }\n }\n fclose(file);\n return result;\n}\n long long totalPhysMem = memInfo.totalram;\n//Multiply in next statement to avoid int overflow on right hand side...\ntotalPhysMem *= memInfo.mem_unit;\n long long physMemUsed = memInfo.totalram - memInfo.freeram;\n//Multiply in next statement to avoid int overflow on right hand side...\nphysMemUsed *= memInfo.mem_unit;\n int getValue(){ //Note: this value is in KB!\n FILE* file = fopen(\"/proc/self/status\", \"r\");\n int result = -1;\n char line[128];\n\n while (fgets(line, 128, file) != NULL){\n if (strncmp(line, \"VmRSS:\", 6) == 0){\n result = parseLine(line);\n break;\n }\n }\n fclose(file);\n return result;\n}\n #include \"stdlib.h\"\n#include \"stdio.h\"\n#include \"string.h\"\n\nstatic unsigned long long lastTotalUser, lastTotalUserLow, lastTotalSys, lastTotalIdle;\n\nvoid init(){\n FILE* file = fopen(\"/proc/stat\", \"r\");\n fscanf(file, \"cpu %llu %llu %llu %llu\", &lastTotalUser, &lastTotalUserLow,\n &lastTotalSys, &lastTotalIdle);\n fclose(file);\n}\n\ndouble getCurrentValue(){\n double percent;\n FILE* file;\n unsigned long long totalUser, totalUserLow, totalSys, totalIdle, total;\n\n file = fopen(\"/proc/stat\", \"r\");\n fscanf(file, \"cpu %llu %llu %llu %llu\", &totalUser, &totalUserLow,\n &totalSys, &totalIdle);\n fclose(file);\n\n if (totalUser < lastTotalUser || totalUserLow < lastTotalUserLow ||\n totalSys < lastTotalSys || totalIdle < lastTotalIdle){\n //Overflow detection. Just skip this value.\n percent = -1.0;\n }\n else{\n total = (totalUser - lastTotalUser) + (totalUserLow - lastTotalUserLow) +\n (totalSys - lastTotalSys);\n percent = total;\n total += (totalIdle - lastTotalIdle);\n percent /= total;\n percent *= 100;\n }\n\n lastTotalUser = totalUser;\n lastTotalUserLow = totalUserLow;\n lastTotalSys = totalSys;\n lastTotalIdle = totalIdle;\n\n return percent;\n}\n #include \"stdlib.h\"\n#include \"stdio.h\"\n#include \"string.h\"\n#include \"sys/times.h\"\n#include \"sys/vtimes.h\"\n\nstatic clock_t lastCPU, lastSysCPU, lastUserCPU;\nstatic int numProcessors;\n\nvoid init(){\n FILE* file;\n struct tms timeSample;\n char line[128];\n\n lastCPU = times(&timeSample);\n lastSysCPU = timeSample.tms_stime;\n lastUserCPU = timeSample.tms_utime;\n\n file = fopen(\"/proc/cpuinfo\", \"r\");\n numProcessors = 0;\n while(fgets(line, 128, file) != NULL){\n if (strncmp(line, \"processor\", 9) == 0) numProcessors++;\n }\n fclose(file);\n}\n\ndouble getCurrentValue(){\n struct tms timeSample;\n clock_t now;\n double percent;\n\n now = times(&timeSample);\n if (now <= lastCPU || timeSample.tms_stime < lastSysCPU ||\n timeSample.tms_utime < lastUserCPU){\n //Overflow detection. Just skip this value.\n percent = -1.0;\n }\n else{\n percent = (timeSample.tms_stime - lastSysCPU) +\n (timeSample.tms_utime - lastUserCPU);\n percent /= (now - lastCPU);\n percent /= numProcessors;\n percent *= 100;\n }\n lastCPU = now;\n lastSysCPU = timeSample.tms_stime;\n lastUserCPU = timeSample.tms_utime;\n\n return percent;\n}\n getrusage()"
},
{
"answer_id": 64422,
"author": "Martin Del Vecchio",
"author_id": 5397,
"author_profile": "https://Stackoverflow.com/users/5397",
"pm_score": 6,
"selected": false,
"text": "Anderson cxc # more /proc/meminfo\nMemTotal: 4083948 kB\nMemFree: 2198520 kB\nBuffers: 82080 kB\nCached: 1141460 kB\nSwapCached: 0 kB\nActive: 1137960 kB\nInactive: 608588 kB\nHighTotal: 3276672 kB\nHighFree: 1607744 kB\nLowTotal: 807276 kB\nLowFree: 590776 kB\nSwapTotal: 2096440 kB\nSwapFree: 2096440 kB\nDirty: 32 kB\nWriteback: 0 kB\nAnonPages: 523252 kB\nMapped: 93560 kB\nSlab: 52880 kB\nSReclaimable: 24652 kB\nSUnreclaim: 28228 kB\nPageTables: 2284 kB\nNFS_Unstable: 0 kB\nBounce: 0 kB\nCommitLimit: 4138412 kB\nCommitted_AS: 1845072 kB\nVmallocTotal: 118776 kB\nVmallocUsed: 3964 kB\nVmallocChunk: 112860 kB\nHugePages_Total: 0\nHugePages_Free: 0\nHugePages_Rsvd: 0\nHugepagesize: 2048 kB\n Anderson cxc # more /proc/stat\ncpu 2329889 0 2364567 1063530460 9034 9463 96111 0\ncpu0 572526 0 636532 265864398 2928 1621 6899 0\ncpu1 590441 0 531079 265949732 4763 351 8522 0\ncpu2 562983 0 645163 265796890 682 7490 71650 0\ncpu3 603938 0 551790 265919440 660 0 9040 0\nintr 37124247\nctxt 50795173133\nbtime 1218807985\nprocesses 116889\nprocs_running 1\nprocs_blocked 0\n cpu 2330047 0 2365006 1063853632 9035 9463 96114 0\n cpu 2330047 0 2365007 1063854028 9035 9463 96114 0\n 19340 (whatever) S 19115 19115 3084 34816 19115 4202752 118200 607 0 0 770 384 2\n 7 20 0 77 0 266764385 692477952 105074 4294967295 134512640 146462952 321468364\n8 3214683328 4294960144 0 2147221247 268439552 1276 4294967295 0 0 17 0 0 0 0\n Name: whatever\nState: S (sleeping)\nTgid: 19340\nPid: 19340\nPPid: 19115\nTracerPid: 0\nUid: 0 0 0 0\nGid: 0 0 0 0\nFDSize: 256\nGroups: 0 1 2 3 4 6 10 11 20 26 27\nVmPeak: 676252 kB\nVmSize: 651352 kB\nVmLck: 0 kB\nVmHWM: 420300 kB\nVmRSS: 420296 kB\nVmData: 581028 kB\nVmStk: 112 kB\nVmExe: 11672 kB\nVmLib: 76608 kB\nVmPTE: 1244 kB\nThreads: 77\nSigQ: 0/36864\nSigPnd: 0000000000000000\nShdPnd: 0000000000000000\nSigBlk: fffffffe7ffbfeff\nSigIgn: 0000000010001000\nSigCgt: 20000001800004fc\nCapInh: 0000000000000000\nCapPrm: 00000000ffffffff\nCapEff: 00000000fffffeff\nCpus_allowed: 0f\nMems_allowed: 1\nvoluntary_ctxt_switches: 6518\nnonvoluntary_ctxt_switches: 6598\n"
},
{
"answer_id": 1911863,
"author": "Michael Taylor",
"author_id": 172534,
"author_profile": "https://Stackoverflow.com/users/172534",
"pm_score": 7,
"selected": false,
"text": "struct statfs stats;\nif (0 == statfs(\"/\", &stats))\n{\n myFreeSwap = (uint64_t)stats.f_bsize * stats.f_bfree;\n}\n sysctl -n vm.swapusage\nvm.swapusage: total = 3072.00M used = 2511.78M free = 560.22M (encrypted)\n xsw_usage vmusage = {0};\nsize_t size = sizeof(vmusage);\nif( sysctlbyname(\"vm.swapusage\", &vmusage, &size, NULL, 0)!=0 )\n{\n perror( \"unable to get swap usage by calling sysctlbyname(\\\"vm.swapusage\\\",...)\" );\n}\n task_info #include<mach/mach.h>\n\nstruct task_basic_info t_info;\nmach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;\n\nif (KERN_SUCCESS != task_info(mach_task_self(),\n TASK_BASIC_INFO, (task_info_t)&t_info,\n &t_info_count))\n{\n return -1;\n}\n// resident size is in t_info.resident_size;\n// virtual size is in t_info.virtual_size;\n sysctl #include <sys/types.h>\n#include <sys/sysctl.h>\n...\nint mib[2];\nint64_t physical_memory;\nmib[0] = CTL_HW;\nmib[1] = HW_MEMSIZE;\nlength = sizeof(int64_t);\nsysctl(mib, 2, &physical_memory, &length, NULL, 0);\n host_statistics #include <mach/vm_statistics.h>\n#include <mach/mach_types.h>\n#include <mach/mach_init.h>\n#include <mach/mach_host.h>\n\nint main(int argc, const char * argv[]) {\n vm_size_t page_size;\n mach_port_t mach_port;\n mach_msg_type_number_t count;\n vm_statistics64_data_t vm_stats;\n\n mach_port = mach_host_self();\n count = sizeof(vm_stats) / sizeof(natural_t);\n if (KERN_SUCCESS == host_page_size(mach_port, &page_size) &&\n KERN_SUCCESS == host_statistics64(mach_port, HOST_VM_INFO,\n (host_info64_t)&vm_stats, &count))\n {\n long long free_memory = (int64_t)vm_stats.free_count * (int64_t)page_size;\n\n long long used_memory = ((int64_t)vm_stats.active_count +\n (int64_t)vm_stats.inactive_count +\n (int64_t)vm_stats.wire_count) * (int64_t)page_size;\n printf(\"free memory: %lld\\nused memory: %lld\\n\", free_memory, used_memory);\n }\n\n return 0;\n}\n"
},
{
"answer_id": 13947253,
"author": "Mohsen Zahraee",
"author_id": 1907986,
"author_profile": "https://Stackoverflow.com/users/1907986",
"pm_score": 4,
"selected": false,
"text": "#include <windows.h>\n#include <stdio.h>\n\n//------------------------------------------------------------------------------------------------------------------\n// Prototype(s)...\n//------------------------------------------------------------------------------------------------------------------\nCHAR cpuusage(void);\n\n//-----------------------------------------------------\ntypedef BOOL ( __stdcall * pfnGetSystemTimes)( LPFILETIME lpIdleTime, LPFILETIME lpKernelTime, LPFILETIME lpUserTime );\nstatic pfnGetSystemTimes s_pfnGetSystemTimes = NULL;\n\nstatic HMODULE s_hKernel = NULL;\n//-----------------------------------------------------\nvoid GetSystemTimesAddress()\n{\n if(s_hKernel == NULL)\n {\n s_hKernel = LoadLibrary(L\"Kernel32.dll\");\n if(s_hKernel != NULL)\n {\n s_pfnGetSystemTimes = (pfnGetSystemTimes)GetProcAddress(s_hKernel, \"GetSystemTimes\");\n if(s_pfnGetSystemTimes == NULL)\n {\n FreeLibrary(s_hKernel);\n s_hKernel = NULL;\n }\n }\n }\n}\n//----------------------------------------------------------------------------------------------------------------\n\n//----------------------------------------------------------------------------------------------------------------\n// cpuusage(void)\n// ==============\n// Return a CHAR value in the range 0 - 100 representing actual CPU usage in percent.\n//----------------------------------------------------------------------------------------------------------------\nCHAR cpuusage()\n{\n FILETIME ft_sys_idle;\n FILETIME ft_sys_kernel;\n FILETIME ft_sys_user;\n\n ULARGE_INTEGER ul_sys_idle;\n ULARGE_INTEGER ul_sys_kernel;\n ULARGE_INTEGER ul_sys_user;\n\n static ULARGE_INTEGER ul_sys_idle_old;\n static ULARGE_INTEGER ul_sys_kernel_old;\n static ULARGE_INTEGER ul_sys_user_old;\n\n CHAR usage = 0;\n\n // We cannot directly use GetSystemTimes in the C language\n /* Add this line :: pfnGetSystemTimes */\n s_pfnGetSystemTimes(&ft_sys_idle, /* System idle time */\n &ft_sys_kernel, /* system kernel time */\n &ft_sys_user); /* System user time */\n\n CopyMemory(&ul_sys_idle , &ft_sys_idle , sizeof(FILETIME)); // Could been optimized away...\n CopyMemory(&ul_sys_kernel, &ft_sys_kernel, sizeof(FILETIME)); // Could been optimized away...\n CopyMemory(&ul_sys_user , &ft_sys_user , sizeof(FILETIME)); // Could been optimized away...\n\n usage =\n (\n (\n (\n (\n (ul_sys_kernel.QuadPart - ul_sys_kernel_old.QuadPart)+\n (ul_sys_user.QuadPart - ul_sys_user_old.QuadPart)\n )\n -\n (ul_sys_idle.QuadPart-ul_sys_idle_old.QuadPart)\n )\n *\n (100)\n )\n /\n (\n (ul_sys_kernel.QuadPart - ul_sys_kernel_old.QuadPart)+\n (ul_sys_user.QuadPart - ul_sys_user_old.QuadPart)\n )\n );\n\n ul_sys_idle_old.QuadPart = ul_sys_idle.QuadPart;\n ul_sys_user_old.QuadPart = ul_sys_user.QuadPart;\n ul_sys_kernel_old.QuadPart = ul_sys_kernel.QuadPart;\n\n return usage;\n}\n\n\n//------------------------------------------------------------------------------------------------------------------\n// Entry point\n//------------------------------------------------------------------------------------------------------------------\nint main(void)\n{\n int n;\n GetSystemTimesAddress();\n for(n=0; n<20; n++)\n {\n printf(\"CPU Usage: %3d%%\\r\", cpuusage());\n Sleep(2000);\n }\n printf(\"\\n\");\n return 0;\n}\n"
},
{
"answer_id": 30452461,
"author": "Boernii",
"author_id": 4894793,
"author_profile": "https://Stackoverflow.com/users/4894793",
"pm_score": 2,
"selected": false,
"text": "#include <atomic.h>\n#include <libc.h>\n#include <pthread.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/iofunc.h>\n#include <sys/neutrino.h>\n#include <sys/resmgr.h>\n#include <sys/syspage.h>\n#include <unistd.h>\n#include <inttypes.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys/types.h>\n#include <sys/debug.h>\n#include <sys/procfs.h>\n#include <sys/syspage.h>\n#include <sys/neutrino.h>\n#include <sys/time.h>\n#include <time.h>\n#include <fcntl.h>\n#include <devctl.h>\n#include <errno.h>\n\n#define MAX_CPUS 32\n\nstatic float Loads[MAX_CPUS];\nstatic _uint64 LastSutime[MAX_CPUS];\nstatic _uint64 LastNsec[MAX_CPUS];\nstatic int ProcFd = -1;\nstatic int NumCpus = 0;\n\n\nint find_ncpus(void) {\n return NumCpus;\n}\n\nint get_cpu(int cpu) {\n int ret;\n ret = (int)Loads[ cpu % MAX_CPUS ];\n ret = max(0,ret);\n ret = min(100,ret);\n return( ret );\n}\n\nstatic _uint64 nanoseconds( void ) {\n _uint64 sec, usec;\n struct timeval tval;\n gettimeofday( &tval, NULL );\n sec = tval.tv_sec;\n usec = tval.tv_usec;\n return( ( ( sec * 1000000 ) + usec ) * 1000 );\n}\n\nint sample_cpus( void ) {\n int i;\n debug_thread_t debug_data;\n _uint64 current_nsec, sutime_delta, time_delta;\n memset( &debug_data, 0, sizeof( debug_data ) );\n \n for( i=0; i<NumCpus; i++ ) {\n /* Get the sutime of the idle thread #i+1 */\n debug_data.tid = i + 1;\n devctl( ProcFd, DCMD_PROC_TIDSTATUS,\n &debug_data, sizeof( debug_data ), NULL );\n /* Get the current time */\n current_nsec = nanoseconds();\n /* Get the deltas between now and the last samples */\n sutime_delta = debug_data.sutime - LastSutime[i];\n time_delta = current_nsec - LastNsec[i];\n /* Figure out the load */\n Loads[i] = 100.0 - ( (float)( sutime_delta * 100 ) / (float)time_delta );\n /* Flat out strange rounding issues. */\n if( Loads[i] < 0 ) {\n Loads[i] = 0;\n }\n /* Keep these for reference in the next cycle */\n LastNsec[i] = current_nsec;\n LastSutime[i] = debug_data.sutime;\n }\n return EOK;\n}\n\nint init_cpu( void ) {\n int i;\n debug_thread_t debug_data;\n memset( &debug_data, 0, sizeof( debug_data ) );\n/* Open a connection to proc to talk over.*/\n ProcFd = open( \"/proc/1/as\", O_RDONLY );\n if( ProcFd == -1 ) {\n fprintf( stderr, \"pload: Unable to access procnto: %s\\n\",strerror( errno ) );\n fflush( stderr );\n return -1;\n }\n i = fcntl(ProcFd,F_GETFD);\n if(i != -1){\n i |= FD_CLOEXEC;\n if(fcntl(ProcFd,F_SETFD,i) != -1){\n /* Grab this value */\n NumCpus = _syspage_ptr->num_cpu;\n /* Get a starting point for the comparisons */\n for( i=0; i<NumCpus; i++ ) {\n /*\n * the sutime of idle thread is how much\n * time that thread has been using, we can compare this\n * against how much time has passed to get an idea of the\n * load on the system.\n */\n debug_data.tid = i + 1;\n devctl( ProcFd, DCMD_PROC_TIDSTATUS, &debug_data, sizeof( debug_data ), NULL );\n LastSutime[i] = debug_data.sutime;\n LastNsec[i] = nanoseconds();\n }\n return(EOK);\n }\n }\n close(ProcFd);\n return(-1);\n}\n\nvoid close_cpu(void){\n if(ProcFd != -1){\n close(ProcFd);\n ProcFd = -1;\n }\n}\n\nint main(int argc, char* argv[]){\n int i,j;\n init_cpu();\n printf(\"System has: %d CPUs\\n\", NumCpus);\n for(i=0; i<20; i++) {\n sample_cpus();\n for(j=0; j<NumCpus;j++)\n printf(\"CPU #%d: %f\\n\", j, Loads[j]);\n sleep(1);\n }\n close_cpu();\n}\n #include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <err.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n\nint main( int argc, char *argv[] ){\n struct stat statbuf;\n paddr_t freemem;\n stat( \"/proc\", &statbuf );\n freemem = (paddr_t)statbuf.st_size;\n printf( \"Free memory: %d bytes\\n\", freemem );\n printf( \"Free memory: %d KB\\n\", freemem / 1024 );\n printf( \"Free memory: %d MB\\n\", freemem / ( 1024 * 1024 ) );\n return 0;\n} \n"
},
{
"answer_id": 31464645,
"author": "Mark Lakata",
"author_id": 364818,
"author_profile": "https://Stackoverflow.com/users/364818",
"pm_score": 4,
"selected": false,
"text": "sysinfo #include <sys/sysinfo.h>\n\n int sysinfo(struct sysinfo *info);\n Until Linux 2.3.16, sysinfo() used to return information in the\n following structure:\n\n struct sysinfo {\n long uptime; /* Seconds since boot */\n unsigned long loads[3]; /* 1, 5, and 15 minute load averages */\n unsigned long totalram; /* Total usable main memory size */\n unsigned long freeram; /* Available memory size */\n unsigned long sharedram; /* Amount of shared memory */\n unsigned long bufferram; /* Memory used by buffers */\n unsigned long totalswap; /* Total swap space size */\n unsigned long freeswap; /* swap space still available */\n unsigned short procs; /* Number of current processes */\n char _f[22]; /* Pads structure to 64 bytes */\n };\n\n and the sizes were given in bytes.\n\n Since Linux 2.3.23 (i386), 2.3.48 (all architectures) the structure\n is:\n\n struct sysinfo {\n long uptime; /* Seconds since boot */\n unsigned long loads[3]; /* 1, 5, and 15 minute load averages */\n unsigned long totalram; /* Total usable main memory size */\n unsigned long freeram; /* Available memory size */\n unsigned long sharedram; /* Amount of shared memory */\n unsigned long bufferram; /* Memory used by buffers */\n unsigned long totalswap; /* Total swap space size */\n unsigned long freeswap; /* swap space still available */\n unsigned short procs; /* Number of current processes */\n unsigned long totalhigh; /* Total high memory size */\n unsigned long freehigh; /* Available high memory size */\n unsigned int mem_unit; /* Memory unit size in bytes */\n char _f[20-2*sizeof(long)-sizeof(int)]; /* Padding to 64 bytes */\n };\n\n and the sizes are given as multiples of mem_unit bytes.\n"
},
{
"answer_id": 40268513,
"author": "Salman Ghaffar",
"author_id": 7037557,
"author_profile": "https://Stackoverflow.com/users/7037557",
"pm_score": 0,
"selected": false,
"text": "static HANDLE self;\nstatic int numProcessors;\nSYSTEM_INFO sysInfo;\n\ndouble percent;\n\nnumProcessors = sysInfo.dwNumberOfProcessors;\n\n//Getting system times information\nFILETIME SysidleTime;\nFILETIME SyskernelTime; \nFILETIME SysuserTime; \nULARGE_INTEGER SyskernelTimeInt, SysuserTimeInt;\nGetSystemTimes(&SysidleTime, &SyskernelTime, &SysuserTime);\nmemcpy(&SyskernelTimeInt, &SyskernelTime, sizeof(FILETIME));\nmemcpy(&SysuserTimeInt, &SysuserTime, sizeof(FILETIME));\n__int64 denomenator = SysuserTimeInt.QuadPart + SyskernelTimeInt.QuadPart; \n\n//Getting process times information\nFILETIME ProccreationTime, ProcexitTime, ProcKernelTime, ProcUserTime;\nULARGE_INTEGER ProccreationTimeInt, ProcexitTimeInt, ProcKernelTimeInt, ProcUserTimeInt;\nGetProcessTimes(self, &ProccreationTime, &ProcexitTime, &ProcKernelTime, &ProcUserTime);\nmemcpy(&ProcKernelTimeInt, &ProcKernelTime, sizeof(FILETIME));\nmemcpy(&ProcUserTimeInt, &ProcUserTime, sizeof(FILETIME));\n__int64 numerator = ProcUserTimeInt.QuadPart + ProcKernelTimeInt.QuadPart;\n//QuadPart represents a 64-bit signed integer (ULARGE_INTEGER)\n\npercent = 100*(numerator/denomenator);\n"
},
{
"answer_id": 42925322,
"author": "Steven Warner",
"author_id": 4721690,
"author_profile": "https://Stackoverflow.com/users/4721690",
"pm_score": 2,
"selected": false,
"text": "/proc/[pid]/statm\n\n Provides information about memory usage, measured in pages.\n The columns are:\n\n size (1) total program size\n (same as VmSize in /proc/[pid]/status)\n resident (2) resident set size\n (same as VmRSS in /proc/[pid]/status)\n shared (3) number of resident shared pages (i.e., backed by a file)\n (same as RssFile+RssShmem in /proc/[pid]/status)\n text (4) text (code)\n lib (5) library (unused since Linux 2.6; always 0)\n data (6) data + stack\n dt (7) dirty pages (unused since Linux 2.6; always 0)\n"
},
{
"answer_id": 49996245,
"author": "souch",
"author_id": 4964856,
"author_profile": "https://Stackoverflow.com/users/4964856",
"pm_score": 2,
"selected": false,
"text": "#include <mach/mach_init.h>\n#include <mach/mach_error.h>\n#include <mach/mach_host.h>\n#include <mach/vm_map.h>\n\nstatic unsigned long long _previousTotalTicks = 0;\nstatic unsigned long long _previousIdleTicks = 0;\n\n// Returns 1.0f for \"CPU fully pinned\", 0.0f for \"CPU idle\", or somewhere in between\n// You'll need to call this at regular intervals, since it measures the load between\n// the previous call and the current one.\nfloat GetCPULoad()\n{\n host_cpu_load_info_data_t cpuinfo;\n mach_msg_type_number_t count = HOST_CPU_LOAD_INFO_COUNT;\n if (host_statistics(mach_host_self(), HOST_CPU_LOAD_INFO, (host_info_t)&cpuinfo, &count) == KERN_SUCCESS)\n {\n unsigned long long totalTicks = 0;\n for(int i=0; i<CPU_STATE_MAX; i++) totalTicks += cpuinfo.cpu_ticks[i];\n return CalculateCPULoad(cpuinfo.cpu_ticks[CPU_STATE_IDLE], totalTicks);\n }\n else return -1.0f;\n}\n\nfloat CalculateCPULoad(unsigned long long idleTicks, unsigned long long totalTicks)\n{\n unsigned long long totalTicksSinceLastTime = totalTicks-_previousTotalTicks;\n unsigned long long idleTicksSinceLastTime = idleTicks-_previousIdleTicks;\n float ret = 1.0f-((totalTicksSinceLastTime > 0) ? ((float)idleTicksSinceLastTime)/totalTicksSinceLastTime : 0);\n _previousTotalTicks = totalTicks;\n _previousIdleTicks = idleTicks;\n return ret;\n}\n"
}
] |
2008/09/15
|
[
"https://Stackoverflow.com/questions/63181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6448/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.