qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
91,699
|
<p>Python's convention is that variables are created by first assignment, and trying to read their value before one has been assigned raises an exception. PHP by contrast implicitly creates a variable when it is read, with a null value. This means it is easy to do this in PHP:</p>
<pre><code>function mymodule_important_calculation() {
$result = /* ... long and complex calculation ... */;
return $resukt;
}
</code></pre>
<p>This function always returns null, and if null is a valid value for the functuion then the bug might go undetected for some time. The Python equivalent would complain that the variable <code>resukt</code> is being used before it is assigned.</p>
<p>So... is there a way to configure PHP to be stricter with variable assignments?</p>
|
[
{
"answer_id": 91776,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 0,
"selected": false,
"text": "error_reporting = E_ALL\n error_reporting(E_ALL);\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/91699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8925/"
] |
91,715
|
<p>I've not used C++ very much in the past, and have recently been doing a lot of C#, and I'm really struggling to get back into the basics of C++ again. This is particularly tricky as work mandates that none of the most handy C++ constructs can be used, so all strings must be char *'s, and there is no provision for STL lists.</p>
<p>What I'm currently trying to do is to create a list of strings, something which would take me no time at all using STL or in C#. Basically I want to have a function such as:</p>
<pre><code>char **registeredNames = new char*[numberOfNames];
</code></pre>
<p>Then,</p>
<pre><code>RegisterName(const * char const name, const int length)
{
//loop to see if name already registered snipped
if(notFound)
{
registeredNames[lastIndex++] = name;
}
}
</code></pre>
<p>or, if it was C#...</p>
<pre><code>if(!registeredNames.Contains(name))
{
registeredNames.Add(name);
}
</code></pre>
<p>and I realize that it doesn't work. I know the const nature of the passed variables (a const pointer and a const string) makes it rather difficult, but my basic problem is that I've always avoided this situation in the past by using STL lists etc. so I've never had to work around it!</p>
|
[
{
"answer_id": 91749,
"author": "Maximilian",
"author_id": 1733,
"author_profile": "https://Stackoverflow.com/users/1733",
"pm_score": 1,
"selected": false,
"text": "static int lastIndex = 0;\nstatic char **registeredNames = new char*[numberOfNames];\n\nvoid RegisterName(const * char const name)\n{\n bool found = false;\n //loop to see if name already registered snipped\n for (int i = 0; i < lastIndex; i++)\n {\n if (strcmp(name, registeredNames[i] == 0))\n {\n found = true;\n break;\n }\n }\n\n if (!found)\n {\n registeredNames[lastIndex++] = name;\n }\n}\n"
},
{
"answer_id": 91759,
"author": "Seb Rose",
"author_id": 12405,
"author_profile": "https://Stackoverflow.com/users/12405",
"pm_score": 4,
"selected": true,
"text": "for (int index=0; index<=lastIndex; index++)\n{\n if (strcmp(registeredNames[index], name) == 0)\n {\n return; // Already registered\n }\n}\n char* nameCopy = malloc(length+1);\nstrcpy(nameCopy, name);\nregisteredNames[lastIndex++] = nameCopy;\n"
},
{
"answer_id": 91761,
"author": "PierreBdR",
"author_id": 7136,
"author_profile": "https://Stackoverflow.com/users/7136",
"pm_score": 1,
"selected": false,
"text": "void RegisterName(const char* name)\n{\n // loop to see if name already registered snipped\n if(notFound)\n {\n registerNames[lastIndex++] = stdndup(name, MAX_STRING_LENGTH);\n }\n}\n"
},
{
"answer_id": 91762,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 1,
"selected": false,
"text": "const char **registeredNames = new const char * [numberOfNames];\n const * char const"
},
{
"answer_id": 91988,
"author": "Mark",
"author_id": 4405,
"author_profile": "https://Stackoverflow.com/users/4405",
"pm_score": 3,
"selected": false,
"text": "for ( i = 0; i < lastIndex; i++ ) {\n if ( !strcmp(®isteredNames[i], name ) {\n break; // name was found\n }\n}\nif ( i == lastIndex ) {\n // name was not found in the registeredNames list\n registeredNames[lastIndex++] = strdup(name);\n}\n"
},
{
"answer_id": 92149,
"author": "jheriko",
"author_id": 17604,
"author_profile": "https://Stackoverflow.com/users/17604",
"pm_score": 0,
"selected": false,
"text": "T** list = 0;\nunsigned int length = 0;\n\nT* AddItem(T Item)\n{\n list = realloc(list, sizeof(T)*(length+1));\n if(!list) return 0;\n list[length] = new T(Item);\n ++length;\n return list[length];\n}\n\nvoid CleanupList()\n{\n for(unsigned int i = 0; i < length; ++i)\n {\n delete item[i];\n }\n free(list)\n}\n"
},
{
"answer_id": 92584,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 0,
"selected": false,
"text": "const char ** registeredNames[i] const char *"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/91715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15667/"
] |
91,731
|
<p>How do you update a summary field's value from post function in JIRA?</p>
|
[
{
"answer_id": 92157,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "public class SomePostFunction implements FunctionProvider {\n\n public void execute(Map transientVars, Map args, PropertySet ps) throws WorkflowException {\n String newValue = \"foobar\";\n // TODO update summary so it's value becomes newValue\n }\n\n}\n"
},
{
"answer_id": 98302,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "src/java/com/atlassian/jira/workflow/function/issue/UpdateIssueFieldFunction.java"
},
{
"answer_id": 910844,
"author": "Evgeny",
"author_id": 11414,
"author_profile": "https://Stackoverflow.com/users/11414",
"pm_score": 0,
"selected": false,
"text": " transientVars.get(\"issue\").setSummary(newValue);\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/91731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
91,734
|
<p>I'm a little blockheaded right now…</p>
<p>I have a date string in european format <strong>dd.mm.yyyy</strong> and need to transform it to <strong>mm.dd.yyyy</strong> with classic ASP. Any quick ideas?</p>
|
[
{
"answer_id": 91780,
"author": "Anheledir",
"author_id": 5703,
"author_profile": "https://Stackoverflow.com/users/5703",
"pm_score": 2,
"selected": false,
"text": "payment_date = MID(payment_date,4,3) & LEFT(payment_date,3) & MID(payment_date,7)\n"
},
{
"answer_id": 91787,
"author": "Re0sless",
"author_id": 2098,
"author_profile": "https://Stackoverflow.com/users/2098",
"pm_score": 4,
"selected": true,
"text": "d = split(\".\",\"dd.mm.yyyy\")\ns = d(1) & \".\" & d(0) & \".\" & d(2)\n"
},
{
"answer_id": 91802,
"author": "Vincent McNabb",
"author_id": 16299,
"author_profile": "https://Stackoverflow.com/users/16299",
"pm_score": 2,
"selected": false,
"text": "Dim arrParts() As String\nDim theDate As Date\n\narrParts = Split(strOldFormat, \".\")\ntheDate = DateTime.DateSerial(parts(2), parts(1), parts(0))\n\nstrNewFormat = Format(theDate, \"mm.dd.yyyy\")\n"
},
{
"answer_id": 132742,
"author": "jamting",
"author_id": 2639,
"author_profile": "https://Stackoverflow.com/users/2639",
"pm_score": 2,
"selected": false,
"text": "Dim OldString, NewString\n\nOldString = \"31.12.2008\"\n\nDim myRegExp\nSet myRegExp = New RegExp\nmyRegExp.Global = True\nmyRegExp.Pattern = \"(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.]((19|20)[0-9]{2})\"\n\nIf myRegExp.Test Then\n NewString = myRegExp.Replace(OldString, \"$2.$1.$3\")\nElse\n ' A date of for instance 32 December would end up here\n NewString = \"Invalid date\"\nEnd If\n"
},
{
"answer_id": 62530580,
"author": "Miguel",
"author_id": 10343244,
"author_profile": "https://Stackoverflow.com/users/10343244",
"pm_score": 0,
"selected": false,
"text": "function MyDateFormat(mydate)\n 'format: YYYYMMDDHHMMSS\n MyDateFormat = year(mydate) & right(\"0\" & month(mydate),2) & _\n right(\"0\" & day(mydate),2) & right(\"0\" & hour(mydate),2) &_\n right(\"0\" & minute(mydate),2) & right(\"0\" & second(mydate),2)\nend function\n\nresponse.write(MyDateFormat(Now))\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/91734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5703/"
] |
91,745
|
<p>I am building a table using the DataGridView where a user can select items from a dropdown in each cell. To simplify the problem, lets say i have 1 column. I am using the DataGridViewComboBoxColumn in the designer. I am trying to support having each row in that column have a different list of items to choose from.</p>
<p>Is this possible?</p>
|
[
{
"answer_id": 163247,
"author": "WaterBoy",
"author_id": 3270,
"author_profile": "https://Stackoverflow.com/users/3270",
"pm_score": 5,
"selected": true,
"text": "private void setCellComboBoxItems(DataGridView dataGrid, int rowIndex, int colIndex, object[] itemsToAdd)\n{\n DataGridViewComboBoxCell dgvcbc = (DataGridViewComboBoxCell) dataGrid.Rows[rowIndex].Cells[colIndex];\n // You might pass a boolean to determine whether to clear or not.\n dgvcbc.Items.Clear();\n foreach (object itemToAdd in itemsToAdd)\n {\n dgvcbc.Items.Add(itemToAdd);\n }\n}\n"
},
{
"answer_id": 1641437,
"author": "Steve",
"author_id": 198620,
"author_profile": "https://Stackoverflow.com/users/198620",
"pm_score": 2,
"selected": false,
"text": "private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)\n{\n if (e.ColumnIndex == DataGridViewComboBoxColumnNumber)\n {\n setCellComboBoxItems(myDataGridView, e.RowIndex, e.ColumnIndex, someObj);\n }\n}\n"
},
{
"answer_id": 8879383,
"author": "Jay",
"author_id": 1151740,
"author_profile": "https://Stackoverflow.com/users/1151740",
"pm_score": 1,
"selected": false,
"text": " Private Sub FillGroups()\n Try\n 'Create Connection and SQLCommand here.\n\n Conn.Open()\n Dim dr As SqlDataReader = cm.ExecuteReader\n\n dgvGroups.Rows.Clear()\n\n Dim PreviousGroup As String = \"\"\n\n Dim l As New List(Of Groups)\n\n While dr.Read\n\n Dim g As New Groups\n g.RegionID = CheckInt(dr(\"cg_id\"))\n g.RegionName = CheckString(dr(\"cg_name\"))\n g.GroupID = CheckInt(dr(\"vg_id\"))\n g.GroupName = CheckString(dr(\"vg_name\"))\n l.Add(g)\n\n End While\n dr.Close()\n Conn.Close()\n\n For Each a In (From r In l Select r.RegionName, r.RegionID).Distinct\n\n Dim RegionID As Integer = a.RegionID 'Doing it this way avoids a warning\n\n dgvGroups.Rows.Add(New Object() {a.RegionID, a.RegionName})\n\n Dim c As DataGridViewComboBoxCell = CType(dgvGroups.Rows(dgvGroups.RowCount - 1).Cells(colGroup.Index), DataGridViewComboBoxCell)\n c.DataSource = (From g In l Where g.RegionID = RegionID Select g.GroupID, g.GroupName).ToArray\n c.DisplayMember = \"GroupName\"\n c.ValueMember = \"GroupID\"\n Next\n\n Catch ex As Exception\n End Try\nEnd Sub\n\nPrivate Class Groups\n\n Private _RegionID As Integer\n Public Property RegionID() As Integer\n Get\n Return _RegionID\n End Get\n Set(ByVal value As Integer)\n _RegionID = value\n End Set\n End Property\n\n Private _RegionName As String\n Public Property RegionName() As String\n Get\n Return _RegionName\n End Get\n Set(ByVal value As String)\n _RegionName = value\n End Set\n End Property\n\n Private _GroupName As String\n Public Property GroupName() As String\n Get\n Return _GroupName\n End Get\n Set(ByVal value As String)\n _GroupName = value\n End Set\n End Property\n\n Private _GroupID As Integer\n Public Property GroupID() As Integer\n Get \n Return _GroupID\n End Get\n Set(ByVal value As Integer)\n _GroupID = value\n End Set\n End Property\n\nEnd Class\n"
},
{
"answer_id": 35395898,
"author": "Ahmed Soliman",
"author_id": 4334304,
"author_profile": "https://Stackoverflow.com/users/4334304",
"pm_score": 0,
"selected": false,
"text": " private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)\n {\n if (dataGridView1.Rows[e.RowIndex].Cells[0].Value != null && dataGridView1.CurrentCell.ColumnIndex == 0)\n {\n\n SqlConnection conn = new SqlConnection(\"data source=.;initial catalog=pharmacy;integrated security=true\");\n SqlCommand cmd = new SqlCommand(\"select [drugTypeParent],[drugTypeChild] from [drugs] where [drugName]='\" + dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString() + \"'\", conn);\n conn.Open();\n SqlDataReader dr = cmd.ExecuteReader();\n while (dr.Read())\n {\n\n object[] o = new object[] { dr[0].ToString(),dr[1].ToString() };\n DataGridViewComboBoxCell dgvcbc = (DataGridViewComboBoxCell)dataGridView1.Rows[e.RowIndex].Cells[1];\n\n dgvcbc.Items.Clear();\n foreach (object itemToAdd in o)\n {\n dgvcbc.Items.Add(itemToAdd);\n }\n }\n dr.Close();\n conn.Close();\n }\n }\n"
},
{
"answer_id": 37096974,
"author": "jock mcspiffy",
"author_id": 6305941,
"author_profile": "https://Stackoverflow.com/users/6305941",
"pm_score": -1,
"selected": false,
"text": " //Populate the Datatable with the Lookup lists\n private DataTable typeDataTable(DataGridView dataGridView, Lookup<string, Element> type_Lookup, Dictionary<Element, string> type_dictionary, string strNewStyle, string strOldStyle, string strID, string strCount)\n {\n int row = 0;\n\n DataTable dt = new DataTable();\n\n dt.Columns.Add(strOldStyle, typeof(string));\n dt.Columns.Add(strID, typeof(string));\n dt.Columns.Add(strCount, typeof(int));\n dt.Columns.Add(\"combobox\", typeof(DataGridViewComboBoxCell));\n\n\n\n //Add All Doc Types to ComboBoxes\n DataGridViewComboBoxCell CmBx = new DataGridViewComboBoxCell();\n CmBx.DataSource = new BindingSource(type_dictionary, null);\n CmBx.DisplayMember = \"Value\";\n CmBx.ValueMember = \"Key\";\n\n\n //Add Style Comboboxes\n DataGridViewComboBoxColumn Data_CmBx_Col = new DataGridViewComboBoxColumn();\n Data_CmBx_Col.HeaderText = strNewStyle;\n dataGridView.Columns.Add(addDataGrdViewComboBox(Data_CmBx_Col, type_dictionary));\n\n setCellComboBoxItems(dataGridView, 1, 3, CmBx);\n\n //Add style Rows\n foreach (IGrouping<string, Element> StyleGroup in type_Lookup)\n {\n row++;\n //Iterate through each group in the Igrouping\n //Add Style Rows\n dt.Rows.Add(StyleGroup.Key, row, StyleGroup.Count().ToString());\n\n\n }\n return dt;\n }\n\n\n\n\n private void setCellComboBoxItems(DataGridView dataGrid, int rowIndex, int colIndex, DataGridViewComboBoxCell CmBx)\n {\n DataGridViewComboBoxCell dgvcbc = (DataGridViewComboBoxCell)dataGrid.Rows[rowIndex].Cells[colIndex];\n // You might pass a boolean to determine whether to clear or not.\n dgvcbc.Items.Clear();\n foreach (DataGridViewComboBoxCell itemToAdd in CmBx.Items)\n {\n dgvcbc.Items.Add(itemToAdd);\n }\n"
},
{
"answer_id": 53238441,
"author": "bh_earth0",
"author_id": 3137362,
"author_profile": "https://Stackoverflow.com/users/3137362",
"pm_score": 0,
"selected": false,
"text": "dgv1.datasource = datatable1;\ndgv1.columns.add ( \"cbxcol\" , typeof(string) );\n\n// different source for each comboboxcell in rows\nvar dict_rowInd_cbxDs = new Dictionary<int, object>();\ndict_rowInd_cbxDs[1] = new list<string>(){\"en\" , \"us\"};\ndict_rowInd_cbxDs[2] = new list<string>(){ \"car\", \"bike\"};\n\n// !!!!!! setting comboboxcell after creating doesnt work here\nforeach( row in dgv.Rows.asEnumerable() )\n{ \n var cell = res_tn.dgv.CurrentCell as DataGridViewComboBoxCell;\n cell.DataSource = dict_dgvRowI_cbxDs[res_tn.dgv.CurrentCell.RowIndex];\n\n}\n dgv1.datasource = datatable1;\ndgv1.columns.add ( \"cbxcol\" , typeof(string) );\n\n// different source for each comboboxcell in rows\nvar dict_rowInd_cbxDs = new Dictionary<int, object>();\ndict_rowInd_cbxDs[1] = new list<string>(){\"en\" , \"us\"};\ndict_rowInd_cbxDs[2] = new list<string>(){ \"car\", \"bike\"};\n\n\n// cmboboxcell datasource Assingment Must be done after BindingComplete (not tested ) or cellbeginEdit (tested by me) \nres_tn.dgv.CellBeginEdit += (s1, e1) => {\n if (res_tn.dgv.CurrentCell is DataGridViewComboBoxCell) {\n if (dict_dgvRowI_cbxDs.ContainsKey(res_tn.dgv.CurrentCell.RowIndex)) \n {\n var cll = res_tn.dgv.CurrentCell as DataGridViewComboBoxCell;\n cll.DataSource = dict_dgvRowI_cbxDs[res_tn.dgv.CurrentCell.RowIndex];\n\n // required if it is list<mycustomClass>\n // cll.DisplayMember = \"ColName\";\n // cll.ValueMember = \"This\";\n }\n }\n\n};\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/91745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] |
91,747
|
<p>How can I set the background color of a specific item in a <em>System.Windows.Forms.ListBox</em>?</p>
<p>I would like to be able to set multiple ones if possible.</p>
|
[
{
"answer_id": 91758,
"author": "Grad van Horck",
"author_id": 12569,
"author_profile": "https://Stackoverflow.com/users/12569",
"pm_score": 7,
"selected": true,
"text": "DrawMode OwnerDrawFixed private void listBox_DrawItem(object sender, DrawItemEventArgs e)\n{\n e.DrawBackground();\n Graphics g = e.Graphics;\n\n g.FillRectangle(new SolidBrush(Color.Silver), e.Bounds);\n\n // Print text\n\n e.DrawFocusRectangle();\n}\n"
},
{
"answer_id": 91770,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 2,
"selected": false,
"text": "// Set the background to a predefined colour\nMyListBox.BackColor = Color.Red;\n// OR: Set parts of a color.\nMyListBox.BackColor.R = 255;\nMyListBox.BackColor.G = 0;\nMyListBox.BackColor.B = 0;\n // Set the background of the first item in the list\nMyListView.Items[0].BackColor = Color.Red;\n"
},
{
"answer_id": 3709452,
"author": "Shadow The Kid Wizard",
"author_id": 447356,
"author_profile": "https://Stackoverflow.com/users/447356",
"pm_score": 6,
"selected": false,
"text": "//global brushes with ordinary/selected colors\nprivate SolidBrush reportsForegroundBrushSelected = new SolidBrush(Color.White);\nprivate SolidBrush reportsForegroundBrush = new SolidBrush(Color.Black);\nprivate SolidBrush reportsBackgroundBrushSelected = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));\nprivate SolidBrush reportsBackgroundBrush1 = new SolidBrush(Color.White);\nprivate SolidBrush reportsBackgroundBrush2 = new SolidBrush(Color.Gray);\n\n//custom method to draw the items, don't forget to set DrawMode of the ListBox to OwnerDrawFixed\nprivate void lbReports_DrawItem(object sender, DrawItemEventArgs e)\n{\n e.DrawBackground();\n bool selected = ((e.State & DrawItemState.Selected) == DrawItemState.Selected);\n\n int index = e.Index;\n if (index >= 0 && index < lbReports.Items.Count)\n {\n string text = lbReports.Items[index].ToString();\n Graphics g = e.Graphics;\n\n //background:\n SolidBrush backgroundBrush;\n if (selected)\n backgroundBrush = reportsBackgroundBrushSelected;\n else if ((index % 2) == 0)\n backgroundBrush = reportsBackgroundBrush1;\n else\n backgroundBrush = reportsBackgroundBrush2;\n g.FillRectangle(backgroundBrush, e.Bounds);\n\n //text:\n SolidBrush foregroundBrush = (selected) ? reportsForegroundBrushSelected : reportsForegroundBrush;\n g.DrawString(text, e.Font, foregroundBrush, lbReports.GetItemRectangle(index).Location);\n }\n\n e.DrawFocusRectangle();\n}\n"
},
{
"answer_id": 41631585,
"author": "Serdar Karaca",
"author_id": 2920105,
"author_profile": "https://Stackoverflow.com/users/2920105",
"pm_score": -1,
"selected": false,
"text": "public MainForm()\n{\n InitializeComponent();\n this.listbox1.DrawItem += new DrawItemEventHandler(this.listbox1_DrawItem);\n}\n\nprivate void listbox1_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)\n{\n e.DrawBackground();\n Brush myBrush = Brushes.Black;\n var item = listbox1.Items[e.Index];\n if(e.Index % 2 == 0)\n {\n e.Graphics.FillRectangle(new SolidBrush(Color.Gold), e.Bounds);\n }\n e.Graphics.DrawString(((ListBox)sender).Items[e.Index].ToString(), \n e.Font, myBrush,e.Bounds, StringFormat.GenericDefault);\n e.DrawFocusRectangle();\n }\n}\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/91747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11137/"
] |
91,766
|
<p>I have a DataGrid where each column has a SortExpression. I would like the sort expression to be the equivalent of "ORDER BY LEN(myField)".</p>
<p>I have tried </p>
<pre><code>SortExpression="LEN(myField)"
</code></pre>
<p>but this throws an exception as it is not valid syntax. Any ideas?</p>
|
[
{
"answer_id": 91806,
"author": "Ilya Kochetov",
"author_id": 15329,
"author_profile": "https://Stackoverflow.com/users/15329",
"pm_score": 2,
"selected": false,
"text": "SELECT\n ColumnA as FieldA\n , ColumnB as FieldB\n , LEN(ColumnA) as FieldL\nFROM TableName\nORDER BY L\n SortExpression=\"FieldL\"\n"
},
{
"answer_id": 91815,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 0,
"selected": false,
"text": "SortExpression DataType"
},
{
"answer_id": 94077,
"author": "Adam Vigh",
"author_id": 1613872,
"author_profile": "https://Stackoverflow.com/users/1613872",
"pm_score": 0,
"selected": false,
"text": "query.OrderBy(column => column.MyField.Length);\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/91766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15393/"
] |
91,778
|
<p>To create a new event handler on a control you can do this</p>
<pre><code>c.Click += new EventHandler(mainFormButton_Click);
</code></pre>
<p>or this</p>
<pre><code>c.Click += mainFormButton_Click;
</code></pre>
<p>and to remove an event handler you can do this</p>
<pre><code>c.Click -= mainFormButton_Click;
</code></pre>
<p>But how do you remove all event handlers from an event?</p>
|
[
{
"answer_id": 91803,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 6,
"selected": false,
"text": "List<EventHandler> delegates = new List<EventHandler>();\n\nprivate event EventHandler MyRealEvent;\n\npublic event EventHandler MyEvent\n{\n add\n {\n MyRealEvent += value;\n delegates.Add(value);\n }\n\n remove\n {\n MyRealEvent -= value;\n delegates.Remove(value);\n }\n}\n\npublic void RemoveAllEvents()\n{\n foreach(EventHandler eh in delegates)\n {\n MyRealEvent -= eh;\n }\n delegates.Clear();\n}\n"
},
{
"answer_id": 91853,
"author": "xsl",
"author_id": 11387,
"author_profile": "https://Stackoverflow.com/users/11387",
"pm_score": 9,
"selected": true,
"text": "Click button1 public partial class Form1 : Form\n{\n public Form1()\n {\n InitializeComponent();\n\n button1.Click += button1_Click;\n button1.Click += button1_Click2;\n button2.Click += button2_Click;\n }\n\n private void button1_Click(object sender, EventArgs e) => MessageBox.Show(\"Hello\");\n private void button1_Click2(object sender, EventArgs e) => MessageBox.Show(\"World\");\n private void button2_Click(object sender, EventArgs e) => RemoveClickEvent(button1);\n\n private void RemoveClickEvent(Button b)\n {\n FieldInfo f1 = typeof(Control).GetField(\"EventClick\", \n BindingFlags.Static | BindingFlags.NonPublic);\n\n object obj = f1.GetValue(b);\n PropertyInfo pi = b.GetType().GetProperty(\"Events\", \n BindingFlags.NonPublic | BindingFlags.Instance);\n\n EventHandlerList list = (EventHandlerList)pi.GetValue(b, null);\n list.RemoveHandler(obj, list[obj]);\n }\n}\n"
},
{
"answer_id": 1032221,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "// Add handlers...\nif (something)\n{\n c.Click += DoesSomething;\n}\nelse\n{\n c.Click += DoesSomethingElse;\n}\n\n// Remove handlers...\nc.Click -= DoesSomething;\nc.Click -= DoesSomethingElse;\n"
},
{
"answer_id": 1597332,
"author": "SwDevMan81",
"author_id": 95573,
"author_profile": "https://Stackoverflow.com/users/95573",
"pm_score": 2,
"selected": false,
"text": "namespace CMessWin05\n{\n public class EventSuppressor\n {\n Control _source;\n EventHandlerList _sourceEventHandlerList;\n FieldInfo _headFI;\n Dictionary<object, Delegate[]> _handlers;\n PropertyInfo _sourceEventsInfo;\n Type _eventHandlerListType;\n Type _sourceType;\n\n\n public EventSuppressor(Control control)\n {\n if (control == null)\n throw new ArgumentNullException(\"control\", \"An instance of a control must be provided.\");\n\n _source = control;\n _sourceType = _source.GetType();\n _sourceEventsInfo = _sourceType.GetProperty(\"Events\", BindingFlags.Instance | BindingFlags.NonPublic);\n _sourceEventHandlerList = (EventHandlerList)_sourceEventsInfo.GetValue(_source, null);\n _eventHandlerListType = _sourceEventHandlerList.GetType();\n _headFI = _eventHandlerListType.GetField(\"head\", BindingFlags.Instance | BindingFlags.NonPublic);\n }\n\n private void BuildList()\n {\n _handlers = new Dictionary<object, Delegate[]>();\n object head = _headFI.GetValue(_sourceEventHandlerList);\n if (head != null)\n {\n Type listEntryType = head.GetType();\n FieldInfo delegateFI = listEntryType.GetField(\"handler\", BindingFlags.Instance | BindingFlags.NonPublic);\n FieldInfo keyFI = listEntryType.GetField(\"key\", BindingFlags.Instance | BindingFlags.NonPublic);\n FieldInfo nextFI = listEntryType.GetField(\"next\", BindingFlags.Instance | BindingFlags.NonPublic);\n BuildListWalk(head, delegateFI, keyFI, nextFI);\n }\n }\n\n private void BuildListWalk(object entry, FieldInfo delegateFI, FieldInfo keyFI, FieldInfo nextFI)\n {\n if (entry != null)\n {\n Delegate dele = (Delegate)delegateFI.GetValue(entry);\n object key = keyFI.GetValue(entry);\n object next = nextFI.GetValue(entry);\n\n Delegate[] listeners = dele.GetInvocationList();\n if(listeners != null && listeners.Length > 0)\n _handlers.Add(key, listeners);\n\n if (next != null)\n {\n BuildListWalk(next, delegateFI, keyFI, nextFI);\n }\n }\n }\n\n public void Resume()\n {\n if (_handlers == null)\n throw new ApplicationException(\"Events have not been suppressed.\");\n\n foreach (KeyValuePair<object, Delegate[]> pair in _handlers)\n {\n for (int x = 0; x < pair.Value.Length; x++)\n _sourceEventHandlerList.AddHandler(pair.Key, pair.Value[x]);\n }\n\n _handlers = null;\n }\n\n public void Suppress()\n {\n if (_handlers != null)\n throw new ApplicationException(\"Events are already being suppressed.\");\n\n BuildList();\n\n foreach (KeyValuePair<object, Delegate[]> pair in _handlers)\n {\n for (int x = pair.Value.Length - 1; x >= 0; x--)\n _sourceEventHandlerList.RemoveHandler(pair.Key, pair.Value[x]);\n }\n }\n\n }\n}\n"
},
{
"answer_id": 2382433,
"author": "Francine",
"author_id": 286592,
"author_profile": "https://Stackoverflow.com/users/286592",
"pm_score": -1,
"selected": false,
"text": "// This class allows you to selectively suppress event handlers for controls. You instantiate\n// the suppressor object with the control, and after that you can use it to suppress all events\n// or a single event. If you try to suppress an event which has already been suppressed\n// it will be ignored. Same with resuming; you can resume all events which were suppressed,\n// or a single one. If you try to resume an un-suppressed event handler, it will be ignored.\n\n//cEventSuppressor _supButton1 = null;\n//private cEventSuppressor SupButton1 {\n// get {\n// if (_supButton1 == null) {\n// _supButton1 = new cEventSuppressor(this.button1);\n// }\n// return _supButton1;\n// }\n//}\n//private void button1_Click(object sender, EventArgs e) {\n// MessageBox.Show(\"Clicked!\");\n//}\n\n//private void button2_Click(object sender, EventArgs e) {\n// SupButton1.Suppress(\"button1_Click\");\n//}\n\n//private void button3_Click(object sender, EventArgs e) {\n// SupButton1.Resume(\"button1_Click\");\n//}\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\n\nusing System.Reflection;\nusing System.Windows.Forms;\nusing System.ComponentModel;\n\nnamespace Crystal.Utilities {\n public class cEventSuppressor {\n Control _source;\n EventHandlerList _sourceEventHandlerList;\n FieldInfo _headFI;\n Dictionary<object, Delegate[]> suppressedHandlers = new Dictionary<object, Delegate[]>();\n PropertyInfo _sourceEventsInfo;\n Type _eventHandlerListType;\n Type _sourceType;\n\n public cEventSuppressor(Control control) {\n if (control == null)\n throw new ArgumentNullException(\"control\", \"An instance of a control must be provided.\");\n\n _source = control;\n _sourceType = _source.GetType();\n _sourceEventsInfo = _sourceType.GetProperty(\"Events\", BindingFlags.Instance | BindingFlags.NonPublic);\n _sourceEventHandlerList = (EventHandlerList)_sourceEventsInfo.GetValue(_source, null);\n _eventHandlerListType = _sourceEventHandlerList.GetType();\n _headFI = _eventHandlerListType.GetField(\"head\", BindingFlags.Instance | BindingFlags.NonPublic);\n }\n private Dictionary<object, Delegate[]> BuildList() {\n Dictionary<object, Delegate[]> retval = new Dictionary<object, Delegate[]>();\n object head = _headFI.GetValue(_sourceEventHandlerList);\n if (head != null) {\n Type listEntryType = head.GetType();\n FieldInfo delegateFI = listEntryType.GetField(\"handler\", BindingFlags.Instance | BindingFlags.NonPublic);\n FieldInfo keyFI = listEntryType.GetField(\"key\", BindingFlags.Instance | BindingFlags.NonPublic);\n FieldInfo nextFI = listEntryType.GetField(\"next\", BindingFlags.Instance | BindingFlags.NonPublic);\n retval = BuildListWalk(retval, head, delegateFI, keyFI, nextFI);\n }\n return retval;\n }\n\n private Dictionary<object, Delegate[]> BuildListWalk(Dictionary<object, Delegate[]> dict,\n object entry, FieldInfo delegateFI, FieldInfo keyFI, FieldInfo nextFI) {\n if (entry != null) {\n Delegate dele = (Delegate)delegateFI.GetValue(entry);\n object key = keyFI.GetValue(entry);\n object next = nextFI.GetValue(entry);\n\n if (dele != null) {\n Delegate[] listeners = dele.GetInvocationList();\n if (listeners != null && listeners.Length > 0) {\n dict.Add(key, listeners);\n }\n }\n if (next != null) {\n dict = BuildListWalk(dict, next, delegateFI, keyFI, nextFI);\n }\n }\n return dict;\n }\n public void Resume() {\n }\n public void Resume(string pMethodName) {\n //if (_handlers == null)\n // throw new ApplicationException(\"Events have not been suppressed.\");\n Dictionary<object, Delegate[]> toRemove = new Dictionary<object, Delegate[]>();\n\n // goes through all handlers which have been suppressed. If we are resuming,\n // all handlers, or if we find the matching handler, add it back to the\n // control's event handlers\n foreach (KeyValuePair<object, Delegate[]> pair in suppressedHandlers) {\n\n for (int x = 0; x < pair.Value.Length; x++) {\n\n string methodName = pair.Value[x].Method.Name;\n if (pMethodName == null || methodName.Equals(pMethodName)) {\n _sourceEventHandlerList.AddHandler(pair.Key, pair.Value[x]);\n toRemove.Add(pair.Key, pair.Value);\n }\n }\n }\n // remove all un-suppressed handlers from the list of suppressed handlers\n foreach (KeyValuePair<object, Delegate[]> pair in toRemove) {\n for (int x = 0; x < pair.Value.Length; x++) {\n suppressedHandlers.Remove(pair.Key);\n }\n }\n //_handlers = null;\n }\n public void Suppress() {\n Suppress(null);\n }\n public void Suppress(string pMethodName) {\n //if (_handlers != null)\n // throw new ApplicationException(\"Events are already being suppressed.\");\n\n Dictionary<object, Delegate[]> dict = BuildList();\n\n foreach (KeyValuePair<object, Delegate[]> pair in dict) {\n for (int x = pair.Value.Length - 1; x >= 0; x--) {\n //MethodInfo mi = pair.Value[x].Method;\n //string s1 = mi.Name; // name of the method\n //object o = pair.Value[x].Target;\n // can use this to invoke method pair.Value[x].DynamicInvoke\n string methodName = pair.Value[x].Method.Name;\n\n if (pMethodName == null || methodName.Equals(pMethodName)) {\n _sourceEventHandlerList.RemoveHandler(pair.Key, pair.Value[x]);\n suppressedHandlers.Add(pair.Key, pair.Value);\n }\n }\n }\n }\n } \n}\n"
},
{
"answer_id": 4352051,
"author": "Ivan Ferrer Villa",
"author_id": 382515,
"author_profile": "https://Stackoverflow.com/users/382515",
"pm_score": 4,
"selected": false,
"text": "\n Public Event MyEvent()\n Protected Overrides Sub Dispose(ByVal disposing As Boolean)\n If MyEventEvent IsNot Nothing Then\n For Each d In MyEventEvent.GetInvocationList ' If this throws an exception, try using .ToArray\n RemoveHandler MyEvent, d\n Next\n End If\n End Sub\n ~MyClass()\n {\n if (MyEventEvent != null)\n {\n foreach (var d in MyEventEvent.GetInvocationList())\n {\n MyEventEvent -= (MyEvent)d;\n }\n }\n\n }\n d.target d.method"
},
{
"answer_id": 5475424,
"author": "Stephen Punak",
"author_id": 682408,
"author_profile": "https://Stackoverflow.com/users/682408",
"pm_score": 8,
"selected": false,
"text": "void OnFormClosing(object sender, FormClosingEventArgs e)\n{\n foreach(Delegate d in FindClicked.GetInvocationList())\n {\n FindClicked -= (FindClickedHandler)d;\n }\n}\n"
},
{
"answer_id": 5536365,
"author": "Anoop Muraleedharan",
"author_id": 690767,
"author_profile": "https://Stackoverflow.com/users/690767",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Drawing;\nusing System.Windows.Forms;\nusing System.Reflection;\npublic static class EventExtension\n{\n public static void RemoveEvents<T>(this T target, string eventName) where T:Control\n {\n if (ReferenceEquals(target, null)) throw new NullReferenceException(\"Argument \\\"target\\\" may not be null.\");\n FieldInfo fieldInfo = typeof(Control).GetField(eventName, BindingFlags.Static | BindingFlags.NonPublic);\n if (ReferenceEquals(fieldInfo, null)) throw new ArgumentException(\n string.Concat(\"The control \", typeof(T).Name, \" does not have a property with the name \\\"\", eventName, \"\\\"\"), nameof(eventName));\n object eventInstance = fieldInfo.GetValue(target);\n PropertyInfo propInfo = typeof(T).GetProperty(\"Events\", BindingFlags.NonPublic | BindingFlags.Instance);\n EventHandlerList list = (EventHandlerList)propInfo.GetValue(target, null);\n list.RemoveHandler(eventInstance, list[eventInstance]);\n }\n}\n Button button = new Button();\nbutton.RemoveEvents(nameof(button.EventClick));\n Panel panel = new Panel();\npanel.RemoveEvents(nameof(panel.EventDoubleClick));\n"
},
{
"answer_id": 5754729,
"author": "mmike",
"author_id": 720423,
"author_profile": "https://Stackoverflow.com/users/720423",
"pm_score": 2,
"selected": false,
"text": "public event EventHandler<Cles_graph_doivent_etre_redessines> les_graph_doivent_etre_redessines;\npublic void remove_event()\n{\n if (this.les_graph_doivent_etre_redessines != null)\n {\n foreach (EventHandler<Cles_graph_doivent_etre_redessines> F_les_graph_doivent_etre_redessines in this.les_graph_doivent_etre_redessines.GetInvocationList())\n {\n this.les_graph_doivent_etre_redessines -= F_les_graph_doivent_etre_redessines;\n }\n }\n}\n"
},
{
"answer_id": 7899618,
"author": "suso",
"author_id": 567562,
"author_profile": "https://Stackoverflow.com/users/567562",
"pm_score": -1,
"selected": false,
"text": "EventDescriptor ed = TypeDescriptor.GetEvents(this.button1).Find(\"MouseDown\",true); \nDelegate delegate = Delegate.CreateDelegate(typeof(EventHandler), this, \"button1_MouseDownClicked\");\nif(ed!=null) \n ed.RemoveEventHandler(this.button1, delegate);\n"
},
{
"answer_id": 8108103,
"author": "LionSoft",
"author_id": 301257,
"author_profile": "https://Stackoverflow.com/users/301257",
"pm_score": 6,
"selected": false,
"text": "public static void ClearEventInvocations(this object obj, string eventName)\n{\n var fi = obj.GetType().GetEventField(eventName);\n if (fi == null) return;\n fi.SetValue(obj, null);\n}\n\nprivate static FieldInfo GetEventField(this Type type, string eventName)\n{\n FieldInfo field = null;\n while (type != null)\n {\n /* Find events defined as field */\n field = type.GetField(eventName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic);\n if (field != null && (field.FieldType == typeof(MulticastDelegate) || field.FieldType.IsSubclassOf(typeof(MulticastDelegate))))\n break;\n\n /* Find events defined as property { add; remove; } */\n field = type.GetField(\"EVENT_\" + eventName.ToUpper(), BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic);\n if (field != null)\n break;\n type = type.BaseType;\n }\n return field;\n}\n"
},
{
"answer_id": 11688939,
"author": "Sergio Cabral",
"author_id": 1396511,
"author_profile": "https://Stackoverflow.com/users/1396511",
"pm_score": 1,
"selected": false,
"text": "EventHandlerList listaEventos;\n\nprivate void btnDetach_Click(object sender, EventArgs e)\n{\n listaEventos = DetachEvents(comboBox1);\n}\n\nprivate void btnAttach_Click(object sender, EventArgs e)\n{\n AttachEvents(comboBox1, listaEventos);\n}\n\npublic EventHandlerList DetachEvents(Component obj)\n{\n object objNew = obj.GetType().GetConstructor(new Type[] { }).Invoke(new object[] { });\n PropertyInfo propEvents = obj.GetType().GetProperty(\"Events\", BindingFlags.NonPublic | BindingFlags.Instance);\n\n EventHandlerList eventHandlerList_obj = (EventHandlerList)propEvents.GetValue(obj, null);\n EventHandlerList eventHandlerList_objNew = (EventHandlerList)propEvents.GetValue(objNew, null);\n\n eventHandlerList_objNew.AddHandlers(eventHandlerList_obj);\n eventHandlerList_obj.Dispose();\n\n return eventHandlerList_objNew;\n}\n\npublic void AttachEvents(Component obj, EventHandlerList eventos)\n{\n PropertyInfo propEvents = obj.GetType().GetProperty(\"Events\", BindingFlags.NonPublic | BindingFlags.Instance);\n\n EventHandlerList eventHandlerList_obj = (EventHandlerList)propEvents.GetValue(obj, null);\n\n eventHandlerList_obj.AddHandlers(eventos);\n}\n"
},
{
"answer_id": 31114831,
"author": "RenniePet",
"author_id": 253938,
"author_profile": "https://Stackoverflow.com/users/253938",
"pm_score": -1,
"selected": false,
"text": " /// <summary>\n /// Method to remove a (single) SocketAsyncEventArgs.Completed event handler. This is \n /// partially based on information found here: http://stackoverflow.com/a/91853/253938\n /// \n /// But note that this may not be a good idea, being very .Net implementation-dependent. Note \n /// in particular use of \"m_Completed\" instead of \"Completed\".\n /// </summary>\n private static void RemoveCompletedEventHandler(SocketAsyncEventArgs eventArgs)\n {\n FieldInfo fieldInfo = typeof(SocketAsyncEventArgs).GetField(\"m_Completed\", \n BindingFlags.Instance | BindingFlags.NonPublic);\n eventArgs.Completed -= (EventHandler<SocketAsyncEventArgs>)fieldInfo.GetValue(eventArgs);\n }\n"
},
{
"answer_id": 38506787,
"author": "Vinicius Schneider",
"author_id": 6605414,
"author_profile": "https://Stackoverflow.com/users/6605414",
"pm_score": 4,
"selected": false,
"text": "public class MyMain()\n public void MyMethod() {\n AnotherClass.TheEventHandler += DoSomeThing;\n }\n\n private void DoSomething(object sender, EventArgs e) {\n Debug.WriteLine(\"I did something\");\n AnotherClass.ClearAllDelegatesOfTheEventHandler();\n }\n\n}\n\npublic static class AnotherClass {\n\n public static event EventHandler TheEventHandler;\n\n public static void ClearAllDelegatesOfTheEventHandler() {\n\n foreach (Delegate d in TheEventHandler.GetInvocationList())\n {\n TheEventHandler -= (EventHandler)d;\n }\n }\n}\n"
},
{
"answer_id": 39537438,
"author": "Jhonattan",
"author_id": 2766725,
"author_profile": "https://Stackoverflow.com/users/2766725",
"pm_score": 0,
"selected": false,
"text": " public static void RemoveItemEvents<T>(this T target, string eventName) \n where T : ToolStripItem\n { \n RemoveObjectEvents<T>(target, eventName);\n }\n\n public static void RemoveControlEvents<T>(this T target, string eventName)\n where T : Control\n {\n RemoveObjectEvents<T>(target, eventName);\n }\n\n private static void RemoveObjectEvents<T>(T target, string Event) where T : class\n {\n var typeOfT = typeof(T);\n var fieldInfo = typeOfT.BaseType.GetField(\n Event, BindingFlags.Static | BindingFlags.NonPublic);\n var provertyValue = fieldInfo.GetValue(target);\n var propertyInfo = typeOfT.GetProperty(\n \"Events\", BindingFlags.NonPublic | BindingFlags.Instance);\n var eventHandlerList = (EventHandlerList)propertyInfo.GetValue(target, null);\n eventHandlerList.RemoveHandler(provertyValue, eventHandlerList[provertyValue]);\n }\n var toolStripButton = new ToolStripButton();\n toolStripButton.RemoveItemEvents(\"EventClick\");\n\n var button = new Button();\n button.RemoveControlEvents(\"EventClick\");\n"
},
{
"answer_id": 60286642,
"author": "Anatoliy",
"author_id": 1847209,
"author_profile": "https://Stackoverflow.com/users/1847209",
"pm_score": 0,
"selected": false,
"text": "public static class EventExtension\n{\n public static void RemoveEvents<T>(this T target) where T : Control\n {\n var propInfo = typeof(T).GetProperty(\"Events\", BindingFlags.NonPublic | BindingFlags.Instance);\n var list = (EventHandlerList)propInfo.GetValue(target, null);\n list.Dispose();\n }\n}\n"
},
{
"answer_id": 66956934,
"author": "Vassili",
"author_id": 6741458,
"author_profile": "https://Stackoverflow.com/users/6741458",
"pm_score": 1,
"selected": false,
"text": " static Dictionary<Type, List<FieldInfo>> dicEventFieldInfos = new Dictionary<Type, List<FieldInfo>>();\n\n static BindingFlags AllBindings\n {\n get { return BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; }\n }\n\n static void BuildEventFields(Type t, List<FieldInfo> lst)\n {\n foreach (EventInfo ei in t.GetEvents(AllBindings))\n {\n Type dt = ei.DeclaringType;\n FieldInfo fi = dt.GetField(ei.Name, AllBindings);\n if (fi != null)\n lst.Add(fi);\n }\n }\n static List<FieldInfo> GetTypeEventFields(Type t)\n {\n if (dicEventFieldInfos.ContainsKey(t))\n return dicEventFieldInfos[t];\n\n List<FieldInfo> lst = new List<FieldInfo>();\n BuildEventFields(t, lst);\n dicEventFieldInfos.Add(t, lst);\n return lst;\n }\n static EventHandlerList GetStaticEventHandlerList(Type t, object obj)\n {\n MethodInfo mi = t.GetMethod(\"get_Events\", AllBindings);\n return (EventHandlerList)mi.Invoke(obj, new object[] { });\n }\n public static void RemoveEventHandler(object obj, string EventName = \"\")\n {\n if (obj == null)\n return;\n\n Type t = obj.GetType();\n List<FieldInfo> event_fields = GetTypeEventFields(t);\n EventHandlerList static_event_handlers = null;\n\n foreach (FieldInfo fi in event_fields)\n {\n if (EventName != \"\" && string.Compare(EventName, fi.Name, true) != 0)\n continue;\n var eventName = fi.Name;\n // After hours and hours of research and trial and error, it turns out that\n // STATIC Events have to be treated differently from INSTANCE Events...\n if (fi.IsStatic)\n {\n // STATIC EVENT\n if (static_event_handlers == null)\n static_event_handlers = GetStaticEventHandlerList(t, obj);\n\n object idx = fi.GetValue(obj);\n Delegate eh = static_event_handlers[idx];\n if (eh == null)\n continue;\n\n Delegate[] dels = eh.GetInvocationList();\n if (dels == null)\n continue;\n\n EventInfo ei = t.GetEvent(eventName, AllBindings);\n foreach (Delegate del in dels)\n ei.RemoveEventHandler(obj, del);\n }\n else\n {\n // INSTANCE EVENT\n EventInfo ei = t.GetEvent(eventName, AllBindings);\n if (ei != null)\n {\n object val = fi.GetValue(obj);\n Delegate mdel = (val as Delegate);\n if (mdel != null)\n {\n foreach (Delegate del in mdel.GetInvocationList())\n {\n ei.RemoveEventHandler(obj, del);\n }\n }\n }\n }\n }\n }\n\n\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/91778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7297/"
] |
91,784
|
<p>I have a table with say 3 columns. There's no primary key so there can be duplicate rows. I need to just keep one and delete the others. Any idea how to do this is Sql Server?</p>
|
[
{
"answer_id": 91794,
"author": "Manrico Corazzi",
"author_id": 4690,
"author_profile": "https://Stackoverflow.com/users/4690",
"pm_score": 6,
"selected": true,
"text": "INSERT INTO TABLE_2 \nSELECT DISTINCT * FROM TABLE_1\nGO\nDELETE FROM TABLE_1\nGO\nINSERT INTO TABLE_1\nSELECT * FROM TABLE_2\nGO\n"
},
{
"answer_id": 91980,
"author": "Martin",
"author_id": 11357,
"author_profile": "https://Stackoverflow.com/users/11357",
"pm_score": 3,
"selected": false,
"text": "SELECT col1, col2, count(*)\nFROM t1\nGROUP BY col1, col2\nHAVING count(*) > 1\n set rowcount 1\ndelete from t1\nwhere col1=1 and col2=1\n SELECT col1, col2, col3=count(*)\nINTO holdkey\nFROM t1\nGROUP BY col1, col2\nHAVING count(*) > 1\n SELECT DISTINCT t1.*\nINTO holddups\nFROM t1, holdkey\nWHERE t1.col1 = holdkey.col1\nAND t1.col2 = holdkey.col2\n SELECT col1, col2, count(*)\nFROM holddups\nGROUP BY col1, col2\n DELETE t1\nFROM t1, holdkey\nWHERE t1.col1 = holdkey.col1\nAND t1.col2 = holdkey.col2\n INSERT t1 SELECT * FROM holddups\n DELETE FROM our_table\nWHERE rowid not in\n(SELECT MIN(rowid)\nFROM our_table\nGROUP BY column1, column2, column3... ;\n"
},
{
"answer_id": 92232,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": -1,
"selected": false,
"text": " SELECT *\n FROM myTable t1, myTable t2\n WHERE t1.field = t2.field AND t1.id > t2.id\n"
},
{
"answer_id": 93021,
"author": "Seibar",
"author_id": 357,
"author_profile": "https://Stackoverflow.com/users/357",
"pm_score": 2,
"selected": false,
"text": "DELETE MyTable \nFROM MyTable\nLEFT OUTER JOIN (\n SELECT MIN(RowId) as RowId, Col1, Col2, Col3 \n FROM MyTable \n GROUP BY Col1, Col2, Col3\n) as KeepRows ON\n MyTable.RowId = KeepRows.RowId\nWHERE\n KeepRows.RowId IS NULL\n"
},
{
"answer_id": 94915,
"author": "Dave Jackson",
"author_id": 12328,
"author_profile": "https://Stackoverflow.com/users/12328",
"pm_score": 0,
"selected": false,
"text": "create table #table1 (colWithDupes1 int, colWithDupes2 int)\ninsert into #table1\n(colWithDupes1, colWithDupes2)\nSelect 1, 2 union all\nSelect 1, 2 union all\nSelect 2, 2 union all\nSelect 3, 4 union all\nSelect 3, 4 union all\nSelect 3, 4 union all\nSelect 4, 2 union all\nSelect 4, 2 \n\n\nselect * from #table1\n\nset rowcount 1\nselect 1\n\nwhile @@rowcount > 0\ndelete #table1 where 1 < (select count(*) from #table1 a2 \n where #table1.colWithDupes1 = a2.colWithDupes1\nand #table1.colWithDupes2 = a2.colWithDupes2\n)\n\nset rowcount 0\n\nselect * from #table1\n"
},
{
"answer_id": 100117,
"author": "Jonas Lincoln",
"author_id": 17436,
"author_profile": "https://Stackoverflow.com/users/17436",
"pm_score": 2,
"selected": false,
"text": "CREATE TABLE #temp (i INT)\n\nINSERT INTO #temp VALUES (1)\nINSERT INTO #temp VALUES (1)\nINSERT INTO #temp VALUES (2)\nINSERT INTO #temp VALUES (3)\nINSERT INTO #temp VALUES (3)\nINSERT INTO #temp VALUES (4)\n\nSELECT * FROM #temp\n\n;\nWITH [#temp+rowid] AS\n(SELECT ROW_NUMBER() OVER (ORDER BY i ASC) AS ROWID, * FROM #temp)\nDELETE FROM [#temp+rowid] WHERE rowid IN \n(SELECT MIN(rowid) FROM [#temp+rowid] GROUP BY i HAVING COUNT(*) > 1)\n\nSELECT * FROM #temp\n\nDROP TABLE #temp \n"
},
{
"answer_id": 101985,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "select distinct * into #t from duplicates_tbl\n\ntruncate duplicates_tbl\n\ninsert duplicates_tbl select * from #t\n\ndrop table #t\n"
},
{
"answer_id": 603732,
"author": "Brann",
"author_id": 47341,
"author_profile": "https://Stackoverflow.com/users/47341",
"pm_score": 0,
"selected": false,
"text": " select 'set rowcount ' + convert(varchar,COUNT(*)-1) + ' delete from MyTable where field=''' + field +'''' + ' set rowcount 0' from mytable group by field having COUNT(*)>1\n set rowcount 3 delete from Mytable where field='foo' set rowcount 0\n....\n....\nset rowcount 5 delete from Mytable where field='bar' set rowcount 0\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/91784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1688440/"
] |
91,791
|
<p>When doing shell scripting, typically data will be in files of single line records like csv. It's really simple to handle this data with <code>grep</code> and <code>sed</code>. But I have to deal with XML often, so I'd really like a way to script access to that XML data via the command line. What are the best tools?</p>
|
[
{
"answer_id": 91801,
"author": "Joseph Holsten",
"author_id": 16981,
"author_profile": "https://Stackoverflow.com/users/16981",
"pm_score": 5,
"selected": false,
"text": "sggrep sgsort xmlnorm"
},
{
"answer_id": 609667,
"author": "bortzmeyer",
"author_id": 15625,
"author_profile": "https://Stackoverflow.com/users/15625",
"pm_score": 5,
"selected": false,
"text": " xpath -q -e '/entry[@xml:lang=\"fr\"]' *xml\n"
},
{
"answer_id": 3097477,
"author": "Vi.",
"author_id": 266720,
"author_profile": "https://Stackoverflow.com/users/266720",
"pm_score": 5,
"selected": false,
"text": "xml2 2xml <?xml version=\"1.0\"?>\n<foo>\n text\n more text\n <textnode>ddd</textnode><textnode a=\"bv\">dsss</textnode>\n <![CDATA[ asfdasdsa <foo> sdfsdfdsf <bar> ]]>\n</foo>\n xml2 < q.xml /foo=\n/foo= text\n/foo= more text\n/foo= \n/foo/textnode=ddd\n/foo/textnode\n/foo/textnode/@a=bv\n/foo/textnode=dsss\n/foo=\n/foo= asfdasdsa <foo> sdfsdfdsf <bar> \n/foo=\n xml2 < q.xml | grep textnode | sed 's!/foo!/bar/baz!' | 2xml <bar><baz><textnode>ddd</textnode><textnode a=\"bv\">dsss</textnode></baz></bar>\n html2 2html"
},
{
"answer_id": 14492020,
"author": "Dave Jarvis",
"author_id": 59087,
"author_profile": "https://Stackoverflow.com/users/59087",
"pm_score": 4,
"selected": false,
"text": "xmllint --xpath //title books.xml\n $ xmllint --version\nxmllint: using libxml version 20900\n $ xmllint\nUsage : xmllint [options] XMLfiles ...\n Parse the XML files and output the result of the parsing\n --version : display the version of the XML library used\n --debug : dump a debug tree of the in-memory document\n ...\n --schematron schema : do validation against a schematron\n --sax1: use the old SAX1 interfaces for processing\n --sax: do not build a tree but work just at the SAX level\n --oldxml10: use XML-1.0 parsing rules before the 5th edition\n --xpath expr: evaluate the XPath expression, inply --noout\n"
},
{
"answer_id": 17934553,
"author": "Clay",
"author_id": 444917,
"author_profile": "https://Stackoverflow.com/users/444917",
"pm_score": 3,
"selected": false,
"text": "<root>\n <one>I like applesauce</one>\n <two>You sure bet I do!</two>\n</root>\n # load XML file into local variable and cast as XML type.\n$doc = [xml](Get-Content ./test.xml)\n\n$doc.root.one #echoes \"I like applesauce\"\n$doc.root.one = \"Who doesn't like applesauce?\" #replace inner text of <one> node\n\n# create new node...\n$newNode = $doc.CreateElement(\"three\")\n$newNode.set_InnerText(\"And don't you forget it!\")\n\n# ...and position it in the hierarchy\n$doc.root.AppendChild($newNode)\n\n# write results to disk\n$doc.save(\"./testNew.xml\")\n <root>\n <one>Who likes applesauce?</one>\n <two>You sure bet I do!</two>\n <three>And don't you forget it!</three>\n</root>\n"
},
{
"answer_id": 27904664,
"author": "Gilles Quenot",
"author_id": 465183,
"author_profile": "https://Stackoverflow.com/users/465183",
"pm_score": 2,
"selected": false,
"text": "saxon-lint $ saxon-lint --html --xpath 'count(//a)' http://stackoverflow.com/q/91791\n328\n $ saxon-lint --xpath '//a[@class=\"x\"]' file.xml\n"
},
{
"answer_id": 60684677,
"author": "methuselah-0",
"author_id": 7612826,
"author_profile": "https://Stackoverflow.com/users/7612826",
"pm_score": 1,
"selected": false,
"text": "xmldoc=$(cat <<EOF\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<job xmlns=\"http://www.sample.com/\">programming</job>\nEOF\n)\nselection='//*[namespace-uri()=\"http://www.sample.com/\" and local-name()=\"job\" and re:test(.,\"^pro.*ing$\")]/text()'\necho \"$xmldoc\" | xp \"$selection\"\n# prints programming\n xp()\n{ \nlocal selection=\"$1\";\nlocal xmldoc;\nif ! [[ -t 0 ]]; then\n read -rd '' xmldoc;\nelse\n xmldoc=\"$2\";\nfi;\npython3 <(printf '%b' \"from lxml.html import tostring\\nfrom lxml import etree\\nfrom sys import stdin\\nregexpNS = \\\"http://exslt.org/regular-expressions\\\"\\ntree = etree.parse(stdin)\\nfor e in tree.xpath('\"\"$selection\"\"', namespaces={'re':regexpNS}):\\n if isinstance(e, str):\\n print(e)\\n else:\\n print(tostring(e).decode('UTF-8'))\") <<< \"$xmldoc\"\n}\n xmldoc=$(cat <<'EOF'\n<resources>\n <string name=\"app_name\">Keep Accounts</string>\n <string name=\"login\">\"login\"</string>\n <string name=\"login_password\">\"password:\"</string>\n <string name=\"login_account_hint\">input to login</string>\n <string name=\"login_password_hint\">input your password</string>\n <string name=\"login_fail\">login failed</string>\n</resources>\nEOF\n)\necho \"$xmldoc\" | xq '.resources.string = ([.resources.string[]|select(.\"#text\" == \"Keep Accounts\") .\"#text\" = \"Keep Accounts 2\"])' -x\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/91791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16981/"
] |
91,800
|
<p>I'm using a FullTextSqlQuery in SharePoint 2007 (MOSS) and need to order the results by two columns:</p>
<pre><code>SELECT WorkId FROM SCOPE() ORDER BY Author ASC, Rank DESC
</code></pre>
<p>However it seems that only the first column from ORDER BY is taken into account when returning results. In this case the results are ordered correctly by Author, but not by Rank. If I change the order the results will be ordered by Rank, but not by Author.</p>
<p>I had to resort to my own sorting of the results, which I don't like very much. Has anybody a solution to this?</p>
<p><strong>Edit</strong>: Unfortunately it also doesn't accept expressions in the ORDER BY clause (SharePoint throws an exception). My guess is that even if the query looks like legitimate SQL it is parsed somehow before being served to the SQL server.</p>
<p>I tried to catch the query with SQL Profiler, but to no avail.</p>
<p><strong>Edit 2</strong>: In the end I used ordering by a single column (Author in my case, since it's the most important) and did the second ordering in code on the TOP N of the results. Works good enough for the project, but leaves a bad feeling of kludgy code.</p>
|
[
{
"answer_id": 93524,
"author": "Adam Hawkes",
"author_id": 6703,
"author_profile": "https://Stackoverflow.com/users/6703",
"pm_score": 0,
"selected": false,
"text": "SELECT WorkId FROM SCOPE() ORDER BY AUTHOR + (10 - Rank) ASC\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/91800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15682/"
] |
91,810
|
<p>Working with python interactively, it's sometimes necessary to display a result which is some arbitrarily complex data structure (like lists with embedded lists, etc.)
The default way to display them is just one massive linear dump which just wraps over and over and you have to parse carefully to read it.</p>
<p>Is there something that will take any python object and display it in a more rational manner. e.g.</p>
<pre><code>[0, 1,
[a, b, c],
2, 3, 4]
</code></pre>
<p>instead of:</p>
<pre><code>[0, 1, [a, b, c], 2, 3, 4]
</code></pre>
<p>I know that's not a very good example, but I think you get the idea.</p>
|
[
{
"answer_id": 91818,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 6,
"selected": true,
"text": "from pprint import pprint\na = [0, 1, ['a', 'b', 'c'], 2, 3, 4]\npprint(a)\n"
},
{
"answer_id": 92260,
"author": "rjmunro",
"author_id": 3408,
"author_profile": "https://Stackoverflow.com/users/3408",
"pm_score": 4,
"selected": false,
"text": "import yaml\na = [0, 1, ['a', 'b', 'c'], 2, 3, 4]\nprint yaml.dump(a)\n - 0\n- 1\n- [a, b, c]\n- 2\n- 3\n- 4\n"
},
{
"answer_id": 93312,
"author": "AdamKG",
"author_id": 16361,
"author_profile": "https://Stackoverflow.com/users/16361",
"pm_score": 3,
"selected": false,
"text": "pprint.pprint pprint.pformat __repr__ __repr__ def __repr__(self):\n from pprint import pformat\n\n return \"<ClassName %s>\" % pformat({\"attrs\":self.attrs,\n \"that_i\":self.that_i,\n \"care_about\":self.care_about})\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/91810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4086/"
] |
91,817
|
<p>I discovered that you can start your variable name with a '@' character in C#.
In my C# project I was using a web service (I added a web reference to my project) that was written in Java. One of the interface objects defined in the WSDL had a member variable with the name "params". Obviously this is a reserved word in C# so you can't have a class with a member variable with the name "params". The proxy object that was generated contained a property that looked like this:</p>
<pre><code>public ArrayList @params {
get { return this.paramsField; }
set { this.paramsField = value; }
}
</code></pre>
<p>I searched through the VS 2008 c# documentation but couldn't find anything about it. Also searching Google didn't give me any useful answers. So what is the exact meaning or use of the '@' character in a variable/property name?</p>
|
[
{
"answer_id": 91829,
"author": "Mark Embling",
"author_id": 6844,
"author_profile": "https://Stackoverflow.com/users/6844",
"pm_score": 3,
"selected": false,
"text": "event _event @event"
},
{
"answer_id": 91888,
"author": "Tomer Gabel",
"author_id": 11558,
"author_profile": "https://Stackoverflow.com/users/11558",
"pm_score": 5,
"selected": false,
"text": "path = \"c:\\\\temp\\\\somefile.txt\" path = @\"c:\\temp\\somefile.txt\""
},
{
"answer_id": 14893191,
"author": "Colonel Panic",
"author_id": 284795,
"author_profile": "https://Stackoverflow.com/users/284795",
"pm_score": 4,
"selected": false,
"text": "@ x @x > string x = \"abc\";\n> Object.ReferenceEquals(x, @x).Dump();\nTrue\n @ > string string;\nIdentifier expected; 'string' is a keyword\n\n> string @string;\n"
},
{
"answer_id": 20358051,
"author": "BartoszKP",
"author_id": 2642204,
"author_profile": "https://Stackoverflow.com/users/2642204",
"pm_score": 2,
"selected": false,
"text": "@this public static TValue GetValueOrDefault<TKey, TValue>(\n this IDictionary<TKey, TValue> @this,\n TKey key,\n TValue defaultValue)\n {\n if (!@this.ContainsKey(key))\n {\n return defaultValue;\n }\n\n return @this[key];\n }\n"
},
{
"answer_id": 21798798,
"author": "Mina Gabriel",
"author_id": 1410185,
"author_profile": "https://Stackoverflow.com/users/1410185",
"pm_score": 1,
"selected": false,
"text": " int @int = 3; \n @ int"
},
{
"answer_id": 22838275,
"author": "Umar Abbas",
"author_id": 1482460,
"author_profile": "https://Stackoverflow.com/users/1482460",
"pm_score": 4,
"selected": false,
"text": "@ @int @string @double string @public = \"Reserved Keyword used for me and its fine\";\n string public = \"This will not compile\";\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/91817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13287/"
] |
91,821
|
<p>I have a model class:</p>
<pre><code>class Person(db.Model):
first_name = db.StringProperty(required=True)
last_name = db.StringProperty(required=True)
</code></pre>
<p>I have an instance of this class in <code>p</code>, and string <code>s</code> contains the value <code>'first_name'</code>. I would like to do something like:</p>
<pre><code>print p[s]
</code></pre>
<p>and </p>
<pre><code>p[s] = new_value
</code></pre>
<p>Both of which result in a <code>TypeError</code>.</p>
<p>Does anybody know how I can achieve what I would like?</p>
|
[
{
"answer_id": 91859,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 1,
"selected": false,
"text": "getattr(p, s)\nsetattr(p, s, new_value)\n"
},
{
"answer_id": 91911,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 1,
"selected": false,
"text": "p.model_properties()[s].get_value_for_datastore(p)\n"
},
{
"answer_id": 91970,
"author": "Antti Rasinen",
"author_id": 8570,
"author_profile": "https://Stackoverflow.com/users/8570",
"pm_score": 3,
"selected": false,
"text": "getattr(p, s)\nsetattr(p, s, new_value)\n"
},
{
"answer_id": 97760,
"author": "David Sykes",
"author_id": 3154,
"author_profile": "https://Stackoverflow.com/users/3154",
"pm_score": 2,
"selected": false,
"text": "p.properties()[s].get_value_for_datastore(p)\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/91821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3154/"
] |
91,826
|
<p>Is there a version of FitNesse that works on Delphi 2006/2007/2009?</p>
<p>If so where can I find It?</p>
<p>Are there any other programs like FitNesse that work on Delphi 2006?</p>
|
[
{
"answer_id": 91859,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 1,
"selected": false,
"text": "getattr(p, s)\nsetattr(p, s, new_value)\n"
},
{
"answer_id": 91911,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 1,
"selected": false,
"text": "p.model_properties()[s].get_value_for_datastore(p)\n"
},
{
"answer_id": 91970,
"author": "Antti Rasinen",
"author_id": 8570,
"author_profile": "https://Stackoverflow.com/users/8570",
"pm_score": 3,
"selected": false,
"text": "getattr(p, s)\nsetattr(p, s, new_value)\n"
},
{
"answer_id": 97760,
"author": "David Sykes",
"author_id": 3154,
"author_profile": "https://Stackoverflow.com/users/3154",
"pm_score": 2,
"selected": false,
"text": "p.properties()[s].get_value_for_datastore(p)\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/91826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17560/"
] |
91,831
|
<p>Say I have the following web.config:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<authentication mode="Windows"></authentication>
</system.web>
</configuration>
</code></pre>
<p>Using ASP.NET C#, how can I detect the Mode value of the Authentication tag?</p>
|
[
{
"answer_id": 91836,
"author": "redsquare",
"author_id": 6440,
"author_profile": "https://Stackoverflow.com/users/6440",
"pm_score": 3,
"selected": true,
"text": "Context.User.Identity.AuthenticationType"
},
{
"answer_id": 91842,
"author": "Paul van Brenk",
"author_id": 1837197,
"author_profile": "https://Stackoverflow.com/users/1837197",
"pm_score": 5,
"selected": false,
"text": "// Get the current Mode property.\nAuthenticationMode currentMode = \n authenticationSection.Mode;\n\n// Set the Mode property to Windows.\nauthenticationSection.Mode = \n AuthenticationMode.Windows;\n"
},
{
"answer_id": 91898,
"author": "timvw",
"author_id": 15267,
"author_profile": "https://Stackoverflow.com/users/15267",
"pm_score": -1,
"selected": false,
"text": "protected void Page_Load(object sender, EventArgs e)\n{\n XmlDocument config = new XmlDocument();\n config.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);\n XmlNode node = config.SelectSingleNode(\"//configuration/system.web/authentication\");\n this.Label1.Text = node.Attributes[\"mode\"].Value;\n}\n"
},
{
"answer_id": 7054094,
"author": "bkaid",
"author_id": 265570,
"author_profile": "https://Stackoverflow.com/users/265570",
"pm_score": 4,
"selected": false,
"text": "System.Web.Configuration var configuration = WebConfigurationManager.OpenWebConfiguration(\"/\");\nvar authenticationSection = (AuthenticationSection)configuration.GetSection(\"system.web/authentication\");\nif (authenticationSection.Mode == AuthenticationMode.Forms)\n{\n //do something\n}\n"
},
{
"answer_id": 39698844,
"author": "clD",
"author_id": 1533273,
"author_profile": "https://Stackoverflow.com/users/1533273",
"pm_score": 3,
"selected": false,
"text": "ConfigurationManager AuthenticationMode AuthenticationMode authMode = ((AuthenticationSection) ConfigurationManager.GetSection(\"system.web/authentication\")).Mode;\n Enum.GetName(Type, Object) Enum.GetName(typeof(AuthenticationMode), authMode); // e.g. \"Windows\"\n"
},
{
"answer_id": 69190778,
"author": "SZL",
"author_id": 2278037,
"author_profile": "https://Stackoverflow.com/users/2278037",
"pm_score": 0,
"selected": false,
"text": "public Startup(IHostingEnvironment env, IConfiguration config)\n{\n var enabledAuthTypes = config[\"IIS_HTTPAUTH\"].Split(';').Where(l => !String.IsNullOrWhiteSpace(l)).ToList();\n}\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/91831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] |
91,840
|
<p>Could anyone explain me finally what is the best strategy to implement transparent and fluent support of multi-tenant functionality in NHibernate powered domain model?</p>
<p>Im looking for the way, how to keep the domain logic as isolated as possible from the multi-tenant stuff like filtering by TenantID etc</p>
|
[
{
"answer_id": 249727,
"author": "Yuriy Ostapenko",
"author_id": 32702,
"author_profile": "https://Stackoverflow.com/users/32702",
"pm_score": 1,
"selected": false,
"text": " public class ContextualConnectionProvider : DriverConnectionProvider\n {\n\n protected override string ConnectionString\n {\n get\n {\n return GetCurrentTenantDatabaseConnectionStringInternally();\n }\n }\n\n public override void Configure(IDictionary<string, string> settings)\n {\n ConfigureDriver(settings);\n }\n\n }\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/91840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9198/"
] |
91,857
|
<p>Can I safely rename the cygdrive folder? Also, I would like to add other folders at root and map them to folders on windows in the same way as /cygdrive/c maps to my C drive. Is that possible?</p>
|
[
{
"answer_id": 91865,
"author": "Thomas Owens",
"author_id": 572,
"author_profile": "https://Stackoverflow.com/users/572",
"pm_score": 1,
"selected": false,
"text": "mount"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/91857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45603/"
] |
91,899
|
<p>I'm using grep to generate a list of files I need to move:</p>
<pre><code>grep -L -r 'Subject: \[SPAM\]' .
</code></pre>
<p>How can I pass this list to the mv command and move the files somewhere else?</p>
|
[
{
"answer_id": 91954,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 1,
"selected": false,
"text": "IFS=$'\\n'; # set the field separator to line break\nfor $mail in $(grep -L -r 'Subject: \\[SPAM\\]' .); do mv \"$mail\" your_dir; done;\nIFS=' '; # restore FS\n"
},
{
"answer_id": 91965,
"author": "daveb",
"author_id": 11858,
"author_profile": "https://Stackoverflow.com/users/11858",
"pm_score": 7,
"selected": true,
"text": "'Subject \\[SPAM\\]' grep -L -Z -r 'Subject: \\[SPAM\\]' . | xargs -0 -I{} mv {} DIR\n xargs -0\n -L -l -I{} mv {} DIR\n {} mv filenames DIR"
},
{
"answer_id": 92007,
"author": "Tobias Kunze",
"author_id": 6070,
"author_profile": "https://Stackoverflow.com/users/6070",
"pm_score": 5,
"selected": false,
"text": "grep -L -r 'Subject: \\[SPAM\\]' . | while read f; do mv \"$f\" out; done\n"
},
{
"answer_id": 2945731,
"author": "Brad Vokey",
"author_id": 354860,
"author_profile": "https://Stackoverflow.com/users/354860",
"pm_score": 4,
"selected": false,
"text": "grep -l 'Subject: \\[SPAM\\]' | xargs -I '{}' mv '{}' DIR\n"
},
{
"answer_id": 9275611,
"author": "Ritz",
"author_id": 1208880,
"author_profile": "https://Stackoverflow.com/users/1208880",
"pm_score": 2,
"selected": false,
"text": "mv $(grep -l 'Subject: \\[SPAM\\]' | awk -F ':' '{print $1}') your_file\n"
},
{
"answer_id": 29429932,
"author": "vladkras",
"author_id": 1713660,
"author_profile": "https://Stackoverflow.com/users/1713660",
"pm_score": 3,
"selected": false,
"text": "grep -lir 'spam' ./ | xargs mv -t ../spam ./"
},
{
"answer_id": 32498852,
"author": "Loukan ElKadi",
"author_id": 5320562,
"author_profile": "https://Stackoverflow.com/users/5320562",
"pm_score": 2,
"selected": false,
"text": "mv `grep -L -r 'Subject: \\[SPAM\\]' .` <directory_path>\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/91899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17582/"
] |
91,905
|
<p>I want to add a mailto link on our web page. I want to add a urgent priority to this mail.</p>
|
[
{
"answer_id": 91921,
"author": "Robit",
"author_id": 17026,
"author_profile": "https://Stackoverflow.com/users/17026",
"pm_score": 4,
"selected": true,
"text": "<a href=\"mailto:webmaster@website.com?subject=Urgent\">Send a email</a> \n"
},
{
"answer_id": 91974,
"author": "Garth Kidd",
"author_id": 5700,
"author_profile": "https://Stackoverflow.com/users/5700",
"pm_score": 2,
"selected": false,
"text": "subject= body= mailto: body= body"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/91905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17584/"
] |
91,932
|
<p>How does it work, what is it used for and when should one use it?</p>
|
[
{
"answer_id": 92108,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 7,
"selected": true,
"text": "Car() run() mycar = new Car()\nmycar.run()\n run() run() Class Car()\n{\n this.motor = new Motor(this) \n\n // passing \"this\" is important for the motor so it knows what it is running\n\n method run()\n {\n this.motor.run()\n }\n\n method changeMotor(motor)\n {\n this.motor = motor \n }\n\n}\n"
},
{
"answer_id": 95008,
"author": "Jorge Córdoba",
"author_id": 2695,
"author_profile": "https://Stackoverflow.com/users/2695",
"pm_score": 5,
"selected": false,
"text": "namespace StrategyPatterns\n{\n // Interface definition for a Sort algorithm\n public interface ISort\n {\n void Sort(List<string> list)\n }\n\n // QuickSort implementation\n public class CQuickSorter : ISort\n {\n void Sort(List<string> list)\n {\n // Here will be the actual implementation\n }\n }\n\n // BubbleSort implementation\n public class CBubbleSort : ISort\n {\n void Sort(List<string> list)\n {\n // The actual implementation of the sort\n }\n }\n\n // MergeSort implementation\n public class CMergeSort : ISort\n {\n void Sort(List<string> list)\n {\n // Again the real implementation comes here\n }\n }\n\n public class Context\n {\n private ISort sorter;\n\n public Context(ISort sorter)\n {\n // We pass to the context the strategy to use\n this.sorter = sorter;\n }\n\n public ISort Sorter\n {\n get{return sorter;)\n }\n }\n\n public class MainClass\n {\n static void Main()\n {\n List<string> myList = new List<string>();\n\n myList.Add(\"Hello world\");\n myList.Add(\"Another item\");\n myList.Add(\"Item item\");\n\n Context cn = new Context(new CQuickSorter());\n // Sort using the QuickSort strategy\n cn.Sorter.Sort(myList);\n myList.Add(\"This one goes for the mergesort\");\n cn = new Context(new CMergeSort());\n // Sort using the merge sort strategy\n cn.Sorter.Sort(myList);\n }\n }\n}\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/91932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2695/"
] |
91,933
|
<p>I've been working on a project where I need to iterate through a collection of data and remove entries where the "primary key" is duplicated. I have tried using a</p>
<pre><code>List<int>
</code></pre>
<p>and </p>
<pre><code>Dictionary<int, bool>
</code></pre>
<p>With the dictionary I found slightly better performance, even though I never need the Boolean tagged with each entry. My expectation is that this is because a List allows for indexed access and a Dictionary does not. What I was wondering is, is there a better solution to this problem. I do not need to access the entries again, I only need to track what "primary keys" I have seen and make sure I only perform addition work on entries that have a new primary key. I'm using C# and .NET 2.0. And I have no control over fixing the input data to remove the duplicates from the source (unfortunately!). And so you can have a feel for scaling, overall I'm checking for duplicates about 1,000,000 times in the application, but in subsets of no more than about 64,000 that need to be unique.</p>
|
[
{
"answer_id": 91979,
"author": "Jorge Córdoba",
"author_id": 2695,
"author_profile": "https://Stackoverflow.com/users/2695",
"pm_score": 0,
"selected": false,
"text": "foreach (int key in keys)\n{\n if (!MyDataDict.ContainsKey(key))\n {\n if (!MyDuplicatesDict.ContainsKey(key))\n MyDuplicatesDict.Add(key);\n }\n else\n MyDataDict.Add(key); \n}\n"
},
{
"answer_id": 94269,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": " // initailize to a size if you know your set size\nList<int> FoundKeys = new List<int>( 64000 );\nDictionary<int,int> FoundDuplicates = new Dictionary<int,int>();\n\nforeach ( int Key in MyKeys )\n{\n // this is an O(log N) operation\n int index = FoundKeys.BinarySearch( Key );\n if ( index < 0 ) \n {\n // if the Key is not in our list, \n // index is the two's compliment of the next value that is in the list\n // i.e. the position it should occupy, and we maintain sorted-ness!\n FoundKeys.Insert( ~index, Key );\n }\n else \n {\n if ( DuplicateKeys.ContainsKey( Key ) )\n {\n DuplicateKeys[Key]++;\n }\n else\n {\n DuplicateKeys.Add( Key, 1 );\n }\n } \n} \n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/91933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4660/"
] |
91,957
|
<p>How do I use groovy to search+replace in XML?</p>
<p>I need something as short/easy as possible, since I'll be giving this code to the testers for their SoapUI scripting.</p>
<p>More specifically, how do I turn:</p>
<pre><code><root><data></data></root>
</code></pre>
<p>into:</p>
<pre><code><root><data>value</data></root>
</code></pre>
|
[
{
"answer_id": 92419,
"author": "s3v1",
"author_id": 17554,
"author_profile": "https://Stackoverflow.com/users/17554",
"pm_score": 1,
"selected": false,
"text": "import org.custommonkey.xmlunit.Diff\nimport org.custommonkey.xmlunit.XMLUnit\n\ndef input = '''<root><data></data></root>'''\ndef expectedResult = '''<root><data>value</data></root>'''\n\ndef xml = new XmlParser().parseText(input)\n\ndef p = xml.'**'.data\np.each{it.value=\"value\"}\n\ndef writer = new StringWriter()\nnew XmlNodePrinter(new PrintWriter(writer)).print(xml)\ndef result = writer.toString()\n\nXMLUnit.setIgnoreWhitespace(true)\ndef xmlDiff = new Diff(result, expectedResult)\nassert xmlDiff.identical()\n"
},
{
"answer_id": 101567,
"author": "s3v1",
"author_id": 17554,
"author_profile": "https://Stackoverflow.com/users/17554",
"pm_score": 1,
"selected": false,
"text": "def rtv = { xml, tag, value ->\n def doc = DOMBuilder.parse(new StringReader(xml))\n def root = doc.documentElement\n use(DOMCategory) { root.'**'.\"$tag\".each{it.value=value} }\n return DOMUtil.serialize(root) \n}\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<?mso-infoPathSolution name=\"urn:schemas-microsoft-com:office:infopath:FA_Ansoegning:http---ementor-dk-application-2007-06-22-\" href=\"manifest.xsf\" solutionVersion=\"1.0.0.14\" productVersion=\"12.0.0\" PIVersion=\"1.0.0.0\" ?>\n<?mso-application progid=\"InfoPath.Document\" versionProgid=\"InfoPath.Document.2\"?>\n<application:FA_Ansoegning xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\nxmlns:application=\"http://corp.dk/application/2007/06/22/\"\nxmlns:xd=\"http://schemas.microsoft.com/office/infopath/2003\"\nxmlns:my=\"http://schemas.microsoft.com/office/infopath/2003/myXSD/200 8-04-14T14:31:48\">\n <Mobiltlf></Mobiltlf>\n <E-mail-adresse></E-mail-adresse>\n</application:FA_Ansoegning>\n"
},
{
"answer_id": 113942,
"author": "GerG",
"author_id": 17249,
"author_profile": "https://Stackoverflow.com/users/17249",
"pm_score": 0,
"selected": false,
"text": "import javax.xml.transform.TransformerFactory\nimport javax.xml.transform.stream.StreamResult\nimport javax.xml.transform.stream.StreamSource\n\ndef xml = \"\"\"\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<?mso-infoPathSolution name=\"urn:schemas-microsoft-com:office:infopath:FA_Ansoegning:http---ementor-dk-application-2007-06-22-\" href=\"manifest.xsf\" solutionVersion=\"1.0.0.14\" productVersion=\"12.0.0\" PIVersion=\"1.0.0.0\" ?>\n<?mso-application progid=\"InfoPath.Document\" versionProgid=\"InfoPath.Document.2\"?>\n<application:FA_Ansoegning xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\nxmlns:application=\"http://ementor.dk/application/2007/06/22/\"\nxmlns:xd=\"http://schemas.microsoft.com/office/infopath/2003\"\nxmlns:my=\"http://schemas.microsoft.com/office/infopath/2003/myXSD/200 8-04-14T14:31:48\">\n <Mobiltlf></Mobiltlf>\n <E-mail-adresse></E-mail-adresse>\n</application:FA_Ansoegning>\n\"\"\".trim()\n\ndef xslt = \"\"\"\n<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">\n <xsl:param name=\"mobil\" select=\"'***dummy***'\"/>\n <xsl:param name=\"email\" select=\"'***dummy***'\"/>\n\n <xsl:template match=\"@*|node()\">\n <xsl:copy>\n <xsl:apply-templates select=\"@*|node()\"/>\n </xsl:copy>\n </xsl:template>\n\n <xsl:template match=\"Mobiltlf\">\n <xsl:copy>\n <xsl:value-of select=\"\\$mobil\"/>\n </xsl:copy>\n </xsl:template>\n\n <xsl:template match=\"E-mail-adresse\">\n <xsl:copy>\n <xsl:value-of select=\"\\$email\"/>\n </xsl:copy>\n </xsl:template>\n</xsl:stylesheet>\n\"\"\".trim()\n\ndef factory = TransformerFactory.newInstance()\ndef transformer = factory.newTransformer(new StreamSource(new StringReader(xslt)))\n\ntransformer.setParameter('mobil', '1234567890')\ntransformer.setParameter('email', 'john.doe@foobar.com')\n\ntransformer.transform(new StreamSource(new StringReader(xml)), new StreamResult(System.out))\n <?xml version=\"1.0\" encoding=\"UTF-8\"?><?mso-infoPathSolution name=\"urn:schemas-microsoft-com:office:infopath:FA_Ansoegning:http---ementor-dk-application-2007-06-22-\" href=\"manifest.xsf\" solutionVersion=\"1.0.0.14\" productVersion=\"12.0.0\" PIVersion=\"1.0.0.0\" ?>\n<?mso-application progid=\"InfoPath.Document\" versionProgid=\"InfoPath.Document.2\"?>\n<application:FA_Ansoegning xmlns:application=\"http://ementor.dk/application/2007/06/22/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xd=\"http://schemas.microsoft.com/office/infopath/2003\" xmlns:my=\"http://schemas.microsoft.com/office/infopath/2003/myXSD/200 8-04-14T14:31:48\">\n <Mobiltlf>1234567890</Mobiltlf>\n <E-mail-adresse>john.doe@foobar.com</E-mail-adresse>\n</application:FA_Ansoegning>\n"
},
{
"answer_id": 115192,
"author": "s3v1",
"author_id": 17554,
"author_profile": "https://Stackoverflow.com/users/17554",
"pm_score": 1,
"selected": false,
"text": "xml.replace(\"<Mobiltlf></Mobiltlf>\", <Mobiltlf>32165487</Mobiltlf>\")\n"
},
{
"answer_id": 119650,
"author": "GerG",
"author_id": 17249,
"author_profile": "https://Stackoverflow.com/users/17249",
"pm_score": 3,
"selected": true,
"text": "xml.replaceFirst(\"<Mobiltlf>[^<]*</Mobiltlf>\", '<Mobiltlf>32165487</Mobiltlf>')\n"
},
{
"answer_id": 120013,
"author": "s3v1",
"author_id": 17554,
"author_profile": "https://Stackoverflow.com/users/17554",
"pm_score": 0,
"selected": false,
"text": "def rtv = { xmlSource, tagName, newValue ->\n regex = \"<$tagName>[^<]*</$tagName>\"\n replacement = \"<$tagName>${newValue}</$tagName>\"\n xmlSource = xmlSource.replaceAll(regex, replacement)\n return xmlSource\n}\n\ninput = rtv( input, \"Mobiltlf\", \"32165487\" )\ninput = rtv( input, \"E-mail-adresse\", \"bob@email.com\" )\nprintln input\n <Mobiltlf type=\"national\" anotherattribute=\"value\"></Mobiltlf>\n"
},
{
"answer_id": 125591,
"author": "GerG",
"author_id": 17249,
"author_profile": "https://Stackoverflow.com/users/17249",
"pm_score": 1,
"selected": false,
"text": "def input = \"\"\"\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<?mso-infoPathSolution name=\"urn:schemas-microsoft-com:office:infopath:FA_Ansoegning:http---ementor-dk-application-2007-06-22-\" href=\"manifest.xsf\" solutionVersion=\"1.0.0.14\" productVersion=\"12.0.0\" PIVersion=\"1.0.0.0\" ?>\n<?mso-application progid=\"InfoPath.Document\" versionProgid=\"InfoPath.Document.2\"?>\n<application:FA_Ansoegning xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\nxmlns:application=\"http://ementor.dk/application/2007/06/22/\"\nxmlns:xd=\"http://schemas.microsoft.com/office/infopath/2003\"\nxmlns:my=\"http://schemas.microsoft.com/office/infopath/2003/myXSD/200 8-04-14T14:31:48\">\n <Mobiltlf type=\"national\" anotherattribute=\"value\"></Mobiltlf>\n <E-mail-adresse attr=\"whatever\"></E-mail-adresse>\n</application:FA_Ansoegning>\n\"\"\".trim()\n\ndef rtv = { xmlSource, tagName, newValue ->\n regex = \"(<$tagName[^>]*>)([^<]*)(</$tagName>)\"\n replacement = \"\\$1${newValue}\\$3\"\n xmlSource = xmlSource.replaceAll(regex, replacement)\n return xmlSource\n}\n\ninput = rtv( input, \"Mobiltlf\", \"32165487\" )\ninput = rtv( input, \"E-mail-adresse\", \"bob@email.com\" )\nprintln input\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<?mso-infoPathSolution name=\"urn:schemas-microsoft-com:office:infopath:FA_Ansoegning:http---ementor-dk-application-2007-06-22-\" href=\"manifest.xsf\" solutionVersion=\"1.0.0.14\" productVersion=\"12.0.0\" PIVersion=\"1.0.0.0\" ?>\n<?mso-application progid=\"InfoPath.Document\" versionProgid=\"InfoPath.Document.2\"?>\n<application:FA_Ansoegning xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\nxmlns:application=\"http://ementor.dk/application/2007/06/22/\"\nxmlns:xd=\"http://schemas.microsoft.com/office/infopath/2003\"\nxmlns:my=\"http://schemas.microsoft.com/office/infopath/2003/myXSD/200 8-04-14T14:31:48\">\n <Mobiltlf type=\"national\" anotherattribute=\"value\">32165487</Mobiltlf>\n <E-mail-adresse attr=\"whatever\">bob@email.com</E-mail-adresse>\n</application:FA_Ansoegning>\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/91957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17554/"
] |
91,981
|
<p>Is there a way to mock object construction using JMock in Java? </p>
<p>For example, if I have a method as such:</p>
<pre class="lang-java prettyprint-override"><code>public Object createObject(String objectType) {
if(objectType.equals("Integer") {
return new Integer();
} else if (objectType.equals("String") {
return new String();
}
}
</code></pre>
<p>...is there a way to mock out the expectation of the object construction in a test method? </p>
<p>I'd like to be able to place expectations that certain constructors are being called, rather than having an extra bit of code to check the type (as it won't always be as convoluted and simple as my example).</p>
<p>So instead of:</p>
<pre class="lang-java prettyprint-override"><code>assertTrue(a.createObject() instanceof Integer);
</code></pre>
<p>I could have an expectation of the certain constructor being called. Just to make it a bit cleaner, and express what is actually being tested in a more readable way.</p>
<p>Please excuse the simple example, the actual problem I'm working on is a bit more complicated, but having the expectation would simplify it.</p>
<hr>
<p>For a bit more background:</p>
<p>I have a simple factory method, which creates wrapper objects. The objects being wrapped can require parameters which are difficult to obtain in a test class (it's pre-existing code), so it is difficult to construct them.</p>
<p>Perhaps closer to what I'm actually looking for is: is there a way to mock an entire class (using CGLib) in one fell swoop, without specifying every method to stub out? </p>
<p>So the mock is being wrapped in a constructor, so obviously methods can be called on it, is JMock capable of dynamically mocking out each method? </p>
<p>My guess is no, as that would be pretty complicated. But knowing I'm barking up the wrong tree is valuable too :-)</p>
|
[
{
"answer_id": 92718,
"author": "Grundlefleck",
"author_id": 4120,
"author_profile": "https://Stackoverflow.com/users/4120",
"pm_score": 1,
"selected": false,
"text": "public Wrapper wrapObject(Object toWrap) {\n if(toWrap instanceof ClassA) {\n return new Wrapper((ClassA) toWrap);\n } else if (toWrap instanceof ClassB) {\n return new Wrapper((ClassB) toWrap);\n } // etc\n\n else {\n return null;\n }\n}\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/91981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4120/"
] |
91,984
|
<p>When I use <kbd>CTRL</kbd>+<kbd>H</kbd> I end up on the Java Search tab. I would very much like a shortcut to go directly to File Search instead. Is that possible?</p>
<p>See image here for what I'm talking about:
<a href="https://i.stack.imgur.com/S3Qlf.png" rel="noreferrer"><img src="https://i.stack.imgur.com/S3Qlf.png" alt="enter image description here"></a></p>
|
[
{
"answer_id": 49437058,
"author": "Gabriel Staples",
"author_id": 4561887,
"author_profile": "https://Stackoverflow.com/users/4561887",
"pm_score": 0,
"selected": false,
"text": "rea *.txt *32*f1*c *3*1*c*h *"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/91984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/86/"
] |
91,986
|
<p>I've got the following SQL:</p>
<pre><code>select * from transaction_log where stoptime like '%2008%'
</code></pre>
<p>How do I write this in LINQ to SQL syntax?</p>
|
[
{
"answer_id": 92009,
"author": "Nick Craver",
"author_id": 13249,
"author_profile": "https://Stackoverflow.com/users/13249",
"pm_score": 6,
"selected": true,
"text": "var query = from l in transaction_log\n where SqlMethods.Like(l.stoptime, \"%2008%\")\n select l;\n var query = from l in transaction_log\n where l.stoptime.Contains(\"2008\")\n select l;\n var query = from l in transaction_log\n where l.stoptime.Year = 2008\n select l;\n"
},
{
"answer_id": 92010,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "from x in context.Table where x.Contains(\"2008\") select x\n"
},
{
"answer_id": 94576,
"author": "Scott Marlowe",
"author_id": 1683,
"author_profile": "https://Stackoverflow.com/users/1683",
"pm_score": 0,
"selected": false,
"text": "var query = from p in dbTransSummary.Transaction_Logs\n where ( (DateTime) p.StopTime).Year == dtRollUpDate.Year\n select\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/91986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1683/"
] |
91,994
|
<p>This is probably a silly question, but curiosity has gotten the better of me. I've been seeing code lately that seems to "reverse" the order of expressions for relational operators e.g.:</p>
<pre><code>if (0 == someVariable)
</code></pre>
<p>As opposed to what I normally see/write:</p>
<pre><code>if (someVariable == 0)
</code></pre>
<p>To me, the second method seems more readable and intuitive, so I'm wondering if there's some reason I'm seeing the first method? Logically, both statements evaluate to the same result, so is it just a matter of personal preference how they're written?</p>
|
[
{
"answer_id": 92003,
"author": "user7116",
"author_id": 7116,
"author_profile": "https://Stackoverflow.com/users/7116",
"pm_score": 1,
"selected": false,
"text": "if (succeeded = TRUE)\n{\n // I could be in trouble here if 'succeeded' was FALSE\n}\n if (TRUE = succeeded)\n{\n // This will fail to compile, and I'll fix my mistake\n}\n if (myInteger = 9)\n{\n // this will fail to compile\n}\n"
},
{
"answer_id": 92021,
"author": "pdc",
"author_id": 8925,
"author_profile": "https://Stackoverflow.com/users/8925",
"pm_score": 2,
"selected": false,
"text": "if (someVariable = 0) {\n ...\n}\n someVariable == = if if"
},
{
"answer_id": 92240,
"author": "marijne",
"author_id": 7038,
"author_profile": "https://Stackoverflow.com/users/7038",
"pm_score": 1,
"selected": false,
"text": "if (0 > number)\n if (NULL != pointer)\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/91994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9324/"
] |
92,001
|
<p>AKA - What's this obsession with pointers?</p>
<p>Having only really used modern, object oriented languages like ActionScript, Java and C#, I don't really understand the importance of pointers and what you use them for. What am I missing out on here?</p>
|
[
{
"answer_id": 92054,
"author": "Adam Wright",
"author_id": 1200,
"author_profile": "https://Stackoverflow.com/users/1200",
"pm_score": 7,
"selected": true,
"text": "char* foo (foo + 5)"
},
{
"answer_id": 92208,
"author": "slim",
"author_id": 7512,
"author_profile": "https://Stackoverflow.com/users/7512",
"pm_score": 2,
"selected": false,
"text": "StringBuffer x = new StringBuffer(\"Hello\");\nStringBuffer y = x;\nx.append(\" boys\");\nSystem.out.println(y);\n"
},
{
"answer_id": 92369,
"author": "Cody Hatch",
"author_id": 17086,
"author_profile": "https://Stackoverflow.com/users/17086",
"pm_score": 2,
"selected": false,
"text": "char dict[10][81];\n"
},
{
"answer_id": 92499,
"author": "schwerwolf",
"author_id": 7045,
"author_profile": "https://Stackoverflow.com/users/7045",
"pm_score": 1,
"selected": false,
"text": "SomeObject store[100];\nint a_ptr = 20;\nSomeObject A = store[a_ptr];\n store[a_ptr] = A;\n SomeObject A;\nSomeObject* a_ptr = &A;\n// Any changes to a_ptr's contents hereafter will affect\n// the one-true-object that it addresses. No need to reassign.\n"
},
{
"answer_id": 92636,
"author": "user9282",
"author_id": 9282,
"author_profile": "https://Stackoverflow.com/users/9282",
"pm_score": 2,
"selected": false,
"text": "void strcpy(char *dest, char *src)\n{ \n while(*dest++ = *src++);\n}\n"
},
{
"answer_id": 30513130,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 2,
"selected": false,
"text": "null"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11911/"
] |
92,004
|
<p>I'm trying to make a data bound column invisible after data binding, because it won't exist before data binding. However, the DataGrid.Columns collection indicates a count of 0, making it seem as if the automatically generated columns don't belong to the collection.</p>
<p>How can I make a column that is automatically generated during binding invisible?</p>
|
[
{
"answer_id": 92028,
"author": "Nick Craver",
"author_id": 13249,
"author_profile": "https://Stackoverflow.com/users/13249",
"pm_score": 0,
"selected": false,
"text": "protected void GridView_RowCreated(object sender, GridViewRowEventArgs e)\n{\n e.Row.Cells[1].Visible = false;\n}\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741/"
] |
92,006
|
<p>I have an algorithm that generates strings based on a list of input words. How do I separate only the strings that sounds like English words? ie. discard <strong>RDLO</strong> while keeping <strong>LORD</strong>.</p>
<p><strong>EDIT:</strong> To clarify, they do not need to be actual words in the dictionary. They just need to sound like English. For example <strong>KEAL</strong> would be accepted.</p>
|
[
{
"answer_id": 92083,
"author": "Russ",
"author_id": 6496,
"author_profile": "https://Stackoverflow.com/users/6496",
"pm_score": 2,
"selected": false,
"text": "def soundex(name, len=4):\n digits = '01230120022455012623010202'\n sndx = ''\n fc = ''\n\n for c in name.upper():\n if c.isalpha():\n if not fc: fc = c\n d = digits[ord(c)-ord('A')]\n if not sndx or (d != sndx[-1]):\n sndx += d\n\n sndx = fc + sndx[1:]\n sndx = sndx.replace('0','')\n return (sndx + (len * '0'))[:len]\n\nreal_words = load_english_dictionary()\nsoundex_cache = [ soundex(word) for word in real_words ]\n\nif soundex(candidate) in soundex_cache:\n print \"keep\"\nelse:\n print \"discard\"\n"
},
{
"answer_id": 92190,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 4,
"selected": false,
"text": "from reverend.thomas import Bayes\nguesser = Bayes()\nguesser.train('french','La souris est rentrée dans son trou.')\nguesser.train('english','my tailor is rich.')\nguesser.train('french','Je ne sais pas si je viendrai demain.')\nguesser.train('english','I do not plan to update my website soon.')\n\n>>> print guesser.guess('Jumping out of cliffs it not a good idea.')\n[('english', 0.99990000000000001), ('french', 9.9999999999988987e-005)]\n\n>>> print guesser.guess('Demain il fera très probablement chaud.')\n[('french', 0.99990000000000001), ('english', 9.9999999999988987e-005)]\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/976/"
] |
92,008
|
<p>How do I programmatically set the record pointer in a C# DataGridView? </p>
<p>I've tried "DataGridView.Rows[DesiredRowIndex].Selected=true;", and that does not work. All it does is highlight that row within the grid; it doesn not move the record pointer to that row.</p>
|
[
{
"answer_id": 92105,
"author": "Wolfwyrd",
"author_id": 15570,
"author_profile": "https://Stackoverflow.com/users/15570",
"pm_score": 3,
"selected": true,
"text": "dataGridView1.CurrentCell = this.dataGridView1[YourColumn,YourRow];\n"
},
{
"answer_id": 12528343,
"author": "Ashar Nawaz",
"author_id": 1688470,
"author_profile": "https://Stackoverflow.com/users/1688470",
"pm_score": 1,
"selected": false,
"text": "DataGrid dataGridView1.Focus();\ndataGridView1.CurrentCell = this.dataGridView1[YourColumn,YourRow];\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7148/"
] |
92,027
|
<p>For a registration form I have something simple like:</p>
<pre><code> <tr:panelLabelAndMessage
label="Zip/City"
showRequired="true">
<tr:inputText
id="zip"
value="#{data['registration'].zipCode}"
contentStyle="width:36px"
simple="true"
required="true" />
<tr:inputText
id="city"
value="#{data['registration'].city}"
contentStyle="width:133px"
simple="true"
required="true" />
</tr:panelLabelAndMessage>
<tr:message for="zip" />
<tr:message for="city" />
</code></pre>
<p>When including the last two lines, I get two messages on validation error. When ommiting last to lines, a javascript alert shows up, which is not what I want. </p>
<p>Is there a solution to show only one validation failed message somehow?</p>
<p>Thanks a lot!</p>
|
[
{
"answer_id": 107817,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "panelLabelAndMessage inputText"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11705/"
] |
92,035
|
<p>I have a datagridview with a DataGridViewComboboxColumn column with 3 values:</p>
<p>"Small", "Medium", "Large"</p>
<p>I get back the users default which in this case is "Medium"</p>
<p>I want to show a dropdown cell in the datagridview but default the value to "Medium". i would do this in a regular combobox by doing selected index or just stting the Text property of a combo box.</p>
|
[
{
"answer_id": 92186,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "[DataGridViewComboboxColumnName].DataPropertyName = \"PropertyNameToBindTo\";\n"
},
{
"answer_id": 712960,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "DataGridView.Rows[rowindex].Cells[columnindex].Value \n"
},
{
"answer_id": 3590320,
"author": "Sandeep Pathak",
"author_id": 422437,
"author_profile": "https://Stackoverflow.com/users/422437",
"pm_score": 0,
"selected": false,
"text": " this.dataGridViewStudentInformation.Columns[ColumnIndex].DataPropertyName = dataGridViewStudentInformation.Columns[2].Name ; //Set the ColumnName to which you want to bind. \n"
},
{
"answer_id": 20755543,
"author": "user2866884",
"author_id": 2866884,
"author_profile": "https://Stackoverflow.com/users/2866884",
"pm_score": 2,
"selected": false,
"text": "DataGridViewComboBoxColumn ColumnPage = new DataGridViewComboBoxColumn();\nColumnPage.DefaultCellStyle.NullValue = \"Medium\";\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] |
92,043
|
<p>I've tried the tools listed <a href="http://wiki.postgresql.org/wiki/Converting_from_other_Databases_to_PostgreSQL" rel="noreferrer">here</a>, some with more success than others, but none gave me valid postgres syntax I could use (tinyint errors etc.)</p>
|
[
{
"answer_id": 106760,
"author": "vog",
"author_id": 19163,
"author_profile": "https://Stackoverflow.com/users/19163",
"pm_score": 5,
"selected": true,
"text": "mysqldump"
},
{
"answer_id": 15670452,
"author": "Linus Oleander",
"author_id": 560073,
"author_profile": "https://Stackoverflow.com/users/560073",
"pm_score": 2,
"selected": false,
"text": "[sudo] gem install mysql2psql mysql2psql mysql2psql.yml mysql2psql.yml mysql2psql force_truncate true mysql2psql.yml"
},
{
"answer_id": 18580569,
"author": "Michał Powaga",
"author_id": 1027198,
"author_profile": "https://Stackoverflow.com/users/1027198",
"pm_score": 1,
"selected": false,
"text": "# if a socket is specified we will use that\n# if tcp is chosen you can use compression\nmysql:\n hostname: localhost\n port: 3306\n socket: /tmp/mysql.sock\n username: mysql2psql\n password:\n database: mysql2psql_test\n compress: false\ndestination:\n # if file is given, output goes to file, else postgres\n file:\n postgres:\n hostname: localhost\n port: 5432\n username: mysql2psql\n password:\n database: mysql2psql_test\n > py-mysql2pgsql -h\nusage: py-mysql2pgsql [-h] [-v] [-f FILE]\n\nTool for migrating/converting data from mysql to postgresql.\n\noptional arguments:\n -h, --help show this help message and exit\n -v, --verbose Show progress of data migration.\n -f FILE, --file FILE Location of configuration file (default:\n mysql2pgsql.yml). If none exists at that path,\n one will be created for you.\n"
},
{
"answer_id": 46362080,
"author": "Cees Timmerman",
"author_id": 819417,
"author_profile": "https://Stackoverflow.com/users/819417",
"pm_score": 0,
"selected": false,
"text": "function mysql2pgsql($mysql){\n return preg_replace(\"/limit (\\d+), *(\\d+)/i\", \"limit $1 offset $2\", preg_replace(\"/as '([^']+)'/i\", 'as \"$1\"', $mysql)); // Note: limit needs order\n}\n CREATE \"mediumtext\" -> \"text\", \"^LOCK.*\" -> \"\", \"^UNLOCK.*\" -> \"\", \"`\" -> '\"', \"'\" -> \"''\" in 'data', \"0000-00-00\" -> \"2000-01-01\", deduplicate constraint names, \" CHARACTER SET utf8 \" -> \" \".\n\"int(10)\" -> \"int\" was missed in the last table, so pass that part of the mysqldump through http://www.sqlines.com/online again.\n"
},
{
"answer_id": 47132273,
"author": "R.Sehdev",
"author_id": 3919627,
"author_profile": "https://Stackoverflow.com/users/3919627",
"pm_score": 4,
"selected": false,
"text": "http://www.sqlines.com/online\n"
},
{
"answer_id": 67422858,
"author": "Paul Rougieux",
"author_id": 2641825,
"author_profile": "https://Stackoverflow.com/users/2641825",
"pm_score": 2,
"selected": false,
"text": "sudo apt install pgloader\n sudo su postgres\ncreatedb -O user db_migrated\n pgloader mysql://user@localhost/db postgresql:///db_migrated\n brew install --HEAD pgloader"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4196/"
] |
92,076
|
<p>I'm writing some xlst file which I want to use under linux and Windows.
In this file I use node-set function which declared in different namespaces for MSXML and xsltproc ("urn:schemas-microsoft-com:xslt" and "<a href="http://exslt.org/common" rel="nofollow noreferrer">http://exslt.org/common</a>" respectively). Is there any platform independent way of using node-set?</p>
|
[
{
"answer_id": 92511,
"author": "James Sulak",
"author_id": 207,
"author_profile": "https://Stackoverflow.com/users/207",
"pm_score": 3,
"selected": false,
"text": "<xsl:choose>\n <xsl:when test=\"function-available('exslt:node-set')\">\n <xsl:apply-templates select=\"exslt:node-set($nodelist)\" />\n </xsl:when>\n <xsl:when test=\"function-available('msxsl:node-set')\">\n <xsl:apply-templates select=\"msxsl:node-set($nodelist)\" />\n </xsl:when>\n <!-- etc -->\n</xsl:choose>\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17569/"
] |
92,079
|
<p>Why does C++ Builder 6 always compile all files? </p>
<p>I make some changes on one file but BCB 6 compiles all files when I start the app. Any idea? I use Windows XP SP2.</p>
|
[
{
"answer_id": 1080949,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "#include \"all.h\"\n#pragma hdrstop\n #include <string>\n #include \"all.h\"\n #pragma hdrstop\n\n #include \"Unit1.h\"\n #include <vcl>\n #include \"all.h\"\n #pragma hdrstop\n\n #include \"Unit2.h\"\n #include <string>\n #include <vcl>\n #include <string>\n #include \"all.h\"\n #pragma hdrstop\n\n #include \"Unit1.h\"\n #include <vcl>\n #include <vcl> //!!!!!!!!!!!!!!!!!!! produce a second version of an precompiled file\n #pragma hdrstop\n\n #include \"Unit2.h\"\n #include <string>\n #include <vcl>\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17465/"
] |
92,082
|
<p>How can I add a column with a default value to an existing table in <a href="http://en.wikipedia.org/wiki/Microsoft_SQL_Server#Genesis" rel="noreferrer">SQL Server 2000</a> / <a href="http://en.wikipedia.org/wiki/Microsoft_SQL_Server#SQL_Server_2005" rel="noreferrer">SQL Server 2005</a>?</p>
|
[
{
"answer_id": 92092,
"author": "Benjamin Autin",
"author_id": 1440933,
"author_profile": "https://Stackoverflow.com/users/1440933",
"pm_score": 6,
"selected": false,
"text": "ALTER TABLE ADD ColumnName {Column_Type} Constraint\n"
},
{
"answer_id": 92101,
"author": "dbugger",
"author_id": 15754,
"author_profile": "https://Stackoverflow.com/users/15754",
"pm_score": 10,
"selected": false,
"text": "ALTER TABLE Protocols\nADD ProtocolTypeID int NOT NULL DEFAULT(1)\nGO\n"
},
{
"answer_id": 92123,
"author": "James Boother",
"author_id": 16030,
"author_profile": "https://Stackoverflow.com/users/16030",
"pm_score": 13,
"selected": true,
"text": "ALTER TABLE {TABLENAME} \nADD {COLUMNNAME} {TYPE} {NULL|NOT NULL} \nCONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}\nWITH VALUES\n ALTER TABLE SomeTable\n ADD SomeCol Bit NULL --Or NOT NULL.\n CONSTRAINT D_SomeTable_SomeCol --When Omitted a Default-Constraint Name is autogenerated.\n DEFAULT (0)--Optional Default-Constraint.\nWITH VALUES --Add if Column is Nullable and you want the Default Value for Existing Records.\n CONSTRAINT D_SomeTable_SomeCol DF__SomeTa__SomeC__4FB7FEF6 WITH VALUES NOT NULL WITH VALUES SomeTable SomeCol 0 SomeCol NULL NULL"
},
{
"answer_id": 92166,
"author": "ddc0660",
"author_id": 16027,
"author_profile": "https://Stackoverflow.com/users/16027",
"pm_score": 7,
"selected": false,
"text": "ALTER TABLE <table name> \nADD <new column name> <data type> NOT NULL\nGO\nALTER TABLE <table name> \nADD CONSTRAINT <constraint name> DEFAULT <default value> FOR <new column name>\nGO\n"
},
{
"answer_id": 128056,
"author": "jalbert",
"author_id": 1360388,
"author_profile": "https://Stackoverflow.com/users/1360388",
"pm_score": 7,
"selected": false,
"text": "NOT NULL DEFAULT ALTER TABLE NOT NULL DEFAULT"
},
{
"answer_id": 4401381,
"author": "JerryOL",
"author_id": 7964,
"author_profile": "https://Stackoverflow.com/users/7964",
"pm_score": 7,
"selected": false,
"text": "-- Add a column with a default DateTime \n-- to capture when each record is added.\n\nALTER TABLE myTableName \nADD RecordAddedDate SMALLDATETIME NULL DEFAULT (GETDATE()) \nGO \n"
},
{
"answer_id": 5639381,
"author": "phunk_munkie",
"author_id": 704595,
"author_profile": "https://Stackoverflow.com/users/704595",
"pm_score": 8,
"selected": false,
"text": "WITH VALUES ALTER TABLE table\nADD column BIT -- Demonstration with NULL-able column added\nCONSTRAINT Constraint_name DEFAULT 0 WITH VALUES\n"
},
{
"answer_id": 8285284,
"author": "gngolakia",
"author_id": 1050111,
"author_profile": "https://Stackoverflow.com/users/1050111",
"pm_score": 6,
"selected": false,
"text": " ALTER TABLE {TABLENAME}\n ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL}\n CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}\n USE AdventureWorks;\n EXEC sp_msforeachtable\n'PRINT ''ALTER TABLE ? ADD Date_Created DATETIME DEFAULT GETDATE();''' ;\n"
},
{
"answer_id": 8640716,
"author": "giá vàng",
"author_id": 1013886,
"author_profile": "https://Stackoverflow.com/users/1013886",
"pm_score": 6,
"selected": false,
"text": "ALTER TABLE {TABLENAME} \nADD {COLUMNNAME} {TYPE} {NULL|NOT NULL} \nCONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}\n"
},
{
"answer_id": 10756580,
"author": "adeel41",
"author_id": 189738,
"author_profile": "https://Stackoverflow.com/users/189738",
"pm_score": 7,
"selected": false,
"text": "ALTER TABLE MyTable\nADD MyNewColumn INT NOT NULL DEFAULT 0\n"
},
{
"answer_id": 10843628,
"author": "Christo",
"author_id": 214747,
"author_profile": "https://Stackoverflow.com/users/214747",
"pm_score": 6,
"selected": false,
"text": "ALTER TABLE [schema].[tablename] ADD DEFAULT ((0)) FOR [columnname]\n alter table [schema].[tablename] drop constraint [constraintname]\n"
},
{
"answer_id": 11813717,
"author": "Evan V",
"author_id": 1441037,
"author_profile": "https://Stackoverflow.com/users/1441037",
"pm_score": 7,
"selected": false,
"text": "ALTER TABLE MYTABLE ADD MYNEWCOLUMN VARCHAR(200) DEFAULT 'SNUGGLES'\n"
},
{
"answer_id": 22199380,
"author": "andy",
"author_id": 3224712,
"author_profile": "https://Stackoverflow.com/users/3224712",
"pm_score": 5,
"selected": false,
"text": "ALTER TABLE [Employees] ADD Seniority int not null default 0 GO\n"
},
{
"answer_id": 24333598,
"author": "Catto",
"author_id": 17877,
"author_profile": "https://Stackoverflow.com/users/17877",
"pm_score": 6,
"selected": false,
"text": "ALTER TABLE [dbo.table_name]\n ADD [Column_Name] BIT NOT NULL\nDefault ( 0 )\n -------------------------------------------------------------------------\n-- Drop COLUMN\n-- Name of Column: Column_EmployeeName\n-- Name of Table: table_Emplyee\n--------------------------------------------------------------------------\nIF EXISTS (\n SELECT 1\n FROM INFORMATION_SCHEMA.COLUMNS\n WHERE TABLE_NAME = 'table_Emplyee'\n AND COLUMN_NAME = 'Column_EmployeeName'\n )\n BEGIN\n\n IF EXISTS ( SELECT 1\n FROM sys.default_constraints\n WHERE object_id = OBJECT_ID('[dbo].[DF_table_Emplyee_Column_EmployeeName]')\n AND parent_object_id = OBJECT_ID('[dbo].[table_Emplyee]')\n )\n BEGIN\n ------ DROP Contraint\n\n ALTER TABLE [dbo].[table_Emplyee] DROP CONSTRAINT [DF_table_Emplyee_Column_EmployeeName]\n PRINT '[DF_table_Emplyee_Column_EmployeeName] was dropped'\n END\n -- ----- DROP Column -----------------------------------------------------------------\n ALTER TABLE [dbo].table_Emplyee\n DROP COLUMN Column_EmployeeName\n PRINT 'Column Column_EmployeeName in images table was dropped'\n END\n\n--------------------------------------------------------------------------\n-- ADD COLUMN Column_EmployeeName IN table_Emplyee table\n--------------------------------------------------------------------------\nIF NOT EXISTS (\n SELECT 1\n FROM INFORMATION_SCHEMA.COLUMNS\n WHERE TABLE_NAME = 'table_Emplyee'\n AND COLUMN_NAME = 'Column_EmployeeName'\n )\n BEGIN\n ----- ADD Column & Contraint\n ALTER TABLE dbo.table_Emplyee\n ADD Column_EmployeeName BIT NOT NULL\n CONSTRAINT [DF_table_Emplyee_Column_EmployeeName] DEFAULT (0)\n PRINT 'Column [DF_table_Emplyee_Column_EmployeeName] in table_Emplyee table was Added'\n PRINT 'Contraint [DF_table_Emplyee_Column_EmployeeName] was Added'\n END\n\nGO\n"
},
{
"answer_id": 25600651,
"author": "Jakir Hossain",
"author_id": 3260960,
"author_profile": "https://Stackoverflow.com/users/3260960",
"pm_score": 4,
"selected": false,
"text": "ALTER TABLE Product\nADD ProductID INT NOT NULL DEFAULT(1)\nGO\n"
},
{
"answer_id": 26367963,
"author": "Gabriel L.",
"author_id": 2826885,
"author_profile": "https://Stackoverflow.com/users/2826885",
"pm_score": 7,
"selected": false,
"text": "ALTER TABLE YourTable\n ADD Column1 INT NOT NULL DEFAULT 0,\n Column2 INT NOT NULL DEFAULT 1,\n Column3 VARCHAR(50) DEFAULT 'Hello'\nGO\n"
},
{
"answer_id": 27127950,
"author": "Mohit Tamrakar",
"author_id": 3414238,
"author_profile": "https://Stackoverflow.com/users/3414238",
"pm_score": 5,
"selected": false,
"text": "ALTER TABLE tes \nADD ssd NUMBER DEFAULT '0';\n"
},
{
"answer_id": 30847241,
"author": "Naveen Desosha",
"author_id": 1914998,
"author_profile": "https://Stackoverflow.com/users/1914998",
"pm_score": 4,
"selected": false,
"text": "ALTER TABLE Product \nADD ReferenceID uniqueidentifier not null \ndefault (cast(cast(0 as binary) as uniqueidentifier))\n"
},
{
"answer_id": 34131674,
"author": "Chanukya",
"author_id": 5093602,
"author_profile": "https://Stackoverflow.com/users/5093602",
"pm_score": 3,
"selected": false,
"text": "ALTER TABLE [TABLENAME] ADD MyNewColumn INT not null default 0 GO\n"
},
{
"answer_id": 34208117,
"author": "Tony L.",
"author_id": 3347858,
"author_profile": "https://Stackoverflow.com/users/3347858",
"pm_score": 6,
"selected": false,
"text": "(getdate()) 'abc' 0"
},
{
"answer_id": 34414140,
"author": "Chiragkumar Thakar",
"author_id": 4574888,
"author_profile": "https://Stackoverflow.com/users/4574888",
"pm_score": 4,
"selected": false,
"text": "ALTER TABLE [table]\nADD Column1 Datatype\n ALTER TABLE [test]\nADD ID Int\n ALTER TABLE [test]\nADD ID Int IDENTITY(1,1) NOT NULL\n"
},
{
"answer_id": 36856212,
"author": "Jeevan Gharti",
"author_id": 2650834,
"author_profile": "https://Stackoverflow.com/users/2650834",
"pm_score": 4,
"selected": false,
"text": "IF NOT EXISTS (\n SELECT * FROM INFORMATION_SCHEMA.COLUMNS\n WHERE TABLE_NAME ='TABLENAME' AND COLUMN_NAME = 'COLUMNNAME'\n)\nBEGIN\n ALTER TABLE TABLENAME ADD COLUMNNAME Nvarchar(MAX) Not Null default\nEND\n"
},
{
"answer_id": 37118360,
"author": "usefulBee",
"author_id": 2093880,
"author_profile": "https://Stackoverflow.com/users/2093880",
"pm_score": 3,
"selected": false,
"text": "New Column Select Type Save"
},
{
"answer_id": 37412089,
"author": "Sandeep Kumar",
"author_id": 6280120,
"author_profile": "https://Stackoverflow.com/users/6280120",
"pm_score": 3,
"selected": false,
"text": "ALTER TABLE tbl_table ADD int_column int NOT NULL DEFAULT(0)\n"
},
{
"answer_id": 39405328,
"author": "Mohit Dagar",
"author_id": 4261212,
"author_profile": "https://Stackoverflow.com/users/4261212",
"pm_score": 4,
"selected": false,
"text": "CREATE TABLE TestTable\n (FirstCol INT NOT NULL)\n GO\n ------------------------------\n -- Option 1\n ------------------------------\n -- Adding New Column\n ALTER TABLE TestTable\n ADD SecondCol INT\n GO\n -- Updating it with Default\n UPDATE TestTable\n SET SecondCol = 0\n GO\n -- Alter\n ALTER TABLE TestTable\n ALTER COLUMN SecondCol INT NOT NULL\n GO\n"
},
{
"answer_id": 40145396,
"author": "Laxmi",
"author_id": 6755093,
"author_profile": "https://Stackoverflow.com/users/6755093",
"pm_score": 5,
"selected": false,
"text": "CREATE TABLE STUDENT (STUDENT_ID INT NOT NULL)\n ALTER TABLE STUDENT \nADD STUDENT_NAME INT NOT NULL DEFAULT(0)\n\nSELECT * \nFROM STUDENT\n"
},
{
"answer_id": 42695588,
"author": "Ananda G",
"author_id": 2256217,
"author_profile": "https://Stackoverflow.com/users/2256217",
"pm_score": 4,
"selected": false,
"text": "IF NOT EXISTS IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.columns WHERE table_name = 'TaskSheet' AND column_name = 'IsBilledToClient')\nBEGIN\nALTER TABLE dbo.TaskSheet ADD\n IsBilledToClient bit NOT NULL DEFAULT ((1))\nEND\nGO\n TaskSheet IsBilledToClient 1 BIT IsBilledToClient ALTER TABLE {TABLENAME}\nADD {COLUMNNAME} {TYPE} {NULL|NOT NULL}\nCONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}\n[WITH VALUES]\n"
},
{
"answer_id": 42801734,
"author": "Arun D",
"author_id": 5261509,
"author_profile": "https://Stackoverflow.com/users/5261509",
"pm_score": 3,
"selected": false,
"text": "ALTER TABLE tableName ADD ColumnName datatype DEFAULT DefaultValue;\n"
},
{
"answer_id": 43800406,
"author": "Ste Bov",
"author_id": 4442467,
"author_profile": "https://Stackoverflow.com/users/4442467",
"pm_score": 5,
"selected": false,
"text": "ALTER TABLE {schemaName}.{tableName}\n ADD {columnName} {datatype} NULL\n CONSTRAINT {constraintName} DEFAULT {DefaultValue}\n\nUPDATE {schemaName}.{tableName}\n SET {columnName} = {DefaultValue}\n WHERE {columName} IS NULL\n\nALTER TABLE {schemaName}.{tableName}\n ALTER COLUMN {columnName} {datatype} NOT NULL\n WHILE 1=1\nBEGIN\n UPDATE TOP (1000000) {schemaName}.{tableName}\n SET {columnName} = {DefaultValue}\n WHERE {columName} IS NULL\n\n IF @@ROWCOUNT < 1000000\n BREAK;\nEND\n"
},
{
"answer_id": 46561968,
"author": "raju chowrsiya",
"author_id": 5819598,
"author_profile": "https://Stackoverflow.com/users/5819598",
"pm_score": 3,
"selected": false,
"text": "alter table table_name add field field_name data_type\n USE data_base_name;\nGO\nCREATE DEFAULT default_name AS 'default_value';\n exec sp_bindefault 'default_name' , 'schema_name.table_name.field_name'\n USE master;\nGO\nEXEC sp_bindefault 'today', 'HumanResources.Employee.HireDate';\n"
},
{
"answer_id": 48617607,
"author": "Akhil Singh",
"author_id": 7528842,
"author_profile": "https://Stackoverflow.com/users/7528842",
"pm_score": 5,
"selected": false,
"text": "ALTER TABLE TableName\nADD ColumnName (type) -- NULL OR NOT NULL\nDEFAULT (default value)\nWITH VALUES\n ALTER TABLE Activities\nADD status int NOT NULL DEFAULT (0)\nWITH VALUES\n ALTER TABLE Table_1\nADD row3 int NOT NULL\nCONSTRAINT CONSTRAINT_NAME DEFAULT (0)\nWITH VALUES\n"
},
{
"answer_id": 48687262,
"author": "wild coder",
"author_id": 9106094,
"author_profile": "https://Stackoverflow.com/users/9106094",
"pm_score": 4,
"selected": false,
"text": "--Adding Value with Default Value\nALTER TABLE TestTable\nADD ThirdCol INT NOT NULL DEFAULT(0)\nGO\n"
},
{
"answer_id": 48761215,
"author": "Krishan Dutt Sharma",
"author_id": 9308236,
"author_profile": "https://Stackoverflow.com/users/9308236",
"pm_score": 2,
"selected": false,
"text": "ALTER TABLE Table1 ADD Col3 INT NOT NULL DEFAULT(0)\n"
},
{
"answer_id": 49839398,
"author": "Erfan Mohammadi",
"author_id": 4214920,
"author_profile": "https://Stackoverflow.com/users/4214920",
"pm_score": 3,
"selected": false,
"text": "--Adding New Column with Default Value\nALTER TABLE TABLENAME \nADD COLUMNNAME DATATYPE NULL|NOT NULL DEFAULT (DEFAULT_VALUE)\n --Adding CONSTRAINT And Set Default Value on Column\nALTER TABLE TABLENAME ADD CONSTRAINT [CONSTRAINT_Name] DEFAULT \n(DEFAULT_VALUE) FOR [COLUMNNAME]\n"
},
{
"answer_id": 52053260,
"author": "Anshul Dubey",
"author_id": 5239013,
"author_profile": "https://Stackoverflow.com/users/5239013",
"pm_score": 4,
"selected": false,
"text": "ALTER TABLE MyTable\nADD MyNewColumn DataType DEFAULT DefaultValue\n"
},
{
"answer_id": 58934529,
"author": "Samay",
"author_id": 4675202,
"author_profile": "https://Stackoverflow.com/users/4675202",
"pm_score": 2,
"selected": false,
"text": "ALTER TABLE {tablename}\nADD \n {columnname} {datatype} DEFAULT {default_value}\n int ALTER TABLE [Table1]\nADD \n [Column1] INT DEFAULT 1\n"
},
{
"answer_id": 61683667,
"author": "jithu thomas",
"author_id": 11170679,
"author_profile": "https://Stackoverflow.com/users/11170679",
"pm_score": 2,
"selected": false,
"text": "OFFLINE ONLINE IGNORE ALTER_SPECIFICATION ALTER [ONLINE | OFFLINE] [IGNORE] TABLE tbl_name\n alter_specification [, alter_specification] ...\n\n alter_specification:\n ...\n ADD [COLUMN] (col_name column_definition,...)\n ...\n\nEg: ALTER TABLE table1 ADD COLUMN foo INT DEFAULT 0;\n"
},
{
"answer_id": 62352803,
"author": "Somendra Kanaujia",
"author_id": 11784748,
"author_profile": "https://Stackoverflow.com/users/11784748",
"pm_score": 3,
"selected": false,
"text": "ALTER TABLE <YOUR_TABLENAME>\nADD <YOUR_COLUMNNAME> <DATATYPE> <NULL|NOT NULL> \nADD CONSTRAINT <CONSTRAINT_NAME> ----OPTIONAL\nDEFAULT <DEFAULT_VALUE>\n ALTER TABLE TEMP_TABLENAME\nADD COLUMN1 NUMERIC(10,0) NOT NULL\nADD CONSTRAINT ABCDE ----OPTIONAL\nDEFAULT (0)\n"
},
{
"answer_id": 69717519,
"author": "Priyanka Vadhwani",
"author_id": 10349278,
"author_profile": "https://Stackoverflow.com/users/10349278",
"pm_score": 0,
"selected": false,
"text": "ALTER TABLE {TABLENAME} \nADD {COLUMNNAME} {TYPE} {NULL|NOT NULL} \nCONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}\nWITH VALUES\n ALTER TABLE Admin_Master \nADD Can_View_Password BIT NULL \nCONSTRAINT DF_Admin_Master_Can_View_Password DEFAULT (1)\nWITH VALUES \n"
},
{
"answer_id": 70013571,
"author": "ishant kaushik",
"author_id": 16513489,
"author_profile": "https://Stackoverflow.com/users/16513489",
"pm_score": 3,
"selected": false,
"text": "CREATE TABLE ExistingTable (ID INT)\nGO\nINSERT INTO ExistingTable (ID)\nVALUES (1), (2), (3)\nGO\nSELECT *\nFROM ExistingTable\n ALTER TABLE ExistingTable\nADD ColWithDefault VARCHAR(10) DEFAULT 'Hi'\nGO\n 'Hi' INSERT INTO ExistingTable(ID)\nVALUES (4)\nGO\nSelect * from ExistingTable\nGO\n ALTER TABLE ExistingTable\nADD DefaultColWithVal VARCHAR(10) DEFAULT 'DefaultAll'\nWITH VALUES\nGO\nSelect * from ExistingTable\nGO\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7241/"
] |
92,093
|
<p>I am working on a SQL query that reads from a SQLServer database to produce an extract file. One of the requirements to remove the leading zeroes from a particular field, which is a simple <code>VARCHAR(10)</code> field. So, for example, if the field contains '00001A', the SELECT statement needs to return the data as '1A'.</p>
<p>Is there a way in SQL to easily remove the leading zeroes in this way? I know there is an <code>RTRIM</code> function, but this seems only to remove spaces. </p>
|
[
{
"answer_id": 92363,
"author": "Ian Horwill",
"author_id": 5816,
"author_profile": "https://Stackoverflow.com/users/5816",
"pm_score": 8,
"selected": true,
"text": "select substring(ColumnName, patindex('%[^0]%',ColumnName), 10)\n"
},
{
"answer_id": 4504913,
"author": "Kathryn Wilson",
"author_id": 550612,
"author_profile": "https://Stackoverflow.com/users/550612",
"pm_score": 2,
"selected": false,
"text": "select CASE\n WHEN ColumnName = substring(ColumnName, patindex('%[^0]%',ColumnName), 10) \n THEN '0'\n ELSE substring(ColumnName, patindex('%[^0]%',ColumnName), 10) \n END\n"
},
{
"answer_id": 11978913,
"author": "MTZ",
"author_id": 1601905,
"author_profile": "https://Stackoverflow.com/users/1601905",
"pm_score": 5,
"selected": false,
"text": "select replace(ltrim(replace(ColumnName,'0',' ')),' ','0')\n"
},
{
"answer_id": 12012414,
"author": "Nat",
"author_id": 1607814,
"author_profile": "https://Stackoverflow.com/users/1607814",
"pm_score": 3,
"selected": false,
"text": "select substring(substring('B10000N0Z', patindex('%[0]%','B10000N0Z'), 20), \n patindex('%[^0]%',substring('B10000N0Z', patindex('%[0]%','B10000N0Z'), \n 20)), 20)\n N0Z"
},
{
"answer_id": 22939235,
"author": "Afzal",
"author_id": 3511273,
"author_profile": "https://Stackoverflow.com/users/3511273",
"pm_score": -1,
"selected": false,
"text": "SELECT replace(left(Convert(nvarchar,GETDATE(),101),2),'0','')+RIGHT(Convert(nvarchar,GETDATE(),101),8) \n GETDATE()"
},
{
"answer_id": 25399844,
"author": "user3809240",
"author_id": 3809240,
"author_profile": "https://Stackoverflow.com/users/3809240",
"pm_score": -1,
"selected": false,
"text": "select ltrim('000045', '0') from dual;\n\nLTRIM\n-----\n45\n"
},
{
"answer_id": 26909939,
"author": "ekc",
"author_id": 4248387,
"author_profile": "https://Stackoverflow.com/users/4248387",
"pm_score": 3,
"selected": false,
"text": "select \n case \n when left(column,1) = '0' \n then right(column, (len(column)-1)) \n else column \n end\n"
},
{
"answer_id": 35373156,
"author": "Brian Ellison",
"author_id": 5920739,
"author_profile": "https://Stackoverflow.com/users/5920739",
"pm_score": -1,
"selected": false,
"text": "WHEN left(column, 3) = '000' THEN right(column, (len(column)-3))\n\nWHEN left(column, 2) = '00' THEN right(a.column, (len(column)-2))\n\nWHEN left(column, 1) = '0' THEN right(a.column, (len(column)-1))\n\nELSE \n"
},
{
"answer_id": 36689325,
"author": "Stelian",
"author_id": 6218798,
"author_profile": "https://Stackoverflow.com/users/6218798",
"pm_score": 3,
"selected": false,
"text": "SELECT REPLACE(LTRIM(REPLACE('000010A', '0', ' ')),' ', '0')\n"
},
{
"answer_id": 40868049,
"author": "Lynn Caveny",
"author_id": 7225894,
"author_profile": "https://Stackoverflow.com/users/7225894",
"pm_score": -1,
"selected": false,
"text": "select CASE\n WHEN TRY_CONVERT(bigint,Mtrl_Nbr) = 0\n THEN ''\n ELSE substring(Mtrl_Nbr, patindex('%[^0]%',Mtrl_Nbr), 18)\n END\n"
},
{
"answer_id": 48179132,
"author": "Madhurupa Moitra",
"author_id": 9154612,
"author_profile": "https://Stackoverflow.com/users/9154612",
"pm_score": -1,
"selected": false,
"text": " SELECT REPLACE(columnname,'0','') FROM table\n"
},
{
"answer_id": 48556389,
"author": "Shailendra Mishra",
"author_id": 2528335,
"author_profile": "https://Stackoverflow.com/users/2528335",
"pm_score": 0,
"selected": false,
"text": "DECLARE @LeadingZeros VARCHAR(10) ='-000987000'\n\nSET @LeadingZeros =\n CASE WHEN PATINDEX('%-0', @LeadingZeros) = 1 THEN \n @LeadingZeros\n ELSE \n CAST(CAST(@LeadingZeros AS INT) AS VARCHAR(10)) \n END \n\nSELECT @LeadingZeros\n CAST(CAST(@LeadingZeros AS INT) AS VARCHAR(10)) \n"
},
{
"answer_id": 54454715,
"author": "Vikas",
"author_id": 415865,
"author_profile": "https://Stackoverflow.com/users/415865",
"pm_score": 0,
"selected": false,
"text": "SET ANSI_NULLS ON\nGO\nSET QUOTED_IDENTIFIER ON\nGO\n-- =============================================\n-- Author: Vikas Patel\n-- Create date: 01/31/2019\n-- Description: Remove leading zeros from string\n-- =============================================\nCREATE FUNCTION dbo.funRemoveLeadingZeros \n(\n -- Add the parameters for the function here\n @Input varchar(max)\n)\nRETURNS varchar(max)\nAS\nBEGIN\n -- Declare the return variable here\n DECLARE @Result varchar(max)\n\n -- Add the T-SQL statements to compute the return value here\n SET @Result = @Input\n\n WHILE LEFT(@Result, 1) = '0'\n BEGIN\n SET @Result = SUBSTRING(@Result, 2, LEN(@Result) - 1)\n END\n\n -- Return the result of the function\n RETURN @Result\n\nEND\nGO\n"
},
{
"answer_id": 60555560,
"author": "e-Fungus",
"author_id": 6110450,
"author_profile": "https://Stackoverflow.com/users/6110450",
"pm_score": 0,
"selected": false,
"text": "SELECT ISNULL(STUFF(ColumnName\n ,1\n ,patindex('%[^0]%',ColumnName)-1\n ,'')\n ,REPLACE(ColumnName,'0','')\n )\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7585/"
] |
92,100
|
<p>Is it possible to set code behind a resource dictionary in WPF. For example in a usercontrol for a button you declare it in XAML. The event handling code for the button click is done in the code file behind the control. If I was to create a data template with a button how can I write the event handler code for it's button click within the resource dictionary.</p>
|
[
{
"answer_id": 98422,
"author": "ageektrapped",
"author_id": 631,
"author_profile": "https://Stackoverflow.com/users/631",
"pm_score": 9,
"selected": true,
"text": "<ResourceDictionary xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n x:Class=\"MyCompany.MyProject.MyResourceDictionary\"\n x:ClassModifier=\"public\">\n namespace MyCompany.MyProject\n{\n partial class MyResourceDictionary : ResourceDictionary\n { \n public MyResourceDictionary()\n {\n InitializeComponent();\n } \n ... // event handlers ahead..\n }\n}\n <Application x:Class=\"SampleProject.App\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:rd=\"using:MyCompany.MyProject\">\n<!-- no need in x:ClassModifier=\"public\" in the header above -->\n\n <Application.Resources>\n <ResourceDictionary>\n <ResourceDictionary.MergedDictionaries>\n\n <!-- This will NOT work -->\n <!-- <ResourceDictionary Source=\"/MyResourceDictionary.xaml\" />-->\n\n <!-- Create instance of your custom dictionary instead of the above source reference -->\n <rd:MyResourceDictionary />\n\n </ResourceDictionary.MergedDictionaries>\n </ResourceDictionary>\n </Application.Resources>\n\n</Application>\n"
},
{
"answer_id": 136805,
"author": "Phobis",
"author_id": 19854,
"author_profile": "https://Stackoverflow.com/users/19854",
"pm_score": 3,
"selected": false,
"text": "Button myButton = this.GetTemplateChild(\"ButtonName\") as Button;\nif(myButton != null){\n ...\n}\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6204/"
] |
92,114
|
<p>There is a limitation on Windows Server 2003 that prevents you from copying extremely large files, in proportion to the amount of RAM you have. The limitation is in the CopyFile and CopyFileEx functions, which are used by xcopy, Explorer, Robocopy, and the .NET FileInfo class.</p>
<p>Here is the error that you get:</p>
<blockquote>
<p>Cannot copy [filename]: Insufficient system resources exist to complete the requested service.</p>
</blockquote>
<p>The is a <a href="http://support.microsoft.com/default.aspx/kb/259837" rel="noreferrer">knowledge base article</a> on the subject, but it pertains to NT4 and 2000.</p>
<p>There is also a suggestion to <a href="http://blogs.technet.com/askperf/archive/2007/05/08/slow-large-file-copy-issues.aspx" rel="noreferrer">use ESEUTIL</a> from an Exchange installation, but I haven't had any luck getting that to work.</p>
<p>Does anybody know of a quick, easy way to handle this? I'm talking about >50Gb on a machine with 2Gb of RAM. I plan to fire up Visual Studio and just write something to do it for me, but it would be nice to have something that was already out there, stable and well-tested.</p>
<p><strong>[Edit]</strong> I provided working C# code to accompany the accepted answer.</p>
|
[
{
"answer_id": 92165,
"author": "jabial",
"author_id": 16995,
"author_profile": "https://Stackoverflow.com/users/16995",
"pm_score": 5,
"selected": true,
"text": "f1 = open(filename1);\nf2 = open(filename2, \"w\");\nwhile( !f1.eof() ) {\n buffer = f1.read(buffersize);\n err = f2.write(buffer, buffersize);\n if err != NO_ERROR_CODE\n break;\n}\nf1.close(); f2.close();\n using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Text;\n\nnamespace LoopCopy\n{\n class Program\n {\n static void Main(string[] args)\n {\n if (args.Length != 2)\n {\n Console.WriteLine(\n \"Usage: LoopCopy.exe SourceFile DestFile\");\n return;\n }\n\n string srcName = args[0];\n string destName = args[1];\n\n FileInfo sourceFile = new FileInfo(srcName);\n if (!sourceFile.Exists)\n {\n Console.WriteLine(\"Source file {0} does not exist\", \n srcName);\n return;\n }\n long fileLen = sourceFile.Length;\n\n FileInfo destFile = new FileInfo(destName);\n if (destFile.Exists)\n {\n Console.WriteLine(\"Destination file {0} already exists\", \n destName);\n return;\n }\n\n int buflen = 1024;\n byte[] buf = new byte[buflen];\n long totalBytesRead = 0;\n double pctDone = 0;\n string msg = \"\";\n int numReads = 0;\n Console.Write(\"Progress: \");\n using (FileStream sourceStream = \n new FileStream(srcName, FileMode.Open))\n {\n using (FileStream destStream = \n new FileStream(destName, FileMode.CreateNew))\n {\n while (true)\n {\n numReads++;\n int bytesRead = sourceStream.Read(buf, 0, buflen);\n if (bytesRead == 0) break; \n destStream.Write(buf, 0, bytesRead);\n\n totalBytesRead += bytesRead;\n if (numReads % 10 == 0)\n {\n for (int i = 0; i < msg.Length; i++)\n {\n Console.Write(\"\\b \\b\");\n }\n pctDone = (double)\n ((double)totalBytesRead / (double)fileLen);\n msg = string.Format(\"{0}%\", \n (int)(pctDone * 100));\n Console.Write(msg);\n }\n\n if (bytesRead < buflen) break;\n\n }\n }\n }\n\n for (int i = 0; i < msg.Length; i++)\n {\n Console.Write(\"\\b \\b\");\n }\n Console.WriteLine(\"100%\");\n Console.WriteLine(\"Done\");\n }\n }\n}\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1219/"
] |
92,239
|
<p>If you have several <code>div</code>s on a page, you can use CSS to size, float them and move them round a little... but I can't see a way to get past the fact that the first <code>div</code> will show near the top of the page and the last <code>div</code> will be near the bottom! I cannot completely override the order of the elements as they come from the source HTML, can you?</p>
<p>I must be missing something because people say "we can change the look of the whole website by just editing one CSS file.", but that would depend on you still wanting the <code>div</code>s in the same order!</p>
<p>(P.S. I am sure no one uses <code>position:absolute</code> on every element on a page.)</p>
|
[
{
"answer_id": 92357,
"author": "Jonathan Arkell",
"author_id": 11052,
"author_profile": "https://Stackoverflow.com/users/11052",
"pm_score": 4,
"selected": true,
"text": "h1 {\n position: absolute;\n top: 0;\n left: 0;\n}\n\n#content {\n margin-top: 100px;\n margin-right: 250px;\n}\n\n#nav {\n position: absolute;\n top: 0;\n left: 300px;\n}\n\n#side {\n position: absolute;\n right: 0;\n top: 100px;\n} <h1> Stack Overflow </h1>\n<div id=\"content\">\n <h2> Can Css truly blah blah? </h2>\n ...\n</div>\n<div id=\"nav\">\n <ul class=\"main\">\n <li>quiestions</li> ... </ul>\n ....\n</div>\n<div id=\"side\">\n <div class=\"box\">\n <h3> Sponsored By </h3>\n <h4> New Zelands fish market </h4>\n ....\n </div>\n</div>"
},
{
"answer_id": 13326589,
"author": "pieroxy",
"author_id": 1480910,
"author_profile": "https://Stackoverflow.com/users/1480910",
"pm_score": 2,
"selected": false,
"text": "table-caption table-row table-cell"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11461/"
] |
92,258
|
<p>With my multiproject pom I get an error while running release:prepare. There is nothing fancy about the project setup and every release-step before runs fine.
The error I get is:</p>
<pre>
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Unable to tag SCM
Provider message:
The svn tag command failed.
Command output:
svn: Commit failed (details follow):
svn: File '/repos/june/tags/foo-1.0.2/foo.bar.org/pom.xml' already exists
</pre>
<p>Any idea where it comes from and how to get around it?</p>
<p>(sorry for duplicate post - first was closed because I didn't formulate it as a question that can be answered. I hope it's ok now.)</p>
<p><b>EDIT</b><br>
The maven release plugin takes care of the version handling itself. So when I check the path in the subversion repository the path does not yet exist.</p>
<p><b>EDIT 2</b><br>
@Ben: I don't know the server version, however the client is 1.5.2, too.</p>
|
[
{
"answer_id": 751060,
"author": "Dominic Mitchell",
"author_id": 71343,
"author_profile": "https://Stackoverflow.com/users/71343",
"pm_score": 4,
"selected": true,
"text": "<build>\n <pluginManagement>\n <plugins>\n <plugin>\n <artifactId>maven-release-plugin</artifactId>\n <version>2.0-beta-9</version>\n </plugin>\n </plugins>\n </pluginManagement>\n</build>\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16515/"
] |
92,287
|
<p>I am trying to write a C# client to a server that is written in Java. The server expects a 4 byte (DataInputStread readInt() in Java) message header followed by the actual message.</p>
<p>I am absolutely new to C#, how can I send this message header over to the Java Server? I tried it several ways (mostly trial and error without getting too deep into the C# language), and nothing worked. The Java side ended up with the incorrect (very large) message length.</p>
|
[
{
"answer_id": 92375,
"author": "Craig Day",
"author_id": 5193,
"author_profile": "https://Stackoverflow.com/users/5193",
"pm_score": 0,
"selected": false,
"text": "out.write((len >>> 24) & 0xFF);\nout.write((len >>> 16) & 0xFF);\nout.write((len >>> 8) & 0xFF);\nout.write((len >>> 0) & 0xFF);\n"
},
{
"answer_id": 92399,
"author": "Rasmus Faber",
"author_id": 5542,
"author_profile": "https://Stackoverflow.com/users/5542",
"pm_score": 1,
"selected": false,
"text": "using(Socket socket = ...){\n NetworkStream ns = new NetworkStream(socket); \n ns.WriteByte((size>>24) & 0xFF);\n ns.WriteByte((size>>16) & 0xFF);\n ns.WriteByte((size>>8) & 0xFF);\n ns.WriteByte( size & 0xFF);\n // write the actual message\n}\n"
},
{
"answer_id": 92983,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 4,
"selected": false,
"text": "//byte hex values\nJava: 00 00 00 01\n C#: 01 00 00 00\n private static void WriteInt(Stream stream, int n) {\n for(int i=3; i>=0; i--)\n {\n int shift = i * 8; //bits to shift\n byte b = (byte) (n >> shift);\n stream.WriteByte(b);\n }\n}\n private static void WriteToNetwork(System.IO.BinaryWriter stream, int n) {\n n = System.Net.IPAddress.HostToNetworkOrder(n);\n stream.Write(n);\n}\n"
},
{
"answer_id": 93238,
"author": "ageektrapped",
"author_id": 631,
"author_profile": "https://Stackoverflow.com/users/631",
"pm_score": 0,
"selected": false,
"text": "using (Socket socket = new Socket())\nusing (NetworkStream stream = new NetworkStream(socket))\nusing (BinaryWriter writer = new BinaryWriter(stream))\n{\n int myValue = 42;\n writer.Write(IPAddress.HostToNetworkOrder(myValue));\n}\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
92,328
|
<p>Within an event, I'd like to put the focus on a specific TextBox within the ListViewItem's template. The XAML looks like this:</p>
<pre><code><ListView x:Name="myList" ItemsSource="{Binding SomeList}">
<ListView.View>
<GridView>
<GridViewColumn>
<GridViewColumn.CellTemplate>
<DataTemplate>
<!-- Focus this! -->
<TextBox x:Name="myBox"/>
</code></pre>
<p>I've tried the following in the code behind:</p>
<pre><code>(myList.FindName("myBox") as TextBox).Focus();
</code></pre>
<p>but I seem to have misunderstood the <code>FindName()</code> docs, because it returns <code>null</code>.</p>
<p>Also the <code>ListView.Items</code> doesn't help, because that (of course) contains my bound business objects and no ListViewItems.</p>
<p>Neither does <code>myList.ItemContainerGenerator.ContainerFromItem(item)</code>, which also returns null.</p>
|
[
{
"answer_id": 92765,
"author": "Abe Heidebrecht",
"author_id": 9268,
"author_profile": "https://Stackoverflow.com/users/9268",
"pm_score": 4,
"selected": false,
"text": "private void myList_SelectionChanged(object sender, SelectionChangedEventArgs e)\n{\n if (myList.SelectedItem != null)\n {\n object o = myList.SelectedItem;\n ListViewItem lvi = (ListViewItem)myList.ItemContainerGenerator.ContainerFromItem(o);\n TextBox tb = FindByName(\"myBox\", lvi) as TextBox;\n\n if (tb != null)\n tb.Dispatcher.BeginInvoke(new Func<bool>(tb.Focus));\n }\n}\n\nprivate FrameworkElement FindByName(string name, FrameworkElement root)\n{\n Stack<FrameworkElement> tree = new Stack<FrameworkElement>();\n tree.Push(root);\n\n while (tree.Count > 0)\n {\n FrameworkElement current = tree.Pop();\n if (current.Name == name)\n return current;\n\n int count = VisualTreeHelper.GetChildrenCount(current);\n for (int i = 0; i < count; ++i)\n {\n DependencyObject child = VisualTreeHelper.GetChild(current, i);\n if (child is FrameworkElement)\n tree.Push((FrameworkElement)child);\n }\n }\n\n return null;\n}\n"
},
{
"answer_id": 92917,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": -1,
"selected": false,
"text": "Private Sub SelectAllText(ByVal cell As DataGridCell)\n If cell IsNot Nothing Then\n Dim txtBox As TextBox= GetVisualChild(Of TextBox)(cell)\n If txtBox IsNot Nothing Then\n txtBox.Focus()\n txtBox.SelectAll()\n End If\n End If\nEnd Sub\n\nPublic Shared Function GetVisualChild(Of T As {Visual, New})(ByVal parent As Visual) As T\n Dim child As T = Nothing\n Dim numVisuals As Integer = VisualTreeHelper.GetChildrenCount(parent)\n For i As Integer = 0 To numVisuals - 1\n Dim v As Visual = TryCast(VisualTreeHelper.GetChild(parent, i), Visual)\n If v IsNot Nothing Then\n child = TryCast(v, T)\n If child Is Nothing Then\n child = GetVisualChild(Of T)(v)\n Else\n Exit For\n End If\n End If\n Next\n Return child\nEnd Function\n"
},
{
"answer_id": 502619,
"author": "David Schmitt",
"author_id": 4918,
"author_profile": "https://Stackoverflow.com/users/4918",
"pm_score": 5,
"selected": true,
"text": "ContainerFromItem var item = new SomeListItem();\nSomeList.Add(item);\nListViewItem = SomeList.ItemContainerGenerator.ContainerFromItem(item); // returns null\n Add() ItemContainerGenerator CollectionChanged ItemContainerGenerator StatusChanged"
},
{
"answer_id": 3699838,
"author": "miral shah",
"author_id": 446233,
"author_profile": "https://Stackoverflow.com/users/446233",
"pm_score": -1,
"selected": false,
"text": "private void yourtextboxinWPFGrid_LostFocus(object sender, RoutedEventArgs e)\n {\n //textbox can be catched like this. \n var textBox = ((TextBox)sender);\n EmailValidation(textBox.Text);\n }\n"
},
{
"answer_id": 13073720,
"author": "Cillié Malan",
"author_id": 562229,
"author_profile": "https://Stackoverflow.com/users/562229",
"pm_score": 2,
"selected": false,
"text": "public static IEnumerable<ListViewItem> GetListViewItemsFromList(ListView lv)\n{\n return FindChildrenOfType<ListViewItem>(lv);\n}\n\npublic static IEnumerable<T> FindChildrenOfType<T>(this DependencyObject ob)\n where T : class\n{\n foreach (var child in GetChildren(ob))\n {\n T castedChild = child as T;\n if (castedChild != null)\n {\n yield return castedChild;\n }\n else\n {\n foreach (var internalChild in FindChildrenOfType<T>(child))\n {\n yield return internalChild;\n }\n }\n }\n}\n\npublic static IEnumerable<DependencyObject> GetChildren(this DependencyObject ob)\n{\n int childCount = VisualTreeHelper.GetChildrenCount(ob);\n\n for (int i = 0; i < childCount; i++)\n {\n yield return VisualTreeHelper.GetChild(ob, i);\n }\n}\n yield return"
},
{
"answer_id": 42567259,
"author": "Latency",
"author_id": 878539,
"author_profile": "https://Stackoverflow.com/users/878539",
"pm_score": 0,
"selected": false,
"text": "/// <summary>\n/// ListView1_MouseMove\n/// </summary>\n/// <param name=\"sender\"></param>\n/// <param name=\"e\"></param>\nprivate void ListView1_MouseMove(object sender, System.Windows.Input.MouseEventArgs e) {\n if (ListView1.Items.Count <= 0)\n return;\n\n // Retrieve the coordinate of the mouse position.\n var pt = e.GetPosition((UIElement) sender);\n\n // Callback to return the result of the hit test.\n HitTestResultCallback myHitTestResult = result => {\n var obj = result.VisualHit;\n\n // Add additional DependancyObject types to ignore triggered by the cell's parent object container contexts here.\n //-----------\n if (obj is Border)\n return HitTestResultBehavior.Stop;\n //-----------\n\n var parent = VisualTreeHelper.GetParent(obj) as GridViewRowPresenter;\n if (parent == null)\n return HitTestResultBehavior.Stop;\n\n var headers = parent.Columns.ToDictionary(column => column.Header.ToString());\n\n // Traverse up the VisualTree and find the record set.\n DependencyObject d = parent;\n do {\n d = VisualTreeHelper.GetParent(d);\n } while (d != null && !(d is ListViewItem));\n\n // Reached the end of element set as root's scope.\n if (d == null)\n return HitTestResultBehavior.Stop;\n\n var item = d as ListViewItem;\n var index = ListView1.ItemContainerGenerator.IndexFromContainer(item);\n Debug.WriteLine(index);\n\n lblCursorPosition.Text = $\"Over {item.Name} at ({index})\";\n\n // Set the behavior to return visuals at all z-order levels.\n return HitTestResultBehavior.Continue;\n };\n\n // Set up a callback to receive the hit test result enumeration.\n VisualTreeHelper.HitTest((Visual)sender, null, myHitTestResult, new PointHitTestParameters(pt));\n}\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4918/"
] |
92,342
|
<p>Is there the way to apply "greedy" behavior to and keys in Visual Studio? By "greedy" I mean such behavior when all whitespace between cursor position and next word bound can be deleted using one keystroke.</p>
|
[
{
"answer_id": 92388,
"author": "hugoware",
"author_id": 17091,
"author_profile": "https://Stackoverflow.com/users/17091",
"pm_score": 1,
"selected": false,
"text": " Public Sub RemoveWhiteSpace()\n DTE.ActiveDocument.Selection.WordRight(True)\n DTE.ActiveDocument.Selection.Text = \" \"\n End Sub\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2313/"
] |
92,362
|
<p><strong>Has anyone found a way to run Selenium RC / Selenium Grid tests, written in C# in parallel?</strong></p>
<p>I've currently got a sizable test suite written using Selenium RC's C# driver. Running the entire test suite takes a little over an hour to complete. I normally don't have to run the entire suite so it hasn't been a concern up to now, but it's something that I'd like to be able to do more regularly (ie, as part of an automated build)</p>
<p>I've been spending some time recently poking around with the Selenium Grid project whose purpose essentially is to allow those tests to run in parallel. Unfortunately, it seems that the TestDriven.net plugin that I'm using runs the tests serially (ie, one after another). I'm assuming that NUnit would execute the tests in a similar fashion, although I haven't actually tested this out. </p>
<p>I've noticed that the NUnit 2.5 betas are starting to talk about running tests in parallel with pNUnit, but I haven't really familiarized myself enough with the project to know for sure whether this would work. </p>
<p>Another option I'm considering is separating my test suite into different libraries which would let me run a test from each library concurrently, but I'd like to avoid that if possible since I'm not convinced this is a valid reason for splitting up the test suite.</p>
|
[
{
"answer_id": 611452,
"author": "Mark",
"author_id": 18264,
"author_profile": "https://Stackoverflow.com/users/18264",
"pm_score": 3,
"selected": false,
"text": "TestSet TestTeardown [Test] public void Foo(){\n var s = new DefaultSelenium(\"http://grid\", 4444, \"*firefox\",\n \"http://server-under-test\");\n s.Start();\n s.Open(\"mypage.aspx\");\n // Continue\n s.Stop();\n\n}\n [SetUp] s.Start()"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6112/"
] |
92,372
|
<p>Javascript code can be tough to maintain.<br>
I am looking for tools that will help me ensure a reasonable quality level.<br>
So far I have found <a href="https://github.com/pivotal/jsunit" rel="noreferrer">JsUNit</a>, a very nice unit test framework for javascript. Tests can be run automatically from ant on any browser available.<br>
I have not found yet some javascript equivalent of PMD, checkstyle, Findbug...<br></p>
<p>Do you know any static code analysis tool for javascript ? </p>
|
[
{
"answer_id": 4018418,
"author": "Gian Marco",
"author_id": 66629,
"author_profile": "https://Stackoverflow.com/users/66629",
"pm_score": 4,
"selected": false,
"text": "<build>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-antrun-plugin</artifactId>\n <version>1.6</version>\n <executions>\n <execution>\n <phase>compile</phase>\n <goals>\n <goal>run</goal>\n </goals>\n <configuration>\n <target>\n <taskdef name=\"jslint\" classname=\"com.googlecode.jslint4java.ant.JSLintTask\" classpath=\"${settings.localRepository}/com/googlecode/jslint4java/jslint4java-ant/1.4.2/jslint4java-ant-1.4.2.jar\" />\n <jslint options=\"white,browser,devel,undef,eqeqeq,plusplus,bitwise,regexp,strict,newcap,immed\">\n <predef>Ext,Utils</predef>\n <formatter type=\"plain\" />\n <fileset dir=\"${basedir}/src/main/resources/META-INF/resources/js\" includes=\"**/*.js\" />\n </jslint>\n </target>\n </configuration>\n </execution>\n </executions>\n <dependencies>\n <dependency>\n <groupId>com.googlecode.jslint4java</groupId>\n <artifactId>jslint4java-ant</artifactId>\n <version>1.4.2</version>\n </dependency>\n </dependencies>\n </plugin>\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11897/"
] |
92,376
|
<p>Is there any way that I can programmatically create (and I guess access) hidden folders on a storage device from within c#?</p>
|
[
{
"answer_id": 92397,
"author": "Tom Ritter",
"author_id": 8435,
"author_profile": "https://Stackoverflow.com/users/8435",
"pm_score": 8,
"selected": true,
"text": "using System.IO; \n\nstring path = @\"c:\\folders\\newfolder\"; // or whatever \nif (!Directory.Exists(path)) \n{ \nDirectoryInfo di = Directory.CreateDirectory(path); \ndi.Attributes = FileAttributes.Directory | FileAttributes.Hidden; \n}\n"
},
{
"answer_id": 92400,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 5,
"selected": false,
"text": "DirectoryInfo di = new DirectoryInfo(@\"C:\\SomeDirectory\");\n\n//See if directory has hidden flag, if not, make hidden\nif ((di.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden)\n{ \n //Add Hidden flag \n di.Attributes |= FileAttributes.Hidden; \n}\n"
},
{
"answer_id": 92410,
"author": "hangy",
"author_id": 11963,
"author_profile": "https://Stackoverflow.com/users/11963",
"pm_score": 2,
"selected": false,
"text": "string path = @\"c:\\folders\\newfolder\"; // or whatever \nif (!System.IO.Directory.Exists(path)) \n{ \n DirectoryInfo di = Directory.CreateDirectory(path); \n di.Attributes = FileAttributes.Directory | FileAttributes.Hidden; \n}\n"
},
{
"answer_id": 92468,
"author": "Phil J Pearson",
"author_id": 17667,
"author_profile": "https://Stackoverflow.com/users/17667",
"pm_score": 3,
"selected": false,
"text": "CreateHiddenFolder(string name) \n{ \n DirectoryInfo di = new DirectoryInfo(name); \n di.Create(); \n di.Attributes |= FileAttributes.Hidden; \n} \n"
},
{
"answer_id": 28437059,
"author": "Gul Muhammad",
"author_id": 4551403,
"author_profile": "https://Stackoverflow.com/users/4551403",
"pm_score": -1,
"selected": false,
"text": " int index = 0;\n while (index < lst.Count)\n {\n My obj = lst[index];\n lst.RemoveAll(a => a.Path.StartsWith(obj.Path));\n lst.Insert(index, obj );\n index++; \n }\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1816/"
] |
92,396
|
<p>I've always wondered this - why can't you declare variables after a case label in a switch statement? In C++ you can declare variables pretty much anywhere (and declaring them close to first use is obviously a good thing) but the following still won't work:</p>
<pre><code>switch (val)
{
case VAL:
// This won't work
int newVal = 42;
break;
case ANOTHER_VAL:
...
break;
}
</code></pre>
<p>The above gives me the following error (MSC):</p>
<blockquote>
<p>initialization of 'newVal' is skipped by 'case' label</p>
</blockquote>
<p>This seems to be a limitation in other languages too. Why is this such a problem?</p>
|
[
{
"answer_id": 92408,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 5,
"selected": false,
"text": "switch (val)\n{\n case VAL:\n {\n // This **will** work\n int newVal = 42;\n }\n break;\n\n case ANOTHER_VAL:\n ...\n break;\n}\n"
},
{
"answer_id": 92414,
"author": "Dan Shield",
"author_id": 4633,
"author_profile": "https://Stackoverflow.com/users/4633",
"pm_score": 3,
"selected": false,
"text": "switch (val)\n{\n case VAL:\n {\n int newVal = 42;\n }\n break;\n}\n"
},
{
"answer_id": 92422,
"author": "Seb Rose",
"author_id": 12405,
"author_profile": "https://Stackoverflow.com/users/12405",
"pm_score": 3,
"selected": false,
"text": "switch (thing)\n{ \n case A:\n {\n int i = 0; // Completely legal\n }\n break;\n}\n"
},
{
"answer_id": 92423,
"author": "emk",
"author_id": 12089,
"author_profile": "https://Stackoverflow.com/users/12089",
"pm_score": 4,
"selected": false,
"text": "case strcpy(char *to, char *from, size_t count) {\n int n = (count + 7) / 8;\n switch (count % 8) {\n case 0: do { *to = *from++;\n case 7: *to = *from++;\n case 6: *to = *from++;\n case 5: *to = *from++;\n case 4: *to = *from++;\n case 3: *to = *from++;\n case 2: *to = *from++;\n case 1: *to = *from++;\n } while (--n > 0);\n }\n}\n case case goto switch (...) {\n case FOO: {\n MyObject x(...);\n ...\n break; \n }\n ...\n }\n"
},
{
"answer_id": 92432,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "switch (val) \n{ \ncase VAL:\n{\n // This will work\n int newVal = 42;\n break;\n}\ncase ANOTHER_VAL: \n ...\n break;\n}\n"
},
{
"answer_id": 92439,
"author": "TJ Seabrooks",
"author_id": 3022,
"author_profile": "https://Stackoverflow.com/users/3022",
"pm_score": 11,
"selected": true,
"text": "Case switch case switch (val)\n{ \ncase VAL: \n{\n // This will work\n int newVal = 42; \n break;\n}\ncase ANOTHER_VAL: \n...\nbreak;\n}\n"
},
{
"answer_id": 92477,
"author": "slim",
"author_id": 7512,
"author_profile": "https://Stackoverflow.com/users/7512",
"pm_score": 3,
"selected": false,
"text": "switch(val)\n{\ncase VAL:\n int newVal = 42;\ndefault:\n int newVal = 23;\n}\n switch(val) {\n int x;\n case VAL:\n x=1;\n}\n"
},
{
"answer_id": 92497,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "case VAL: \n // This will work\n {\n int newVal = 42; \n }\n break;\n"
},
{
"answer_id": 92730,
"author": "Richard Corden",
"author_id": 11698,
"author_profile": "https://Stackoverflow.com/users/11698",
"pm_score": 7,
"selected": false,
"text": "switch (i)\n{\n case 0:\n int j; // 'j' has indeterminate value\n j = 0; // 'j' set (not initialized) to 0, but this statement\n // is jumped when 'i == 1'\n break;\n case 1:\n ++j; // 'j' is in scope here - but it has an indeterminate value\n break;\n}\n class A {\npublic:\n A ();\n};\n\nswitch (i) // Error - jumping over initialization of 'A'\n{\n case 0:\n A j; // Compiler implicitly calls default constructor\n break;\n case 1:\n break;\n}\n goto LABEL; // Error jumping over initialization\nint j = 0; \nLABEL:\n ;\n"
},
{
"answer_id": 92788,
"author": "Zebra North",
"author_id": 17440,
"author_profile": "https://Stackoverflow.com/users/17440",
"pm_score": 4,
"selected": false,
"text": "case 1:\n int x; // Works\n int y = 0; // Error, initialization is skipped by case\n break;\ncase 2:\n ...\n"
},
{
"answer_id": 94483,
"author": "Jeremy",
"author_id": 3657,
"author_profile": "https://Stackoverflow.com/users/3657",
"pm_score": 4,
"selected": false,
"text": "switch(val)\n{\ncase 0:\n// Do something\nif (0) {\ncase 1:\n// Do something else\n}\ncase 2:\n// Do something in all cases\n}\n"
},
{
"answer_id": 212390,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "switch (val) { \n /* This *will* work, even in C89 */\n int newVal = 42; \ncase VAL:\n newVal = 1984; \n break;\ncase ANOTHER_VAL: \n newVal = 2001;\n break;\n}\n"
},
{
"answer_id": 1368293,
"author": "Peter",
"author_id": 160054,
"author_profile": "https://Stackoverflow.com/users/160054",
"pm_score": 2,
"selected": false,
"text": "switch (something)\n{\n case 1:; // Ugly hack empty statement\n int i = 6;\n do_stuff_with_i(i);\n break;\n case 2:\n do_something();\n break;\n default:\n get_a_life();\n}\n switch (something)\n{\n case 1:\n do_something();\n break;\n case 2:\n int i = 12;\n do_something_else();\n}\n"
},
{
"answer_id": 3654361,
"author": "Dan",
"author_id": 438082,
"author_profile": "https://Stackoverflow.com/users/438082",
"pm_score": 2,
"selected": false,
"text": "switch (i) \n{ \ncase 0: \n int j; \n j = 7; \n break; \n\ncase 1: \n break;\n}\n switch (i) \n{ \ncase 0: \n int j = 7; \n break; \n\ncase 1: \n break;\n}\n"
},
{
"answer_id": 8550253,
"author": "Jeegar Patel",
"author_id": 775964,
"author_profile": "https://Stackoverflow.com/users/775964",
"pm_score": 5,
"selected": false,
"text": "Case statements are only 'labels'\n labeled-statement:\n identifier : statement\n case constant-expression : statement\n default : statement\n case 1: int x=10;\n printf(\" x is %d\",x);\nbreak;\n label can only be a part of statement and declaration is not a statement\n case 1: int x;\n x=10;\n printf(\" x is %d\",x);\n break;\n case 1:\n {\n int x=10;\n printf(\" x is %d\", x);\n }\nbreak;\n case 1: ;\n int x=10;\n printf(\" x is %d\",x);\nbreak;\n main()\n{\n int x; // Declare before\n switch(a)\n {\n case 1: x=10;\n break;\n\n case 2: x=20;\n break;\n }\n}\n switch(a)\n{\n printf(\"This will never print\"); // This will never executed\n\n case 1:\n printf(\" 1\");\n break;\n\n default:\n break;\n}\n"
},
{
"answer_id": 11408021,
"author": "Jingguo Yao",
"author_id": 431698,
"author_profile": "https://Stackoverflow.com/users/431698",
"pm_score": 0,
"selected": false,
"text": "#include <iostream>\n\nusing namespace std;\n\nclass X {\n public:\n X() \n {\n cout << \"constructor\" << endl;\n }\n ~X() \n {\n cout << \"destructor\" << endl;\n }\n};\n\ntemplate <class type>\nvoid ill_formed()\n{\n goto lx;\nly:\n type a;\nlx:\n goto ly;\n}\n\ntemplate <class type>\nvoid ok()\n{\nly:\n type a;\nlx:\n goto ly;\n}\n\nvoid test_class()\n{\n ok<X>();\n // compile error\n ill_formed<X>();\n}\n\nvoid test_scalar() \n{\n ok<int>();\n ill_formed<int>();\n}\n\nint main(int argc, const char *argv[]) \n{\n return 0;\n}\n #include <iostream>\n\nusing namespace std;\n\nint test1()\n{\n int i = 0;\n // There jumps fo \"case 1\" and \"case 2\"\n switch(i) {\n case 1:\n // Compile error because of the initializer\n int r = 1; \n break;\n case 2:\n break;\n };\n}\n\nvoid test2()\n{\n int i = 2;\n switch(i) {\n case 1:\n int r;\n r= 1; \n break;\n case 2:\n cout << \"r: \" << r << endl;\n break;\n };\n}\n\nint main(int argc, const char *argv[]) \n{\n test1();\n test2();\n return 0;\n}\n"
},
{
"answer_id": 14770979,
"author": "Olumide",
"author_id": 181783,
"author_profile": "https://Stackoverflow.com/users/181783",
"pm_score": 0,
"selected": false,
"text": "#include <cstdlib>\n\nstruct Foo{};\n\nint main()\n{\n int i = 42;\n\n switch( i )\n {\n case 42:\n Foo(); // Apparently valid\n break;\n\n default:\n break;\n }\n return EXIT_SUCCESS;\n}\n"
},
{
"answer_id": 19830820,
"author": "AnT stands with Russia",
"author_id": 187690,
"author_profile": "https://Stackoverflow.com/users/187690",
"pm_score": 9,
"selected": false,
"text": "case ANOTHER_VAL: newVal case VAL: newVal switch (val) \n { \n case VAL: /* <- C error is here */\n int newVal = 42; \n break;\n case ANOTHER_VAL: /* <- C++ error is here */\n ...\n break;\n }\n {} newVal case ANOTHER_VAL: {} case VAL: {} case VAL: switch (val) \n { \n case VAL:; /* Now it works in C! */\n int newVal = 42; \n break;\n case ANOTHER_VAL: \n ...\n break;\n }\n {} switch (val) \n { \n case VAL: \n int newVal;\n newVal = 42; \n break;\n case ANOTHER_VAL: /* Now it works in C++! */\n ...\n break;\n }\n ;"
},
{
"answer_id": 27733339,
"author": "Dalmas",
"author_id": 533552,
"author_profile": "https://Stackoverflow.com/users/533552",
"pm_score": 2,
"selected": false,
"text": "switch if/else if switch switch (value) {\n case 1:\n int a = 10;\n break;\n case 2:\n int a = 20;\n break;\n}\n if/else if if (value == 1)\n goto label_1;\nelse if (value == 2)\n goto label_2;\nelse\n goto label_end;\n\n{\nlabel_1:\n int a = 10;\n goto label_end;\nlabel_2:\n int a = 20; // Already declared !\n goto label_end;\n}\n\nlabel_end:\n // The code after the switch block\n case goto switch break case"
},
{
"answer_id": 37368542,
"author": "PcAF",
"author_id": 4932834,
"author_profile": "https://Stackoverflow.com/users/4932834",
"pm_score": 2,
"selected": false,
"text": "int i;\ni = 2;\nswitch(i)\n{\n case 1: \n int k;\n break;\n case 2:\n k = 1;\n cout<<k<<endl;\n break;\n}\n case case constant-expression statement C++ C k goto label;\n\nint x;\n\nlabel:\ncout << x << endl;\n x goto label;\n\n int x = 58; //error, jumping over declaration with initialization\n\n label:\n cout << x << endl;\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
] |
92,426
|
<p>There doesn't appear to be any Perl libraries that can open, manipulate, and re-save PDF documents that use the newer PDF version (1.5 and above I believe) that use a cross-reference stream rather than table. Does anyone know of any unix/linux-based utilities to convert a PDF to an older version? Or perhaps there's a Perl module in CPAN I missed that can handle this?</p>
|
[
{
"answer_id": 92453,
"author": "Roman Plášil",
"author_id": 16590,
"author_profile": "https://Stackoverflow.com/users/16590",
"pm_score": 1,
"selected": false,
"text": "gs -dBATCH -dNOPAUSE -sDEVICE=pdfwriter -dCompatibilityLevel=1.2"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
92,427
|
<p>Based on a simple test I ran, I don't think it's possible to put an inline <style> tag into an ASP.NET server control. The style did not end up rendering to the output HTML. Even if it was possible, I'm sure it is bad practice to do this.</p>
<p>Is it possible to do this? I can see it being useful for quick prototypes that just have 1 or 2 CSS classes to apply.</p>
|
[
{
"answer_id": 92444,
"author": "Vaibhav",
"author_id": 380,
"author_profile": "https://Stackoverflow.com/users/380",
"pm_score": 1,
"selected": false,
"text": "ControlName.Attributes[\"style\"] = \"color:red\";\n"
},
{
"answer_id": 92506,
"author": "NakedBrunch",
"author_id": 3742,
"author_profile": "https://Stackoverflow.com/users/3742",
"pm_score": 6,
"selected": false,
"text": "<asp:Label ID=\"Label1\" runat=\"server\" Text=\"Label\" style=\"color:Red;\"></asp:Label>\n"
},
{
"answer_id": 92585,
"author": "Tom Robinson",
"author_id": 12124,
"author_profile": "https://Stackoverflow.com/users/12124",
"pm_score": 5,
"selected": true,
"text": "<link> <style type=\"text\\css\"></style> myControl.Attributes[\"style\"] = \"color:red\";\n\nmyControl.Attributes.Add(\"style\", \"color:red\");\n myControl.Attributes(\"style\") = \"color:red\";\n\nmyControl.Attributes.Add(\"style\", \"color:red\");\n"
},
{
"answer_id": 24492708,
"author": "Hutch",
"author_id": 2661556,
"author_profile": "https://Stackoverflow.com/users/2661556",
"pm_score": 3,
"selected": false,
"text": "// dangerous: first style will be overwritten\nmyControl.Attributes[\"style\"] = \"text-align:center\";\n// in some other section of code\nmyControl.Attributes[\"style\"] = \"width:100%\";\n // correct: both style settings are applied\nmyControl.Attributes.CssStyle.Add(\"text-align\", \"center\");\n// in some other section of code\nmyControl.Attributes.CssStyle.Add(\"width\", \"100%\");\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2470/"
] |
92,434
|
<p>I'm having a problem with an application hanging and giving me the default "Please tell Microsoft about this problem" popup, instead of the "unhandled exception" dialog in the application.</p>
<p>In the application code, the Application.ThreadException and AppDomain.CurrentDomain.UnhandledException are both redirected to a method which writes an error log to disk, saves a screenshot to disk, and shows a friendly dialog box.</p>
<p>But when this error occurs, none of those three things happen. All I get is this in the event viewer:</p>
<p><em>EventType clr20e3, P1 myapp.exe, P2 4.0.0.0, P3 47d794d4, P4 mscorlib, P5 2.0.0.0, P6 471ebc5b, P7 15e5, P8 27, P9 system.argumentoutofrange, P10 NIL</em></p>
<p>Given that the error only seems to happen after the application has been running for several hours, I wonder if it may be a memory-leak problem. I've searched a bit for "clr20e3" but only managed to find ASP.Net stuff. My application is Windows Forms (.Net 2.0) exe, using quite a few assemblies - in both C# and some unmanaged C++.</p>
<p>I guess that it could also be an error in the error handling method - As some answers suggest, I may try logging at the start of error handler (but given that that is pretty much what I do anyway...).</p>
<p>Any help solving this problem would be much appreciated - whether it is solutions, or suggestions in how to find out what the root cause of the problem is.</p>
<p>UPDATE: The root cause of the original bug was accessing an array with a negative index (that was the system.argumentoutofrange). Why this was not trapped is a bit of a mystery to me, but given than both exceptions were sent to the same handling code, I wonder if there may not have been a condition where (for example) both were invoked and fought over a resource (the log file, for example)?</p>
<p>I managed to prove this much by doing an EventLog.WriteEntry before anything else in the error handling code. Having now added a flag to prevent re-entry in the error handling, I no longer appear to have a problem...</p>
|
[
{
"answer_id": 92495,
"author": "Wolfwyrd",
"author_id": 15570,
"author_profile": "https://Stackoverflow.com/users/15570",
"pm_score": 1,
"selected": false,
"text": "ArgumentOutOfRangeException"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11410/"
] |
92,438
|
<p>I use to run</p>
<pre><code>$s =~ s/[^[:print:]]//g;
</code></pre>
<p>on Perl to get rid of non printable characters. </p>
<p>In Python there's no POSIX regex classes, and I can't write [:print:] having it mean what I want. I know of no way in Python to detect if a character is printable or not. </p>
<p>What would you do? </p>
<p>EDIT: It has to support Unicode characters as well. The string.printable way will happily strip them out of the output.
curses.ascii.isprint will return false for any unicode character.</p>
|
[
{
"answer_id": 92441,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 2,
"selected": false,
"text": "def filter_non_printable(str):\n return ''.join([c for c in str if ord(c) > 31 or ord(c) == 9])\n"
},
{
"answer_id": 92488,
"author": "William Keller",
"author_id": 17095,
"author_profile": "https://Stackoverflow.com/users/17095",
"pm_score": 6,
"selected": false,
"text": "import string\n\nfiltered_string = filter(lambda x: x in string.printable, myStr)\n"
},
{
"answer_id": 92509,
"author": "Kirk Strauser",
"author_id": 32538,
"author_profile": "https://Stackoverflow.com/users/32538",
"pm_score": 3,
"selected": false,
"text": "from curses.ascii import isprint\n\ndef printable(input):\n return ''.join(char for char in input if isprint(char))\n"
},
{
"answer_id": 93029,
"author": "Ants Aasma",
"author_id": 107366,
"author_profile": "https://Stackoverflow.com/users/107366",
"pm_score": 8,
"selected": true,
"text": "import unicodedata, re, itertools, sys\n\nall_chars = (chr(i) for i in range(sys.maxunicode))\ncategories = {'Cc'}\ncontrol_chars = ''.join(c for c in all_chars if unicodedata.category(c) in categories)\n# or equivalently and much more efficiently\ncontrol_chars = ''.join(map(chr, itertools.chain(range(0x00,0x20), range(0x7f,0xa0))))\n\ncontrol_char_re = re.compile('[%s]' % re.escape(control_chars))\n\ndef remove_control_chars(s):\n return control_char_re.sub('', s)\n import unicodedata, re, sys\n\nall_chars = (unichr(i) for i in xrange(sys.maxunicode))\ncategories = {'Cc'}\ncontrol_chars = ''.join(c for c in all_chars if unicodedata.category(c) in categories)\n# or equivalently and much more efficiently\ncontrol_chars = ''.join(map(unichr, range(0x00,0x20) + range(0x7f,0xa0)))\n\ncontrol_char_re = re.compile('[%s]' % re.escape(control_chars))\n\ndef remove_control_chars(s):\n return control_char_re.sub('', s)\n Cc Cf Cs Co Cn"
},
{
"answer_id": 93557,
"author": "Ber",
"author_id": 11527,
"author_profile": "https://Stackoverflow.com/users/11527",
"pm_score": 4,
"selected": false,
"text": "unicodedata.category() import unicodedata\nprintable = {'Lu', 'Ll'}\ndef filter_non_printable(str):\n return ''.join(c for c in str if unicodedata.category(c) in printable)\n"
},
{
"answer_id": 25829509,
"author": "shawnrad",
"author_id": 4038859,
"author_profile": "https://Stackoverflow.com/users/4038859",
"pm_score": 4,
"selected": false,
"text": "def filter_nonprintable(text):\n import itertools\n # Use characters of control category\n nonprintable = itertools.chain(range(0x00,0x20),range(0x7f,0xa0))\n # Use translate to remove all non-printable characters\n return text.translate({character:None for character in nonprintable})\n nonprintable = (ord(c) for c in (chr(i) for i in range(sys.maxunicode)) if unicodedata.category(c)=='Cc')"
},
{
"answer_id": 46148658,
"author": "knowingpark",
"author_id": 951739,
"author_profile": "https://Stackoverflow.com/users/951739",
"pm_score": 1,
"selected": false,
"text": "import re\nt = \"\"\"\n\\n\\t<p> </p>\\n\\t<p> </p>\\n\\t<p> </p>\\n\\t<p> </p>\\n\\t<p>\n\"\"\"\npat = re.compile(r'[\\t\\n]')\nprint(pat.sub(\"\", t))\n"
},
{
"answer_id": 48133754,
"author": "Nilav Baran Ghosh",
"author_id": 1055704,
"author_profile": "https://Stackoverflow.com/users/1055704",
"pm_score": 2,
"selected": false,
"text": "''.join([x if x in string.printable else '' for x in Str])\n"
},
{
"answer_id": 51185178,
"author": "Risadinha",
"author_id": 621690,
"author_profile": "https://Stackoverflow.com/users/621690",
"pm_score": 2,
"selected": false,
"text": "regex re [[:alpha:]]; [[:^alpha:]] \\p{...}"
},
{
"answer_id": 52540226,
"author": "c6401",
"author_id": 4824716,
"author_profile": "https://Stackoverflow.com/users/4824716",
"pm_score": 3,
"selected": false,
"text": "re.sub(f'[^{re.escape(string.printable)}]', '', my_string)\n"
},
{
"answer_id": 54451873,
"author": "ChrisP",
"author_id": 892534,
"author_profile": "https://Stackoverflow.com/users/892534",
"pm_score": 4,
"selected": false,
"text": "import sys\n\n# build a table mapping all non-printable characters to None\nNOPRINT_TRANS_TABLE = {\n i: None for i in range(0, sys.maxunicode + 1) if not chr(i).isprintable()\n}\n\ndef make_printable(s):\n \"\"\"Replace non-printable characters in a string.\"\"\"\n\n # the translate method on str removes characters\n # that map to None from the string\n return s.translate(NOPRINT_TRANS_TABLE)\n\n\nassert make_printable('Café') == 'Café'\nassert make_printable('\\x00\\x11Hello') == 'Hello'\nassert make_printable('') == ''\n str.join"
},
{
"answer_id": 62437138,
"author": "Joe",
"author_id": 5306011,
"author_profile": "https://Stackoverflow.com/users/5306011",
"pm_score": 2,
"selected": false,
"text": "nonprintable = set(map(chr, list(range(0,32)) + list(range(127,160))))\nord_dict = {ord(character):None for character in nonprintable}\ndef filter_nonprintable(text):\n return text.translate(ord_dict)\n\n#use\nstr = \"this is my string\"\nstr = filter_nonprintable(str)\nprint(str)\n"
},
{
"answer_id": 62530464,
"author": "darkdragon",
"author_id": 3779655,
"author_profile": "https://Stackoverflow.com/users/3779655",
"pm_score": 3,
"selected": false,
"text": "import unicodedata\ndef filter_non_printable(s):\n return ''.join(c for c in s if not unicodedata.category(c).startswith('C'))\n"
},
{
"answer_id": 71105750,
"author": "Thomas Juul Dyhr",
"author_id": 6905974,
"author_profile": "https://Stackoverflow.com/users/6905974",
"pm_score": 2,
"selected": false,
"text": " ''.join(c for c in my_string if c.isprintable())\n"
},
{
"answer_id": 74555580,
"author": "Tim Richardson",
"author_id": 401226,
"author_profile": "https://Stackoverflow.com/users/401226",
"pm_score": 0,
"selected": false,
"text": "import sys\nimport unicodedata\n\n# the test string has embedded characters, \\u2069 \\u2068\ntest_string = \"\"\"\"ABC. 6\", \"}\"\"\"\nnonprintable = list((ord(c) for c in (chr(i) for i in range(sys.maxunicode)) if\n unicodedata.category(c) in ['Cc','Cf']))\n\ntranslate_dict = {character: None for character in nonprintable}\nprint(\"Before translate, using repr()\", repr(test_string))\nprint(\"After translate, using repr()\", repr(test_string.translate(translate_dict)))\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5190/"
] |
92,452
|
<p>I've been working on this for a few days now, and I've found several solutions but none of them incredibly simple or lightweight. The problem is basically this: We have a cluster of 10 machines, each of which is running the same software on a multithreaded ESB platform. I can deal with concurrency issues between threads on the same machine fairly easily, but what about concurrency on the same data on different machines? </p>
<p>Essentially the software receives requests to feed a customer's data from one business to another via web services. However, the customer may or may not exist yet on the other system. If it does not, we create it via a web service method. So it requires a sort of test-and-set, but I need a semaphore of some sort to lock out the other machines from causing race conditions. I've had situations before where a remote customer was created twice for a single local customer, which isn't really desirable.</p>
<p>Solutions I've toyed with conceptually are:</p>
<ol>
<li><p>Using our fault-tolerant shared file system to create "lock" files which will be checked for by each machine depending on the customer</p></li>
<li><p>Using a special table in our database, and locking the whole table in order to do a "test-and-set" for a lock record.</p></li>
<li><p>Using Terracotta, an open source server software which assists in scaling, but uses a hub-and-spoke model.</p></li>
<li><p>Using EHCache for synchronous replication of my in-memory "locks."</p></li>
</ol>
<p>I can't imagine that I'm the only person who's ever had this kind of problem. How did you solve it? Did you cook something up in-house or do you have a favorite 3rd-party product?</p>
|
[
{
"answer_id": 97897,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": true,
"text": "java.util.concurrent.locks.Lock lock = Hazelcast.getLock (\"mymonitor\");\nlock.lock ();\ntry {\n// do your stuff\n}finally {\n lock.unlock();\n}\n"
},
{
"answer_id": 103384,
"author": "Taylor Gautier",
"author_id": 19013,
"author_profile": "https://Stackoverflow.com/users/19013",
"pm_score": 2,
"selected": false,
"text": "import java.util.concurrent.locks.*;\n\npublic class Main\n{\n public static final Main instance = new Main();\n private int counter = 0;\n private ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(true);\n\n public void read()\n {\n while (true) {\n rwl.readLock().lock();\n try {\n System.out.println(\"Counter is \" + counter);\n } finally {\n rwl.readLock().unlock();\n }\n try { Thread.currentThread().sleep(1000); } catch (InterruptedException ie) { }\n }\n }\n\n public void write()\n {\n while (true) {\n rwl.writeLock().lock();\n try {\n counter++;\n System.out.println(\"Incrementing counter. Counter is \" + counter);\n } finally {\n rwl.writeLock().unlock();\n }\n try { Thread.currentThread().sleep(3000); } catch (InterruptedException ie) { }\n }\n }\n\n public static void main(String[] args)\n {\n if (args.length > 0) {\n // args --> Writer\n instance.write();\n } else {\n // no args --> Reader\n instance.read();\n }\n }\n}\n"
},
{
"answer_id": 7208058,
"author": "Slava Imeshev",
"author_id": 213480,
"author_profile": "https://Stackoverflow.com/users/213480",
"pm_score": 0,
"selected": false,
"text": "ReadWriteLock rwLock = Cacheonix.getInstance().getCluster().getReadWriteLock();\nLock lock = rwLock.getWriteLock();\ntry {\n ...\n} finally {\n lock.unlock();\n}\n"
},
{
"answer_id": 21073494,
"author": "Nikita Koksharov",
"author_id": 764206,
"author_profile": "https://Stackoverflow.com/users/764206",
"pm_score": 2,
"selected": false,
"text": "java.util.Lock Config config = new Config();\nconfig.addAddress(\"some.server.com:8291\");\nRedisson redisson = Redisson.create(config);\n\nLock lock = redisson.getLock(\"anyLock\");\nlock.lock();\ntry {\n ...\n} finally {\n lock.unlock();\n}\n\nredisson.shutdown();\n"
},
{
"answer_id": 39090822,
"author": "user2179737",
"author_id": 2179737,
"author_profile": "https://Stackoverflow.com/users/2179737",
"pm_score": 0,
"selected": false,
"text": "JdbcSemaphore semaphore = new JdbcSemaphore(ds, semName, maxReservations);\nboolean acq = semaphore.acquire(acquire, 1, TimeUnit.MINUTES);\nif (acq) {\n // do stuff\n semaphore.release();\n} else {\n throw new TimeoutException();\n}\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7567/"
] |
92,465
|
<p>I've started a conversion of a project to Moose and the first thing I noticed was that my critic/tidy tests go to hell. Moose, Tidy and Critic don't seem to like each other as much as they used to.</p>
<p>Are there docs anywhere on how to make critic/tidy be more appreciative of the Moose dialect? What do most Moose users do? Relax/ditch critic for the more heavy Moose modules? Custom policies?</p>
|
[
{
"answer_id": 101658,
"author": "jplindstrom",
"author_id": 10155,
"author_profile": "https://Stackoverflow.com/users/10155",
"pm_score": 3,
"selected": false,
"text": "my $apple = Apple->new({\n color => \"red\",\n type => \"delicious\",\n});\n my $apple = Apple->new({\n color => \"red\",\n type => \"delicious\",\n});\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91911/"
] |
92,471
|
<p>I have a Cocoa app that uses a WebView to display an HTML interface. How would I go about calling an Objective-C method from a Javascript function within the HTML interface?</p>
|
[
{
"answer_id": 30467359,
"author": "Michael Diedrick",
"author_id": 4279586,
"author_profile": "https://Stackoverflow.com/users/4279586",
"pm_score": 2,
"selected": false,
"text": "[testWinWebView setFrameLoadDelegate:self];\n - (void)webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)windowScriptObject forFrame:(WebFrame *)frame {\n //add the controller to the script environment\n //the \"ObjCConnector\" object will now be available to JavaScript\n [windowScriptObject setValue:self forKey:@\"ObjCConnector\"];\n}\n // a few methods to log activity\n- (void)acceptJavaScriptFunctionOne:(NSString*) logText {\n NSLog(@\"acceptJavaScriptFunctionOne: %@\",logText);\n}\n- (void)acceptJavaScriptFunctionTwo:(NSString*) logText {\n NSLog(@\"acceptJavaScriptFunctionTwo: %@\",logText);\n}\n\n//this returns a nice name for the method in the JavaScript environment\n+(NSString*)webScriptNameForSelector:(SEL)sel {\n NSLog(@\"%@ received %@ with sel='%@'\", self, NSStringFromSelector(_cmd), NSStringFromSelector(sel));\n if(sel == @selector(acceptJavaScriptFunctionOne:))\n return @\"functionOne\"; // this is what you're sending in from JS to map to above line\n if(sel == @selector(acceptJavaScriptFunctionTwo:))\n return @\"functionTwo\"; // this is what you're sending in from JS to map to above line\n return nil;\n}\n\n//this allows JavaScript to call the -logJavaScriptString: method\n+ (BOOL)isSelectorExcludedFromWebScript:(SEL)sel {\n NSLog(@\"isSelectorExcludedFromWebScript: %@\", NSStringFromSelector(sel));\n if(sel == @selector(acceptJavaScriptFunctionOne:) ||\n sel == @selector(acceptJavaScriptFunctionTwo:))\n return NO;\n return YES;\n}\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5168/"
] |
92,475
|
<p>I've implemented a stopwatch that works fine without considering that bank holidays and weekends shouldn't be counted in the total duration. I was looking for some open-source library where I could get the elapsed time, passing a start instant, end instant and a set of bank holidays (weekends aren't counted in). The only library that makes me things easier is net.sf.jtemporal, but I have still to amplify the functionality.
Could anyone tell me if there is some useful library to get the wanted functionality?</p>
|
[
{
"answer_id": 92733,
"author": "bastos.sergio",
"author_id": 12772,
"author_profile": "https://Stackoverflow.com/users/12772",
"pm_score": 1,
"selected": false,
"text": "private long CalculateTimeSpan(DateTime BeginDate, DateTime EndDate, ArrayList<DateTime> BankHollidays)\n{\n long ticks = 0;\n while (BeginDate <= EndDate) // iterate until reaching end\n {\n if ((BeginDate is holliday?) || (BeginDate is Weekend?))\n skip;\n else\n ticks += (24*60*60*1000);\n\n BeginDate = BeginDate + 1 day; // add one day and iterate\n }\n\n return ticks;\n}\n"
},
{
"answer_id": 138351,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "/**\n * Calculate elapsed time in milliseconds\n * \n * @param startTime\n * @param endTime\n * @return elapsed time in milliseconds\n */\n\nprotected long calculateElapsedTimeAux(long startTime, long endTime) { \n CustomizedGregorianCalendar calStartTime = new CustomizedGregorianCalendar(this.getTimeZone());\n CustomizedGregorianCalendar calEndTime = new CustomizedGregorianCalendar(this.getTimeZone());\n calStartTime.setTimeInMillis(startTime);\n calEndTime.setTimeInMillis(endTime);\n long ticks = 0;\n\n while (calStartTime.before(calEndTime)) { // iterate until reaching end \n ticks = ticks + increaseElapsedTime(calStartTime, calEndTime);\n }\n\n return ticks;\n}\n\nprivate long increaseElapsedTime(CustomizedGregorianCalendar calStartTime, CustomizedGregorianCalendar calEndTime) {\n long interval;\n long ticks = 0;\n\n interval = HOURS_PER_DAY*MINUTES_PER_HOUR*SECONDS_PER_MIN*MILLISECONDS_PER_SEC; // Interval of one day\n\n if ( calEndTime.getTimeInMillis() - calStartTime.getTimeInMillis() < interval) {\n interval = calEndTime.getTimeInMillis() - calStartTime.getTimeInMillis();\n }\n\n ticks = increaseElapsedTimeAux(calStartTime, calEndTime, interval);\n calStartTime.setTimeInMillis(calStartTime.getTimeInMillis() + interval);\n\n return ticks;\n}\n\nprotected long increaseElapsedTimeAux(CustomizedGregorianCalendar calStartTime, CustomizedGregorianCalendar calEndTime, long interval) {\n long ticks = 0;\n\n CustomizedGregorianCalendar calNextStartTime = new CustomizedGregorianCalendar(this.getTimeZone());\n calNextStartTime.setTimeInMillis(calStartTime.getTimeInMillis() + interval);\n\n if ( (calStartTime.isWorkingDay(_nonWorkingDays) && calNextStartTime.isWorkingDay(_nonWorkingDays)) ) { // calStartTime and calNextStartTime are working days\n ticks = interval;\n\n }\n else {\n if (calStartTime.isWorkingDay(_nonWorkingDays)) { // calStartTime is a working day and calNextStartTime is a non-working day\n ticks = (calStartTime.getNextDay().getTimeInMillis() - calStartTime.getTimeInMillis());\n }\n else {\n if (calNextStartTime.isWorkingDay(_nonWorkingDays)) { // calStartTime is a non-working day and calNextStartTime is a working day\n ticks = (calNextStartTime.getTimeInMillis() - calStartTime.getNextDay().getTimeInMillis());\n }\n else {} // calStartTime and calEndTime are non-working days\n }\n }\n\n return ticks;\n}\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
92,504
|
<p>I'm trying to create a self signed certificate for use with Apache Tomcat 6. Every certificate I can make always results in the browser connecting with AES-128. The customer would like me to demonstrate that I can create a connection at AES-256.</p>
<p>I've tried java's keytool and openssl. I've tried with a variety of parameters, but can't seem to specify anything about the keysize, just the signature size.</p>
<p>How can I get the browser-tomcat connection to use AES-256 with a self signed certificate?</p>
|
[
{
"answer_id": 93696,
"author": "delfuego",
"author_id": 16414,
"author_profile": "https://Stackoverflow.com/users/16414",
"pm_score": 5,
"selected": true,
"text": "keytool -genkey -alias tomcat -keyalg RSA\n import java.util.Arrays;\nimport javax.net.ssl.SSLSocketFactory;\n\npublic class CipherSuites {\n public static void main(String[] args) {\n SSLSocketFactory sslsf = (SSLSocketFactory) SSLSocketFactory.getDefault();\n String[] ciphers = sslsf.getDefaultCipherSuites();\n Arrays.sort(ciphers);\n for (String cipher : ciphers) {\n System.out.println(cipher);\n }\n }\n}\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17583/"
] |
92,514
|
<p>Is there any way to create a ODBC DSN with C#?</p>
<p>Maybe a P/invoke?</p>
|
[
{
"answer_id": 92645,
"author": "Juanma",
"author_id": 3730,
"author_profile": "https://Stackoverflow.com/users/3730",
"pm_score": 2,
"selected": false,
"text": "HKLM\\Software\\ODBC\\ODBC.INI\\ODBC Data Sources\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1098074/"
] |
92,522
|
<p>What is the best way to issue a http get in VB.net? I want to get the result of a request like <a href="http://api.hostip.info/?ip=68.180.206.184" rel="noreferrer">http://api.hostip.info/?ip=68.180.206.184</a> </p>
|
[
{
"answer_id": 92544,
"author": "hangy",
"author_id": 11963,
"author_profile": "https://Stackoverflow.com/users/11963",
"pm_score": 7,
"selected": true,
"text": "Dim webClient As New System.Net.WebClient\nDim result As String = webClient.DownloadString(\"http://api.hostip.info/?ip=68.180.206.184\")\n System.Net.WebClient webClient = new System.Net.WebClient();\nstring result = webClient.DownloadString(\"http://api.hostip.info/?ip=68.180.206.184\");\n"
},
{
"answer_id": 92549,
"author": "chrissie1",
"author_id": 2936,
"author_profile": "https://Stackoverflow.com/users/2936",
"pm_score": 3,
"selected": false,
"text": "Try\n Dim _WebRequest As System.Net.WebRequest = Nothing\n _WebRequest = System.Net.WebRequest.Create(http://api.hostip.info/?ip=68.180.206.184)\nCatch ex As Exception\n Windows.Forms.MessageBox.Show(ex.Message)\n Exit Sub\nEnd Try\n\nTry\n _NormalImage = Image.FromStream(_WebRequest.GetResponse().GetResponseStream())\nCatch ex As Exception\n Windows.Forms.MessageBox.Show(ex.Message)\n Exit Sub\nEnd Try\n"
},
{
"answer_id": 92553,
"author": "Oliver Mellet",
"author_id": 12001,
"author_profile": "https://Stackoverflow.com/users/12001",
"pm_score": 2,
"selected": false,
"text": "System.Net.WebClient.DownloadFile DownloadString"
},
{
"answer_id": 92576,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 1,
"selected": false,
"text": "WebRequest request = WebRequest.CreateDefault(RequestUrl);\nrequest.Method = \"GET\";\n\nWebResponse response;\ntry { response = request.GetResponse(); }\ncatch (WebException exc) { response = exc.Response; }\n\nif (response == null)\n throw new HttpException((int)HttpStatusCode.NotFound, \"The requested url could not be found.\");\n\nusing(StreamReader reader = new StreamReader(response.GetResponseStream())) {\n string requestedText = reader.ReadToEnd();\n\n // do what you want with requestedText\n}\n"
},
{
"answer_id": 92588,
"author": "Wolfwyrd",
"author_id": 15570,
"author_profile": "https://Stackoverflow.com/users/15570",
"pm_score": 5,
"selected": false,
"text": "Try\n Dim fr As System.Net.HttpWebRequest\n Dim targetURI As New Uri(\"http://whatever.you.want.to.get/file.html\") \n\n fr = DirectCast(HttpWebRequest.Create(targetURI), System.Net.HttpWebRequest)\n If (fr.GetResponse().ContentLength > 0) Then\n Dim str As New System.IO.StreamReader(fr.GetResponse().GetResponseStream())\n Response.Write(str.ReadToEnd())\n str.Close(); \n End If \nCatch ex As System.Net.WebException\n 'Error in accessing the resource, handle it\nEnd Try\n Sub Main()\n 'Address of URL\n Dim URL As String = http://whatever.com\n ' Get HTML data\n Dim client As WebClient = New WebClient()\n Dim data As Stream = client.OpenRead(URL)\n Dim reader As StreamReader = New StreamReader(data)\n Dim str As String = \"\"\n str = reader.ReadLine()\n Do While str.Length > 0\n Console.WriteLine(str)\n str = reader.ReadLine()\n Loop\nEnd Sub\n"
},
{
"answer_id": 43911430,
"author": "sanket parikh",
"author_id": 5414397,
"author_profile": "https://Stackoverflow.com/users/5414397",
"pm_score": 0,
"selected": false,
"text": "Public Function getLoginresponce(ByVal email As String, ByVal password As String) As String\n Dim requestUrl As String = \"your api\"\n Dim request As HttpWebRequest = TryCast(WebRequest.Create(requestUrl), HttpWebRequest)\n Dim response As HttpWebResponse = TryCast(request.GetResponse(), HttpWebResponse)\n Dim dataStream As Stream = response.GetResponseStream()\n Dim reader As New StreamReader(dataStream)\n Dim responseFromServer As String = reader.ReadToEnd()\n Dim result = responseFromServer\n reader.Close()\n response.Close()\n Return result\nEnd Function\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4221/"
] |
92,533
|
<p>Based on <a href="https://stackoverflow.com/questions/6209/split-a-string-ignoring-quoted-sections#6243">"Split a string by spaces in Python"</a>, which uses <em>shlex.split</em> to split a string with quotes smartly, I would be interested in hearing about other common tasks solved by non-obvious standard library functions. </p>
<p>If this turns into <a href="http://www.doughellmann.com/projects/PyMOTW/" rel="nofollow noreferrer">Module of The Week</a>, that's fine too. </p>
|
[
{
"answer_id": 95159,
"author": "Gregg Lind",
"author_id": 15842,
"author_profile": "https://Stackoverflow.com/users/15842",
"pm_score": 2,
"selected": false,
"text": "# in R, shorter iterables are automatically cycled\n# and all functions \"apply\" in a \"map\"-like way over lists\n> 0:10 + 0:2\n [1] 0 2 4 3 5 7 6 8 10 9 11\n ## this code is terrible, but it demos the idea.\nfrom itertools import cycle\ndef addR(L1,L2):\n n = max( len(L1), len(L2))\n out = [None,]*n\n gen1,gen2 = cycle(L1), cycle(L2)\n ii = 0\n while ii < n:\n out[ii] = gen1.next() + gen2.next()\n ii += 1\n return out\n\nIn [21]: addR(range(10), range(3))\nOut[21]: [0, 2, 4, 3, 5, 7, 6, 8, 10, 9]\n"
},
{
"answer_id": 95825,
"author": "elifiner",
"author_id": 15109,
"author_profile": "https://Stackoverflow.com/users/15109",
"pm_score": 3,
"selected": false,
"text": ">>> import bisect\n>>> lst = [4, 7, 10, 23, 25, 100, 103, 201, 333]\n>>> bisect.bisect_left(lst, 23)\n3\n"
},
{
"answer_id": 101353,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 1,
"selected": false,
"text": "TURN_LEFT_90= 1j\nTURN_RIGHT_90= -1j\n\ncoord= 5+4j # x=5 y=4\nprint coord*TURN_LEFT_90\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15842/"
] |
92,537
|
<p>I have an AST derived from the ANTLR Parser Generator for Java. What I want to do is somehow construct a control flow graph of the source code, where each statement or expression is a unique Node. I understand there must be some recursiveness to this identification, I was wondering what you would suggest as the best option and if ANTLR has a toolset I can use for this job.
Cheers,
Chris</p>
<hr>
<p>EDIT - My main concern is to get a control flow graph(CFG) from the AST. This way I can get a tree representation of the source. To clarify, both the source code and the implementation language is Java.</p>
|
[
{
"answer_id": 93598,
"author": "EfForEffort",
"author_id": 14113,
"author_profile": "https://Stackoverflow.com/users/14113",
"pm_score": 5,
"selected": true,
"text": "for while"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5915/"
] |
92,540
|
<p>In a WinForms 2.0 C# application, what is the typical method used for saving and restoring form position and size in an application?</p>
<p>Related, is it possible to add new User scoped application settings AT RUNTIME? I totally see how to add settings at design time, that's not a problem. But what if I want to create one at runtime?</p>
<p>More details:</p>
<p>My application is a conversion of an existing Visual FoxPro application. I've been trying to read as much as I can about application settings, user settings, etc. and get myself clear on the .Net way of doing things, but there are still several things I am confused on.</p>
<p>In the Fox app, saved settings are stored in the registry. My forms are subclassed, and I have base class code that automatically saves the form position and size in the registry keyed on the form name. Whenever I create a new form, I don't have to do anything special to get this behavior; it's built in to the base class. My .Net forms are also subclassed, that part is working well.</p>
<p>In .Net, I get the impression I'm supposed to use User scoped settings for things like user preferences. Size and location of a form definitely seem like a user preference. But, I can't see any way to automatically add these settings to the project. In other words, every time I add a new form to my project (and their are 100's of forms), I have to remember to ADD a User scoped application setting and be sure to give it the same name as the form, i.e., "FormMySpecialSizePosition" to hold the size and position. I'd rather not have to remember to do that. Is this just tough luck? Or am I totally barking up the wrong tree by trying to use User scoped settings? Do I need to create my own XML file to hold settings, so that I can do whatever I want (i.e, add a new setting at runtime)? Or something else?</p>
<p>Surely this is very common and somebody can tell the "right" way to do it.</p>
|
[
{
"answer_id": 93211,
"author": "Stormenet",
"author_id": 2090,
"author_profile": "https://Stackoverflow.com/users/2090",
"pm_score": 0,
"selected": false,
"text": "public class myForm : Form {\nprotected override void OnLoad(){\n //load the settings and apply them\n base.OnLoad();\n}\n\nprotected override void OnClose(){\n //save the settings\n base.OnClose();\n}\n}\nthen for the other forms:\n\npublic class frmMainScreen : myForm {\n// you get the settings for free ;)\n}"
},
{
"answer_id": 236274,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "private void Form1_Load( object sender, EventArgs e )\n{\n // restore location and size of the form on the desktop\n this.DesktopBounds =\n new Rectangle(Properties.Settings.Default.Location,\n Properties.Settings.Default.Size);\n // restore form's window state\n this.WindowState = ( FormWindowState )Enum.Parse(\n typeof(FormWindowState),\n Properties.Settings.Default.WindowState);\n}\n\nprivate void Form1_FormClosing( object sender, FormClosingEventArgs e )\n{\n System.Drawing.Rectangle bounds = this.WindowState != FormWindowState.Normal ? this.RestoreBounds : this.DesktopBounds;\n Properties.Settings.Default.Location = bounds.Location;\n Properties.Settings.Default.Size = bounds.Size;\n Properties.Settings.Default.WindowState =\n Enum.GetName(typeof(FormWindowState), this.WindowState);\n // persist location ,size and window state of the form on the desktop\n Properties.Settings.Default.Save();\n}\n"
},
{
"answer_id": 1808291,
"author": "fusi",
"author_id": 159132,
"author_profile": "https://Stackoverflow.com/users/159132",
"pm_score": 0,
"selected": false,
"text": "XML Dim winRect As String() = util.ConfigFile.GetUserConfigInstance().GetValue(\"appWindow.rect\").Split(\",\")\nDim winState As String = util.ConfigFile.GetUserConfigInstance().GetValue(\"appWindow.state\")\n\nMe.WindowState = FormWindowState.Normal\n\nMe.Left = CType(winRect(0), Integer)\nMe.Top = CType(winRect(1), Integer)\nMe.Width = CType(winRect(2), Integer)\nMe.Height = CType(winRect(3), Integer)\n\nIf winState = \"maximised\" Then\n Me.WindowState = FormWindowState.Maximized\nEnd If\n Dim winState As String = \"normal\"\nIf Me.WindowState = FormWindowState.Maximized Then\n winState = \"maximised\"\nElseIf Me.WindowState = FormWindowState.Minimized Then\n winState = \"minimised\"\nEnd If\n\nIf Me.WindowState = FormWindowState.Normal Then\n\n Dim winRect As String = CType(Me.Left, String) & \",\" & CType(Me.Top, String) & \",\" & CType(Me.Width, String) & \",\" & CType(Me.Height, String)\n ' only save window rectangle if its not maximised/minimised\n util.ConfigFile.GetUserConfigInstance().SetValue(\"appWindow.rect\", winRect)\nEnd If\n\nutil.ConfigFile.GetUserConfigInstance().SetValue(\"appWindow.state\", winState)\n"
},
{
"answer_id": 9351887,
"author": "slolife",
"author_id": 698,
"author_profile": "https://Stackoverflow.com/users/698",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Windows.Forms;\nusing Microsoft.Win32;\n\n/// <summary>Summary description for FormPlacement.</summary>\npublic class PersistentForm : System.Windows.Forms.Form\n{\n private const string DIALOGKEY = \"Dialogs\";\n\n /// <summary></summary>\n protected override void OnCreateControl()\n {\n LoadSettings();\n base.OnCreateControl ();\n }\n\n /// <summary></summary>\n protected override void OnClosing(System.ComponentModel.CancelEventArgs e)\n {\n SaveSettings();\n base.OnClosing(e);\n }\n\n /// <summary>Saves the form's settings.</summary>\n public void SaveSettings()\n {\n RegistryKey dialogKey = Application.UserAppDataRegistry.CreateSubKey(DIALOGKEY);\n if (dialogKey != null)\n {\n RegistryKey formKey = dialogKey.CreateSubKey(this.GetType().ToString());\n if (formKey != null)\n {\n formKey.SetValue(\"Left\", this.Left);\n formKey.SetValue(\"Top\", this.Top);\n formKey.Close();\n }\n dialogKey.Close();\n }\n }\n\n /// <summary></summary>\n public void LoadSettings()\n {\n RegistryKey dialogKey = Application.UserAppDataRegistry.OpenSubKey(DIALOGKEY);\n if (dialogKey != null)\n {\n RegistryKey formKey = dialogKey.OpenSubKey(this.GetType().ToString());\n if (formKey != null)\n {\n this.Left = (int)formKey.GetValue(\"Left\");\n this.Top = (int)formKey.GetValue(\"Top\");\n formKey.Close();\n }\n dialogKey.Close();\n }\n }\n}\n"
},
{
"answer_id": 9436526,
"author": "Niall Douglas",
"author_id": 805579,
"author_profile": "https://Stackoverflow.com/users/805579",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Drawing;\nusing System.Windows.Forms;\nusing Microsoft.Win32;\nusing System.ComponentModel;\nusing System.Security.Cryptography;\n\nnamespace nedprod\n{\n abstract public class WindowSettings\n {\n private Form form;\n\n public FormWindowState state;\n public Point location;\n public Size size;\n\n public WindowSettings(Form _form)\n {\n this.form = _form;\n }\n internal class MD5Sum\n {\n static MD5CryptoServiceProvider engine = new MD5CryptoServiceProvider();\n private byte[] sum = engine.ComputeHash(BitConverter.GetBytes(0));\n public MD5Sum() { }\n public MD5Sum(string s)\n {\n for (var i = 0; i < sum.Length; i++)\n sum[i] = byte.Parse(s.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber);\n }\n public void Add(byte[] data)\n {\n byte[] temp = new byte[sum.Length + data.Length];\n var i=0;\n for (; i < sum.Length; i++)\n temp[i] = sum[i];\n for (; i < temp.Length; i++)\n temp[i] = data[i - sum.Length];\n sum=engine.ComputeHash(temp);\n }\n public void Add(int data)\n {\n Add(BitConverter.GetBytes(data));\n }\n public void Add(string data)\n {\n Add(Encoding.UTF8.GetBytes(data));\n }\n public static bool operator ==(MD5Sum a, MD5Sum b)\n {\n if (a.sum == b.sum) return true;\n if (a.sum.Length != b.sum.Length) return false;\n for (var i = 0; i < a.sum.Length; i++)\n if (a.sum[i] != b.sum[i]) return false;\n return true;\n }\n public static bool operator !=(MD5Sum a, MD5Sum b)\n {\n return !(a == b);\n }\n public override bool Equals(object obj)\n {\n try\n {\n return (bool)(this == (MD5Sum)obj);\n }\n catch\n {\n return false;\n }\n }\n public override int GetHashCode()\n {\n return ToString().GetHashCode();\n }\n public override string ToString()\n {\n StringBuilder sb = new StringBuilder();\n for (var i = 0; i < sum.Length; i++)\n sb.Append(sum[i].ToString(\"x2\"));\n return sb.ToString();\n }\n }\n private MD5Sum screenconfig()\n {\n MD5Sum md5=new MD5Sum();\n md5.Add(Screen.AllScreens.Length); // Hash the number of screens\n for(var i=0; i<Screen.AllScreens.Length; i++)\n {\n md5.Add(Screen.AllScreens[i].Bounds.ToString()); // Hash the dimensions of this screen\n }\n return md5;\n }\n public void load()\n {\n using (RegistryKey r = Registry.CurrentUser.OpenSubKey(@\"Software\\\" + CompanyId() + @\"\\\" + AppId() + @\"\\Window State\\\" + form.Name))\n {\n if (r != null)\n {\n try\n {\n string _location = (string)r.GetValue(\"location\"), _size = (string)r.GetValue(\"size\");\n state = (FormWindowState)r.GetValue(\"state\");\n location = (Point)TypeDescriptor.GetConverter(typeof(Point)).ConvertFromInvariantString(_location);\n size = (Size)TypeDescriptor.GetConverter(typeof(Size)).ConvertFromInvariantString(_size);\n\n // Don't do anything if the screen config has since changed (otherwise windows vanish off the side)\n if (screenconfig() == new MD5Sum((string) r.GetValue(\"screenconfig\")))\n {\n form.Location = location;\n form.Size = size;\n // Don't restore if miminised (it's unhelpful as the user misses the fact it's opened)\n if (state != FormWindowState.Minimized)\n form.WindowState = state;\n }\n }\n catch (Exception)\n {\n }\n }\n }\n }\n public void save()\n {\n state = form.WindowState;\n if (form.WindowState == FormWindowState.Normal)\n {\n size = form.Size;\n location = form.Location;\n }\n else\n {\n size = form.RestoreBounds.Size;\n location = form.RestoreBounds.Location;\n }\n using (RegistryKey r = Registry.CurrentUser.CreateSubKey(@\"Software\\\" + CompanyId()+@\"\\\"+AppId() + @\"\\Window State\\\" + form.Name, RegistryKeyPermissionCheck.ReadWriteSubTree))\n {\n r.SetValue(\"state\", (int) state, RegistryValueKind.DWord);\n r.SetValue(\"location\", location.X.ToString() + \",\" + location.Y.ToString(), RegistryValueKind.String);\n r.SetValue(\"size\", size.Width.ToString()+\",\"+size.Height.ToString(), RegistryValueKind.String);\n r.SetValue(\"screenconfig\", screenconfig().ToString(), RegistryValueKind.String);\n }\n }\n abstract protected string CompanyId();\n abstract protected string AppId();\n }\n}\n namespace <your app/plugin namespace name>\n{\n public class WindowSettings : nedprod.WindowSettings\n {\n public WindowSettings(Form form) : base(form) { }\n protected override string CompanyId() { return \"<your company name>\"; }\n protected override string AppId() { return \"<your app name>\"; }\n }\n ....\n private void IssuesForm_FormClosing(object sender, FormClosingEventArgs e)\n {\n new WindowSettings(this).save();\n }\n\n private void IssuesForm_Load(object sender, EventArgs e)\n {\n new WindowSettings(this).load();\n }\n"
},
{
"answer_id": 25963789,
"author": "Jonathan Wood",
"author_id": 522663,
"author_profile": "https://Stackoverflow.com/users/522663",
"pm_score": 0,
"selected": false,
"text": "private void SaveWindowPosition()\n{\n Rectangle rect = (WindowState == FormWindowState.Normal) ?\n new Rectangle(DesktopBounds.Left, DesktopBounds.Top, DesktopBounds.Width, DesktopBounds.Height) :\n new Rectangle(RestoreBounds.Left, RestoreBounds.Top, RestoreBounds.Width, RestoreBounds.Height);\n RegistrySettings.SetSetting(\"WindowPosition\", String.Format(\"{0},{1},{2},{3},{4}\",\n (int)this.WindowState,\n rect.Left, rect.Top, rect.Width, rect.Height));\n}\n\nprivate void RestoreWindowPosition()\n{\n try\n {\n string s = RegistrySettings.GetSetting(\"WindowPosition\", String.Empty) as string;\n if (s != null)\n {\n List<int> settings = s.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)\n .Select(v => int.Parse(v)).ToList();\n if (settings.Count == 5)\n {\n this.SetBounds(\n settings[1],\n settings[2],\n settings[3],\n settings[4]);\n this.WindowState = (FormWindowState)settings[0];\n }\n }\n }\n catch { /* Just leave current position if error */ }\n}\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
92,546
|
<p>When refactoring away some <code>#defines</code> I came across declarations similar to the following in a C++ header file:</p>
<pre><code>static const unsigned int VAL = 42;
const unsigned int ANOTHER_VAL = 37;
</code></pre>
<p>The question is, what difference, if any, will the static make? Note that multiple inclusion of the headers isn't possible due to the classic <code>#ifndef HEADER</code> <code>#define HEADER</code> <code>#endif</code> trick (if that matters).</p>
<p>Does the static mean only one copy of <code>VAL</code> is created, in case the header is included by more than one source file?</p>
|
[
{
"answer_id": 92641,
"author": "Justsalt",
"author_id": 13693,
"author_profile": "https://Stackoverflow.com/users/13693",
"pm_score": 8,
"selected": true,
"text": "static VAL VAL static VAL extern extern static const static extern static"
},
{
"answer_id": 92693,
"author": "slicedlime",
"author_id": 11230,
"author_profile": "https://Stackoverflow.com/users/11230",
"pm_score": 6,
"selected": false,
"text": "static int TEST = 0;\nvoid test();\n #include <iostream>\n#include \"test.h\"\n\nint main(void) {\n std::cout << &TEST << std::endl;\n test();\n}\n #include <iostream>\n#include \"test.h\"\n\nvoid test() {\n std::cout << &TEST << std::endl;\n}\n"
},
{
"answer_id": 93663,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 7,
"selected": false,
"text": "static extern .c .cpp static extern static extern extern VAL static ANOTHER_VAL extern static const extern VAL ANOTHER_VAL static"
},
{
"answer_id": 2718315,
"author": "Nitin",
"author_id": 326492,
"author_profile": "https://Stackoverflow.com/users/326492",
"pm_score": 3,
"selected": false,
"text": "const static const int i = 10;\n #include \"a.h\"\n\nfunc()\n{\n cout << i;\n}\n #include \"a.h\"\n\nfunc1()\n{\n cout << i;\n}\n i"
},
{
"answer_id": 28106844,
"author": "Konstantin Burlachenko",
"author_id": 1154447,
"author_profile": "https://Stackoverflow.com/users/1154447",
"pm_score": 1,
"selected": false,
"text": "bruziuz:~/test$ cat a.c\nconst int b = 22;\nint main(){return 0;}\nbruziuz:~/test$ cat b.c\nconst int b=2;\nbruziuz:~/test$ gcc -x c -std=c89 a.c b.c\n/tmp/ccSKKIRZ.o:(.rodata+0x0): multiple definition of `b'\n/tmp/ccDSd0V3.o:(.rodata+0x0): first defined here\ncollect2: error: ld returned 1 exit status\nbruziuz:~/test$ gcc -x c++ -std=c++03 a.c b.c \nbruziuz:~/test$ \nbruziuz:~/test$ gcc --version | head -n1\ngcc (Ubuntu 5.4.0-6ubuntu1~16.04.5) 5.4.0 20160609\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
] |
92,561
|
<p>I am developing an application, and have URLs in the format <code>www.example.com/some_url/some_parameter/some_keyword</code>. I know by design that there is a maximum length that these URLs will have (and still be valid). Should I validate the URL length with every request in order to protect against buffer overflow/injection attacks? I believe this is an obvious yes but I'm not a security expert so perhaps I am missing something.</p>
|
[
{
"answer_id": 31567280,
"author": "thecoshman",
"author_id": 300797,
"author_profile": "https://Stackoverflow.com/users/300797",
"pm_score": 0,
"selected": false,
"text": "@Path(\"/person/(.{0..100}\")"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4527/"
] |
92,613
|
<p>I have some code which is supposed to display a short message. Here's the pertinent code:</p>
<pre><code>DATA SEGMENT 'DATA'
MSG DB 0AH, 0DH, 'Hello, Adam', '$'
CHAR DB 00H
DATA ENDS
CODE SEGMENT 'CODE'
PRINT_MSG:
MOV AH, 09H ;Command to print string of characters
MOV DX, OFFSET MSG ;Mov address of message into DX
INT 21H ;DOS Interrupt
JMP WAITING ;Loop back to waiting state
CODE ENDS
</code></pre>
<p>And the output is:</p>
<pre><code>E:\ece323\software\lab2>MAIN.EXE
?F ^?¶ ? N? ? -!-
Hello, Adam-
</code></pre>
<p>What is going on here?</p>
|
[
{
"answer_id": 92708,
"author": "Nils Pipenbrinck",
"author_id": 15955,
"author_profile": "https://Stackoverflow.com/users/15955",
"pm_score": 2,
"selected": false,
"text": " MOV DX, offset MSG\n LDS DX, MSG ; Check that, it's been ages since I've written 16 bit code.\n MOV AX, SEG DATA ; check that - can be SEGMENT or so as well.\n MOV DS, AX\n"
},
{
"answer_id": 92767,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "DATA SEGMENT 'DATA'\nERROR_MSG DB 'DS:DX is wrong'\nMSG DB 0AH, 0DH, 'Hello, Adam', '$'\nCHAR DB 00H\nDATA ENDS\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13790/"
] |
92,620
|
<p>I came back today to an old script I had for logging into Gmail via SSL. The script worked fine last time I ran it (several months ago) but now it dies immediately with:</p>
<pre><code><urlopen error The read operation timed out>
</code></pre>
<p>If I set the timeout (no matter how long), it dies even more immediately with:</p>
<pre><code><urlopen error The connect operation timed out>
</code></pre>
<p>The latter is reproducible with:</p>
<pre><code>import socket
socket.setdefaulttimeout(30000)
sock = socket.socket()
sock.connect(('www.google.com', 443))
ssl = socket.ssl(sock)
</code></pre>
<p>returning:</p>
<pre><code>socket.sslerror: The connect operation timed out
</code></pre>
<p>but I can't seem to reproduce the former and, after much stepping thru the code, I have no clue what's causing any of this.</p>
|
[
{
"answer_id": 93404,
"author": "defnull",
"author_id": 407880,
"author_profile": "https://Stackoverflow.com/users/407880",
"pm_score": 2,
"selected": false,
"text": "import socket\nsocket.setdefaulttimeout(30000)\nsock = socket.socket()\nsock.connect(('www.google.com', 443))\nssl = socket.ssl(sock)\nssl.server()\n--> '/C=US/ST=California/L=Mountain View/O=Google Inc/CN=www.google.com'\n"
},
{
"answer_id": 67149643,
"author": "Martin Gergov",
"author_id": 1857005,
"author_profile": "https://Stackoverflow.com/users/1857005",
"pm_score": 0,
"selected": false,
"text": "www.google.com ssl import ssl\nimport socket\nfrom pprint import pprint\n\n\nhostname = 'www.google.org'\ncontext = ssl.create_default_context()\n\nwith socket.create_connection((hostname, 443)) as sock:\n with context.wrap_socket(sock, server_hostname=hostname) as ssock:\n pprint(ssock.getpeercert()['subject'])\n ((('countryName', 'US'),),\n (('stateOrProvinceName', 'California'),),\n (('localityName', 'Mountain View'),),\n (('organizationName', 'Google LLC'),),\n (('commonName', 'misc.google.com'),))\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4300/"
] |
92,679
|
<p>We are currently testing a Java Swing application for it's performance. I wonder if there is a good tool to automate this?</p>
|
[
{
"answer_id": 1001001,
"author": "Dema",
"author_id": 407003,
"author_profile": "https://Stackoverflow.com/users/407003",
"pm_score": 0,
"selected": false,
"text": " Scenario: Dialog manipulation\n Given the frame \"SwingSet\" is visible\n And the frame \"SwingSet\" is the container\n When I click the menu \"File/About\"\n Then I should see the dialog \"About Swing!\"\n Given the dialog \"About Swing!\" is the container\n When I click the button \"OK\"\n Then I should not see the dialog \"About Swing!\"\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11962/"
] |
92,689
|
<p>I am writing a Composite control, which contains a listview to display a table of items. Normally when using a ListView in Asp.NET I would define the templates in the code-forward.</p>
<pre><code><asp:ListView runat="server" ID="ArticleList">
<LayoutTemplate>
<div class="ContentContainer">
<div runat="server" id="itemPlaceholder" />
</div>
</LayoutTemplate>
<ItemTemplate>
<div>
<div><%# Eval("Content") %></div>
</div>
</ItemTemplate>
</asp:ListView>
</code></pre>
<p>I assume it's something like:</p>
<pre><code>ListView view = new ListView();
view.LayoutTemplate = .....
view.ItemTemplate = .....
// when do I call these?
view.DataSource = myDataSource;
view.DataBind();
</code></pre>
<p><strong>Update:</strong>
I created 2 templates by implementing the ITemplate interface:</p>
<pre><code>private class LayoutTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
var outer = new HtmlGenericControl("div");
var inner = new HtmlGenericControl("div") { ID = "itemPlaceholder" };
table.Rows.Add(row);
container.Controls.Add(table);
}
}
private class ItemTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
var inner = new HtmlGenericControl("div");
container.Controls.Add(inner);
}
}
</code></pre>
<p>and I can add them using:</p>
<pre><code>dataList.LayoutTemplate = new LayoutTemplate();
dataList.ItemTemplate = new ItemTemplate();
</code></pre>
<p>But then I get stuck, since container.DataItem is null.</p>
|
[
{
"answer_id": 94536,
"author": "sontek",
"author_id": 17176,
"author_profile": "https://Stackoverflow.com/users/17176",
"pm_score": -1,
"selected": false,
"text": "public delegate void InstantiateTemplateDelegate(Control container);\n\npublic class GenericTemplateImplementation : ITemplate\n{\n private InstantiateTemplateDelegate instantiateTemplate;\n\n public void InstantiateIn(Control container)\n {\n this.instantiateTemplate(container);\n }\n\n public GenericTemplateImplementation(InstantiateTemplateDelegate instantiateTemplate)\n {\n this.instantiateTemplate = instantiateTemplate;\n }\n}\n view.LayoutTemplate = new GenericTemplateImplementation(p =>\n {\n p.Controls.Add(new Label { Text = \"Foo\" });\n });\n"
},
{
"answer_id": 149025,
"author": "Paul van Brenk",
"author_id": 1837197,
"author_profile": "https://Stackoverflow.com/users/1837197",
"pm_score": 4,
"selected": true,
"text": "public class FibonacciControl : CompositeControl\n{\n public FibonacciControl()\n {\n // ....\n }\n\n protected override void CreateChildControls()\n {\n base.CreateChildControls();\n\n ListView view = new ListView();\n\n view.LayoutTemplate = new LayoutTemplate();\n view.ItemTemplate = new ItemTemplate();\n\n view.DataSource = FibonacciSequence();\n view.DataBind();\n\n this.Controls.Add(view);\n }\n\n private IEnumerable<int> FibonacciSequence()\n {\n\n int i1 = 0;\n int i2 = 1;\n\n for (int i = 0; i < Iterations; i++)\n {\n yield return i1 + i2;\n int temp = i1 + i2;\n i1 = i2;\n i2 = temp;\n }\n yield break;\n }\n\n public int Iterations { get; set; }\n\n private class LayoutTemplate : ITemplate\n {\n\n public void InstantiateIn(Control container)\n {\n var ol = new HtmlGenericControl(\"ol\");\n var li = new HtmlGenericControl(\"li\") { ID = \"itemPlaceholder\" };\n ol.Controls.Add(li);\n\n container.Controls.Add(ol);\n }\n }\n\n private class ItemTemplate : ITemplate\n {\n public void InstantiateIn(Control container)\n {\n var li = new HtmlGenericControl(\"li\");\n\n li.DataBinding += DataBinding;\n container.Controls.Add(li);\n }\n\n public void DataBinding(object sender, EventArgs e)\n {\n var container = (HtmlGenericControl)sender;\n var dataItem = ((ListViewDataItem)container.NamingContainer).DataItem;\n\n container.Controls.Add( new Literal(){Text = dataItem.ToString() });\n }\n }\n}\n"
},
{
"answer_id": 348158,
"author": "Michael Washington",
"author_id": 384585,
"author_profile": "https://Stackoverflow.com/users/384585",
"pm_score": 0,
"selected": false,
"text": "public partial class View : PortalModuleBase\n{\n protected void Page_Load(object sender, EventArgs e)\n {\n\n }\n\n #region MasterListView_ItemDataBound\n public void MasterListView_ItemDataBound(object sender, ListViewItemEventArgs e)\n {\n ListViewItem objListViewItem = (ListViewItem)e.Item;\n ListViewDataItem objListViewDataItem = objListViewItem as ListViewDataItem;\n\n if (objListViewDataItem != null)\n {\n Tab objTab = (Tab)objListViewDataItem.DataItem;\n IEnumerable<Tab> Tabs = CustomData(objTab.TabID);\n\n Label TabIDLabel = (Label)objListViewItem.FindControl(\"TabIDLabel\");\n Label TabNameLabel = (Label)objListViewItem.FindControl(\"TabNameLabel\");\n\n TabIDLabel.Text = objTab.TabID.ToString();\n TabNameLabel.Text = objTab.TabName;\n\n AddListView(objTab.TabName, objListViewItem, Tabs);\n }\n }\n #endregion\n\n #region CustomData\n static IEnumerable<Tab> CustomData(int? ParentID)\n {\n TabAdminDataContext objTabAdminDataContext = new TabAdminDataContext();\n\n var myCustomData = from Tabs in objTabAdminDataContext.Tabs\n where Tabs.ParentId == ParentID\n select Tabs;\n\n return myCustomData.AsEnumerable();\n }\n #endregion\n\n #region AddListView\n private void AddListView(string CurrentTabName, Control container, IEnumerable<Tab> ChildTabs)\n {\n // The Tab has Children so add a ListView\n if (ChildTabs.Count() > 0)\n {\n ListView ChildListView = new ListView();\n ChildListView.ID = \"ChildListView\";\n ChildListView.ItemCommand += ListView_ItemCommand;\n ChildListView.EnableViewState = true;\n ChildListView.LayoutTemplate = new MyLayoutTemplate();\n ChildListView.ItemTemplate = new MyItemTemplate();\n ChildListView.DataSource = ChildTabs;\n ChildListView.DataBind();\n\n // Put the ListView in a Panel\n var oTR = new HtmlGenericControl(\"tr\") { ID = \"ChildListViewTR\" };\n var oTD = new HtmlGenericControl(\"td\") { ID = \"ChildListViewTD\" };\n\n Panel objPanel = new Panel();\n objPanel.ID = \"ListViewPanel\";\n objPanel.ToolTip = CurrentTabName;\n objPanel.Controls.Add(ChildListView);\n\n oTD.Controls.Add(objPanel);\n oTR.Controls.Add(oTD);\n container.Controls.Add(oTR);\n }\n }\n #endregion\n\n #region ListView_ItemCommand\n protected void ListView_ItemCommand(object sender, ListViewCommandEventArgs e)\n {\n LinkButton objButton = (LinkButton)sender;\n Label1.Text = objButton.Text;\n MasterListView.DataBind();\n }\n #endregion\n\n #region MyLayoutTemplate\n public class MyLayoutTemplate : ITemplate\n {\n public void InstantiateIn(Control container)\n {\n var oTR = new HtmlGenericControl(\"tr\") { ID = \"itemPlaceholder\" };\n container.Controls.Add(oTR);\n }\n }\n #endregion\n\n #region ItemTemplate\n public class MyItemTemplate : ITemplate\n {\n public void InstantiateIn(Control container)\n {\n var oTR = new HtmlGenericControl(\"tr\");\n\n var oTD1 = new HtmlGenericControl(\"td\");\n LinkButton TabIDLinkButton = new LinkButton();\n TabIDLinkButton.ID = \"TabIDLinkButton\";\n oTD1.Controls.Add(TabIDLinkButton);\n oTR.Controls.Add(oTD1);\n\n var oTD2 = new HtmlGenericControl(\"td\");\n Label TabNameLabel = new Label();\n TabNameLabel.ID = \"TabNameLabel\";\n oTD2.Controls.Add(TabNameLabel);\n oTR.Controls.Add(oTD2);\n\n oTR.DataBinding += DataBinding;\n container.Controls.Add(oTR);\n }\n\n public void DataBinding(object sender, EventArgs e)\n {\n var container = (HtmlGenericControl)sender;\n var dataItem = ((ListViewDataItem)container.NamingContainer).DataItem;\n Tab objTab = (Tab)dataItem;\n\n LinkButton TabIDLinkButton = (LinkButton)container.FindControl(\"TabIDLinkButton\");\n Label TabNameLabel = (Label)container.FindControl(\"TabNameLabel\");\n\n TabIDLinkButton.Text = \"+\" + objTab.TabID.ToString();\n TabNameLabel.Text = objTab.TabName;\n\n IEnumerable<Tab> ChildTabs = View.CustomData(objTab.TabID);\n\n View objView = new View();\n objView.AddListView(objTab.TabName, container, ChildTabs);\n }\n\n }\n #endregion\n\n}\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1837197/"
] |
92,696
|
<p>I have a couple databases on a shared SQL Server 2005 cluster instance, that I would like performance metrics on. I have some processes that run for a very long time and suspect that code inefficiencies, rather than insufficient hardware are to blame.</p>
<p>I would like some way to get these performance metrics so that I can rule out the database hardware as the culprit.</p>
|
[
{
"answer_id": 94536,
"author": "sontek",
"author_id": 17176,
"author_profile": "https://Stackoverflow.com/users/17176",
"pm_score": -1,
"selected": false,
"text": "public delegate void InstantiateTemplateDelegate(Control container);\n\npublic class GenericTemplateImplementation : ITemplate\n{\n private InstantiateTemplateDelegate instantiateTemplate;\n\n public void InstantiateIn(Control container)\n {\n this.instantiateTemplate(container);\n }\n\n public GenericTemplateImplementation(InstantiateTemplateDelegate instantiateTemplate)\n {\n this.instantiateTemplate = instantiateTemplate;\n }\n}\n view.LayoutTemplate = new GenericTemplateImplementation(p =>\n {\n p.Controls.Add(new Label { Text = \"Foo\" });\n });\n"
},
{
"answer_id": 149025,
"author": "Paul van Brenk",
"author_id": 1837197,
"author_profile": "https://Stackoverflow.com/users/1837197",
"pm_score": 4,
"selected": true,
"text": "public class FibonacciControl : CompositeControl\n{\n public FibonacciControl()\n {\n // ....\n }\n\n protected override void CreateChildControls()\n {\n base.CreateChildControls();\n\n ListView view = new ListView();\n\n view.LayoutTemplate = new LayoutTemplate();\n view.ItemTemplate = new ItemTemplate();\n\n view.DataSource = FibonacciSequence();\n view.DataBind();\n\n this.Controls.Add(view);\n }\n\n private IEnumerable<int> FibonacciSequence()\n {\n\n int i1 = 0;\n int i2 = 1;\n\n for (int i = 0; i < Iterations; i++)\n {\n yield return i1 + i2;\n int temp = i1 + i2;\n i1 = i2;\n i2 = temp;\n }\n yield break;\n }\n\n public int Iterations { get; set; }\n\n private class LayoutTemplate : ITemplate\n {\n\n public void InstantiateIn(Control container)\n {\n var ol = new HtmlGenericControl(\"ol\");\n var li = new HtmlGenericControl(\"li\") { ID = \"itemPlaceholder\" };\n ol.Controls.Add(li);\n\n container.Controls.Add(ol);\n }\n }\n\n private class ItemTemplate : ITemplate\n {\n public void InstantiateIn(Control container)\n {\n var li = new HtmlGenericControl(\"li\");\n\n li.DataBinding += DataBinding;\n container.Controls.Add(li);\n }\n\n public void DataBinding(object sender, EventArgs e)\n {\n var container = (HtmlGenericControl)sender;\n var dataItem = ((ListViewDataItem)container.NamingContainer).DataItem;\n\n container.Controls.Add( new Literal(){Text = dataItem.ToString() });\n }\n }\n}\n"
},
{
"answer_id": 348158,
"author": "Michael Washington",
"author_id": 384585,
"author_profile": "https://Stackoverflow.com/users/384585",
"pm_score": 0,
"selected": false,
"text": "public partial class View : PortalModuleBase\n{\n protected void Page_Load(object sender, EventArgs e)\n {\n\n }\n\n #region MasterListView_ItemDataBound\n public void MasterListView_ItemDataBound(object sender, ListViewItemEventArgs e)\n {\n ListViewItem objListViewItem = (ListViewItem)e.Item;\n ListViewDataItem objListViewDataItem = objListViewItem as ListViewDataItem;\n\n if (objListViewDataItem != null)\n {\n Tab objTab = (Tab)objListViewDataItem.DataItem;\n IEnumerable<Tab> Tabs = CustomData(objTab.TabID);\n\n Label TabIDLabel = (Label)objListViewItem.FindControl(\"TabIDLabel\");\n Label TabNameLabel = (Label)objListViewItem.FindControl(\"TabNameLabel\");\n\n TabIDLabel.Text = objTab.TabID.ToString();\n TabNameLabel.Text = objTab.TabName;\n\n AddListView(objTab.TabName, objListViewItem, Tabs);\n }\n }\n #endregion\n\n #region CustomData\n static IEnumerable<Tab> CustomData(int? ParentID)\n {\n TabAdminDataContext objTabAdminDataContext = new TabAdminDataContext();\n\n var myCustomData = from Tabs in objTabAdminDataContext.Tabs\n where Tabs.ParentId == ParentID\n select Tabs;\n\n return myCustomData.AsEnumerable();\n }\n #endregion\n\n #region AddListView\n private void AddListView(string CurrentTabName, Control container, IEnumerable<Tab> ChildTabs)\n {\n // The Tab has Children so add a ListView\n if (ChildTabs.Count() > 0)\n {\n ListView ChildListView = new ListView();\n ChildListView.ID = \"ChildListView\";\n ChildListView.ItemCommand += ListView_ItemCommand;\n ChildListView.EnableViewState = true;\n ChildListView.LayoutTemplate = new MyLayoutTemplate();\n ChildListView.ItemTemplate = new MyItemTemplate();\n ChildListView.DataSource = ChildTabs;\n ChildListView.DataBind();\n\n // Put the ListView in a Panel\n var oTR = new HtmlGenericControl(\"tr\") { ID = \"ChildListViewTR\" };\n var oTD = new HtmlGenericControl(\"td\") { ID = \"ChildListViewTD\" };\n\n Panel objPanel = new Panel();\n objPanel.ID = \"ListViewPanel\";\n objPanel.ToolTip = CurrentTabName;\n objPanel.Controls.Add(ChildListView);\n\n oTD.Controls.Add(objPanel);\n oTR.Controls.Add(oTD);\n container.Controls.Add(oTR);\n }\n }\n #endregion\n\n #region ListView_ItemCommand\n protected void ListView_ItemCommand(object sender, ListViewCommandEventArgs e)\n {\n LinkButton objButton = (LinkButton)sender;\n Label1.Text = objButton.Text;\n MasterListView.DataBind();\n }\n #endregion\n\n #region MyLayoutTemplate\n public class MyLayoutTemplate : ITemplate\n {\n public void InstantiateIn(Control container)\n {\n var oTR = new HtmlGenericControl(\"tr\") { ID = \"itemPlaceholder\" };\n container.Controls.Add(oTR);\n }\n }\n #endregion\n\n #region ItemTemplate\n public class MyItemTemplate : ITemplate\n {\n public void InstantiateIn(Control container)\n {\n var oTR = new HtmlGenericControl(\"tr\");\n\n var oTD1 = new HtmlGenericControl(\"td\");\n LinkButton TabIDLinkButton = new LinkButton();\n TabIDLinkButton.ID = \"TabIDLinkButton\";\n oTD1.Controls.Add(TabIDLinkButton);\n oTR.Controls.Add(oTD1);\n\n var oTD2 = new HtmlGenericControl(\"td\");\n Label TabNameLabel = new Label();\n TabNameLabel.ID = \"TabNameLabel\";\n oTD2.Controls.Add(TabNameLabel);\n oTR.Controls.Add(oTD2);\n\n oTR.DataBinding += DataBinding;\n container.Controls.Add(oTR);\n }\n\n public void DataBinding(object sender, EventArgs e)\n {\n var container = (HtmlGenericControl)sender;\n var dataItem = ((ListViewDataItem)container.NamingContainer).DataItem;\n Tab objTab = (Tab)dataItem;\n\n LinkButton TabIDLinkButton = (LinkButton)container.FindControl(\"TabIDLinkButton\");\n Label TabNameLabel = (Label)container.FindControl(\"TabNameLabel\");\n\n TabIDLinkButton.Text = \"+\" + objTab.TabID.ToString();\n TabNameLabel.Text = objTab.TabName;\n\n IEnumerable<Tab> ChildTabs = View.CustomData(objTab.TabID);\n\n View objView = new View();\n objView.AddListView(objTab.TabName, container, ChildTabs);\n }\n\n }\n #endregion\n\n}\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5885/"
] |
92,698
|
<p>I'm looking for an Access 2007 equivalent to SQL Server's COALESCE function.</p>
<p>In SQL Server you could do something like:</p>
<p><strong>Person</strong></p>
<pre><code>John
Steve
Richard
</code></pre>
<p><strong>SQL</strong></p>
<pre><code>DECLARE @PersonList nvarchar(1024)
SELECT @PersonList = COALESCE(@PersonList + ',','') + Person
FROM PersonTable
PRINT @PersonList
</code></pre>
<p>Which produces: John, Steve, Richard</p>
<p>I want to do the same but in Access 2007.</p>
<p>Does anyone know how to combine rows like this in Access 2007?</p>
|
[
{
"answer_id": 92878,
"author": "Nick Craver",
"author_id": 13249,
"author_profile": "https://Stackoverflow.com/users/13249",
"pm_score": 0,
"selected": false,
"text": "Nz(variant, [if null value]) ---Person--- \nJohn\nSteve\nRichard\n\nDECLARE @PersonList nvarchar(1024)\nSELECT @PersonList = Nz(@PersonList + ',','') + Person\nFROM PersonTable\n\nPRINT @PersonList\n"
},
{
"answer_id": 93332,
"author": "Dave DuPlantis",
"author_id": 8174,
"author_profile": "https://Stackoverflow.com/users/8174",
"pm_score": 0,
"selected": false,
"text": "Public Function Coalesce(pstrTableName As String, pstrFieldName As String)\n\nDim rst As DAO.Recordset\nDim str As String\n\n Set rst = CurrentDb.OpenRecordset(pstrTableName)\n Do While rst.EOF = False\n If Len(str) = 0 Then\n str = rst(pstrFieldName)\n Else\n str = str & \",\" & rst(pstrFieldName)\n End If\n rst.MoveNext\n Loop\n\n Coalesce = str\n\nEnd Function\n"
},
{
"answer_id": 93370,
"author": "Philippe Grondier",
"author_id": 11436,
"author_profile": "https://Stackoverflow.com/users/11436",
"pm_score": 0,
"selected": false,
"text": "Dim rs as DAO.recordset, _\n personList as String, _\n personArray() as variant\n\nset rs = currentDb.open(\"Person\")\nset personArray = rs.getRows(rs.recordcount)\n\nrs.close\n"
},
{
"answer_id": 93863,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 5,
"selected": true,
"text": "Function Coalsce(strSQL As String, strDelim, ParamArray NameList() As Variant)\nDim db As Database\nDim rs As DAO.Recordset\nDim strList As String\n\n Set db = CurrentDb\n\n If strSQL <> \"\" Then\n Set rs = db.OpenRecordset(strSQL)\n\n Do While Not rs.EOF\n strList = strList & strDelim & rs.Fields(0)\n rs.MoveNext\n Loop\n\n strList = Mid(strList, Len(strDelim))\n Else\n\n strList = Join(NameList, strDelim)\n End If\n\n Coalsce = strList\n\nEnd Function\n SELECT documents.MembersOnly, \n Coalsce(\"SELECT FName From Persons WHERE Member=True\",\":\") AS Who, \n Coalsce(\"\",\":\",\"Mary\",\"Joe\",\"Pat?\") AS Others\nFROM documents;\n Function ConcatADO(strSQL As String, strColDelim, strRowDelim, ParamArray NameList() As Variant)\n Dim rs As New ADODB.Recordset\n Dim strList As String\n\n On Error GoTo Proc_Err\n\n If strSQL <> \"\" Then\n rs.Open strSQL, CurrentProject.Connection\n strList = rs.GetString(, , strColDelim, strRowDelim)\n strList = Mid(strList, 1, Len(strList) - Len(strRowDelim))\n Else\n strList = Join(NameList, strColDelim)\n End If\n\n ConcatADO = strList\n\n Exit Function\n\n Proc_Err:\n ConcatADO = \"***\" & UCase(Err.Description)\n End Function\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3742/"
] |
92,699
|
<p>I have a table called OffDays, where weekends and holiday dates are kept. I have a table called LeadTime where amount of time (in days) for a product to be manufactured is stored. Finally I have a table called Order where a product and the order date is kept.</p>
<p>Is it possible to query when a product will be finished manufacturing without using stored procedures or loops?</p>
<p>For example:</p>
<ul>
<li>OffDays has 2008-01-10, 2008-01-11, 2008-01-14.</li>
<li>LeadTime has 5 for product 9.</li>
<li>Order has 2008-01-09 for product 9.</li>
</ul>
<p>The calculation I'm looking for is this:</p>
<ul>
<li>2008-01-09 1</li>
<li>2008-01-10 x</li>
<li>2008-01-11 x</li>
<li>2008-01-12 2</li>
<li>2008-01-13 3</li>
<li>2008-01-14 x</li>
<li>2008-01-15 4</li>
<li>2008-01-16 5</li>
</ul>
<p>I'm wondering if it's possible to have a query return 2008-01-16 without having to use a stored procedure, or calculate it in my application code.</p>
<p><strong>Edit (why no stored procs / loops):</strong>
The reason I can't use stored procedures is that they are not supported by the database. I can only add extra tables / data. The application is a third party reporting tool where I can only control the SQL query.</p>
<p><strong>Edit (how i'm doing it now):</strong>
My current method is that I have an extra column in the order table to hold the calculated date, then a scheduled task / cron job runs the calculation on all the orders every hour. This is less than ideal for several reasons.</p>
|
[
{
"answer_id": 92736,
"author": "RB.",
"author_id": 15393,
"author_profile": "https://Stackoverflow.com/users/15393",
"pm_score": 2,
"selected": false,
"text": "SELECT c.dt, l.*, o.*, c.*\n FROM [statistics].dbo.[calendar] c, \n [order] o JOIN\n lead l ON l.leadId = o.leadId\n WHERE c.isWeekday = 1 \n AND c.isHoliday =0 \n AND o.orderId = 1\n AND l.leadDays = ( \n SELECT COUNT(*) \n FROM [statistics].dbo.Calendar c2 \n WHERE c2.dt >= o.startDate\n AND c2.dt <= c.dt \n AND c2.isWeekday=1 \n AND c2.isHoliday=0 \n )\n"
},
{
"answer_id": 92783,
"author": "Stormenet",
"author_id": 2090,
"author_profile": "https://Stackoverflow.com/users/2090",
"pm_score": 0,
"selected": false,
"text": "int leadtime = 5;\ndate order = 2008-01-09;\ndate finishdate = order;\nwhile (leadtime > 0) {\nfinishdate.addDay();\nif (!IsOffday(finishdate)) leadtime--;\n}\nreturn finishdate;"
},
{
"answer_id": 92822,
"author": "finnw",
"author_id": 12048,
"author_profile": "https://Stackoverflow.com/users/12048",
"pm_score": 3,
"selected": true,
"text": "WDId | WDDate\n-----+-----------\n4200 | 2008-01-08\n4201 | 2008-01-09\n4202 | 2008-01-12\n4203 | 2008-01-13\n4204 | 2008-01-16\n4205 | 2008-01-17\n SELECT DeliveryDay.WDDate FROM WorkingDay OrderDay, WorkingDay DeliveryDay, LeadTime, Order where DeliveryDay.WDId = OrderDay.WDId + LeadTime.LTDays AND OrderDay.WDDate = '' AND LeadTime.ProductId = Order.ProductId AND Order.OrderId = 1234\n"
},
{
"answer_id": 93175,
"author": "kamajo",
"author_id": 5415,
"author_profile": "https://Stackoverflow.com/users/5415",
"pm_score": 1,
"selected": false,
"text": "-- Setup test\ncreate table #odays (offd datetime)\ncreate table #leadtime (pid int , ltime int)\ncreate table [#order] (pid int, odate datetime)\n\n\ninsert into #odays \nselect '1/10/8'\ninsert into #odays \nselect '1/11/8'\ninsert into #odays \nselect '1/14/8'\n\n\ninsert into #Leadtime\nvalues (3,5)\ninsert into #leadtime\nvalues (9, 5)\n\ninsert into #order \nvalues( 9, '1/9/8')\n\nselect dateadd(dd, \n(select count(*)-1 \n from #odays \n where offd between odate and \n (select odate+ltime \n from #order o \n left join #leadtime l \n on o.pid = l.pid \n where l.pid = 9\n )\n ),\n odate+ltime) \n from #order o \n left join #leadtime l \n on o.pid = l.pid \n where o.pid = 9\n"
},
{
"answer_id": 93249,
"author": "Kev",
"author_id": 16777,
"author_profile": "https://Stackoverflow.com/users/16777",
"pm_score": 0,
"selected": false,
"text": "CREATE DATABASE test;\nCREATE TABLE offdays\n(\n offdate date NOT NULL,\n CONSTRAINT offdays_pkey PRIMARY KEY (offdate)\n);\ninsert into offdays (offdate) values ('2008-01-10');\ninsert into offdays (offdate) values ('2008-01-11');\ninsert into offdays (offdate) values ('2008-01-14');\ninsert into offdays (offdate) values ('2008-01-18'); -- just for testing\nCREATE TABLE product\n(\n id integer NOT NULL,\n CONSTRAINT product_pkey PRIMARY KEY (id)\n);\ninsert into product (id) values (9);\nCREATE TABLE leadtime\n(\n product integer NOT NULL,\n leaddays integer NOT NULL,\n CONSTRAINT leadtime_pkey PRIMARY KEY (product),\n CONSTRAINT leadtime_product_fkey FOREIGN KEY (product)\n REFERENCES product (id) MATCH SIMPLE\n ON UPDATE NO ACTION ON DELETE NO ACTION\n);\ninsert into leadtime (product, leaddays) values (9, 5);\nCREATE TABLE \"order\"\n(\n product integer NOT NULL,\n \"start\" date NOT NULL,\n CONSTRAINT order_pkey PRIMARY KEY (product),\n CONSTRAINT order_product_fkey FOREIGN KEY (product)\n REFERENCES product (id) MATCH SIMPLE\n ON UPDATE NO ACTION ON DELETE NO ACTION\n);\ninsert into \"order\" (product, \"start\") values (9, '2008-01-09');\n\n-- finally, the query:\n\nselect e.product, offdate + (leaddays - ondays)::integer as \"end\"\nfrom\n(\n select c.product, offdate, (select (a.offdate - c.\"start\") - count(b.offdate) from offdays b where b.offdate < a.offdate) as ondays, d.leaddays\n from offdays a, \"order\" c\n inner join leadtime d on d.product = c.product\n) e\nwhere leaddays >= ondays\norder by \"end\" desc\nlimit 1;\n"
},
{
"answer_id": 95268,
"author": "user17957",
"author_id": 17957,
"author_profile": "https://Stackoverflow.com/users/17957",
"pm_score": 0,
"selected": false,
"text": "--Sample data\ncreate table offdays(datum date);\n\ninsert into offdays(datum)\nselect to_date('2008-01-10','yyyy-MM-dd') UNION \nselect to_date('2008-01-11','yyyy-MM-dd') UNION \nselect to_date('2008-01-14','yyyy-MM-dd') UNION \nselect to_date('2008-01-20','yyyy-MM-dd') UNION\nselect to_date('2008-01-21','yyyy-MM-dd') UNION\nselect to_date('2008-01-26','yyyy-MM-dd');\n\ncreate table leadtime (product_id integer , lead_time integer);\ninsert into leadtime(product_id,lead_time) values (9,5);\n\ncreate table myorder (order_id integer,product_id integer, datum date);\ninsert into myorder(order_id,product_id,datum) \nvalues (1,9,to_date('2008-01-09','yyyy-MM-dd'));\ninsert into myorder(order_id,product_id,datum) \nvalues (2,9,to_date('2008-01-16','yyyy-MM-dd'));\ninsert into myorder(order_id,product_id,datum) \nvalues (3,9,to_date('2008-01-23','yyyy-MM-dd'));\n\n--Query\nselect order_id,min(finished_date)\nFROM \n (select mo.order_id,(mo.datum+lead_time+count(od2.*)::integer-1) as finished_date\n from \n myorder mo\n join leadtime lt on (mo.product_id=lt.product_id)\n join offdays od1 on (mo.datum<od1.datum)\n left outer join offdays od2 on (mo.datum<od2.datum and od2.datum<od1.datum)\n group by mo.order_id,mo.datum,lt.lead_time,od1.datum\n having (mo.datum+lead_time+count(od2.*)::integer-1) < od1.datum) tmp\ngroup by 1; \n\n--Results :\n1 2008.01.16\n2 2008.01.22\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2581/"
] |
92,720
|
<p>I have a web page that includes a bunch of images. Sometimes the image isn't available, so a broken image is displayed in the client's browser.</p>
<p>How do I use jQuery to get the set of images, filter it to broken images then replace the src?</p>
<hr/>
<p>--I thought it would be easier to do this with jQuery, but it turned out much easier to just use a pure JavaScript solution, that is, the one provided by Prestaul.</p>
|
[
{
"answer_id": 92819,
"author": "Prestaul",
"author_id": 5628,
"author_profile": "https://Stackoverflow.com/users/5628",
"pm_score": 11,
"selected": true,
"text": "onError function imgError(image) {\n image.onerror = \"\";\n image.src = \"/images/noimage.gif\";\n return true;\n}\n <img src=\"image.png\" onerror=\"imgError(this);\"/>\n <img src=\"image.png\" onError=\"this.onerror=null;this.src='/images/noimage.gif';\" />\n"
},
{
"answer_id": 92829,
"author": "Nick Craver",
"author_id": 13249,
"author_profile": "https://Stackoverflow.com/users/13249",
"pm_score": 5,
"selected": false,
"text": "jQuery('#images img').preload({\n placeholder:'placeholder.jpg',\n notFound:'notfound.jpg'\n});\n"
},
{
"answer_id": 93017,
"author": "Devon",
"author_id": 13850,
"author_profile": "https://Stackoverflow.com/users/13850",
"pm_score": 6,
"selected": false,
"text": "$(window).load(function() {\n $('img').each(function() {\n if ( !this.complete\n || typeof this.naturalWidth == \"undefined\"\n || this.naturalWidth == 0 ) {\n // image was broken, replace with your new image\n this.src = 'http://www.tranism.com/weblog/images/broken_ipod.gif';\n }\n });\n});\n"
},
{
"answer_id": 168448,
"author": "travis",
"author_id": 1414,
"author_profile": "https://Stackoverflow.com/users/1414",
"pm_score": 8,
"selected": false,
"text": "error $(\"img\").error(function () {\n $(this).unbind(\"error\").attr(\"src\", \"broken.gif\");\n});\n error() .on(\"error\") $(\"img\").on(\"error\", function () {\n $(this).attr(\"src\", \"broken.gif\");\n});\n"
},
{
"answer_id": 2520294,
"author": "Mohamad",
"author_id": 302184,
"author_profile": "https://Stackoverflow.com/users/302184",
"pm_score": 5,
"selected": false,
"text": "$(window).bind('load', function() {\n $('img').each(function() {\n if( (typeof this.naturalWidth != \"undefined\" && this.naturalWidth == 0) \n || this.readyState == 'uninitialized' ) {\n $(this).attr('src', 'missing.jpg');\n }\n });\n});\n"
},
{
"answer_id": 8575302,
"author": "Shade",
"author_id": 1107804,
"author_profile": "https://Stackoverflow.com/users/1107804",
"pm_score": 3,
"selected": false,
"text": "var retries = 0;\n$.imgReload = function() {\n var loaded = 1;\n\n $(\"img\").each(function() {\n if (!this.complete || typeof this.naturalWidth == \"undefined\" || this.naturalWidth == 0) {\n\n var src = $(this).attr(\"src\");\n var date = new Date();\n $(this).attr(\"src\", src + \"?v=\" + date.getTime()); //slightly change url to prevent loading from cache\n loaded =0;\n }\n });\n\n retries +=1;\n if (retries < 10) { // If after 10 retries error images are not fixed maybe because they\n // are not present on server, the recursion will break the loop\n if (loaded == 0) {\n setTimeout('$.imgReload()',4000); // I think 4 seconds is enough to load a small image (<50k) from a slow server\n }\n // All images have been loaded\n else {\n // alert(\"images loaded\");\n }\n }\n // If error images cannot be loaded after 10 retries\n else {\n // alert(\"recursion exceeded\");\n }\n}\n\njQuery(document).ready(function() {\n setTimeout('$.imgReload()',5000);\n});\n"
},
{
"answer_id": 8621397,
"author": "Shade",
"author_id": 1114091,
"author_profile": "https://Stackoverflow.com/users/1114091",
"pm_score": 2,
"selected": false,
"text": "jQuery(window).load(function(){\n $.imgReload();\n});\n document.ready"
},
{
"answer_id": 11052002,
"author": "mouad",
"author_id": 479633,
"author_profile": "https://Stackoverflow.com/users/479633",
"pm_score": 7,
"selected": false,
"text": "error img img $(document).on('error', 'img', function () { ... })\n"
},
{
"answer_id": 17352656,
"author": "yckart",
"author_id": 1250044,
"author_profile": "https://Stackoverflow.com/users/1250044",
"pm_score": 2,
"selected": false,
"text": "(window.jQuery || window.Zepto).fn.fallback = function (fallback) {\n return this.one('error', function () {\n var self = this;\n this.src = (fallback || 'http://lorempixel.com/$width/$height').replace(\n /\\$(\\w+)/g, function (m, t) { return self[t] || ''; }\n );\n });\n};\n \n $* $('img').fallback('http://dummyimage.com/$widthx$height&text=$src');\n"
},
{
"answer_id": 17730147,
"author": "Kevin",
"author_id": 375960,
"author_profile": "https://Stackoverflow.com/users/375960",
"pm_score": 2,
"selected": false,
"text": "$(\"img\").error ->\n e = $(@).get 0\n $(@).hide() if !$.browser.msie && (typeof this.naturalWidth == \"undefined\" || this.naturalWidth == 0)\n"
},
{
"answer_id": 19492959,
"author": "Luis Gustavo Beligante",
"author_id": 2902842,
"author_profile": "https://Stackoverflow.com/users/2902842",
"pm_score": 2,
"selected": false,
"text": "function imgExists(imgPath) {\n var http = jQuery.ajax({\n type:\"HEAD\",\n url: imgPath,\n async: false\n });\n return http.status != 404;\n}\n\nfunction handleImageError() {\n var imgPath;\n\n $('img').each(function() {\n imgPath = $(this).attr('src');\n if (!imgExists(imgPath)) {\n $(this).attr('src', 'images/noimage.jpg');\n }\n });\n}\n"
},
{
"answer_id": 21858938,
"author": "Ashfaque Ali Solangi",
"author_id": 820059,
"author_profile": "https://Stackoverflow.com/users/820059",
"pm_score": 4,
"selected": false,
"text": " $(\"img\").each(function(){\n var img = $(this);\n var image = new Image();\n image.src = $(img).attr(\"src\");\n var no_image = \"https://dummyimage.com/100x100/7080b5/000000&text=No+image\";\n if (image.naturalWidth == 0 || image.readyState == 'uninitialized'){\n $(img).unbind(\"error\").attr(\"src\", no_image).css({\n height: $(img).css(\"height\"),\n width: $(img).css(\"width\"),\n });\n }\n });\n"
},
{
"answer_id": 23014637,
"author": "Phil LaNasa",
"author_id": 2374900,
"author_profile": "https://Stackoverflow.com/users/2374900",
"pm_score": 4,
"selected": false,
"text": "<img onerror=\"this.parentNode.removeChild(this);\">\n"
},
{
"answer_id": 23297041,
"author": "Dylan Valade",
"author_id": 638452,
"author_profile": "https://Stackoverflow.com/users/638452",
"pm_score": 3,
"selected": false,
"text": "img src img height min-height width min-width .dynamicContainer img {\n background: url('/images/placeholder.png');\n background-size: contain;\n}\n src .dynamicContainer img {\n background: url('/images/placeholder.png');\n background-size: contain;\n animation: fadein 1s; \n}\n\n@keyframes fadein {\n 0% { opacity: 0.0; }\n 50% { opacity: 0.5; }\n 100% { opacity: 1.0; }\n}\n .dynamicContainer img {\n background: url('https://picsum.photos/id/237/200');\n background-size: contain;\n animation: fadein 1s;\n}\n\n@keyframes fadein {\n 0% {\n opacity: 0.0;\n }\n 50% {\n opacity: 0.5;\n }\n 100% {\n opacity: 1.0;\n }\n}\n\nimg {\n /* must define dimensions */\n width: 200px;\n height: 200px;\n min-width: 200px;\n min-height: 200px;\n /* hides broken text */\n color: transparent;\n /* optional css below here */\n display: block;\n border: .2em solid black;\n border-radius: 1em;\n margin: 1em;\n} <div class=\"dynamicContainer\">\n <img src=\"https://picsum.photos/200\" alt=\"Found image\" />\n <img src=\"https://picsumx.photos/200\" alt=\"Not found image\" />\n</div>"
},
{
"answer_id": 24475191,
"author": "trante",
"author_id": 429938,
"author_profile": "https://Stackoverflow.com/users/429938",
"pm_score": 2,
"selected": false,
"text": "<img src=\"image1.png\" onerror=\"imgError(this,1);\"/>\n<img src=\"image2.png\" onerror=\"imgError(this,2);\"/>\n\nfunction imgError(image, type) {\n if (typeof jQuery !== 'undefined') {\n var imgWidth=$(image).attr(\"width\");\n var imgHeight=$(image).attr(\"height\");\n\n // Type 1 puts a placeholder image\n // Type 2 hides img tag\n if (type == 1) {\n if (typeof imgWidth !== 'undefined' && typeof imgHeight !== 'undefined') {\n $(image).attr(\"src\", \"http://lorempixel.com/\" + imgWidth + \"/\" + imgHeight + \"/\");\n } else {\n $(image).attr(\"src\", \"http://lorempixel.com/200/200/\");\n }\n } else if (type == 2) {\n $(image).hide();\n }\n }\n return true;\n}\n"
},
{
"answer_id": 25377280,
"author": "Axel",
"author_id": 3931192,
"author_profile": "https://Stackoverflow.com/users/3931192",
"pm_score": 3,
"selected": false,
"text": "onerror=\"\" var sPathToDefaultImg = 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png',\n validateImage = function( domImg ) {\n oImg = new Image();\n oImg.onerror = function() {\n domImg.src = sPathToDefaultImg;\n };\n oImg.src = domImg.src;\n },\n aImg = document.getElementsByTagName( 'IMG' ),\n i = aImg.length;\n\nwhile ( i-- ) {\n validateImage( aImg[i] );\n}\n"
},
{
"answer_id": 26886941,
"author": "horro",
"author_id": 2856041,
"author_profile": "https://Stackoverflow.com/users/2856041",
"pm_score": 3,
"selected": false,
"text": "img innerHTML $(\"div\").innerHTML = <img src=\"wrong-uri\"> <script>\n function imgError(img) {\n img.error=\"\";\n img.src=\"valid-uri\";\n }\n</script>\n\n<img src=\"wrong-uri\" onerror=\"javascript:imgError(this)\">\n javascript: _ innerHTML"
},
{
"answer_id": 36990598,
"author": "Barry",
"author_id": 4513271,
"author_profile": "https://Stackoverflow.com/users/4513271",
"pm_score": 3,
"selected": false,
"text": "fetch(url)\n .then(function(res) {\n if (res.status == '200') {\n return image;\n } else {\n return placeholder;\n }\n }\n"
},
{
"answer_id": 38359229,
"author": "Jordan Bonitatis",
"author_id": 2860951,
"author_profile": "https://Stackoverflow.com/users/2860951",
"pm_score": 2,
"selected": false,
"text": "getInitialState: function(event) {\n return {image: \"http://example.com/primary_image.jpg\"};\n},\nhandleError: function(event) {\n this.setState({image: \"http://example.com/failover_image.jpg\"});\n},\nrender: function() {\n return (\n <img onError={this.handleError} src={src} />;\n );\n}\n"
},
{
"answer_id": 39272741,
"author": "Rohith K P",
"author_id": 3919057,
"author_profile": "https://Stackoverflow.com/users/3919057",
"pm_score": 2,
"selected": false,
"text": " //the placeholder image url\n var defaultUrl = \"url('https://sadasd/image02.png')\";\n\n $('div').each(function(index, item) {\n var currentUrl = $(item).css(\"background-image\").replace(/^url\\(['\"](.+)['\"]\\)/, '$1');\n $('<img>', {\n src: currentUrl\n }).on(\"error\", function(e) {\n $this = $(this);\n $this.css({\n \"background-image\": defaultUrl\n })\n e.target.remove()\n }.bind(this))\n })\n"
},
{
"answer_id": 40263918,
"author": "Nathan Arthur",
"author_id": 937377,
"author_profile": "https://Stackoverflow.com/users/937377",
"pm_score": 5,
"selected": false,
"text": "<img src=\"img.jpg\" onerror=\"this.style.display='none';\" /> var images = document.querySelectorAll('img');\n\nfor (var i = 0; i < images.length; i++) {\n images[i].onerror = function() {\n this.style.display='none';\n }\n} <img src='img.jpg' /> document.querySelectorAll('img').forEach((img) => {\n img.onerror = function() {\n this.style.display = 'none';\n }\n}); <img src='img.jpg' />"
},
{
"answer_id": 40427037,
"author": "Kurt Hartmann",
"author_id": 4805485,
"author_profile": "https://Stackoverflow.com/users/4805485",
"pm_score": 2,
"selected": false,
"text": "function loadImageUseBackupUrlOnError(imgId, primaryUrl, backupUrl) {\n var $img = $('#' + imgId);\n $(new Image()).load().error(function() {\n $img.attr('src', backupUrl);\n }).attr('src', primaryUrl)\n}\n\n<img id=\"myImage\" src=\"primary-image-url\"/>\n<script>\n loadImageUseBackupUrlOnError('myImage','primary-image-url','backup-image-url');\n</script>\n"
},
{
"answer_id": 43281517,
"author": "Dima Dorogonov",
"author_id": 6082084,
"author_profile": "https://Stackoverflow.com/users/6082084",
"pm_score": 2,
"selected": false,
"text": "<img src=\"http://localhost:63342/GetImage/bl-once.png\" width=\"200\" onerror=\"replaceEmptyImage.insertImg(this)\"> var srcToInsertArr = ['empty1.png', 'empty2.png', 'needed.png', 'notActual.png']; // try to insert one by one img from this array\n var path;\n var imgNotFounded = true; // to mark when success\n\n var replaceEmptyImage = {\n insertImg: function (elem) {\n\n if (srcToInsertArr.length == 0) { // if there are no more src to try return\n return \"no-image.png\";\n }\n if(!/undefined/.test(elem.src)) { // remember path\n path = elem.src.split(\"/\").slice(0, -1).join(\"/\"); // \"http://localhost:63342/GetImage\"\n }\n var url = path + \"/\" + srcToInsertArr[0];\n\n srcToInsertArr.splice(0, 1); // tried 1 src\n\n \n if(imgNotFounded){ // while not success\n replaceEmptyImage.getImg(url, path, elem); // CALL GET IMAGE\n }\n \n\n },\n getImg: function (src, path, elem) { // GET IMAGE\n\n if (src && path && elem) { // src = \"http://localhost:63342/GetImage/needed.png\"\n \n var pathArr = src.split(\"/\"); // [\"http:\", \"\", \"localhost:63342\", \"GetImage\", \"needed.png\"]\n var name = pathArr[pathArr.length - 1]; // \"needed.png\"\n\n xhr = new XMLHttpRequest();\n xhr.open('GET', src, true);\n xhr.send();\n\n xhr.onreadystatechange = function () {\n\n if (xhr.status == 200) {\n elem.src = src; // insert correct src\n imgNotFounded = false; // mark success\n }\n else {\n console.log(name + \" doesn't exist!\");\n elem.onerror();\n }\n\n }\n }\n }\n\n };"
},
{
"answer_id": 46010128,
"author": "Nabi K.A.Z.",
"author_id": 1407491,
"author_profile": "https://Stackoverflow.com/users/1407491",
"pm_score": 2,
"selected": false,
"text": "// If missing.png is missing, it is replaced by replacement.png\n$( \"img\" )\n .error(function() {\n $( this ).attr( \"src\", \"replacement.png\" );\n })\n .attr( \"src\", \"missing.png\" );\n // If missing.png is missing, it is replaced by replacement.png\n$( \"img\" )\n .on(\"error\", function() {\n $( this ).attr( \"src\", \"replacement.png\" );\n })\n .attr( \"src\", \"missing.png\" );\n"
},
{
"answer_id": 47338718,
"author": "Dale Nguyen",
"author_id": 3103548,
"author_profile": "https://Stackoverflow.com/users/3103548",
"pm_score": 1,
"selected": false,
"text": "// Replace broken images by a default img\n$('img').each(function(){\n if($(this).attr('src') === ''){\n this.src = '/default_feature_image.png';\n }\n});\n"
},
{
"answer_id": 48251382,
"author": "Lea Verou",
"author_id": 90826,
"author_profile": "https://Stackoverflow.com/users/90826",
"pm_score": 2,
"selected": false,
"text": "error img.naturalWidth img.naturalHeight $$(\"img\").forEach(img => {\n if (!img.naturalWidth && !img.naturalHeight) {\n img.src = img.src;\n }\n}\n"
},
{
"answer_id": 48877973,
"author": "Casper",
"author_id": 3148642,
"author_profile": "https://Stackoverflow.com/users/3148642",
"pm_score": 2,
"selected": false,
"text": "$('img').on('error', function (e) {\n $(this).attr('src', 'broken.png');\n});"
},
{
"answer_id": 50484874,
"author": "xianshenglu",
"author_id": 9147721,
"author_profile": "https://Stackoverflow.com/users/9147721",
"pm_score": 2,
"selected": false,
"text": "window error img {\n width: 100px;\n height: 100px;\n} <script>\n window.addEventListener('error', windowErrorCb, {\n capture: true\n }, true)\n\n function windowErrorCb(event) {\n let target = event.target\n let isImg = target.tagName.toLowerCase() === 'img'\n if (isImg) {\n imgErrorCb()\n return\n }\n\n function imgErrorCb() {\n let isImgErrorHandled = target.hasAttribute('data-src-error')\n if (!isImgErrorHandled) {\n target.setAttribute('data-src-error', 'handled')\n target.src = 'backup.png'\n } else {\n //anything you want to do\n console.log(target.alt, 'both origin and backup image fail to load!');\n }\n }\n }\n</script>\n<img id=\"img\" src=\"error1.png\" alt=\"error1\">\n<img id=\"img\" src=\"error2.png\" alt=\"error2\">\n<img id=\"img\" src=\"https://i.stack.imgur.com/ZXCE2.jpg\" alt=\"avatar\"> head img backup.png backup.png"
},
{
"answer_id": 54471309,
"author": "buycanna.io",
"author_id": 345426,
"author_profile": "https://Stackoverflow.com/users/345426",
"pm_score": 0,
"selected": false,
"text": "console.clear() $('img').one('error', function(err) {\n // console.log(JSON.stringify(err, null, 4))\n $(this).remove()\n console.clear()\n})\n"
},
{
"answer_id": 60654729,
"author": "ricardo_escovar",
"author_id": 1588802,
"author_profile": "https://Stackoverflow.com/users/1588802",
"pm_score": 1,
"selected": false,
"text": "lazyload();\n\nvar errorURL = \"https://example.com/thisimageexist.png\";\n\n$(document).ready(function () {\n $('[data-src]').on(\"error\", function () {\n $(this).attr('src', errorURL);\n });\n});\n"
},
{
"answer_id": 69400552,
"author": "Jawla",
"author_id": 5891662,
"author_profile": "https://Stackoverflow.com/users/5891662",
"pm_score": 2,
"selected": false,
"text": "<img \n src={\"https://urlto/yourimage.png\"} // <--- If this image src fail to load, onError function will be called, where you can add placeholder image or any image you want to load\n width={200} \n alt={\"Image\"} \n onError={(event) => {\n event.target.onerror = \"\";\n event.target.src = \"anyplaceholderimageUrlorPath\"\n return true;\n }}\n />\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17702/"
] |
92,728
|
<p>Was looking for some approaches to incrementally converting an large existing ASP.NET VB.NET project to C# while still being able to deploy it as a single web application (currently deployed on a weekly basis). </p>
<p>My thoughts were to just create a new C# ASP.NET project and slowly move pages over, but I've never attempted to do this and somehow merge it with another ASP.NET project during deployment.</p>
<p>(Clarification: Large ASP.NET VB.NET projects are absolute dogs in the VS IDE...)</p>
<p>Any thoughts?</p>
|
[
{
"answer_id": 92840,
"author": "SpoiledTechie.com",
"author_id": 7644,
"author_profile": "https://Stackoverflow.com/users/7644",
"pm_score": 2,
"selected": false,
"text": "<compilation>\n<codeSubDirectories>\n <add directoryName=\"VB_Code\"/>\n <add directoryName=\"CS_Code\"/>\n</codeSubDirectories>\n</compilation>\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17691/"
] |
92,742
|
<p>Has anyone else experienced (and possibly solved) unintentional pitch changes using MS SAPI TTS voices? </p>
<p>I'm using the SpVoice automation interface with SAPI 5.1.</p>
<p>Right now, my application (VB6 app) can get into a state where the TTS (Microsoft Anna) starts to sound like a chipmunk (proper rate, but high pitch) and even a reboot of Vista does not correct the issue. </p>
<p>I'm passing in XML to the Voice.Speak() function. I've tried sending < pitch absmiddle="0" /> before all other XML and it still does not correct the pitch issue. When I try the TTS voice preview in the Speech control panel, the voice has a normal pitch.</p>
<p>The issue has occurred for me in XP in the past, however a reboot seemed to correct it.</p>
|
[
{
"answer_id": 98837,
"author": "Jason Stevenson",
"author_id": 13368,
"author_profile": "https://Stackoverflow.com/users/13368",
"pm_score": 0,
"selected": false,
"text": "<pitch absmiddle=\"0\">"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17649/"
] |
92,769
|
<p>I'm trying to put together a blog, and have gone with SubText and I've just installed SyntaxHighlighter but it doesn't seem to work properly. SubText or FCKEditor seems to tamper with the HTMl, inlineing everything in the pre tags and placing line-breaks at the end of each line.</p>
<p>Bad times!</p>
<p>Anyone know how to stop this?</p>
|
[
{
"answer_id": 2069859,
"author": "Haacked",
"author_id": 598,
"author_profile": "https://Stackoverflow.com/users/598",
"pm_score": 1,
"selected": false,
"text": "<BlogEntryEditor defaultProvider=\"FCKeditorBlogEntryEditorProvider\">\n <BlogEntryEditor defaultProvider=\"PlainTextBlogEntryEditorProvider\">\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5802/"
] |
92,781
|
<p>I'm looking to have text display vertically, first letter at the bottom, last letter at the top, within a JLabel. Is this possible?</p>
|
[
{
"answer_id": 92805,
"author": "jodonnell",
"author_id": 4223,
"author_profile": "https://Stackoverflow.com/users/4223",
"pm_score": 3,
"selected": false,
"text": "public class JVertLabel extends JComponent{\n private String text;\n\n public JVertLabel(String s){\n text = s;\n }\n\n public void paintComponent(Graphics g){\n super.paintComponent(g);\n Graphics2D g2d = (Graphics2D)g;\n\n g2d.rotate(Math.toRadians(270.0)); \n g2d.drawString(text, 0, 0);\n }\n}\n"
},
{
"answer_id": 92962,
"author": "Arthur Thomas",
"author_id": 14009,
"author_profile": "https://Stackoverflow.com/users/14009",
"pm_score": 4,
"selected": true,
"text": "/*\n * The contents of this file are subject to the Sapient Public License\n * Version 1.0 (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n * http://carbon.sf.net/License.html.\n *\n * Software distributed under the License is distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for\n * the specific language governing rights and limitations under the License.\n *\n * The Original Code is The Carbon Component Framework.\n *\n * The Initial Developer of the Original Code is Sapient Corporation\n *\n * Copyright (C) 2003 Sapient Corporation. All Rights Reserved.\n */\n\n\nimport java.awt.Dimension;\nimport java.awt.FontMetrics;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.Insets;\nimport java.awt.Rectangle;\nimport java.awt.geom.AffineTransform;\n\nimport javax.swing.Icon;\nimport javax.swing.JComponent;\nimport javax.swing.JLabel;\nimport javax.swing.plaf.basic.BasicLabelUI;\n\n/**\n * This is the template for Classes.\n *\n *\n * @since carbon 1.0\n * @author Greg Hinkle, January 2002\n * @version $Revision: 1.4 $($Author: dvoet $ / $Date: 2003/05/05 21:21:27 $)\n * @copyright 2002 Sapient\n */\n\npublic class VerticalLabelUI extends BasicLabelUI {\n static {\n labelUI = new VerticalLabelUI(false);\n }\n\n protected boolean clockwise;\n\n\n public VerticalLabelUI(boolean clockwise) {\n super();\n this.clockwise = clockwise;\n }\n\n\n public Dimension getPreferredSize(JComponent c) {\n Dimension dim = super.getPreferredSize(c);\n return new Dimension( dim.height, dim.width );\n }\n\n private static Rectangle paintIconR = new Rectangle();\n private static Rectangle paintTextR = new Rectangle();\n private static Rectangle paintViewR = new Rectangle();\n private static Insets paintViewInsets = new Insets(0, 0, 0, 0);\n\n public void paint(Graphics g, JComponent c) {\n\n JLabel label = (JLabel)c;\n String text = label.getText();\n Icon icon = (label.isEnabled()) ? label.getIcon() : label.getDisabledIcon();\n\n if ((icon == null) && (text == null)) {\n return;\n }\n\n FontMetrics fm = g.getFontMetrics();\n paintViewInsets = c.getInsets(paintViewInsets);\n\n paintViewR.x = paintViewInsets.left;\n paintViewR.y = paintViewInsets.top;\n\n // Use inverted height & width\n paintViewR.height = c.getWidth() - (paintViewInsets.left + paintViewInsets.right);\n paintViewR.width = c.getHeight() - (paintViewInsets.top + paintViewInsets.bottom);\n\n paintIconR.x = paintIconR.y = paintIconR.width = paintIconR.height = 0;\n paintTextR.x = paintTextR.y = paintTextR.width = paintTextR.height = 0;\n\n String clippedText =\n layoutCL(label, fm, text, icon, paintViewR, paintIconR, paintTextR);\n\n Graphics2D g2 = (Graphics2D) g;\n AffineTransform tr = g2.getTransform();\n if (clockwise) {\n g2.rotate( Math.PI / 2 );\n g2.translate( 0, - c.getWidth() );\n } else {\n g2.rotate( - Math.PI / 2 );\n g2.translate( - c.getHeight(), 0 );\n }\n\n if (icon != null) {\n icon.paintIcon(c, g, paintIconR.x, paintIconR.y);\n }\n\n if (text != null) {\n int textX = paintTextR.x;\n int textY = paintTextR.y + fm.getAscent();\n\n if (label.isEnabled()) {\n paintEnabledText(label, g, clippedText, textX, textY);\n } else {\n paintDisabledText(label, g, clippedText, textX, textY);\n }\n }\n\n g2.setTransform( tr );\n }\n}\n"
},
{
"answer_id": 116791,
"author": "ShawnD",
"author_id": 6186,
"author_profile": "https://Stackoverflow.com/users/6186",
"pm_score": 3,
"selected": false,
"text": "setText(\"<HTML>H<br>E<br>L<br>L<br>O</HTML>\");"
},
{
"answer_id": 32204257,
"author": "Bruno",
"author_id": 5264328,
"author_profile": "https://Stackoverflow.com/users/5264328",
"pm_score": 2,
"selected": false,
"text": "JXLabel label = new JXLabel(\"MY TEXT\");\nlabel.setTextRotation(3 * Math.PI / 2);\n JXLabel label = new JXLabel(\"MY TEXT\");\nlabel.setTextRotation(Math.PI / 2);\n"
},
{
"answer_id": 39345372,
"author": "Luke Usherwood",
"author_id": 932359,
"author_profile": "https://Stackoverflow.com/users/932359",
"pm_score": 2,
"selected": false,
"text": "/**\n VTextIcon is an Icon implementation which draws a short string vertically.\n It's useful for JTabbedPanes with LEFT or RIGHT tabs but can be used in any\n component which supports Icons, such as JLabel or JButton \n\n You can provide a hint to indicate whether to rotate the string \n to the left or right, or not at all, and it checks to make sure \n that the rotation is legal for the given string \n (for example, Chinese/Japanese/Korean scripts have special rules when \n drawn vertically and should never be rotated)\n */\npublic class VTextIcon implements Icon, PropertyChangeListener {\n String fLabel;\n String[] fCharStrings; // for efficiency, break the fLabel into one-char strings to be passed to drawString\n int[] fCharWidths; // Roman characters should be centered when not rotated (Japanese fonts are monospaced)\n int[] fPosition; // Japanese half-height characters need to be shifted when drawn vertically\n int fWidth, fHeight, fCharHeight, fDescent; // Cached for speed\n int fRotation;\n Component fComponent;\n\n static final int POSITION_NORMAL = 0;\n static final int POSITION_TOP_RIGHT = 1;\n static final int POSITION_FAR_TOP_RIGHT = 2;\n\n public static final int ROTATE_DEFAULT = 0x00;\n public static final int ROTATE_NONE = 0x01;\n public static final int ROTATE_LEFT = 0x02;\n public static final int ROTATE_RIGHT = 0x04;\n\n /**\n * Creates a <code>VTextIcon</code> for the specified <code>component</code>\n * with the specified <code>label</code>.\n * It sets the orientation to the default for the string\n * @see #verifyRotation\n */\n public VTextIcon(Component component, String label) {\n this(component, label, ROTATE_DEFAULT);\n }\n\n /**\n * Creates a <code>VTextIcon</code> for the specified <code>component</code>\n * with the specified <code>label</code>.\n * It sets the orientation to the provided value if it's legal for the string\n * @see #verifyRotation\n */\n public VTextIcon(Component component, String label, int rotateHint) {\n fComponent = component;\n fLabel = label;\n fRotation = verifyRotation(label, rotateHint);\n calcDimensions();\n fComponent.addPropertyChangeListener(this);\n }\n\n /**\n * sets the label to the given string, updating the orientation as needed\n * and invalidating the layout if the size changes\n * @see #verifyRotation\n */\n public void setLabel(String label) {\n fLabel = label;\n fRotation = verifyRotation(label, fRotation); // Make sure the current rotation is still legal\n recalcDimensions();\n }\n\n /**\n * Checks for changes to the font on the fComponent\n * so that it can invalidate the layout if the size changes\n */\n public void propertyChange(PropertyChangeEvent e) {\n String prop = e.getPropertyName();\n if(\"font\".equals(prop)) {\n recalcDimensions();\n }\n }\n\n /** \n * Calculates the dimensions. If they've changed,\n * invalidates the component\n */\n void recalcDimensions() {\n int wOld = getIconWidth();\n int hOld = getIconHeight();\n calcDimensions();\n if (wOld != getIconWidth() || hOld != getIconHeight())\n fComponent.invalidate();\n }\n\n void calcDimensions() {\n FontMetrics fm = fComponent.getFontMetrics(fComponent.getFont());\n fCharHeight = fm.getAscent() + fm.getDescent();\n fDescent = fm.getDescent();\n if (fRotation == ROTATE_NONE) {\n int len = fLabel.length();\n char data[] = new char[len];\n fLabel.getChars(0, len, data, 0);\n // if not rotated, width is that of the widest char in the string\n fWidth = 0;\n // we need an array of one-char strings for drawString\n fCharStrings = new String[len];\n fCharWidths = new int[len];\n fPosition = new int[len];\n char ch;\n for (int i = 0; i < len; i++) {\n ch = data[i];\n fCharWidths[i] = fm.charWidth(ch);\n if (fCharWidths[i] > fWidth)\n fWidth = fCharWidths[i];\n fCharStrings[i] = new String(data, i, 1); \n // small kana and punctuation\n if (sDrawsInTopRight.indexOf(ch) >= 0) // if ch is in sDrawsInTopRight\n fPosition[i] = POSITION_TOP_RIGHT;\n else if (sDrawsInFarTopRight.indexOf(ch) >= 0)\n fPosition[i] = POSITION_FAR_TOP_RIGHT;\n else\n fPosition[i] = POSITION_NORMAL;\n }\n // and height is the font height * the char count, + one extra leading at the bottom\n fHeight = fCharHeight * len + fDescent;\n } \n else {\n // if rotated, width is the height of the string\n fWidth = fCharHeight;\n // and height is the width, plus some buffer space \n fHeight = fm.stringWidth(fLabel) + 2*kBufferSpace;\n }\n }\n\n /**\n * Draw the icon at the specified location. Icon implementations\n * may use the Component argument to get properties useful for \n * painting, e.g. the foreground or background color.\n */\n public void paintIcon(Component c, Graphics g, int x, int y) {\n // We don't insist that it be on the same Component\n g.setColor(c.getForeground());\n g.setFont(c.getFont());\n if (fRotation == ROTATE_NONE) {\n int yPos = y + fCharHeight;\n for (int i = 0; i < fCharStrings.length; i++) {\n // Special rules for Japanese - \"half-height\" characters (like ya, yu, yo in combinations)\n // should draw in the top-right quadrant when drawn vertically\n // - they draw in the bottom-left normally\n int tweak;\n switch (fPosition[i]) {\n case POSITION_NORMAL: \n // Roman fonts should be centered. Japanese fonts are always monospaced. \n g.drawString(fCharStrings[i], x+((fWidth-fCharWidths[i])/2), yPos);\n break;\n case POSITION_TOP_RIGHT:\n tweak = fCharHeight/3; // Should be 2, but they aren't actually half-height\n g.drawString(fCharStrings[i], x+(tweak/2), yPos-tweak); \n break;\n case POSITION_FAR_TOP_RIGHT:\n tweak = fCharHeight - fCharHeight/3;\n g.drawString(fCharStrings[i], x+(tweak/2), yPos-tweak); \n break;\n }\n yPos += fCharHeight;\n }\n }\n else if (fRotation == ROTATE_LEFT) {\n g.translate(x+fWidth,y+fHeight);\n ((Graphics2D)g).rotate(-NINETY_DEGREES);\n g.drawString(fLabel, kBufferSpace, -fDescent);\n ((Graphics2D)g).rotate(NINETY_DEGREES);\n g.translate(-(x+fWidth),-(y+fHeight));\n } \n else if (fRotation == ROTATE_RIGHT) {\n g.translate(x,y);\n ((Graphics2D)g).rotate(NINETY_DEGREES);\n g.drawString(fLabel, kBufferSpace, -fDescent);\n ((Graphics2D)g).rotate(-NINETY_DEGREES);\n g.translate(-x,-y);\n } \n\n }\n\n /**\n * Returns the icon's width.\n *\n * @return an int specifying the fixed width of the icon.\n */\n public int getIconWidth() {\n return fWidth;\n }\n\n /**\n * Returns the icon's height.\n *\n * @return an int specifying the fixed height of the icon.\n */\n public int getIconHeight() {\n return fHeight;\n }\n\n /** \n verifyRotation\n\n returns the best rotation for the string (ROTATE_NONE, ROTATE_LEFT, ROTATE_RIGHT)\n\n This is public static so you can use it to test a string without creating a VTextIcon\n\n from http://www.unicode.org/unicode/reports/tr9/tr9-3.html\n When setting text using the Arabic script in vertical lines, \n it is more common to employ a horizontal baseline that \n is rotated by 90� counterclockwise so that the characters \n are ordered from top to bottom. Latin text and numbers \n may be rotated 90� clockwise so that the characters \n are also ordered from top to bottom.\n\n Rotation rules\n - Roman can rotate left, right, or none - default right (counterclockwise)\n - CJK can't rotate\n - Arabic must rotate - default left (clockwise)\n\n from the online edition of _The Unicode Standard, Version 3.0_, file ch10.pdf page 4\n Ideographs are found in three blocks of the Unicode Standard...\n U+4E00-U+9FFF, U+3400-U+4DFF, U+F900-U+FAFF\n\n Hiragana is U+3040-U+309F, katakana is U+30A0-U+30FF\n\n from http://www.unicode.org/unicode/faq/writingdirections.html\n East Asian scripts are frequently written in vertical lines \n which run from top-to-bottom and are arrange columns either \n from left-to-right (Mongolian) or right-to-left (other scripts). \n Most characters use the same shape and orientation when displayed \n horizontally or vertically, but many punctuation characters \n will change their shape when displayed vertically.\n\n Letters and words from other scripts are generally rotated through \n ninety degree angles so that they, too, will read from top to bottom. \n That is, letters from left-to-right scripts will be rotated clockwise \n and letters from right-to-left scripts counterclockwise, both \n through ninety degree angles.\n\n Unlike the bidirectional case, the choice of vertical layout \n is usually treated as a formatting style; therefore, \n the Unicode Standard does not define default rendering behavior \n for vertical text nor provide directionality controls designed to override such behavior\n\n */\n public static int verifyRotation(String label, int rotateHint) {\n boolean hasCJK = false;\n boolean hasMustRotate = false; // Arabic, etc\n\n int len = label.length();\n char data[] = new char[len];\n char ch;\n label.getChars(0, len, data, 0);\n for (int i = 0; i < len; i++) {\n ch = data[i];\n if ((ch >= '\\u4E00' && ch <= '\\u9FFF') ||\n (ch >= '\\u3400' && ch <= '\\u4DFF') ||\n (ch >= '\\uF900' && ch <= '\\uFAFF') ||\n (ch >= '\\u3040' && ch <= '\\u309F') ||\n (ch >= '\\u30A0' && ch <= '\\u30FF') )\n hasCJK = true;\n if ((ch >= '\\u0590' && ch <= '\\u05FF') || // Hebrew\n (ch >= '\\u0600' && ch <= '\\u06FF') || // Arabic\n (ch >= '\\u0700' && ch <= '\\u074F') ) // Syriac\n hasMustRotate = true;\n }\n // If you mix Arabic with Chinese, you're on your own\n if (hasCJK)\n return DEFAULT_CJK;\n\n int legal = hasMustRotate ? LEGAL_MUST_ROTATE : LEGAL_ROMAN;\n if ((rotateHint & legal) > 0)\n return rotateHint;\n\n // The hint wasn't legal, or it was zero\n return hasMustRotate ? DEFAULT_MUST_ROTATE : DEFAULT_ROMAN;\n }\n\n // The small kana characters and Japanese punctuation that draw in the top right quadrant:\n // small a, i, u, e, o, tsu, ya, yu, yo, wa (katakana only) ka ke\n static final String sDrawsInTopRight = \n \"\\u3041\\u3043\\u3045\\u3047\\u3049\\u3063\\u3083\\u3085\\u3087\\u308E\" + // hiragana \n \"\\u30A1\\u30A3\\u30A5\\u30A7\\u30A9\\u30C3\\u30E3\\u30E5\\u30E7\\u30EE\\u30F5\\u30F6\"; // katakana\n static final String sDrawsInFarTopRight = \"\\u3001\\u3002\"; // comma, full stop\n\n static final int DEFAULT_CJK = ROTATE_NONE;\n static final int LEGAL_ROMAN = ROTATE_NONE | ROTATE_LEFT | ROTATE_RIGHT;\n static final int DEFAULT_ROMAN = ROTATE_RIGHT; \n static final int LEGAL_MUST_ROTATE = ROTATE_LEFT | ROTATE_RIGHT;\n static final int DEFAULT_MUST_ROTATE = ROTATE_LEFT;\n\n static final double NINETY_DEGREES = Math.toRadians(90.0);\n static final int kBufferSpace = 5;\n}\n CompositeIcon paintIcon Graphics2D g2 = (Graphics2D) g;\n g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16538/"
] |
92,792
|
<p>I have a user control which is loaded in the page dynamically using the following code in Init of the Page.</p>
<pre><code>Dim oCtl As Object
oCtl = LoadControl("~/Controls/UserControl1.ascx")
oCtl.Id = "UserControl11"
PlaceHolder1.Controls.Clear()
PlaceHolder1.Controls.Add(oCtl)
</code></pre>
<p>The user control also contains a button and I am unable to capture the button click within the user control. </p>
|
[
{
"answer_id": 93120,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "Partial Class DynamicLoad\n Inherits System.Web.UI.Page\n\n Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init\n If IsPostBack Then\n If Not (Session(\"ctl\") Is Nothing) Then\n Dim oCtl As Object\n oCtl = Session(\"ctl\")\n PlaceHolder1.Controls.Add(oCtl)\n End If\n End If\n End Sub\n\n\n Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n If Not IsPostBack Then\n Dim oCtl As Object\n oCtl = LoadControl(\"~/Controls/UserControl1.ascx\")\n\n oCtl.Id = \"UserControl11\"\n PlaceHolder1.Controls.Clear()\n PlaceHolder1.Controls.Add(oCtl)\n\n Session(\"ctl\") = oCtl\n End If\n End Sub\nEnd Class\n Partial Class UserControl1\n Inherits System.Web.UI.UserControl\n Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click\n Label1.Text = \"This is Text AFTER Post Back in User Control 1\"\n End Sub\nEnd Class\n"
},
{
"answer_id": 93355,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init\n If IsPostBack AndAlso Session(\"ctl\") IsNot Nothing Then\n Dim MyControl As Control = Session(\"ctl\")\n PlaceHolder1.Controls.Add(MyControl)\n End If\nEnd Sub\n"
},
{
"answer_id": 93709,
"author": "Matt Blaine",
"author_id": 16272,
"author_profile": "https://Stackoverflow.com/users/16272",
"pm_score": 0,
"selected": false,
"text": "AddHandler Button1.Click, AddressOf Button1_Click\n"
},
{
"answer_id": 201166,
"author": "Adrian Clark",
"author_id": 148,
"author_profile": "https://Stackoverflow.com/users/148",
"pm_score": 3,
"selected": false,
"text": "<%@ Page Language=\"vb\" AutoEventWireup=\"false\" CodeBehind=\"Default.aspx.vb\" Inherits=\"Test_User_Control._Default\" %>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" >\n<head runat=\"server\"><title></title></head>\n<body>\n <form id=\"form1\" runat=\"server\">\n <asp:PlaceHolder ID=\"PlaceHolder1\" runat=\"server\" />\n </form>\n</body>\n</html>\n Partial Public Class _Default\n Inherits System.Web.UI.Page\n\n Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init\n\n Dim control As Control = LoadControl(\"~/UserControl1.ascx\")\n PlaceHolder1.Controls.Add(control)\n\n End Sub\nEnd Class\n <%@ Control Language=\"vb\" AutoEventWireup=\"false\" CodeBehind=\"UserControl1.ascx.vb\" Inherits=\"Test_User_Control.UserControl1\" %>\n<asp:Label ID=\"Label1\" Text=\"Before Button Press\" runat=\"server\" />\n<asp:Button ID=\"Button1\" Text=\"Push me\" runat=\"server\" />\n Public Partial Class UserControl1\n Inherits System.Web.UI.UserControl\n\n Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click\n Label1.Text = \"The button has been pressed!\"\n End Sub\n\nEnd Class\n"
},
{
"answer_id": 545569,
"author": "ljubomir",
"author_id": 11506,
"author_profile": "https://Stackoverflow.com/users/11506",
"pm_score": 2,
"selected": false,
"text": "PlaceHolder1.Controls.Clear()"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
92,802
|
<p>I have a Bash shell script in which I would like to pause execution until the user presses a key. In DOS, this is easily accomplished with the <code>pause</code> command. Is there a Linux equivalent I can use in my script?</p>
|
[
{
"answer_id": 92813,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 10,
"selected": true,
"text": "read user@host:~$ read -n1 -r -p \"Press any key to continue...\" key\n[...]\nuser@host:~$ \n -n1 -r -p key $key -t read -t5 -n1 -r -p 'Press any key in the next five seconds...' key\nif [ \"$?\" -eq \"0\" ]; then\n echo 'A key was pressed.'\nelse\n echo 'No key was pressed.'\nfi\n"
},
{
"answer_id": 92821,
"author": "Alex Fort",
"author_id": 12624,
"author_profile": "https://Stackoverflow.com/users/12624",
"pm_score": -1,
"selected": false,
"text": "function pause(){\n read -p \"$*\"\n}\n"
},
{
"answer_id": 92913,
"author": "xsl",
"author_id": 11387,
"author_profile": "https://Stackoverflow.com/users/11387",
"pm_score": 4,
"selected": false,
"text": "read pause read –n1"
},
{
"answer_id": 17778773,
"author": "y.petremann",
"author_id": 1311620,
"author_profile": "https://Stackoverflow.com/users/1311620",
"pm_score": 7,
"selected": false,
"text": "read -rsp $'Press enter to continue...\\n'\n read -rsp $'Press escape to continue...\\n' -d $'\\e'\n read -rsp $'Press any key to continue...\\n' -n 1 key\n# echo $key\n read -rp $'Are you sure (Y/n) : ' -ei $'Y' key;\n# echo $key\n read -rsp $'Press any key or wait 5 seconds to continue...\\n' -n 1 -t 5;\n read -rst 0.5; timeout=$?\n# echo $timeout\n"
},
{
"answer_id": 24046880,
"author": "mikeserv",
"author_id": 2955202,
"author_profile": "https://Stackoverflow.com/users/2955202",
"pm_score": 4,
"selected": false,
"text": "read -n1 ( trap \"stty $(stty -g;stty -icanon)\" EXIT\n LC_ALL=C dd bs=1 count=1 >/dev/null 2>&1\n) </dev/tty\n read ENTER sed -n q </dev/tty\n"
},
{
"answer_id": 39638013,
"author": "mwfearnley",
"author_id": 446106,
"author_profile": "https://Stackoverflow.com/users/446106",
"pm_score": 2,
"selected": false,
"text": "read do_stuff\nread\ndo_more_stuff\n"
},
{
"answer_id": 41728415,
"author": "BuvinJ",
"author_id": 3220983,
"author_profile": "https://Stackoverflow.com/users/3220983",
"pm_score": 4,
"selected": false,
"text": "echo Press enter to continue; read dummy;\n read"
},
{
"answer_id": 49656617,
"author": "SDsolar",
"author_id": 5093068,
"author_profile": "https://Stackoverflow.com/users/5093068",
"pm_score": 0,
"selected": false,
"text": "read cron time rsync (options)\nread -n 120 -p \"Press 'Enter' to continue...\" ; echo \" \"\n cron rsync echo"
},
{
"answer_id": 51075278,
"author": "Tom Hale",
"author_id": 5353461,
"author_profile": "https://Stackoverflow.com/users/5353461",
"pm_score": 2,
"selected": false,
"text": "bash zsh # Prompt for a keypress to continue. Customise prompt with $*\nfunction pause {\n >/dev/tty printf '%s' \"${*:-Press any key to continue... }\"\n [[ $ZSH_VERSION ]] && read -krs # Use -u0 to read from STDIN\n [[ $BASH_VERSION ]] && </dev/tty read -rsn1\n printf '\\n'\n}\nexport_function pause\n .{ba,z}shrc"
},
{
"answer_id": 69035133,
"author": "SwiftNinjaPro",
"author_id": 10355515,
"author_profile": "https://Stackoverflow.com/users/10355515",
"pm_score": 2,
"selected": false,
"text": "read -n1 -r -s -p \"Press any key to continue...\" ; echo\n read -n1 -r -s -p \"Press any key to continue... (cant find the ANY key? press ENTER) \" ; echo\n"
},
{
"answer_id": 71361396,
"author": "Siddharth Maurya",
"author_id": 14165601,
"author_profile": "https://Stackoverflow.com/users/14165601",
"pm_score": 0,
"selected": false,
"text": "pause git clone https://github.com/savvysiddharth/pause-command.git\ncd pause-command\nsudo make install\n pause read pause \"Pausing execution, Human intervention required...\"\n system(\"pause\");"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4362/"
] |
92,809
|
<p>With the plethora of communication methods available to co-workers, how do you manage to keep distractions at bay for a large enough block of time to accomplish some focused programming?</p>
<p>Do you quit or close all communications, have you informed people that an away message really means you are a way, or something else?</p>
|
[
{
"answer_id": 92899,
"author": "Tony Pitale",
"author_id": 1167846,
"author_profile": "https://Stackoverflow.com/users/1167846",
"pm_score": 1,
"selected": false,
"text": "open"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1167846/"
] |
92,820
|
<pre><code>class A : IFoo
{
}
...
A[] arrayOfA = new A[10];
if(arrayOfA is IFoo[])
{
// this is not called
}
</code></pre>
<p>Q1: Why is <code>arrayOfA</code> not an array of <code>IFoos</code>?</p>
<p>Q2: Why can't I cast <code>arrayOfA</code> to <code>IFoo[]</code>?</p>
|
[
{
"answer_id": 92856,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": -1,
"selected": false,
"text": "if (arrayofA[0] is IFoo) {.....}\n arrayOfA ICloneable IList ICollection IEnumerable IFoo"
},
{
"answer_id": 92876,
"author": "Ed Guiness",
"author_id": 4200,
"author_profile": "https://Stackoverflow.com/users/4200",
"pm_score": 4,
"selected": true,
"text": "arrayOfA IFoo[] using System;\npublic class oink {\n public static void Main() {\n A[] aOa = new A[10];\n\n if (aOa is IFoo[]) { Console.WriteLine(\"aOa is IFoo[]\"); }\n\n }\n public interface IFoo {}\n public class A : IFoo {}\n}\n\nPS D:\\> csc test.cs\nMicrosoft (R) Visual C# 2008 Compiler version 3.5.30729.1\nfor Microsoft (R) .NET Framework version 3.5\nCopyright (C) Microsoft Corporation. All rights reserved.\n\nPS D:\\> D:\\test.exe\naOa is IFoo[]\nPS D:\\>\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7529/"
] |
92,826
|
<p>Simply setting the SVN_EDITOR variable to "mate" does not get the job done. It opens TextMate when appropriate, but then when I save the message and exit, I'm prompted to continue, abort or try again. It seems like the buffer isn't returned to the svn command for use.</p>
|
[
{
"answer_id": 4998988,
"author": "Fabio",
"author_id": 518204,
"author_profile": "https://Stackoverflow.com/users/518204",
"pm_score": 2,
"selected": false,
"text": "~/.subversion/config mate -wl1"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5586/"
] |
92,841
|
<p>I am using CodeDom to generate dynamic code based on user values. One of those values controls what the name of the class I'm generating is. I know I could sterilize the name based on language rules about valid class names using regular expressions, but I'd like to know if there is a specific method built into the framework to validate and/or sterilize a class name.</p>
|
[
{
"answer_id": 92958,
"author": "Zach",
"author_id": 8720,
"author_profile": "https://Stackoverflow.com/users/8720",
"pm_score": 2,
"selected": false,
"text": "CodeCompiler.ValidateIdentifiers(class1);\n"
},
{
"answer_id": 92978,
"author": "Jason Diller",
"author_id": 2187,
"author_profile": "https://Stackoverflow.com/users/2187",
"pm_score": 3,
"selected": false,
"text": "CreateValidIdentifier CSharpCodeProvider CSharpCodeProvider codeProvider = new CSharpCodeProvider(); \nstring sFixedName = codeProvider.CreateValidIdentifier(\"somePossiblyInvalidName\"); \nCodeTypeDeclaration codeType = new CodeTypeDeclaration(sFixedName); \n"
},
{
"answer_id": 92982,
"author": "Micah",
"author_id": 17744,
"author_profile": "https://Stackoverflow.com/users/17744",
"pm_score": 6,
"selected": true,
"text": "System.CodeDom.Compiler.CodeGenerator.IsValidLanguageIndependentIdentifier(string value)\n"
},
{
"answer_id": 93919,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "public static bool IsReservedKeyWord(string identifier)\n {\n Microsoft.CSharp.CSharpCodeProvider csharpProvider = new Microsoft.CSharp.CSharpCodeProvider();\n return csharpProvider.IsValidIdentifier(identifier);\n }\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8720/"
] |
92,842
|
<p>I'm implementing a comment control that uses an ASP.Repeater to display each comment. The comment itself is currently displayed using a table to divide up some images to display the comment in a bubble.</p>
<p>I know that tables are supposed to be the epitome of evil for design layout, and really expensive to display for the browser, but I'm not exactly sure how to put my rounded corners in the correct location and make sure everything lines up.</p>
<p>Does anyone have any suggestions, examples, hacks for the HTML/CSS required, or should I just stick with tables and hope for the best?</p>
|
[
{
"answer_id": 92889,
"author": "Doug Moore",
"author_id": 13179,
"author_profile": "https://Stackoverflow.com/users/13179",
"pm_score": 0,
"selected": false,
"text": "<style>\n .start { background-image: url(\"topofbubble.png\"); height: <heightofimage>; }\n .end { background-image: url(\"bottomofbubble.png\"); height: <heightofimage>; }\n .body {background-image: url(\"sliceofbubblemiddle.png\"); }\n</style>\n\n...\n\n<div class=\"comment\">\n <span class=\"start\"></span>\n <span class=\"body\">I would like to say that div layouts are far better than table layouts.</span>\n <span class=\"end\"></style>\n</div>\n"
},
{
"answer_id": 559290,
"author": "Xanthir",
"author_id": 58347,
"author_profile": "https://Stackoverflow.com/users/58347",
"pm_score": 0,
"selected": false,
"text": "border-radius -moz-border-radius -webkit-border-radius"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12096/"
] |
92,847
|
<p>How do I make an array shorter in Perl? I read some webpages indicating that I can assign:</p>
<pre><code>$#ARRAY = 42;
</code></pre>
<p>I read that the use of $# is deprecated. I need a solution that will work for an array of arrays, too. This didn't work:</p>
<pre><code>$#$ARRAY[$i] = 42;
</code></pre>
|
[
{
"answer_id": 92883,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 0,
"selected": false,
"text": "splice @array, $length;\n#or\nsplice @{$arrays[$i]}, $length;\n"
},
{
"answer_id": 92935,
"author": "Frosty",
"author_id": 7476,
"author_profile": "https://Stackoverflow.com/users/7476",
"pm_score": 3,
"selected": false,
"text": "$#array = $N-1;\n #best for trimming down large arrays into small arrays\n@array = $array[0..($N-1)];\n #This is a little less expensive and clearer\nsplice(@array, $n, @#array);\n #this is the worst solution yet because it requires resizing after the delete\nwhile($N-1 < $#array)\n{\n delete(array[$i]);\n}\n #this is better than deleting because there is no resize\nwhile($N-1 < $#array)\n{\n pop @array;\n #or, \"push $array2, pop @array;\" for the reverse order remainder\n}\n #don't put more values into the array than you actually want\n"
},
{
"answer_id": 92968,
"author": "Rob N",
"author_id": 12421,
"author_profile": "https://Stackoverflow.com/users/12421",
"pm_score": 5,
"selected": true,
"text": "$#ARRAY perldoc perldata splice splice @ARRAY, 43;\n 43 42 $#ARRAY splice $#{$ARRAY->[7]} = 42;\n splice @{$ARRAY->[7]}, 43;\n"
},
{
"answer_id": 93012,
"author": "Axeman",
"author_id": 11289,
"author_profile": "https://Stackoverflow.com/users/11289",
"pm_score": 2,
"selected": false,
"text": "use Data::Dumper;\n$#{$array[3]} = 5;\n$#array = 10;\nprint Dumper( \\@array, $array ), \"\\n\";\n"
},
{
"answer_id": 93241,
"author": "tsee",
"author_id": 13164,
"author_profile": "https://Stackoverflow.com/users/13164",
"pm_score": 3,
"selected": false,
"text": "$#Array = 42\n"
},
{
"answer_id": 94094,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 3,
"selected": false,
"text": "$# $#array $#array $#{ EXPR }"
},
{
"answer_id": 95243,
"author": "xdg",
"author_id": 11800,
"author_profile": "https://Stackoverflow.com/users/11800",
"pm_score": 0,
"selected": false,
"text": "splice @array, -10;\n @new = @old[ 0 .. $#old - 10 ]\n original: length 500 => size 2104\n pound: length 490 => size 2208\n splice: length 490 => size 2104\n delete: length 490 => size 2104\n slice: length 490 => size 2064\n use strict;\nuse warnings;\nuse 5.010;\nuse Devel::Size qw/size/;\n\nmy @original = (1 .. 500);\nshow( 'original', \\@original );\n\nmy @pound = @original;\n$#pound = $#pound - 10;\nshow( 'pound', \\@pound );\n\nmy @splice = @original;\nsplice(@splice,-10);\nshow( 'splice', \\@splice);\n\nmy @delete = @original;\ndelete @delete[ -10 .. -1 ];\nshow( 'delete', \\@delete );\n\nmy @slice = @original[0 .. $#original - 10];\nshow( 'slice', \\@slice);\n\nsub show {\n my ($name, $ref) = @_;\n printf( \"%10s: length %4d => size %d\\n\", $name, scalar @$ref, size($ref));\n}\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4454/"
] |
92,848
|
<p>I have a Win-CGI application I am currently converting to ISAPI.</p>
<p>The application uses the TDataset descendants for Extended Systems Advantage Database Server.</p>
<p>As there can be only one instance of a TAdsSettings object, this must be
in the main thread.</p>
<p>TAdsQuery objects are needed in the request threads.</p>
<p>Will this work - that is, will the AdsQueries in the request threads
pick up the global settings from the AdsSettings object in the main
thread, and will this be thread safe?</p>
|
[
{
"answer_id": 94522,
"author": "Francesca",
"author_id": 9842,
"author_profile": "https://Stackoverflow.com/users/9842",
"pm_score": 0,
"selected": false,
"text": "System.MainThreadID <> Windows.GetCurrentThreadID"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11820/"
] |
92,859
|
<p>This question was <a href="https://stackoverflow.com/questions/13049">already asked in the context of C#/.Net</a>.</p>
<p>Now I'd like to learn the differences between a struct and a class in C++. Please discuss the technical differences as well as reasons for choosing one or the other in OO design.</p>
<p>I'll start with an obvious difference:</p>
<ul>
<li>If you don't specify <code>public:</code> or <code>private:</code>, members of a struct are public by default; members of a class are private by default.</li>
</ul>
<p>I'm sure there are other differences to be found in the obscure corners of the C++ specification.</p>
|
[
{
"answer_id": 92914,
"author": "crashmstr",
"author_id": 1441,
"author_profile": "https://Stackoverflow.com/users/1441",
"pm_score": 5,
"selected": false,
"text": "struct"
},
{
"answer_id": 100899,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "class A{ \npublic: \n int i; \n};\n\nclass A2:A{ \n};\n\nstruct A3:A{ \n};\n\n\nstruct abc{ \n int i;\n};\n\nstruct abc2:abc{ \n};\n\nclass abc3:abc{\n};\n\n\nint _tmain(int argc, _TCHAR* argv[])\n{ \n abc2 objabc;\n objabc.i = 10;\n\n A3 ob;\n ob.i = 10;\n\n //A2 obja; //privately inherited\n //obja.i = 10;\n\n //abc3 obss;\n //obss.i = 10;\n}\n"
},
{
"answer_id": 999810,
"author": "Assaf Lavie",
"author_id": 11208,
"author_profile": "https://Stackoverflow.com/users/11208",
"pm_score": 10,
"selected": true,
"text": "class struct"
},
{
"answer_id": 2661721,
"author": "Gregory Pakosz",
"author_id": 216063,
"author_profile": "https://Stackoverflow.com/users/216063",
"pm_score": 2,
"selected": false,
"text": "struct"
},
{
"answer_id": 3432421,
"author": "Jon Hanna",
"author_id": 400547,
"author_profile": "https://Stackoverflow.com/users/400547",
"pm_score": 7,
"selected": false,
"text": "struct class"
},
{
"answer_id": 6943176,
"author": "ymett",
"author_id": 611142,
"author_profile": "https://Stackoverflow.com/users/611142",
"pm_score": 2,
"selected": false,
"text": "class struct"
},
{
"answer_id": 8104128,
"author": "Stefan Popescu",
"author_id": 1043056,
"author_profile": "https://Stackoverflow.com/users/1043056",
"pm_score": 2,
"selected": false,
"text": "template<class T> // OK\ntemplate<struct T> // ERROR, struct not allowed here\n"
},
{
"answer_id": 19002981,
"author": "Abhishek Sharma",
"author_id": 2173148,
"author_profile": "https://Stackoverflow.com/users/2173148",
"pm_score": -1,
"selected": false,
"text": "Class MyClass\n{\n Public Int DataMember; //By default, accessibility of class data members \n //will be private. So I am making it as Public which \n //can be accessed outside of the class.\n}\n Static Public void Main (string[] arg)\n{\n MyClass _myClassObject1 = new MyClass();\n _myClassObject1.DataMember = 10;\n\n MyClass _myClassObject2 = _myClassObject1;\n _myClassObject2.DataMember=20;\n}\n Structure MyStructure\n{\n Public Int DataMember; //By default, accessibility of Structure data \n //members will be private. So I am making it as \n //Public which can be accessed out side of the structure.\n}\n\nStatic Public void Main (string[] arg)\n{\n MyStructure _myStructObject1 = new MyStructure();\n _myStructObject1.DataMember = 10;\n\n MyStructure _myStructObject2 = _myStructObject1;\n _myStructObject2.DataMember = 20;\n}\n"
},
{
"answer_id": 31603033,
"author": "Suraj K Thomas",
"author_id": 1667476,
"author_profile": "https://Stackoverflow.com/users/1667476",
"pm_score": 4,
"selected": false,
"text": "// Program 1\n#include <stdio.h>\n \nclass Test {\n int x; // x is private\n};\n\nint main()\n{\n Test t;\n t.x = 20; // compiler error because x is private\n getchar();\n return 0;\n}\n // Program 2\n#include <stdio.h>\n \nstruct Test {\n int x; // x is public\n};\n\nint main()\n{\n Test t;\n t.x = 20; // works fine because x is public\n getchar();\n return 0;\n}\n // Program 3\n#include <stdio.h>\n \nclass Base {\npublic:\n int x;\n};\n \nclass Derived : Base { }; // is equivalent to class Derived : private Base {}\n \nint main()\n{\n Derived d;\n d.x = 20; // compiler error because inheritance is private\n getchar();\n return 0;\n}\n // Program 4\n#include <stdio.h>\n \nclass Base {\npublic:\n int x;\n};\n \nstruct Derived : Base { }; // is equivalent to struct Derived : public Base {}\n \nint main()\n{\n Derived d;\n d.x = 20; // works fine because inheritance is public\n getchar();\n return 0;\n}\n"
},
{
"answer_id": 53852827,
"author": "Bathsheba",
"author_id": 2380830,
"author_profile": "https://Stackoverflow.com/users/2380830",
"pm_score": 2,
"selected": false,
"text": "class private struct union public public struct private class template<class T> template<struct T> struct class std::is_class<Y>::value true struct class false enum class"
},
{
"answer_id": 56675481,
"author": "463035818_is_not_a_number",
"author_id": 4117728,
"author_profile": "https://Stackoverflow.com/users/4117728",
"pm_score": 3,
"selected": false,
"text": "class struct struct foo : foo_base { int x;};\nclass bar : bar_base { int x; };\n foo::x foo_base bar::x bar_base"
},
{
"answer_id": 72139416,
"author": "Maciej Urbański",
"author_id": 14896172,
"author_profile": "https://Stackoverflow.com/users/14896172",
"pm_score": -1,
"selected": false,
"text": "class Time\n{\n int minutes;\n int seconds;\n}\n\nstruct Sizes\n{\n int length;\n int width;\n};\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2686/"
] |
92,860
|
<p>What is best practises for communicating events from a usercontrol to parent control/page i want to do something similar to this:</p>
<pre><code>MyPage.aspx:
<asp:Content ID="Content1" ContentPlaceHolderID="MainContentPlaceholder" runat="server">
<uc1:MyUserControl ID="MyUserControl1" runat="server"
OnSomeEvent="MyUserControl_OnSomeEvent" />
MyUserControl.ascx.cs:
public partial class MyUserControl: UserControl
{
public event EventHandler SomeEvent;
....
private void OnSomething()
{
if (SomeEvent!= null)
SomeEvent(this, EventArgs.Empty);
}
</code></pre>
<p>Question is what is best practise?</p>
|
[
{
"answer_id": 92959,
"author": "Doug Moore",
"author_id": 13179,
"author_profile": "https://Stackoverflow.com/users/13179",
"pm_score": 4,
"selected": true,
"text": "<%@ Control Language=\"c#\" AutoEventWireup=\"false\" \n Codebehind=\"WebUserControl1.ascx.cs\" \n Inherits=\"aspnet.eventbubble.WebUserControl1\" \n TargetSchema=\"http://schemas.microsoft.com/intellisense/ie5\"\n%>\n<asp:Panel id=\"Panel1\" runat=\"server\" Width=\"128px\" Height=\"96px\">\n WebUserControl1 \n <asp:Button id=\"Button1\" Text=\"Button\" runat=\"server\"/>\n</asp:Panel>\n public class WebUserControl1 : System.Web.UI.UserControl\n{\n protected System.Web.UI.WebControls.Button Button1;\n protected System.Web.UI.WebControls.Panel Panel1;\n\n private void Page_Load(object sender, System.EventArgs e)\n {\n Response.Write(\"WebUserControl1 :: Page_Load <BR>\");\n }\n\n private void Button1_Click(object sender, System.EventArgs e)\n {\n Response.Write(\"WebUserControl1 :: Begin Button1_Click <BR>\");\n OnBubbleClick(e);\n Response.Write(\"WebUserControl1 :: End Button1_Click <BR>\");\n }\n\n public event EventHandler BubbleClick;\n\n protected void OnBubbleClick(EventArgs e)\n {\n if(BubbleClick != null)\n {\n BubbleClick(this, e);\n }\n } \n\n #region Web Form Designer generated code\n override protected void OnInit(EventArgs e)\n {\n InitializeComponent();\n base.OnInit(e);\n }\n\n private void InitializeComponent()\n {\n this.Button1.Click += new System.EventHandler(this.Button1_Click);\n this.Load += new System.EventHandler(this.Page_Load);\n\n }\n #endregion\n\n}\n <%@ Register TagPrefix=\"ksa\" \n TagName=\"BubbleControl\" \n Src=\"WebUserControl1.ascx\" \n%>\n<%@ Page language=\"c#\" Codebehind=\"WebForm1.aspx.cs\" \n AutoEventWireup=\"false\" Inherits=\"aspnet.eventbubble.WebForm1\" \n%>\n<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" >\n<HTML>\n <HEAD>\n <title>WebForm1</title>\n </HEAD>\n <body MS_POSITIONING=\"GridLayout\">\n <form id=\"Form1\" method=\"post\" runat=\"server\">\n <ksa:BubbleControl id=\"BubbleControl\" runat=\"server\" />\n </form>\n </body>\n</HTML>\n public class WebForm1 : System.Web.UI.Page\n{\n protected WebUserControl1 BubbleControl;\n\n private void Page_Load(object sender, System.EventArgs e)\n {\n Response.Write(\"WebForm1 :: Page_Load <BR>\");\n }\n\n #region Web Form Designer generated code\n override protected void OnInit(EventArgs e)\n {\n InitializeComponent();\n base.OnInit(e);\n }\n\n private void InitializeComponent()\n { \n this.Load += new System.EventHandler(this.Page_Load);\n BubbleControl.BubbleClick += new EventHandler(WebForm1_BubbleClick);\n }\n #endregion\n\n private void WebForm1_BubbleClick(object sender, EventArgs e)\n {\n Response.Write(\"WebForm1 :: WebForm1_BubbleClick from \" + \n sender.GetType().ToString() + \"<BR>\"); \n }\n}\n"
},
{
"answer_id": 30356695,
"author": "Eric Barr",
"author_id": 1313642,
"author_profile": "https://Stackoverflow.com/users/1313642",
"pm_score": 0,
"selected": false,
"text": "<%@ Control Language=\"vb\" AutoEventWireup=\"false\" CodeBehind=\"CountryDropDownList.ascx.vb\" Inherits=\"CountryDropDownList\" %>\n<asp:DropDownList runat=\"server\" ID=\"ddlCountryList\" OnSelectedIndexChanged=\"ddlCountryList_SelectedIndexChanged\" AutoPostBack=\"true\">\n <asp:ListItem Value=\"\"></asp:ListItem>\n <asp:ListItem value=\"US\">United States</asp:ListItem>\n <asp:ListItem value=\"AF\">Afghanistan</asp:ListItem>\n <asp:ListItem value=\"AL\">Albania</asp:ListItem>\n</asp:DropDownList>\n Public Class CountryDropDownList\n Inherits System.Web.UI.UserControl\n Public Event SelectedCountryChanged As EventHandler\n\n Protected Sub ddlCountryList_SelectedIndexChanged(sender As Object, e As EventArgs)\n ' bubble the event up to the parent\n RaiseEvent SelectedCountryChanged(Me, e)\n End Sub\nEnd Class\n <%@ Page Language=\"vb\" AutoEventWireup=\"false\" CodeBehind=\"UpdateProfile.aspx.vb\" Inherits=\"UpdateProfile\" MaintainScrollPositionOnPostback=\"true\" %>\n<%@ Register Src=\"~/UserControls/CountryDropDownList.ascx\" TagPrefix=\"SO\" TagName=\"ucCountryDropDownList\" %>\n<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" >\n<HTML>\n <HEAD>\n <title>WebForm1</title>\n </HEAD>\n <body>\n <form id=\"Form1\" method=\"post\" runat=\"server\">\n <SO:ucCountryDropDownList id=\"ddlCountry\" runat=\"server\" />\n </form>\n </body>\n</HTML>\n Protected Sub OnSelectedCountryChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlCountry.SelectedCountryChanged\n ' add your code here\nEnd Sub\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15555/"
] |
92,862
|
<p>In Ruby, like in many other OO programming languages, operators are overloadable. However, only certain character operators can be overloaded.</p>
<p>This list may be incomplete but, here are some of the operators that cannot be overloaded: </p>
<pre><code>!, not, &&, and, ||, or
</code></pre>
|
[
{
"answer_id": 92931,
"author": "Jordi Bunster",
"author_id": 4272,
"author_profile": "https://Stackoverflow.com/users/4272",
"pm_score": 4,
"selected": false,
"text": "5 + 5 5.+(5) foo[bar] = baz foo.[]=(bar, baz)"
},
{
"answer_id": 98232,
"author": "Ryan Bigg",
"author_id": 15245,
"author_profile": "https://Stackoverflow.com/users/15245",
"pm_score": 1,
"selected": false,
"text": "<< string = \"test\"\nstring << \"ing\"\n string.<<(\"ing\")\n"
},
{
"answer_id": 109347,
"author": "Jörg W Mittag",
"author_id": 2988,
"author_profile": "https://Stackoverflow.com/users/2988",
"pm_score": 3,
"selected": false,
"text": "! && || and or a != b !(a == b) a += b a = a+b"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1167846/"
] |
92,869
|
<p>I am going to be starting up a new project at work and want to get into unit testing. We will be using Visual Studio 2008, C#, and the ASP.NET MVC stuff. I am looking at using either NUnit or the built-in test projects that Visual Studio 2008 has, but I am open to researching other suggestions. Is one system better than the other or perhaps easier to use/understand than the other?</p>
<p>I am looking to get this project set up as kind of the "best practice" for our development efforts going forward.</p>
|
[
{
"answer_id": 547199,
"author": "Tuomas Hietanen",
"author_id": 17791,
"author_profile": "https://Stackoverflow.com/users/17791",
"pm_score": 3,
"selected": false,
"text": " #if !MSTEST\n using NUnit.Framework;\n #else\n using Microsoft.VisualStudio.TestTools.UnitTesting;\n using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;\n using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;\n using SetUp = Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute;\n using TearDown = Microsoft.VisualStudio.TestTools.UnitTesting.TestCleanupAttribute;\n #endif\n"
},
{
"answer_id": 1319780,
"author": "AlSki",
"author_id": 54239,
"author_profile": "https://Stackoverflow.com/users/54239",
"pm_score": 3,
"selected": false,
"text": "using"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13593/"
] |
92,894
|
<p>I've done many web apps where the first thing you do is make a user table with usernames, passwords, names, e-mails and all of the other usual flotsam. My current project presents a situation where non-users records need to function similarly to users, but do not need to the ability to be a first order user. </p>
<p>Is it reasonable to create a second table, <code>people_tb</code>, that is the main relational table and data store, and only use the <code>users_tb</code> for authentication? Does separating <code>user_tb</code> from <code>people_tb</code> present any problems? If this is commonly done, what are some strategies and solutions as well as drawbacks? </p>
|
[
{
"answer_id": 92965,
"author": "ern",
"author_id": 5609,
"author_profile": "https://Stackoverflow.com/users/5609",
"pm_score": 0,
"selected": false,
"text": "people users people"
},
{
"answer_id": 93090,
"author": "Rick Glos",
"author_id": 16008,
"author_profile": "https://Stackoverflow.com/users/16008",
"pm_score": 0,
"selected": false,
"text": "aspnet_Users aspnet_Membership aspnet_User.UserID"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1227/"
] |
92,928
|
<p>In Python for *nix, does <code>time.sleep()</code> block the thread or the process?</p>
|
[
{
"answer_id": 92986,
"author": "Zach Burlingame",
"author_id": 2233,
"author_profile": "https://Stackoverflow.com/users/2233",
"pm_score": 6,
"selected": false,
"text": "sleep()"
},
{
"answer_id": 93179,
"author": "Nick Bastin",
"author_id": 1502059,
"author_profile": "https://Stackoverflow.com/users/1502059",
"pm_score": 10,
"selected": true,
"text": "floatsleep() import time\nfrom threading import Thread\n\nclass worker(Thread):\n def run(self):\n for x in xrange(0,11):\n print x\n time.sleep(1)\n\nclass waiter(Thread):\n def run(self):\n for x in xrange(100,103):\n print x\n time.sleep(5)\n\ndef run():\n worker().start()\n waiter().start()\n >>> thread_test.run()\n0\n100\n>>> 1\n2\n3\n4\n5\n101\n6\n7\n8\n9\n10\n102\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17732/"
] |
92,971
|
<p>I'm trying to detect the size of the screen I'm starting emacs on, and adjust the size and position the window it is starting in (I guess that's the frame in emacs-speak) accordingly. I'm trying to set up my .emacs so that I always get a "reasonably-big" window with it's top-left corner near the top-left of my screen.</p>
<p>I guess this is a <em>big</em> ask for the general case, so to narrow things down a bit I'm most interested in GNU Emacs 22 on Windows and (Debian) Linux.</p>
|
[
{
"answer_id": 93005,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "(setq initial-frame-alist\n (append '((width . 263) (height . 112) (top . -5) (left . 5) (font . \"4.System VIO\"))\n initial-frame-alist))\n\n(setq default-frame-alist\n (append '((width . 263) (height . 112) (top . -5) (left . 5) (font . \"4.System VIO\"))\n default-frame-alist))\n"
},
{
"answer_id": 93019,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "(setq default-frame-alist\n '((top . 200) (left . 400)\n (width . 80) (height . 40)\n (cursor-color . \"white\")\n (cursor-type . box)\n (foreground-color . \"yellow\")\n (background-color . \"black\")\n (font . \"-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1\")))\n\n(setq initial-frame-alist '((top . 10) (left . 30)))\n"
},
{
"answer_id": 93084,
"author": "JB.",
"author_id": 12274,
"author_profile": "https://Stackoverflow.com/users/12274",
"pm_score": 4,
"selected": false,
"text": "Emacs.geometry: 80x70\n"
},
{
"answer_id": 94172,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 6,
"selected": false,
"text": ".emacs (if (window-system)\n (set-frame-height (selected-frame) 60))\n set-frame-size set-frame-position set-frame-width C-h f M-x describe-function"
},
{
"answer_id": 94277,
"author": "Bryan Oakley",
"author_id": 7432,
"author_profile": "https://Stackoverflow.com/users/7432",
"pm_score": 7,
"selected": true,
"text": "(defun set-frame-size-according-to-resolution ()\n (interactive)\n (if window-system\n (progn\n ;; use 120 char wide window for largeish displays\n ;; and smaller 80 column windows for smaller displays\n ;; pick whatever numbers make sense for you\n (if (> (x-display-pixel-width) 1280)\n (add-to-list 'default-frame-alist (cons 'width 120))\n (add-to-list 'default-frame-alist (cons 'width 80)))\n ;; for the height, subtract a couple hundred pixels\n ;; from the screen height (for panels, menubars and\n ;; whatnot), then divide by the height of a char to\n ;; get the height we want\n (add-to-list 'default-frame-alist \n (cons 'height (/ (- (x-display-pixel-height) 200)\n (frame-char-height)))))))\n\n(set-frame-size-according-to-resolution)\n (display-graphic-p)"
},
{
"answer_id": 94329,
"author": "Graeme Perrow",
"author_id": 1821,
"author_profile": "https://Stackoverflow.com/users/1821",
"pm_score": 4,
"selected": false,
"text": "emacs -geometry 80x60+20+30"
},
{
"answer_id": 3538748,
"author": "Jérôme Radix",
"author_id": 3673,
"author_profile": "https://Stackoverflow.com/users/3673",
"pm_score": 3,
"selected": false,
"text": "(defun w32-maximize-frame ()\n \"Maximize the current frame\"\n (interactive)\n (w32-send-sys-command 61488))\n"
},
{
"answer_id": 7660628,
"author": "ftravers",
"author_id": 408489,
"author_profile": "https://Stackoverflow.com/users/408489",
"pm_score": 3,
"selected": false,
"text": "(defun toggle-fullscreen ()\n (interactive)\n (x-send-client-message nil 0 nil \"_NET_WM_STATE\" 32\n '(2 \"_NET_WM_STATE_MAXIMIZED_VERT\" 0))\n (x-send-client-message nil 0 nil \"_NET_WM_STATE\" 32\n '(2 \"_NET_WM_STATE_MAXIMIZED_HORZ\" 0))\n)\n(toggle-fullscreen)\n"
},
{
"answer_id": 11912263,
"author": "WisdomFusion",
"author_id": 191071,
"author_profile": "https://Stackoverflow.com/users/191071",
"pm_score": 1,
"selected": false,
"text": "(defun set-frame-size-according-to-resolution ()\n (interactive)\n (if window-system\n (progn\n ;; use 120 char wide window for largeish displays\n ;; and smaller 80 column windows for smaller displays\n ;; pick whatever numbers make sense for you\n (if (> (x-display-pixel-width) 1280)\n (add-to-list 'default-frame-alist (cons 'width 120))\n (add-to-list 'default-frame-alist (cons 'width 80)))\n ;; for the height, subtract a couple hundred pixels\n ;; from the screen height (for panels, menubars and\n ;; whatnot), then divide by the height of a char to\n ;; get the height we want\n (add-to-list 'default-frame-alist \n (cons 'height (/ (- (x-display-pixel-height) 200)\n (frame-char-height)))))))\n\n(set-frame-size-according-to-resolution)\n"
},
{
"answer_id": 12334932,
"author": "norbux",
"author_id": 1657376,
"author_profile": "https://Stackoverflow.com/users/1657376",
"pm_score": 4,
"selected": false,
"text": ".emacs (add-to-list 'default-frame-alist '(height . 24))\n\n(add-to-list 'default-frame-alist '(width . 80)) \n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6402/"
] |
92,984
|
<p>A friend of mine and I were having a discussion regarding currying and partial function application in Javascript, and we came to very different conclusions as to whether either were achievable. I came up with this implementation of <code>Function.prototype.curry</code>, which was the basis of our discussion:</p>
<pre><code>Function.prototype.curry = function() {
if (!arguments.length) return this;
var args = Array.prototype.slice.apply(arguments);
var mmm_curry = this, args;
return function() {
var inner_args = Array.prototype.slice.apply(arguments);
return mmm_curry.apply(this, args.concat(inner_args));
}
}
</code></pre>
<p>Which is used as follows:</p>
<pre><code>var vindaloo = function(a, b) {
return (a + b);
}
var karahi = vindaloo.curry(1);
var masala = karahi(2);
var gulai = karahi(3);
print(masala);
print(other);
</code></pre>
<p>The output of which is as follows in Spidermonkey:</p>
<pre><code>$ js curry.js
3
4
</code></pre>
<p>His opinion was that since the Javascript <code>function</code> primitive does not natively support "partial function application", it's completely wrong to refer to the function bound to the variable <code>karahi</code> as partially applied. His argument was that when the <code>vindaloo</code> function is curried, the function itself is completely applied and a closure is returned, not a "partially applied function".</p>
<p>Now, my opinion is that while Javascript itself does not provide support for partial application in its' <code>function</code> primitives (unlike say, ML or Haskell), that doesn't mean you can't create a higher order function of the language which is capable of encapsulating concept of a partially applied function. Also, despite being "applied", the scope of the function is still bound to the closure returned by it causing it to remain "partially applied".</p>
<p>Which is correct?</p>
|
[
{
"answer_id": 93243,
"author": "Michael Johnson",
"author_id": 17688,
"author_profile": "https://Stackoverflow.com/users/17688",
"pm_score": 3,
"selected": true,
"text": "vindaloo.curry = function(a) {\n return function(b) {\n return a + b;\n };\n};\n function karahi(b) {\n return 1 + b;\n};\n"
},
{
"answer_id": 36359346,
"author": "risto",
"author_id": 1589324,
"author_profile": "https://Stackoverflow.com/users/1589324",
"pm_score": 0,
"selected": false,
"text": "> const add = a => b => a + b\n> const add10 = add(10)\n> [1,2,3].map(add10)\n[ 11, 12, 13 ]\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11109/"
] |
92,985
|
<p>We used Drools as part of a solution to act as a sort of filter in a very intense processing application, maybe running up to 100 rules on 500,000 + working memory objects.
turns out that it is extremely slow.
anybody else have any experience using Drools in a batch type processing application?</p>
|
[
{
"answer_id": 4751644,
"author": "Adam B",
"author_id": 52465,
"author_profile": "https://Stackoverflow.com/users/52465",
"pm_score": 1,
"selected": false,
"text": "OptimizerFactory.setDefaultOptimizer(OptimizerFactory.SAFE_REFLECTIVE);\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/92985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13143/"
] |
93,039
|
<p>In what segment (.BSS, .DATA, other) of an executable file are static variables stored so that they don't have name collision?
For example:</p>
<pre><code>
foo.c: bar.c:
static int foo = 1; static int foo = 10;
void fooTest() { void barTest() {
static int bar = 2; static int bar = 20;
foo++; foo++;
bar++; bar++;
printf("%d,%d", foo, bar); printf("%d, %d", foo, bar);
} }
</code></pre>
<p>If I compile both files and link it to a main that calls fooTest() and barTest repeatedly, the printf statements increment independently. Makes sense since the foo and bar variables are local to the translation unit.</p>
<p>But where is the storage allocated?</p>
<p>To be clear, the assumption is that you have a toolchain that would output a file in ELF format. Thus, I <em>believe</em> that there <strong>has</strong> to be some space reserved in the executable file for those static variables.<br>
For discussion purposes, lets assume we use the GCC toolchain.</p>
|
[
{
"answer_id": 93103,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 4,
"selected": false,
"text": "DATA"
},
{
"answer_id": 93188,
"author": "ugasoft",
"author_id": 10120,
"author_profile": "https://Stackoverflow.com/users/10120",
"pm_score": 4,
"selected": false,
"text": " Memory Area Characteristics and Object Lifetimes\n -------------- ------------------------------------------------\n\n Const Data The const data area stores string literals and\n other data whose values are known at compile\n time. No objects of class type can exist in\n this area. All data in this area is available\n during the entire lifetime of the program.\n\n Further, all of this data is read-only, and the\n results of trying to modify it are undefined.\n This is in part because even the underlying\n storage format is subject to arbitrary\n optimization by the implementation. For\n example, a particular compiler may store string\n literals in overlapping objects if it wants to.\n\n\n Stack The stack stores automatic variables. Typically\n allocation is much faster than for dynamic\n storage (heap or free store) because a memory\n allocation involves only pointer increment\n rather than more complex management. Objects\n are constructed immediately after memory is\n allocated and destroyed immediately before\n memory is deallocated, so there is no\n opportunity for programmers to directly\n manipulate allocated but uninitialized stack\n space (barring willful tampering using explicit\n dtors and placement new).\n\n\n Free Store The free store is one of the two dynamic memory\n areas, allocated/freed by new/delete. Object\n lifetime can be less than the time the storage\n is allocated; that is, free store objects can\n have memory allocated without being immediately\n initialized, and can be destroyed without the\n memory being immediately deallocated. During\n the period when the storage is allocated but\n outside the object's lifetime, the storage may\n be accessed and manipulated through a void* but\n none of the proto-object's nonstatic members or\n member functions may be accessed, have their\n addresses taken, or be otherwise manipulated.\n\n\n Heap The heap is the other dynamic memory area,\n allocated/freed by malloc/free and their\n variants. Note that while the default global\n new and delete might be implemented in terms of\n malloc and free by a particular compiler, the\n heap is not the same as free store and memory\n allocated in one area cannot be safely\n deallocated in the other. Memory allocated from\n the heap can be used for objects of class type\n by placement-new construction and explicit\n destruction. If so used, the notes about free\n store object lifetime apply similarly here.\n\n\n Global/Static Global or static variables and objects have\n their storage allocated at program startup, but\n may not be initialized until after the program\n has begun executing. For instance, a static\n variable in a function is initialized only the\n first time program execution passes through its\n definition. The order of initialization of\n global variables across translation units is not\n defined, and special care is needed to manage\n dependencies between global objects (including\n class statics). As always, uninitialized proto-\n objects' storage may be accessed and manipulated\n through a void* but no nonstatic members or\n member functions may be used or referenced\n outside the object's actual lifetime.\n"
},
{
"answer_id": 93352,
"author": "Ilya",
"author_id": 6807,
"author_profile": "https://Stackoverflow.com/users/6807",
"pm_score": 2,
"selected": false,
"text": "static"
},
{
"answer_id": 109120,
"author": "yogeesh",
"author_id": 9030,
"author_profile": "https://Stackoverflow.com/users/9030",
"pm_score": 5,
"selected": false,
"text": "storage : where is it stored, for example data, stack, heap...\nscope : who can see us, for example global, local...\ntype : what is our type, for example int, int*...\naddress : where are we located\nvalue : what is our value\n"
},
{
"answer_id": 24484939,
"author": "Anurag Bhakuni",
"author_id": 3767017,
"author_profile": "https://Stackoverflow.com/users/3767017",
"pm_score": -1,
"selected": false,
"text": "void main(void)\n{\nstatic int i;\n}\n void main(void)\n{\nstatic int i=10;\n}\n"
},
{
"answer_id": 26345806,
"author": "Dan",
"author_id": 173611,
"author_profile": "https://Stackoverflow.com/users/173611",
"pm_score": 2,
"selected": false,
"text": "(gdb) disas fooTest\nDump of assembler code for function fooTest:\n 0x000000000040052d <+0>: push %rbp\n 0x000000000040052e <+1>: mov %rsp,%rbp\n 0x0000000000400531 <+4>: mov 0x200b09(%rip),%eax # 0x601040 <foo>\n 0x0000000000400537 <+10>: add $0x1,%eax\n 0x000000000040053a <+13>: mov %eax,0x200b00(%rip) # 0x601040 <foo>\n 0x0000000000400540 <+19>: mov 0x200afe(%rip),%eax # 0x601044 <bar.2180>\n 0x0000000000400546 <+25>: add $0x1,%eax\n 0x0000000000400549 <+28>: mov %eax,0x200af5(%rip) # 0x601044 <bar.2180>\n 0x000000000040054f <+34>: mov 0x200aef(%rip),%edx # 0x601044 <bar.2180>\n 0x0000000000400555 <+40>: mov 0x200ae5(%rip),%eax # 0x601040 <foo>\n 0x000000000040055b <+46>: mov %eax,%esi\n 0x000000000040055d <+48>: mov $0x400654,%edi\n 0x0000000000400562 <+53>: mov $0x0,%eax\n 0x0000000000400567 <+58>: callq 0x400410 <printf@plt>\n 0x000000000040056c <+63>: pop %rbp\n 0x000000000040056d <+64>: retq \nEnd of assembler dump.\n\n(gdb) disas barTest\nDump of assembler code for function barTest:\n 0x000000000040056e <+0>: push %rbp\n 0x000000000040056f <+1>: mov %rsp,%rbp\n 0x0000000000400572 <+4>: mov 0x200ad0(%rip),%eax # 0x601048 <foo>\n 0x0000000000400578 <+10>: add $0x1,%eax\n 0x000000000040057b <+13>: mov %eax,0x200ac7(%rip) # 0x601048 <foo>\n 0x0000000000400581 <+19>: mov 0x200ac5(%rip),%eax # 0x60104c <bar.2180>\n 0x0000000000400587 <+25>: add $0x1,%eax\n 0x000000000040058a <+28>: mov %eax,0x200abc(%rip) # 0x60104c <bar.2180>\n 0x0000000000400590 <+34>: mov 0x200ab6(%rip),%edx # 0x60104c <bar.2180>\n 0x0000000000400596 <+40>: mov 0x200aac(%rip),%eax # 0x601048 <foo>\n 0x000000000040059c <+46>: mov %eax,%esi\n 0x000000000040059e <+48>: mov $0x40065c,%edi\n 0x00000000004005a3 <+53>: mov $0x0,%eax\n 0x00000000004005a8 <+58>: callq 0x400410 <printf@plt>\n 0x00000000004005ad <+63>: pop %rbp\n 0x00000000004005ae <+64>: retq \nEnd of assembler dump.\n Disassembly of section .data:\n\n0000000000601030 <__data_start>:\n ...\n\n0000000000601038 <__dso_handle>:\n ...\n\n0000000000601040 <foo>:\n 601040: 01 00 add %eax,(%rax)\n ...\n\n0000000000601044 <bar.2180>:\n 601044: 02 00 add (%rax),%al\n ...\n\n0000000000601048 <foo>:\n 601048: 0a 00 or (%rax),%al\n ...\n\n000000000060104c <bar.2180>:\n 60104c: 14 00 adc $0x0,%al\n"
},
{
"answer_id": 30642087,
"author": "Ciro Santilli OurBigBook.com",
"author_id": 895245,
"author_profile": "https://Stackoverflow.com/users/895245",
"pm_score": 4,
"selected": false,
"text": "objdump -Sr #include <stdio.h>\n\nint f() {\n static int i = 1;\n i++;\n return i;\n}\n\nint main() {\n printf(\"%d\\n\", f());\n printf(\"%d\\n\", f());\n return 0;\n}\n gcc -ggdb -c main.c\n objdump -Sr main.o\n -S -r f static int i = 1;\n i++;\n4: 8b 05 00 00 00 00 mov 0x0(%rip),%eax # a <f+0xa>\n 6: R_X86_64_PC32 .data-0x4\n .data-0x4 .data -0x4 %rip R_X86_64_PC32 00 00 00 00 i = 1 static int i = 0 .bss static int i = 1 .data"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/93039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10703/"
] |
93,056
|
<p>this should be simple...could someone provide me a simple code sample that has an aspx page hosting both a silverlight app (consisting of, say a button) and an iframe (pointing to, say stackoverflow.com). The silverlight app and iframe could be in separate div's, the same div, whatever. </p>
<p>Everything I've tried so far leaves me with a page that has no silverlight control rendered on it.</p>
<p>EDIT: At the request for what my xaml looks like (Plus I should point out that my controls render just fine if I comment out the iframe.)</p>
<pre><code><UserControl x:Class="SilverlightApplication1.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid x:Name="LayoutRoot" Background="Pink">
<Button Content="Click Me!"/>
</Grid>
</UserControl>
</code></pre>
<p>Thats it. Just for good measure here is my aspx page...</p>
<pre><code><form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"/>
<div style="height:100%;">
<asp:Silverlight ID="Silverlight1" runat="server" Source="~/ClientBin/SilverlightApplication1.xap" MinimumVersion="2.0.30523" Width="400" Height="400" />
</div>
<iframe src ="http://www.google.com" width="400"/>
</form>
</code></pre>
|
[
{
"answer_id": 93637,
"author": "Ola Karlsson",
"author_id": 10696,
"author_profile": "https://Stackoverflow.com/users/10696",
"pm_score": 2,
"selected": false,
"text": "<%@ Page Language=\"C#\" AutoEventWireup=\"true\" %>\n\n<%@ Register Assembly=\"System.Web.Silverlight\" Namespace=\"System.Web.UI.SilverlightControls\"\n TagPrefix=\"asp\" %>\n\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\" style=\"height:100%;\">\n<head runat=\"server\">\n <title>Test Page</title>\n</head>\n<body style=\"height:100%;margin:0;\">\n <form id=\"form1\" runat=\"server\" style=\"height:100%;\">\n <asp:ScriptManager ID=\"ScriptManager1\" runat=\"server\"></asp:ScriptManager>\n <div style=\"height:100%;\">\n <asp:Silverlight ID=\"Xaml1\" runat=\"server\" Source=\"~/ClientBin/Test.xap\" MinimumVersion=\"2.0.30523\" Width=\"400\" Height=\"400\" />\n </div>\n <iframe src =\"http://www.google.com\" width=\"400\"></iframe>\n </form>\n</body>\n</html>\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/93056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6419/"
] |
93,058
|
<p>I can switch between windows with "C-x o", but if I have opened multiple frames, can I move between them without the mouse as well? </p>
<p>I just realized that the question probably sounds braindead without this detail: I'm on Mac OS X (Finnish keyboard) and switching between windows of the same application is difficult.</p>
|
[
{
"answer_id": 2337484,
"author": "Trey Jackson",
"author_id": 6148,
"author_profile": "https://Stackoverflow.com/users/6148",
"pm_score": 3,
"selected": false,
"text": "framemove.el (require 'framemove)\n(framemove-default-keybindings) ;; default prefix is Meta\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/93058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4110/"
] |
93,063
|
<p>I'm wondering if there's an integrated solution to have a database with versioned records supported by rails (ala version_fu ar_versioned) and a differ thanks!</p>
|
[
{
"answer_id": 736806,
"author": "Brian Armstrong",
"author_id": 76486,
"author_profile": "https://Stackoverflow.com/users/76486",
"pm_score": 0,
"selected": false,
"text": "acts_as_audited htmldiff"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/93063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
93,073
|
<p>How do you implement an <strong>efficient and thread safe reference counting system</strong> on X86 CPUs in the C++ programming language? </p>
<p>I always run into the problem that the <strong>critical operations not atomic</strong>, and the available X86 Interlock operations are not sufficient for implementing the ref counting system.</p>
<p>The following article covers this topic, but requires special CPU instructions:</p>
<p><a href="http://www.ddj.com/architect/184401888" rel="noreferrer">http://www.ddj.com/architect/184401888</a></p>
|
[
{
"answer_id": 93130,
"author": "moonshadow",
"author_id": 11834,
"author_profile": "https://Stackoverflow.com/users/11834",
"pm_score": 3,
"selected": false,
"text": "do\n read the count\n perform mathematical operation\n interlockedcompareexchange( destination, updated count, old count)\nuntil the interlockedcompareexchange returns the success code.\n"
},
{
"answer_id": 349263,
"author": "Daniel Earwicker",
"author_id": 27423,
"author_profile": "https://Stackoverflow.com/users/27423",
"pm_score": 1,
"selected": false,
"text": "a = b;\n if (a != null)\n if (InterlockedDecrement(ref a.m_ref) == 0)\n a.FinalRelease();\n\nif (b != null)\n InterlockedIncrement(ref b.m_ref);\n\na = b;\n"
}
] |
2008/09/18
|
[
"https://Stackoverflow.com/questions/93073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15288/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.