text
stringlengths 8
267k
| meta
dict |
---|---|
Q: Is it possible to connect to Mac OS X 10.5 Leopard's built in vnc server at a low color depth from Windows? If I attempt to connect to Mac OS X 10.5 Leopard's built in vnc server at a low color depth from Windows, the client bombs after connecting. It only works when I set it to the highest color depth. I've tried with at least 3 windows VNC clients. Any ideas? There some setting I can set in Mac OS X?
It takes about 20 seconds to repaint the screen with my current connection and high bit depth setting.
A: Not with the builtin VNC server. Vine Server allows you to change the bit depth that clients connect at though.
A: In my experience you can't lower the color depth with the default vnc server. I won't assert it, because maybe that behaviour could be changed using a console command.
I'd recommend installing another VNC server in mac, like http://sourceforge.net/projects/osxvnc/
A: The built-in vnc seems to have very little configurability that I can see.
As an alternative, you can try using osxvnc which I believe allows different bit depths
A: You can from the client side switch to High Color(16 bits) but not Low Color(8 bits). You can also enable JPEG compression. With both of these options on the sessions speed of to me from completely unusable(~45s for initial screen draw and ~5s lag on clicking menus) to quite usable(<5s for initial screen draw and <1s lag on clicking menus).
Note that these times are for connecting from a remote computer to my home iMac on a cable modem. Also this is running dual screens witch get sent out even though I only use the primary one on VNC. I have yet to figure out a way to switch off the secondary screen in VNC and its to troublesome to unplug it.
A: I use both. I find the built-in VNC server in OS X offers the most compatibility with keystrokes. I use it when I'm on the local network. When using VPN (much slower), I setup Vine Server ("System Server" mode) on a non-standard port # (say 5905), with a much lower color resolution, so the screen doesn't take 30 seconds to redraw whenever I click something.
Then I just ask my client to connect over the appropriate port: 5900 calls the built-in VNC server (for high rez use on the LAN), & 5905 calls Vine Server (for screen update speed over VPN). Best of both worlds.
A: I gave up and started using LogMeIn's free edition.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Getting actual file name (with proper casing) on Windows Windows file system is case insensitive. How, given a file/folder name (e.g. "somefile"), I get the actual name of that file/folder (e.g. it should return "SomeFile" if Explorer displays it so)?
Some ways I know, all of which seem quite backwards:
*
*Given the full path, search for each folder on the path (via FindFirstFile). This gives proper cased results of each folder. At the last step, search for the file itself.
*Get filename from handle (as in MSDN example). This requires opening a file, creating file mapping, getting it's name, parsing device names etc. Pretty convoluted. And it does not work for folders or zero-size files.
Am I missing some obvious WinAPI call? The simplest ones, like GetActualPathName() or GetFullPathName() return the name using casing that was passed in (e.g. returns "program files" if that was passed in, even if it should be "Program Files").
I'm looking for a native solution (not .NET one).
A: And hereby I answer my own question, based on original answer from cspirz.
Here's a function that given absolute, relative or network path, will return the path with upper/lower case as it would be displayed on Windows. If some component of the path does not exist, it will return the passed in path from that point.
It is quite involved because it tries to handle network paths and other edge cases. It operates on wide character strings and uses std::wstring. Yes, in theory Unicode TCHAR could be not the same as wchar_t; that is an exercise for the reader :)
std::wstring GetActualPathName( const wchar_t* path )
{
// This is quite involved, but the meat is SHGetFileInfo
const wchar_t kSeparator = L'\\';
// copy input string because we'll be temporary modifying it in place
size_t length = wcslen(path);
wchar_t buffer[MAX_PATH];
memcpy( buffer, path, (length+1) * sizeof(path[0]) );
size_t i = 0;
std::wstring result;
// for network paths (\\server\share\RestOfPath), getting the display
// name mangles it into unusable form (e.g. "\\server\share" turns
// into "share on server (server)"). So detect this case and just skip
// up to two path components
if( length >= 2 && buffer[0] == kSeparator && buffer[1] == kSeparator )
{
int skippedCount = 0;
i = 2; // start after '\\'
while( i < length && skippedCount < 2 )
{
if( buffer[i] == kSeparator )
++skippedCount;
++i;
}
result.append( buffer, i );
}
// for drive names, just add it uppercased
else if( length >= 2 && buffer[1] == L':' )
{
result += towupper(buffer[0]);
result += L':';
if( length >= 3 && buffer[2] == kSeparator )
{
result += kSeparator;
i = 3; // start after drive, colon and separator
}
else
{
i = 2; // start after drive and colon
}
}
size_t lastComponentStart = i;
bool addSeparator = false;
while( i < length )
{
// skip until path separator
while( i < length && buffer[i] != kSeparator )
++i;
if( addSeparator )
result += kSeparator;
// if we found path separator, get real filename of this
// last path name component
bool foundSeparator = (i < length);
buffer[i] = 0;
SHFILEINFOW info;
// nuke the path separator so that we get real name of current path component
info.szDisplayName[0] = 0;
if( SHGetFileInfoW( buffer, 0, &info, sizeof(info), SHGFI_DISPLAYNAME ) )
{
result += info.szDisplayName;
}
else
{
// most likely file does not exist.
// So just append original path name component.
result.append( buffer + lastComponentStart, i - lastComponentStart );
}
// restore path separator that we might have nuked before
if( foundSeparator )
buffer[i] = kSeparator;
++i;
lastComponentStart = i;
addSeparator = true;
}
return result;
}
Again, thanks to cspirz for pointing me to SHGetFileInfo.
A: Have you tried using SHGetFileInfo?
A: There is another solution. First call GetShortPathName() and then GetLongPathName(). Guess what character case will be used then? ;-)
A: Just found that the Scripting.FileSystemObject suggested by @bugmagnet 10 years ago is a treasure. Unlike my old method, it works on Absolute Path, Relative Path, UNC Path and Very Long Path (path longer than MAX_PATH). Shame on me for not testing his method earlier.
For future reference, I would like to present this code which can be compiled in both C and C++ mode. In C++ mode, the code will use STL and ATL. In C mode, you can clearly see how everything is working behind the scene.
#include <Windows.h>
#include <objbase.h>
#include <conio.h> // for _getch()
#ifndef __cplusplus
# include <stdio.h>
#define SafeFree(p, fn) \
if (p) { fn(p); (p) = NULL; }
#define SafeFreeCOM(p) \
if (p) { (p)->lpVtbl->Release(p); (p) = NULL; }
static HRESULT CorrectPathCasing2(
LPCWSTR const pszSrc, LPWSTR *ppszDst)
{
DWORD const clsCtx = CLSCTX_INPROC_SERVER;
LCID const lcid = LOCALE_USER_DEFAULT;
LPCWSTR const pszProgId = L"Scripting.FileSystemObject";
LPCWSTR const pszMethod = L"GetAbsolutePathName";
HRESULT hr = 0;
CLSID clsid = { 0 };
IDispatch *pDisp = NULL;
DISPID dispid = 0;
VARIANT vtSrc = { VT_BSTR };
VARIANT vtDst = { VT_BSTR };
DISPPARAMS params = { 0 };
SIZE_T cbDst = 0;
LPWSTR pszDst = NULL;
// CoCreateInstance<IDispatch>(pszProgId, &pDisp)
hr = CLSIDFromProgID(pszProgId, &clsid);
if (FAILED(hr)) goto eof;
hr = CoCreateInstance(&clsid, NULL, clsCtx,
&IID_IDispatch, (void**)&pDisp);
if (FAILED(hr)) goto eof;
if (!pDisp) {
hr = E_UNEXPECTED; goto eof;
}
// Variant<BSTR> vtSrc(pszSrc), vtDst;
// vtDst = pDisp->InvokeMethod( pDisp->GetIDOfName(pszMethod), vtSrc );
hr = pDisp->lpVtbl->GetIDsOfNames(pDisp, NULL,
(LPOLESTR*)&pszMethod, 1, lcid, &dispid);
if (FAILED(hr)) goto eof;
vtSrc.bstrVal = SysAllocString(pszSrc);
if (!vtSrc.bstrVal) {
hr = E_OUTOFMEMORY; goto eof;
}
params.rgvarg = &vtSrc;
params.cArgs = 1;
hr = pDisp->lpVtbl->Invoke(pDisp, dispid, NULL, lcid,
DISPATCH_METHOD, ¶ms, &vtDst, NULL, NULL);
if (FAILED(hr)) goto eof;
if (!vtDst.bstrVal) {
hr = E_UNEXPECTED; goto eof;
}
// *ppszDst = AllocWStrCopyBStrFrom(vtDst.bstrVal);
cbDst = SysStringByteLen(vtDst.bstrVal);
pszDst = HeapAlloc(GetProcessHeap(),
HEAP_ZERO_MEMORY, cbDst + sizeof(WCHAR));
if (!pszDst) {
hr = E_OUTOFMEMORY; goto eof;
}
CopyMemory(pszDst, vtDst.bstrVal, cbDst);
*ppszDst = pszDst;
eof:
SafeFree(vtDst.bstrVal, SysFreeString);
SafeFree(vtSrc.bstrVal, SysFreeString);
SafeFreeCOM(pDisp);
return hr;
}
static void Cout(char const *psz)
{
printf("%s", psz);
}
static void CoutErr(HRESULT hr)
{
printf("Error HRESULT 0x%.8X!\n", hr);
}
static void Test(LPCWSTR pszPath)
{
LPWSTR pszRet = NULL;
HRESULT hr = CorrectPathCasing2(pszPath, &pszRet);
if (FAILED(hr)) {
wprintf(L"Input: <%s>\n", pszPath);
CoutErr(hr);
}
else {
wprintf(L"Was: <%s>\nNow: <%s>\n", pszPath, pszRet);
HeapFree(GetProcessHeap(), 0, pszRet);
}
}
#else // Use C++ STL and ATL
# include <iostream>
# include <iomanip>
# include <string>
# include <atlbase.h>
static HRESULT CorrectPathCasing2(
std::wstring const &srcPath,
std::wstring &dstPath)
{
HRESULT hr = 0;
CComPtr<IDispatch> disp;
hr = disp.CoCreateInstance(L"Scripting.FileSystemObject");
if (FAILED(hr)) return hr;
CComVariant src(srcPath.c_str()), dst;
hr = disp.Invoke1(L"GetAbsolutePathName", &src, &dst);
if (FAILED(hr)) return hr;
SIZE_T cch = SysStringLen(dst.bstrVal);
dstPath = std::wstring(dst.bstrVal, cch);
return hr;
}
static void Cout(char const *psz)
{
std::cout << psz;
}
static void CoutErr(HRESULT hr)
{
std::wcout
<< std::hex << std::setfill(L'0') << std::setw(8)
<< "Error HRESULT 0x" << hr << "\n";
}
static void Test(std::wstring const &path)
{
std::wstring output;
HRESULT hr = CorrectPathCasing2(path, output);
if (FAILED(hr)) {
std::wcout << L"Input: <" << path << ">\n";
CoutErr(hr);
}
else {
std::wcout << L"Was: <" << path << ">\n"
<< "Now: <" << output << ">\n";
}
}
#endif
static void TestRoutine(void)
{
HRESULT hr = CoInitialize(NULL);
if (FAILED(hr)) {
Cout("CoInitialize failed!\n");
CoutErr(hr);
return;
}
Cout("\n[ Absolute Path ]\n");
Test(L"c:\\uSers\\RayMai\\docuMENTs");
Test(L"C:\\WINDOWS\\SYSTEM32");
Cout("\n[ Relative Path ]\n");
Test(L".");
Test(L"..");
Test(L"\\");
Cout("\n[ UNC Path ]\n");
Test(L"\\\\VMWARE-HOST\\SHARED FOLDERS\\D\\PROGRAMS INSTALLER");
Cout("\n[ Very Long Path ]\n");
Test(L"\\\\?\\C:\\VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
L"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
L"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
L"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
L"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
L"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
L"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
L"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
L"VERYVERYVERYLOOOOOOOONGFOLDERNAME");
Cout("\n!! Worth Nothing Behavior !!\n");
Test(L"");
Test(L"1234notexist");
Test(L"C:\\bad\\PATH");
CoUninitialize();
}
int main(void)
{
TestRoutine();
_getch();
return 0;
}
Screenshot:
Old Answer:
I found that FindFirstFile() will return the proper casing file name (last part of path) in fd.cFileName. If we pass c:\winDOWs\exPLORER.exe as first parameter to FindFirstFile(), the fd.cFileName would be explorer.exe like this:
If we replace the last part of path with fd.cFileName, we will get the last part right; the path would become c:\winDOWs\explorer.exe.
Assuming the path is always absolute path (no change in text length), we can just apply this 'algorithm' to every part of path (except the drive letter part).
Talk is cheap, here is the code:
#include <windows.h>
#include <stdio.h>
/*
c:\windows\windowsupdate.log --> c:\windows\WindowsUpdate.log
*/
static HRESULT MyProcessLastPart(LPTSTR szPath)
{
HRESULT hr = 0;
HANDLE hFind = NULL;
WIN32_FIND_DATA fd = {0};
TCHAR *p = NULL, *q = NULL;
/* thePart = GetCorrectCasingFileName(thePath); */
hFind = FindFirstFile(szPath, &fd);
if (hFind == INVALID_HANDLE_VALUE) {
hr = HRESULT_FROM_WIN32(GetLastError());
hFind = NULL; goto eof;
}
/* thePath = thePath.ReplaceLast(thePart); */
for (p = szPath; *p; ++p);
for (q = fd.cFileName; *q; ++q, --p);
for (q = fd.cFileName; *p = *q; ++p, ++q);
eof:
if (hFind) { FindClose(hFind); }
return hr;
}
/*
Important! 'szPath' should be absolute path only.
MUST NOT SPECIFY relative path or UNC or short file name.
*/
EXTERN_C
HRESULT __stdcall
CorrectPathCasing(
LPTSTR szPath)
{
HRESULT hr = 0;
TCHAR *p = NULL;
if (GetFileAttributes(szPath) == -1) {
hr = HRESULT_FROM_WIN32(GetLastError()); goto eof;
}
for (p = szPath; *p; ++p)
{
if (*p == '\\' || *p == '/')
{
TCHAR slashChar = *p;
if (p[-1] == ':') /* p[-2] is drive letter */
{
p[-2] = toupper(p[-2]);
continue;
}
*p = '\0';
hr = MyProcessLastPart(szPath);
*p = slashChar;
if (FAILED(hr)) goto eof;
}
}
hr = MyProcessLastPart(szPath);
eof:
return hr;
}
int main()
{
TCHAR szPath[] = TEXT("c:\\windows\\EXPLORER.exe");
HRESULT hr = CorrectPathCasing(szPath);
if (SUCCEEDED(hr))
{
MessageBox(NULL, szPath, TEXT("Test"), MB_ICONINFORMATION);
}
return 0;
}
Advantages:
*
*The code works on every version of Windows since Windows 95.
*Basic error-handling.
*Highest performance possible. FindFirstFile() is very fast, direct buffer manipulation makes it even faster.
*Just C and pure WinAPI. Small executable size.
Disadvantages:
*
*Only absolute path is supported, other are undefined behavior.
*Not sure if it is relying on undocumented behavior.
*The code might be too raw too much DIY for some people. Might get you flamed.
Reason behind the code style:
I use goto for error-handling because I was used to it (goto is very handy for error-handling in C). I use for loop to perform functions like strcpy and strchr on-the-fly because I want to be certain what was actually executed.
A: Okay, this is VBScript, but even so I'd suggest using the Scripting.FileSystemObject object
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
Dim f
Set f = fso.GetFile("C:\testfile.dat") 'actually named "testFILE.dAt"
wscript.echo f.Name
The response I get is from this snippet is
testFILE.dAt
Hope that at least points you in the right direction.
A: FindFirstFileNameW will work with a few drawbacks:
*
*it doesn't work on UNC paths
*it strips the drive letter so you need to add it back
*if there are more than one hard link to your file you need to identify the right one
A: After a quick test, GetLongPathName() does what you want.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74451",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: Silverlight- DataGrid control - Selection Changed event interfering with sorting I'm currently playing with the Silverlight(Beta 2) Datagrid control. Before I wired up the SelectionChanged event, the grid would sort perfectly by clicking on the header. Now, when the grid is clicked, it will fire the SelectionChanged event when I click the header to sort. Is there any way around this?
In a semi-related topic, I'd like to have the SelectionChanged event fire when I click on an already selected item (so that I can have a pop-up occur to allow the user to edit the selected value). Right now, you have to click on a different value and then back to the value you wanted in order for it to pop up. Is there another way?
Included is my code.
The Page:
<UserControl x:Class="WebServicesApp.Page"
xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"
Width="1280" Height="1024" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d">
<Grid x:Name="LayoutRoot" Background="White">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" x:Name="OurStack" Orientation="Vertical" Margin="5,5,5,5">
<ContentControl VerticalAlignment="Center" HorizontalAlignment="Center">
<StackPanel x:Name="SearchStackPanel" Orientation="Horizontal" Margin="5,5,5,5">
<TextBlock x:Name="SearchEmail" HorizontalAlignment="Stretch" VerticalAlignment="Center" Text="Email Address:" Margin="5,5,5,5" />
<TextBox x:Name="InputText" HorizontalAlignment="Stretch" VerticalAlignment="Center" Width="150" Height="Auto" Margin="5,5,5,5"/>
<Button x:Name="SearchButton" Content="Search" Click="CallServiceButton_Click" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75" Height="Auto" Background="#FFAFAFAF" Margin="5,5,5,5"/>
</StackPanel>
</ContentControl>
<Grid x:Name="DisplayRoot" Background="White" ShowGridLines="True"
HorizontalAlignment="Center" VerticalAlignment="Center" MaxHeight="300" MinHeight="100" MaxWidth="800" MinWidth="200"
ScrollViewer.HorizontalScrollBarVisibility="Visible" ScrollViewer.VerticalScrollBarVisibility="Visible">
<data:DataGrid ItemsSource="{Binding ''}" CanUserReorderColumns="False" CanUserResizeColumns="False"
AutoGenerateColumns="False" AlternatingRowBackground="#FFAFAFAF" SelectionMode="Single"
HorizontalAlignment="Center" VerticalAlignment="Center" Margin="5,5,5,5" x:Name="IncidentGrid" SelectionChanged="IncidentGrid_SelectionChanged">
<data:DataGrid.Columns>
<data:DataGridTextColumn DisplayMemberBinding="{Binding Address}" Header="Email Address" IsReadOnly="True" /> <!--Width="150"-->
<data:DataGridTextColumn DisplayMemberBinding="{Binding whereClause}" Header="Where Clause" IsReadOnly="True" /> <!--Width="500"-->
<data:DataGridTextColumn DisplayMemberBinding="{Binding Enabled}" Header="Enabled" IsReadOnly="True" />
</data:DataGrid.Columns>
</data:DataGrid>
</Grid>
</StackPanel>
<Grid x:Name="EditPersonPopupGrid" Visibility="Collapsed">
<Rectangle HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Opacity="0.765" Fill="#FF8A8A8A" />
<Border CornerRadius="30" Background="#FF2D1DCC" Width="700" Height="400" HorizontalAlignment="Center" VerticalAlignment="Center" BorderThickness="1,1,1,1" BorderBrush="#FF000000">
<StackPanel x:Name="EditPersonStackPanel" Orientation="Vertical" Background="White" HorizontalAlignment="Center" VerticalAlignment="Center" Width="650" >
<ContentControl>
<StackPanel x:Name="EmailEditStackPanel" Orientation="Horizontal">
<TextBlock Text="Email Address:" Width="200" Margin="5,0,5,0" />
<TextBox x:Name="EmailPopupTextBox" Width="200" />
</StackPanel>
</ContentControl>
<ContentControl>
<StackPanel x:Name="AppliesToDropdownStackPanel" Orientation="Horizontal" Margin="2,2,2,0">
<TextBlock Text="Don't send when update was done by:" />
<StackPanel Orientation="Vertical" MaxHeight="275" MaxWidth="350" >
<TextBlock x:Name="SelectedItemTextBlock" TextAlignment="Right" Width="200" Margin="5,0,5,0" />
<Grid x:Name="UserDropDownGrid" MaxHeight="75" MaxWidth="200" Visibility="Collapsed" ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.HorizontalScrollBarVisibility="Hidden" >
<Rectangle Fill="White" />
<Border Background="White">
<ListBox x:Name="UsersListBox" SelectionChanged="UsersListBox_SelectionChanged" ItemsSource="{Binding UserID}" />
</Border>
</Grid>
</StackPanel>
<Button x:Name="DropDownButton" Click="DropDownButton_Click" VerticalAlignment="Top" Width="25" Height="25">
<Path Height="10" Width="10" Fill="#FF000000" Stretch="Fill" Stroke="#FF000000" Data="M514.66669,354 L542.16669,354 L527.74988,368.41684 z" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="1,1,1,1"/>
</Button>
</StackPanel>
</ContentControl>
<TextBlock Text="Where Clause Condition:" />
<TextBox x:Name="WhereClauseTextBox" Height="200" Width="800" AcceptsReturn="True" TextWrapping="Wrap" />
<ContentControl>
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<Button x:Name="TestConditionButton" Content="Test Condition" Margin="5,5,5,5" Click="TestConditionButton_Click" />
<Button x:Name="Save" Content="Save" HorizontalAlignment="Right" Margin="5,5,5,5" Click="Save_Click" />
<Button x:Name="Cancel" Content="Cancel" HorizontalAlignment="Right" Margin="5,5,5,5" Click="Cancel_Click" />
</StackPanel>
<TextBlock x:Name="TestContitionResults" Visibility="Collapsed" />
</StackPanel>
</ContentControl>
</StackPanel>
</Border>
</Grid>
</Grid>
And the call that occurs when the grid's selection is changed:
Private Sub IncidentGrid_SelectionChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
If mFirstTime Then
mFirstTime = False
Else
Dim data As SimpleASMX.EMailMonitor = CType(IncidentGrid.SelectedItem, SimpleASMX.EMailMonitor)
Dim selectedGridItem As SimpleASMX.EMailMonitor = Nothing
If IncidentGrid.SelectedItem IsNot Nothing Then
selectedGridItem = CType(IncidentGrid.SelectedItem, SimpleASMX.EMailMonitor)
EmailPopupTextBox.Text = selectedGridItem.Address
SelectedItemTextBlock.Text = selectedGridItem.AppliesToUserID
WhereClauseTextBox.Text = selectedGridItem.whereClause
IncidentGrid.SelectedIndex = mEmailMonitorData.IndexOf(selectedGridItem)
End If
If IncidentGrid.SelectedIndex > -1 Then
EditPersonPopupGrid.Visibility = Windows.Visibility.Visible
Else
EditPersonPopupGrid.Visibility = Windows.Visibility.Collapsed
End If
End If
End Sub
Sorry if my code is atrocious, I'm still learning Silverlight.
A: That looks like a Silverlight bug to me. I've just tried it and what's happening on my end is that the SelectionChanged event fires twice when you click the column header and to make matters worse, the index of the selected item doesn't stay synched with the currently selected item.
I'd suggest you work your way around it by using the knowledge that the first time SelectionChanged fires, the value of the datagrid's SelectedItem property will be null
Here's some sample code that at least lives with the issue. Your SelectionChanged logic can go in the if clause.
public partial class Page : UserControl
{
private Person _currentSelectedPerson;
public Page()
{
InitializeComponent();
List<Person> persons = new List<Person>();
persons.Add(new Person() { Age = 5, Name = "Tom" });
persons.Add(new Person() { Age = 3, Name = "Lisa" });
persons.Add(new Person() { Age = 4, Name = "Sam" });
dg.ItemsSource = persons;
}
private void SelectionChanged(object sender, EventArgs e)
{
DataGrid grid = sender as DataGrid;
if (grid.SelectedItem != null)
{
_currentSelectedPerson = grid.SelectedItem as Person;
}
else
{
grid.SelectedItem = _currentSelectedPerson;
}
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
A: Frozen Columns in Silverlight DataGrid..
http://dotnetdreamer.wordpress.com/2009/01/31/silverlight-2-datagrid-frozen-columns/
A: There's a bugfix for the first issue you mentioned (selection changed event getting fired on resort).
See the following URL for Microsoft's patch:
http://www.microsoft.com/downloads/details.aspx?familyid=084A1BB2-0078-4009-94EE-E659C6409DB0&displaylang=en
A: This worked, but now if I sort twice, on the first one it sorts, and then does the popup as the first selected item of the grid . If I close the popup grid, and then try to sort a second time, it stack overflows, and crashes firefox out.
I'm thinking I may need to rethink working in silverlight until the system gets a bit more stable.
Thanks for the answer Hovito!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74461",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I use an icon that is a resource in WPF? I have a .ico file that is embedded as a resource (build action set to resource). I am trying to create a NotifyIcon. How can I reference my icon?
notifyIcon = new NotifyIcon();
notifyIcon.Icon = ?? // my icon file is called MyIcon.ico and is embedded
A: If you are just looking for the simple answer, I think this is it where MyApp is your application name and where that's the root namespace name for your application. You have to use the pack URI syntax, but it doesn't have to be that complicated to pull an icon out of your embedded resources.
<Window x:Class="MyApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Height="100"
Width="200"
Icon="pack://application:,,,/MyApp;component/Resources/small_icon.ico">
A: A common usage pattern is to have the notify icon the same as the main window's icon. The icon is defined as a PNG file.
To do this, add the image to the project's resources and then use as follows:
var iconHandle = MyNamespace.Properties.Resources.MyImage.GetHicon();
this.notifyIcon.Icon = System.Drawing.Icon.FromHandle(iconHandle);
In the window XAML:
<Window x:Class="MyNamespace.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:local="clr-namespace:Seahorse"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="600"
Icon="images\MyImage.png">
A: I created a project here and used an embedded resource (build action was set to Embedded Resource, rather than just resource). This solution doesn't work with Resource, but you may be able to manipulate it. I put this on the OnIntialized() but it doesn't have to go there.
//IconTest = namespace; exclamic.ico = resource
System.IO.Stream stream = this.GetType().Assembly.GetManifestResourceStream("IconTest.Resources.exclamic.ico");
if (stream != null)
{
//Decode the icon from the stream and set the first frame to the BitmapSource
BitmapDecoder decoder = IconBitmapDecoder.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.None);
BitmapSource source = decoder.Frames[0];
//set the source of your image
image.Source = source;
}
A: Well, you don't want to use the resx style resources: you just stick the ico file in your project in a folder (lets say "ArtWork") and in the properties, set the Build Action to "Resources" ...
Then you can reference it in XAML using PACK URIs ... "pack://application:,,,/Artwork/Notify.ico"
See here: http://msdn.microsoft.com/en-us/library/aa970069.aspx and the sample
If you want to be a little bit more ... WPF-like, you should look into the WPF Contrib project on CodePlex which has a NotifyIcon control which you can create in XAML and which uses standard WPF menus (so you can stick "anything" in the menu).
A: Your icon file should be added to one of your project assemblies and its Build Action should be set to Resource. After adding a reference to the assembly, you can create a NotifyIcon like this:
System.Windows.Forms.NotifyIcon icon = new System.Windows.Forms.NotifyIcon();
Stream iconStream = Application.GetResourceStream( new Uri( "pack://application:,,,/YourReferencedAssembly;component/YourPossibleSubFolder/YourResourceFile.ico" )).Stream;
icon.Icon = new System.Drawing.Icon( iconStream );
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "73"
} |
Q: Redundant Call to Object.ToString() I have a function that takes, amongst others, a parameter declared as int privateCount. When I want to call ToString() on this param, ReSharper greys it out and marks it as a redundant call. So, curious as I am, I remove the ToString(), and the code still builds!
How can a C# compiler allow this, where str is a string?
str += privateCount + ...
A: It is not only bad practice, but also less performant: The integer has to be boxed because String.Concat expectes an object while int.ToString() does not require boxing.
A: The + operator for string is overloaded to call String.Concat passing in the left and right side of the expression. Thus:
string x = "123" + 45;
Gets compiled to:
String.Concat("123", 45);
Since String.Concat takes in two objects, the right hand side (45) is boxed and then ToString() is called on it.
Note that this "overloading" is not via operator overloading in the language (aka it's not a method named op_Addition) but is handled by the compiler.
A: C# automatically converts the objects to strings for you. Consider this line of code:
aString = aString + 23;
This is valid C#; it compiles down to a call to String.Concat(), which takes two objects as arguments. Those objects are automatically converted to string objects for you.
The same thing occurs when you write:
aString += 23;
Again, this compiles down to the same call to String.Concat(); it's just written differently.
A: This is a valid bad practice, as you must think twice if the variable is a string or an int. What if the variable would be called myInt?
myInt = myInt + 23;
it is more readable and understandable in this form?
myInt = mInt + "23";
or even:
myInt = string.Format("{0}{1}", myInt, 23);
We know from the code that it is a string and not an integer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74471",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: How to create a scalable Moebius-strip in WPF? A moebius strip is a surface with one side.
How would one define such an object in XAML/WPF?
How could such an object be manipulated in 3D, scaled up and down and rotated using C#?
A: Using the Helix Toolkit I was able to get it one on-screen in a couple of minutes. One of their demo-apps renders a parametric surface on screen and allows you to change the equations. The 'magic' is in the math, which I copied from the Mathematica StackExchange-site:
u *= 2 * pi;
v = (v - 0.5) * 2 * pi;
x = ( 1 + (v/2) * cos(u/2)) * cos(u);
y = ( 1 + (v/2) * cos(u/2)) * sin(u);
z = (v/2) * sin(u/2);
On screen it looks like this:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74479",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why should I care about compacting an MS Access .mdb file? We distribute an application that uses an MS Access .mdb file. Somebody has noticed that after opening the file in MS Access the file size shrinks a lot. That suggests that the file is a good candidate for compacting, but we don't supply the means for our users to do that.
So, my question is, does it matter? Do we care? What bad things can happen if our users never compact the database?
A: Make sure you compact and repair the database regularly, especially if the database application experiences frequent record updates, deletions and insertions. Not only will this keep the size of the database file down to the minimum - which will help speed up database operations and network communications - it performs database housekeeping, too, which is of even greater benefit to the stability of your data. But before you compact the database, make sure that you make a backup of the file, just in case something goes wrong with the compaction.
Jet compacts a database to reorganize the content within the file so that each 4 KB "page" (2KB for Access 95/97) of space allotted for data, tables, or indexes is located in a contiguous area. Jet recovers the space from records marked as deleted and rewrites the records in each table in primary key order, like a clustered index. This will make your db's read/write ops faster.
Jet also updates the table statistics during compaction. This includes identifying the number of records in each table, which will allow Jet to use the most optimal method to scan for records, either by using the indexes or by using a full table scan when there are few records. After compaction, run each stored query so that Jet re-optimizes it using these updated table statistics, which can improve query performance.
Access 2000, 2002, 2003 and 2007 combine the compaction with a repair operation if it's needed. The repair process:
1 - Cleans up incomplete transactions
2 - Compares data in system tables with data in actual tables, queries and indexes and repairs the mistakes
3 - Repairs very simple data structure mistakes, such as lost pointers to multi-page records (which isn't always successful and is why "repair" doesn't always work to save a corrupted Access database)
4 - Replaces missing information about a VBA project's structure
5 - Replaces missing information needed to open a form, report and module
6 - Repairs simple object structure mistakes in forms, reports, and modules
The bad things that can happen if the users never compact/repair the db is that it will become slow due to bloat, and it may become unstable - meaning corrupted.
A: Compacting an Access database (also known as a MS JET database) is a bit like defragmenting a hard drive. Access (or, more accurately, the MS JET database engine) isn't very good with re-using space - so when a record is updated, inserted, or deleted, the space is not always reclaimed - instead, new space is added to the end of the database file and used instead.
A general rule of thumb is that if your [Access] database will be written to (updated, changed, or added to), you should allow for compacting - otherwise it will grow in size (much more than just the data you've added, too).
So, to answer your question(s):
*
*Yes, it does matter (unless your database is read-only).
*You should care (unless you don't care about your user's disk space).
*If you don't compact an Access database, over time it will grow much, much, much larger than the data inside it would suggest, slowing down performance and increasing the possibilities of errors and corruption. (As a file-based database, Access database files are notorious for corruption, especially when accessed over a network.)
This article on How to Compact Microsoft Access Database Through ADO will give you a good starting point if you decide to add this functionality to your app.
A: In addition to making your database smaller, it'll recompute the indexes on your tables and defragment your tables which can make access faster. It'll also find any inconsistencies that should never happen in your database, but might, due to bugs or crashes in Access.
It's not totally without risk though -- a bug in Access 2007 would occasionally delete your database during the process.
So it's generally a good thing to do, but pair it with a good backup routine. With the backup in place, you can also recover from any 'unrecoverable' compact and repair problems with a minimum of data loss.
A: I would offer the users a method for compacting the database. I've seen databases grow to 600+ megabytes when compacting will reduce to 60-80.
A: To echo Nate:
In older versions, I've had it corrupt databases - so a good backup regime is essential. I wouldn't code anything into your app to do that automatically. However, if a customer finds that their database is running really slow, your tech support people could talk them through it if need be (with appropriate backups of course).
If their database is getting to be so large that the compaction starts to be come a necessity though, maybe it's time to move to MS-SQL.
A: I've found that Access database files almost always get corrupted over time. Compacting and repairing them helps hold that off for a while.
A: Well it really matters! mdb files keep increasing in size each time you manipulate its data, until it reaches unbearable size. But you don't have to supply a compacting method through your interface. You can add the following code in your mdb file to have it compacted each time the file is closed:
Application.SetOption ("Auto Compact"), 1
A: I would also highly recommend looking in to VistaDB (http://www.vistadb.net/) or SQL Compact(http://www.microsoft.com/sql/editions/compact/) for your application. These might not be the right fit for your app... but are def worth a look.
A: If you don't offer your users a way to decompress and the raw size isn't an issue to begin with, then don't bother.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74484",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Limit dev environment to e-mail only certain domains for testing (XP smtp IIS) I'm developing a website on an XP virtual machine and have an SMTP virtual server set up in IIS -- it delivers mail just fine. What I would like is to confirm that any emails the site sends are only going to a specific domain.
The XP firewall seems to only involve incoming connections, I can't block outgoing TCP on port 25. And I haven't been able to configure the SMTP server to filter by delivery address.
With this setup, is there any easy way to filter outgoing email by destination address?
A: Here's one idea:
Under Advanced Delivery options (SMTP Virtual Server Properties > Delivery tab > Advanced). There you can set a "Smart Host" which is the SMTP server that will be used to actually send the mail, so you could possibly have it deliver directly to the specific domain's incoming SMTP server.
A: I think the easiest way would be to add a check to your mail sending code on the website (there's got to be some class which is in charge of sending the mails out).
You could include a check which is only active when the code is compiled in debug mode (using compiler directives). Thus, when you are developing and building the site in debug mode, this code checks if the outgoing messages are valid (specific domain) or not. If they are it lets them go, else it doesn't send the mail.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74494",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What is the "best" canonical implementation of Equals() for reference types? Implementing Equals() for reference types is harder than it seems. My current canonical implementation goes like this:
public bool Equals( MyClass obj )
{
// If both refer to the same reference they are equal.
if( ReferenceEquals( obj, this ) )
return true;
// If the other object is null they are not equal because in C# this cannot be null.
if( ReferenceEquals( obj, null ) )
return false;
// Compare data to evaluate equality
return _data.Equals( obj._data );
}
public override bool Equals( object obj )
{
// If both refer to the same reference they are equal.
if( ReferenceEquals( obj, this ) )
return true;
// If the other object is null or is of a different types the objects are not equal.
if( ReferenceEquals( obj, null ) || obj.GetType() != GetType() )
return false;
// Use type-safe equality comparison
return Equals( (MyClass)obj );
}
public override int GetHashCode()
{
// Use data's hash code as our hashcode
return _data.GetHashCode();
}
I think that this covers all corner (inheritance and such) cases but I may be wrong. What do you guys think?
A: I wrote a fairly comprehensive guide to this a while back. For a start your equals implementations should be shared (i.e. the overload taking an object should pass through to the one taking a strongly typed object). Additionally you need to consider things such as your object should be immutable because of the need to override GetHashCode. More info here:
http://gregbeech.com/blog/implementing-object-equality-in-dotnet
A: Better hope that this._data is not null if it's also a reference type.
public bool Equals( MyClass obj )
{
if (obj == null) {
return false;
}
else {
return (this._data != null && this._data.Equals( obj._data ))
|| obj._data == null;
}
}
public override bool Equals( object obj )
{
if (obj == null || !(obj is MyClass)) {
return false;
}
else {
return this.Equals( (MyClass)obj );
}
}
public override int GetHashCode() {
return this._data == null ? 0 : this._data.GetHashCode();
}
A: It depends on whether you're writing a value type or a reference type. For a sortable value type, I recommend this:
A code snippet for Visual Studio 2005 that implements a skeleton value type adhering to Framework Design Guidelines
A: Concerning inheritance, I think you should just let the OO paradigm does its magic.
Specifically, the GetType() check should be removed, it might break polymorphism down the line.
A: I agree with chakrit, objects of different types should be allowed to be semantically equal if they have the same data or ID.
Personally, I use the following:
public override bool Equals(object obj)
{
var other = obj as MyClass;
if (other == null) return false;
return this.data.Equals(other.data);
}
A: As the link in the accepted answer by Greg Beech is broken, I hope this answer might be helpful to some.
Microsoft's documentation provides the following example for a typical implementation of Equals() on reference types (i.e. class):
public override bool Equals(object obj) => this.Equals(obj as TwoDPoint);
public bool Equals(TwoDPoint p)
{
if (p is null)
{
return false;
}
// Optimization for a common success case.
if (Object.ReferenceEquals(this, p))
{
return true;
}
// If run-time types are not exactly the same, return false.
if (this.GetType() != p.GetType())
{
return false;
}
// Return true if the fields match.
// Note that the base class is not invoked because it is
// System.Object, which defines Equals as reference equality.
return (X == p.X) && (Y == p.Y);
}
The complete example with more details including what to do in derived classes or for structs, can be found at "How to define value equality for a class or struct (C# Programming Guide)"
As an alternative to what is described in Microsoft's doc, the method GetHashCode() can also be implemented as follows:
public override int GetHashCode()
{
return HashCode.Combine(X, Y);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74514",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Using 7-Zip from Delphi? I would like to use the 7-Zip DLLs from Delphi but have not been able to find decent documentation or examples. Does anyone know how to use the 7-Zip DLLs from Delphi?
A: 7 Zip Plugin API
http://www.progdigy.com/?page_id=13
A: Zip and 7z with NO DLL, try out Synopse:
http://synopse.info/forum/viewtopic.php?pid=163
A: Delphi now has native, cross platform zip support with TZipFile in XE2:
How to extract zip files with TZipFile in Delphi XE2 and FireMonkey
A: As of release 1.102 the JEDI Code Library has support for 7-Zip built into the JclCompression unit. Haven't used it myself yet, though.
A: Expanding on Oliver Giesen's answer, as with a lot of the JEDI Code Library, I couldn't find any decent documentation, but this works for me:
uses
JclCompression;
procedure TfrmSevenZipTest.Button1Click(Sender: TObject);
const
FILENAME = 'F:\temp\test.zip';
var
archiveclass: TJclDecompressArchiveClass;
archive: TJclDecompressArchive;
item: TJclCompressionItem;
s: String;
i: Integer;
begin
archiveclass := GetArchiveFormats.FindDecompressFormat(FILENAME);
if not Assigned(archiveclass) then
raise Exception.Create('Could not determine the Format of ' + FILENAME);
archive := archiveclass.Create(FILENAME);
try
if not (archive is TJclSevenZipDecompressArchive) then
raise Exception.Create('This format is not handled by 7z.dll');
archive.ListFiles;
s := Format('test.zip Item Count: %d'#13#10#13#10, [archive.ItemCount]);
for i := 0 to archive.ItemCount - 1 do
begin
item := archive.Items[i];
case item.Kind of
ikFile:
s := s + IntToStr(i+1) + ': ' + item.PackedName + #13#10;
ikDirectory:
s := s + IntToStr(i+1) + ': ' + item.PackedName + '\'#13#10;//'
end;
end;
if archive.ItemCount > 0 then
begin
// archive.Items[0].Selected := true;
// archive.ExtractSelected('F:\temp\test');
archive.ExtractAll('F:\temp\test');
end;
ShowMessage(s);
finally
archive.Free;
end;
end;
A: If you intend to use 7Zip only for zip and unzip take a look at the TZip component.
I have written a small wrapper for my own purposes, which you can find in the Zipper.pas file, feel free to reuse.
A: I tried many solutions and had problems, this one worked.
Download https://github.com/zedalaye/d7zip
Copy 7z.dll and sevenzip.pas to your project diroctory and add sevenzip.pas to your project.
Then you can use this to unzip:
using sevenzip;
procedure Unzip7zFile (zipFullFname:string);
var
outDir:string;
begin
with CreateInArchive(CLSID_CFormat7z) do
begin
OpenFile(zipFullFname);
outDir := ChangeFileExt(zipFullFname, '');
ForceDirectories (outDir);
ExtractTo(outDir);
end;
end;
Usage:
Unzip7zFile(ExtractFilePath(Application.ExeName) + 'STR_SI_FULL_1000420.7z');
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74519",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
} |
Q: I'm looking to use Visual Studio to write and compile using the open source version of Qt4 Does anyone have details in setting up Qt4 in Visual Studio 2008? Links to other resources would be appreciated as well.
I already know that the commercial version of Qt has applications to this end. I also realize that I'll probably need to compile from source as the installer for the open source does not support Visual Studio and installs Cygwin.
A: Looks like it's been done with Visual Studio 2005:
http://wiki.qgis.org/qgiswiki/Building_QT_4_with_Visual_C%2B%2B_2005
I'd imagine it would work with Visual Studio 2008, even if it requires some changes.
A: It's even simpler now with QT4, you no longer need the patch. Basically you just need to supply "-spec win32-msvc2008" to configure.
There are detailed instructions here http://tom.paschenda.org/blog/?p=28
The visual studio add-in is also open-source and available.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: TFS annotate/blame summary report for a project In Team Foundation Server, I know that you can use the Annotate feature to see who last edited each line in a particular file (equivalent to "Blame" in CVS). What I'd like to do is akin to running Annotate on every file in a project, and get a summary report of all the developers who have edited a file in the project, and how many lines of code they currently "own" in that project.
Aside from systematically running Annotate of each file, I can't see a way to do this. Any ideas that would make this process faster?
PS - I'm doing to this to see how much of a consultant's code still remains in a particular (rather large) project, not to keep tabs on my developers, in case you're worried about my motivation :)
A: It's easy enough to use the "tf.exe history" command recursively across a directory of files in TFS. This will tell you who changed what files.
However what you're after is a little bit more than this - you want to know if the latest versions of any files have lines written by a particular user.
The Team Foundation Power Tools ship with a command-line version of annotate called "tfpt.exe annotate". This has a /noprompt option to direct the output to the console, but it only outputs the changeset id - not the user name.
You could also use the TFS VersionControl object model to write a tool that does exactly what you need.
A: If you install the TFS Power tools (at least for VS2005); it's called annotate.
It might be part of VS2008...
A: Annotate is now part of Visual Studio (I think it was introduced in VS 2010).
Docs
A: You can use TFS Analysis Cube to see generate a code churn report, which I believe is something you would like.
A: I'm writing an answer to an 8 year old question :). Its not really a full answer, but a suggestion to look into excel reports for TFS.
TFS2013 / 2015 on prem has something has an excel report that can be used to visualize Code Churn.
In VS open team explorer then select "Documents" then explode "Excel Reports". I believe Code Churn report has something like discussed. The report is made by some default project template so I think tfs2013 on prem just creates it.
Code Churn Excel Report VS2015
https://msdn.microsoft.com/en-us/library/dd695782.aspx
A: I had very similar requirement to get details of particular attribute in a file e.g. who added, when, related work items etc.; Following GitHub project is having implementation to get required details and required minimal changes to work with multiple files or project -
SonarQube SCM TFVC plugin
It requires analysis to be executed from Windows machines with the Team Foundation Server Object Model installed (download for TFS 2013).
This blog post is also having good explaination and sample application -
TFS SDK: Connecting to TFS 2010 & TFS 2012 Programmatically
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74526",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: VisualSVN Server wants a username and password I've renamed my server and am trying to get to the VisualSVN Server repository via TortoiseSVN. In this post Gordon helped me find the right command - thanks Gordon.
Now VisualSVN Server is asking me for a username and password. I don't recall setting one and if I did I've forgotten it. Any idea how to reset this username / password?
A: It depends on how your Visual SVN Server is set up. If you are using native windows authentication, just enter you domain username and password. Otherwise, you will have to log into the machine running Visual SVN Server and reset your password there. Visual SVN Server provides a convenient tool for managing users, passwords, permissions, etc. This tool should be available from the Start Menu on your server.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74560",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: How to write static code analyzer for .net I am interested in writing static code analyzer for vb.net to see if it conforms to my company standard coding guidelines. Please advise from where i have to start.
A: I would suggest you use Mono's Gendarme. It's a very nice tool, with plenty of built in rules. It also generates nice HTML reports.
A: if you need mroe architectural insight use NDepend. This tool does not stop to amaze me. It can do soo much more than FxCop. It's commercial though, but has a free trial version
A: Rather than write your own static code analyzer, I recommend you use FxCop: and instead, write custom FxCop rules for your needs. It'll save you a lot of time.
http://www.binarycoder.net/fxcop/
A: FXCop is a good start for coding problems/mistakes, StyleCop is good for coding style (obviously), but if neither of those two work then you then you can either write a parser yourself or use the VBCodeProvider class in the .Net Framework
A: Start with FxCop. If you can't do what you're trying there, try something like NStatic or NDepend.
A: The best options are to use FxCop or StyleCop and write custom rules if necessary.
A: Use FxCop, this isn't a project you want to undertake personally. The parsing/lexical rules involved and the possible catches would be insane. The only way I could imagine doing it while retaining a modicum of sanity would be to use Lisp thanks to the extreme amount of expressiveness, but again, best to use FxCop.
If you must write a custom in-house tool for some (dogmatic?) reason, I'd recommend writing a Lisp program that does only basic rules-checking. Don't try to make it comprehensive, we're talking the kind of frontier that AI researchers are dealing with in terms of the parsing capabilities of a piece of software.
Just use Lisp to find the possible obvious offenders, or just at catching whatever it ends up being good at catching in terms of non-compliant code, then subject it to a brief human eye scan. I highly recommend abusing macros if you do use Lisp to write the parser.
A: I agree with one of the posters that it would be a quite difficult taks, but rather than with Lisp I'd start with F#, just like Microsoft did for their 3rd party windows drivers analysis tool:
http://arstechnica.com/journals/microsoft.ars/2005/11/10/1796
F# shares Lisp's expressiveness (ok, almost) and works on CLR just like VB.NET, which would make the whole thing easier.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74561",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: CSS : Bad Gray Line to the side of the Navigation Bar on my Website I'm maintaining the Perl Beginners' Site and used a modified template from Open Source Web Designs. Now, the problem is that I still have an undesired artifact: a gray line on the left side of the main frame, to the left of the navigation menu. Here's an image highlighting the undesired effect.
How can I fix the CSS to remedy this problem?
A: It's the background-image on the body showing through. Quick fix (edit style.css or add elsewhere):
#page-container
{
background-color: white;
}
A: That is an image. (see it here: http://perl-begin.org/images/background.gif) It's set in the BODY class of your stylesheet.
A: The grey line is supposed to be there. The reason why it looks odd is because the very top is hidden by the buffer element. Remove the background-color rule from this ruleset:
.buffer {
float: left; width: 160px; height: 20px; margin: 0px; padding: 0px; background-color: rgb(255,255,255);
}
A: I think it's this:
#page-container {
border-left: solid 1px rgb(150,150,150); border-right: solid 1px rgb(150,150,150);
}
However, I'm not seeing why the right border isn't showing up....
A: I would do a quick fix on this to add the style:
border-left:2px solid #BDBDBD;
to the .buffer class
.buffer {style.css (line 328)
background-color:#FFFFFF;
border-left:2px solid #BDBDBD; /* Grey border */
float:left;
height:20px;
margin:0px;
padding:0px;
width:160px;
}
A: I found the problem.
The problem is that you need to set a white background on #page-container. As things stand, it has a transparent background, so the 5pt left margin on navbar-sidebanner is revealing the bg of the page_container ... so change that bg and you're cool.
A: Thanks to all the people who answered. The problem was indeed the transparency of the #page-container and the background image of the body. I fixed them both in the stylesheet.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74570",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Installing just Quicktime libraries on Windows There's Quicktime SDK for Windows, but any application that uses it needs quicktime runtime libraries to be installed on the system (SDK itself just has headers and library stubs, and not the actual DLLs).
If my application uses Quicktime, I'd like to install the necessary libraries with it's installer, thus not requiring user to install Quicktime separately. What I'm looking for is some sort of "quicktime redistributable".
As of now (quicktime 7.x), I can't find a way to do that. I could bundle whole quicktime installer (about 20 MiB), and launch it with MSI's silent/unattended flag. However, that way it has several side effects:
*
*creates Quicktime player shortcut on desktop and in quick launch bar
*hijacks file associations, (e.g. .mov becomes associated with Quicktime Player, even if it was associated with something else before)
*installs some service/process (qttask) that presumably watches for Quicktime associations, or handles auto-updates.
*installs Quicktime Player, which I don't need in fact.
Of the above, first three are quite bad.
Is there a way to "just install the libraries" for Quicktime?
In my application, I'd use Quicktime to import images, movies and audio files in various formats. If there is no sane way to install Quicktime runtime without side effects (changed file associations, extra icons, ...), then I should be seriously looking at alternative solutions (e.g. FreeImage to load images, perhaps DirectShow for video/audio).
A: If you need to redistribute QuickTime, see QuickTime Licensing for details. You're not allowed to redistribute any of the QuickTime libraries without a written agreement with Apple. Many CD-replication companies will actually request proof of this agreement before printing large numbers of CDs.
I would definitely not distribute "QuickTime Lite" without consulting with either a lawyer or your Apple licensing representative.
Your best bet, AFAIK, is to use the full QuickTime installer (all 20MB of it), and have your main installer run it with a "silent" flag. That, at least, will allow your users to install QuickTime without a half-dozen dialogs (and without those annoying pictures of surfers in bikinis). The people at Apple's licensing division seemed to think that using the "silent" flag was acceptable, at least when we consulted them.
One warning: If the user already has an older version of QuickTime 6 Pro (or earlier) installed, then installing QuickTime 7 silently will nuke their QuickTime Pro registration and they'll have to repurchase it. We actually detect this situation in our installer and display a warning during the installation process, much like Apple does.
Yes, this is a pain. After 6+ years of working with QuickTime, I'd honestly recommend looking at other video frameworks. We're currently evaluating Ogg Theora.
A: You could include, with your setup package, a program called Quicktime Lite. It comes with the same libraries as Quicktime uses, but is much, much smaller.
Here"s the link:
Download Quicktime Lite
A: Quicktime Alternative does what you want, but for the reasons others have stated here, its illegal. Apple probably is not going to let you do what you want.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74586",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to make clipboard ring appear in VS2008 toolbox? It seems as if making the clipboard ring appear in the VS2008 toolbox is pretty elusive. Does anyone know how to turn this on ? Ctrl-Shift-V works fine, but I'd like to see what on the ring.
A: You should give Ditto a try. It saves everything you put in your clipboard into an sqlite database. A shortcut pops it up and shows the history of your clippings.
The nice thing is that you can instantly search in this window through all your clippings.
I set it up to remeber everything in my clipboard for 60 days and made a habit of copying everything that might be usefull. That way I can quickly find that particular SQL statement, i did last week. Just dont search for "select" ;-)
Try it for some days and you will be amazed. There is also a portable Version
A: If you drag text to the toolbox doesn't it appear?
A: It was removed in Visual Studio 2005. I'm trying to find a source for this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74604",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I make an HTML table the same width as its containing div tag? I have a table inside a div. I want the table to occupy the entire width of the div tag.
In the CSS, I've set the width of the table to 100%. Unfortunately, when the div has some margin on it, the table ends up wider than the div it's in.
I need to support IE6 and IE7 (as this is an internal app), although I'd obviously like a fully cross-browser solution if possible!
I'm using the following DOCTYPE...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Edit: Unfortunately I can't hard-code the width as I'm dynamically generating the HTML and it includes nesting the divs recursively inside each other (with left margin on each div, this creates a nice 'nested' effect).
A: The following works for me in Firefox and IE7... a guideline, though is: if you set width on an element, don't set margin or padding on the same element. This holds true especially if you're mixing units -- say, mixing percents and pixels.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Test</title>
</head>
<body>
<div style="width: 500px; background-color:#F33;">
This is the outer div
<div style="background-color: #FAA; padding: 10px; margin:10px;">
This is the inner div
<table cellpadding="0" cellspacing="0" style="width: 100%">
<tr>
<td style="border: 1px solid blue; background-color:#FEE;">Here is my td</td>
</tr>
</table>
</div>
</div>
</body>
</html>
See here for an example.
A: Percentage-based widths are relative to the first parent element that has a width specified. If your div does not have a width specified then the width of the table has nothing to do with it. Can you post a simplified version of the markup that shows what your DOM tree looks like?
From another angle, if your parent div DOES have a width set and the margin is still affecting your table then you are probably in quirks mode. You have specified your DOCTYPE, but be aware that the DOCTYPE element MUST be the first line in the file. Something else to note when dealing with IE6, by default, if your content is wider than your parent, the parent will be stretched to accommodate, you can stop this by adding overflow: hidden to your css for the parent element but in the process you might obscure some of the child element's content.
A: Not really sure what the problem is here - this works fine in IE6/7 and FF3. Setting the width of the .container DIV element sets the table's width. Adding margins to the .container div doesn't affect the table. Maybe there's something else in your markup / CSS that's affecting the layout?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Boxes and Tables</title>
<style type="text/css">
div.container {
background-color: yellow;
border: 1px solid #000;
width: 500px;
margin: 5px auto;
}
table.contained {
width: 100%;
border-collapse: collapse;
}
table td {
border: 2px solid #999;
}
</style>
</head>
<body>
<div class="container">
<table class="contained">
<thead>
<tr><th>Column1</th><th>Column2</th><th>Column3</th></tr>
</thead>
<tbody>
<tr><td>Value</td><td>Value</td><td>Value</td></tr>
<tr><td>Value</td><td>Value</td><td>Value</td></tr>
<tr><td>Value</td><td>Value</td><td>Value</td></tr>
<tr><td>Value</td><td>Value</td><td>Value</td></tr>
<tr><td>Value</td><td>Value</td><td>Value</td></tr>
</tbody>
</table>
</div>
</body>
</html>
A: Add the below CSS to your <table>:
table-layout: fixed;
width: 100%;
A: I figured out the heart of the problem here. It has to do with border-collapse. I've had this same problem for a while now. Since tables often have thin borders the problem is not obvious to most people. If you put a regular table with width set to 100% inside a div, as Nate has, you will be fine.
However, if you specify border-collapse:collapse on the table, the table will break out of the div. This is not obvious to most people because it may only break out by one pixel, or depending on the context it's in and the user agent, perhaps not at all.
To make it clearer what is going on, try this: Put Nate's example next to David Heggie's example in an html file.
It will look like both work fine. But now, change Nate's inline TD style to border: 40px solid blue. Change David's table td style to border: 40px solid #999;. At this point, David's table breaks out of the div by 50% of its border on each side. Nate's still works.
Put a border-collapse:collapse style on Nate's table and his breaks now too.
It's the border-collapse that is causing it!
A: In the case where you're automatically generating code that may have margins on it, adding a simple, unstyled <div> element wrapping your table might do the trick.
A: I've always used <table width="100%">
A: That is the big problem with the way CSS treats width property and the reason Microsoft implemented box model differently at first. Microsoft lost, and now it's either width or margin/padding/border for an element.
Situation may change to better in CSS3 with box-sizing property
A: Maybe this extensive article about Internet Explorer and the CSS box model will help?
A: try this:
div {
padding: 0px;
}
table {
width: 100%;
margin: 0px;
}
by setting the padding of the div to zero, you will remove the space between the borders of the div and the content of it. by setting the width of the table to 100% and it's margin to zero, you will remove the space between the borders of the table and it's container.
A: Incidentally, is there a good reason for you not to use the strict doctype? strict should always be the default. transitional is only intended for legacy code.
A: The following code works on IE6/8, Chrome, Firefox, Safari:
<style type="text/css">
div.container
{
width: 500px;
padding: 10px;
margin: 10px;
border: 1px solid red;
}
table.contained
{
width: 100%;
border: 1px solid blue;
}
</style>
<div class="container">
<table class="contained">
<tr>
<td>Hello</td><td>World</td>
</tr>
</table>
</div>
Try copy and paste and build on it (just move the style part to the header or to a separate .css file), maybe the way you using of putting the CSS inline (using the style tag) has something to do with the problem, or it is some other CSS surrounding the div table blocks? Floating can also give troubles.
P.S. I set red and blue borders to see where the areas expand to for a more visual check.
A: overflow: auto; on the outermost div may help if you are seeing weird things - like the outermost div being smaller than you want it or not taking up the entire size of the divs inside of it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74612",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "29"
} |
Q: Delphi Out of resources Every project I compile with Delphi 7, in which I do not compile with run-time packages, gives a linker error: "Too many resources". Even a blank application gives this error.
In other words: Delphi died on me.
A: What happens when you try to build it from the command line?
(i.e., \Program Files\Borland\Delphi7\Bin\dcc32.exe)
Also, have you build any custom .RES files for this project? If not, try deleting the default .RES that Delphi created for you, and let it get re-created by the project.
You can also force an update to the .RES file by changing something trivial, like the version #, saving your project, then changing it back again.
Sorry these are not answers... but hopefully we will find the issue with a little poking around.
A: Make sure you don't duplicate the resource inclusion, like having multiple {$R *.dfm} lines in a unit or multiple {$R *.res} for the project. Could also be included anywhere in a unit like {$R MyProject.res} as well...
A: Most likely a corrupted project.res file. Try renaming the old and see if it is successfully recreated?
A: I get this error in few projects in Delphi 6.
I found a workaround for this. PFB the details: (Take a backup of the .res file if it is modified)
*
*Change {$R .res} to {$R *.res}
*Compile the project
*Delete the .res file and place the original file (whose backup was taken)
*Change the {$ *.res} to {$R .res}
*Hit Compile/Build
A: This sometimes happens when you migrate a project from a previous version of Delphi. The solution as mentioned earlier is to delete the .res file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How To Detect If Type is Another Generic Type example:
public static void DoSomething<K,V>(IDictionary<K,V> items) {
items.Keys.Each(key => {
if (items[key] **is IEnumerable<?>**) { /* do something */ }
else { /* do something else */ }
}
Can this be done without using reflection? How do I say IEnumerable in C#? Should I just use IEnumerable since IEnumerable<> implements IEnumerable?
A: A word of warning about generic types and using IsAssignableFrom()...
Say you have the following:
public class MyListBase<T> : IEnumerable<T> where T : ItemBase
{
}
public class MyItem : ItemBase
{
}
public class MyDerivedList : MyListBase<MyItem>
{
}
Calling IsAssignableFrom on the base list type or on the derived list type will return false, yet clearly MyDerivedList inherits MyListBase<T>. (A quick note for Jeff, generics absolutely must be wrapped in a code block or tildes to get the <T>, otherwise it's omitted. Is this intended?) The problem stems from the fact that MyListBase<MyItem> is treated as an entirely different type than MyListBase<T>. The following article could explain this a little better. http://mikehadlow.blogspot.com/2006/08/reflecting-generics.html
Instead, try the following recursive function:
public static bool IsDerivedFromGenericType(Type givenType, Type genericType)
{
Type baseType = givenType.BaseType;
if (baseType == null) return false;
if (baseType.IsGenericType)
{
if (baseType.GetGenericTypeDefinition() == genericType) return true;
}
return IsDerivedFromGenericType(baseType, genericType);
}
/EDIT: Konrad's new post which takes the generic recursion into account as well as interfaces is spot on. Very nice work. :)
/EDIT2: If a check is made on whether genericType is an interface, performance benefits could be realized. The check can be an if block around the current interface code, but if you're interested in using .NET 3.5, a friend of mine offers the following:
public static bool IsAssignableToGenericType(Type givenType, Type genericType)
{
var interfaces = givenType.GetInterfaces().Where(it => it.IsGenericType).Select(it => it.GetGenericTypeDefinition());
var foundInterface = interfaces.FirstOrDefault(it => it == genericType);
if (foundInterface != null) return true;
Type baseType = givenType.BaseType;
if (baseType == null) return false;
return baseType.IsGenericType ?
baseType.GetGenericTypeDefinition() == genericType :
IsAssignableToGenericType(baseType, genericType);
}
A: The previously accepted answer is nice but it is wrong. Thankfully, the error is a small one. Checking for IEnumerable is not enough if you really want to know about the generic version of the interface; there are a lot of classes that implement only the nongeneric interface. I'll give the answer in a minute. First, though, I'd like to point out that the accepted answer is overly complicated, since the following code would achieve the same under the given circumstances:
if (items[key] is IEnumerable)
This does even more because it works for each item separately (and not on their common subclass, V).
Now, for the correct solution. This is a bit more complicated because we have to take the generic type IEnumerable`1 (that is, the type IEnumerable<> with one type parameter) and inject the right generic argument:
static bool IsGenericEnumerable(Type t) {
var genArgs = t.GetGenericArguments();
if (genArgs.Length == 1 &&
typeof(IEnumerable<>).MakeGenericType(genArgs).IsAssignableFrom(t))
return true;
else
return t.BaseType != null && IsGenericEnumerable(t.BaseType);
}
You can test the correctness of this code easily:
var xs = new List<string>();
var ys = new System.Collections.ArrayList();
Console.WriteLine(IsGenericEnumerable(xs.GetType()));
Console.WriteLine(IsGenericEnumerable(ys.GetType()));
yields:
True
False
Don't be overly concerned by the fact that this uses reflection. While it's true that this adds runtime overhead, so does the use of the is operator.
Of course the above code is awfully constrained and could be expanded into a more generally applicable method, IsAssignableToGenericType. The following implementation is slightly incorrect1 and I’ll leave it here for historic purposes only. Do not use it. Instead, James has provided an excellent, correct implementation in his answer.
public static bool IsAssignableToGenericType(Type givenType, Type genericType) {
var interfaceTypes = givenType.GetInterfaces();
foreach (var it in interfaceTypes)
if (it.IsGenericType)
if (it.GetGenericTypeDefinition() == genericType) return true;
Type baseType = givenType.BaseType;
if (baseType == null) return false;
return baseType.IsGenericType &&
baseType.GetGenericTypeDefinition() == genericType ||
IsAssignableToGenericType(baseType, genericType);
}
1 It fails when the genericType is the same as givenType; for the same reason, it fails for nullable types, i.e.
IsAssignableToGenericType(typeof(List<int>), typeof(List<>)) == false
IsAssignableToGenericType(typeof(int?), typeof(Nullable<>)) == false
I’ve created a gist with a comprehensive suite of test cases.
A: if (typeof(IEnumerable).IsAssignableFrom(typeof(V))) {
A: Thanks for the great info. For convienience, I've refactored this into an extension method and reduced it to a single statement.
public static bool IsAssignableToGenericType(this Type givenType, Type genericType)
{
return givenType.GetInterfaces().Any(t => t.IsGenericType && t.GetGenericTypeDefinition() == genericType) ||
givenType.BaseType != null && (givenType.BaseType.IsGenericType && givenType.BaseType.GetGenericTypeDefinition() == genericType ||
givenType.BaseType.IsAssignableToGenericType(genericType));
}
Now it can be easily called with:
sometype.IsAssignableToGenericType(typeof(MyGenericType<>))
A: Thanks very much for this post. I wanted to provide a version of Konrad Rudolph's solution that has worked better for me. I had minor issues with that version, notably when testing if a Type is a nullable value type:
public static bool IsAssignableToGenericType(Type givenType, Type genericType)
{
var interfaceTypes = givenType.GetInterfaces();
foreach (var it in interfaceTypes)
{
if (it.IsGenericType && it.GetGenericTypeDefinition() == genericType)
return true;
}
if (givenType.IsGenericType && givenType.GetGenericTypeDefinition() == genericType)
return true;
Type baseType = givenType.BaseType;
if (baseType == null) return false;
return IsAssignableToGenericType(baseType, genericType);
}
A: I'd use overloading:
public static void DoSomething<K,V>(IDictionary<K,V> items)
where V : IEnumerable
{
items.Keys.Each(key => { /* do something */ });
}
public static void DoSomething<K,V>(IDictionary<K,V> items)
{
items.Keys.Each(key => { /* do something else */ });
}
A: I'm not sure I understand what you mean here. Do you want to know if the object is of any generic type or do you want to test if it is a specific generic type? Or do you just want to know if is enumerable?
I don't think the first is possible. The second is definitely possible, just treat it as any other type. For the third, just test it against IEnumerable as you suggested.
Also, you cannot use the 'is' operator on types.
// Not allowed
if (string is Object)
Foo();
// You have to use
if (typeof(object).IsAssignableFrom(typeof(string))
Foo();
See this question about types for more details. Maybe it'll help you.
A: I used to think such a situation may be solvable in a way similar to @Thomas Danecker's solution, but adding another template argument:
public static void DoSomething<K, V, U>(IDictionary<K,V> items)
where V : IEnumerable<U> { /* do something */ }
public static void DoSomething<K, V>(IDictionary<K,V> items)
{ /* do something else */ }
But I noticed now that it does't work unless I specify the template arguments of the first method explicitly. This is clearly not customized per each item in the dictionary, but it may be a kind of poor-man's solution.
I would be very thankful if someone could point out anything incorrect I might have done here.
A: You want to check out the Type.IsInstanceOfType method
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74616",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "34"
} |
Q: Date.getTime() not including time? Can't understand why the following takes place:
String date = "06-04-2007 07:05";
SimpleDateFormat fmt = new SimpleDateFormat("MM-dd-yyyy HH:mm");
Date myDate = fmt.parse(date);
System.out.println(myDate); //Mon Jun 04 07:05:00 EDT 2007
long timestamp = myDate.getTime();
System.out.println(timestamp); //1180955100000 -- where are the milliseconds?
// on the other hand...
myDate = new Date();
System.out.println(myDate); //Tue Sep 16 13:02:44 EDT 2008
timestamp = myDate.getTime();
System.out.println(timestamp); //1221584564703 -- why, oh, why?
A: What milliseconds? You are providing only minutes information in the first example, whereas your second example grabs current date from the system with milliseconds, what is it you're looking for?
String date = "06-04-2007 07:05:00.999";
SimpleDateFormat fmt = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss.S");
Date myDate = fmt.parse(date);
System.out.println(myDate);
long timestamp = myDate.getTime();
System.out.println(timestamp);
A: Because simple date format you specified discards the milliseconds. So the resulting Date object does not have that info. So when you print it out, its all 0s.
On the other hand, the Date object does retain the milliseconds when you assign it a value with milliseconds (in this case, using new Date()). So when you print them out, it contains the millisecs too.
A: Instead of using the Sun JDK Time/Date libraries (which leave much to be desired) I recommend taking a look at http://joda-time.sourceforge.net.
This is a very mature and active sourceforge project and has a very elegant API.
A: tl;dr
The accepted Answer by Vinko Vrsalovic is correct. Your input is whole minutes, so the milliseconds for fractional second should indeed be zero.
Use java.time.
LocalDateTime.parse
(
"06-04-2007 07:05" ,
DateTimeFormatter.ofPattern( "MM-dd-uuuu HH:mm" )
)
.atZone
(
ZoneId.of( "Africa/Casablanca" )
)
.toInstant()
.getEpochMilli()
java.time
The modern approach uses the java.time classes defined in JSR 310 that years ago supplanted the terrible classes you are using.
Define a formatting pattern to match your input. FYI: Learn to use standard ISO 8601 formats for exchanging date-time values as text.
String input = "06-04-2007 07:05" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM-dd-uuuu HH:mm" ) ;
Parse your input as a LocalDateTime, as it lacks an indicator of time zone or offset-from-UTC.
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
This represents a date and a time-of-day, but lacks the context of a time zone or offset. So we do not know if you meant 7 AM in Tokyo Japan, 7 AM in Toulouse France, or 7 AM in Toledo Ohio US. This issue of time zone is crucial, because your desired count of milliseconds is a count since the first moment of 1970 as seen in UTC (an offset of zero hours-minutes-seconds), 1970-01-01T00:00Z.
So we must place your input value, the LocalDateTime object, in the context of a time zone or offset.
If your input was intended to represent a date and time in UTC, use OffsetDateTime with ZoneOffset.UTC.
OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC ) ; // Do this if your date and time represent a moment as seen in UTC.
If your input was intended to represent a date and time as seen through the wall-clock time used by the people of a particular region, use ZonedDateTime.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
Next we want to interrogate for the count of milliseconds since the epoch of first moment of 1970 in UTC. With either a OffsetDateTime or ZonedDateTime object in hand, extract a Instant by calling toInstant.
Instant instant = odt.toInstant() ;
…or…
Instant instant = zdt.toInstant() ;
Now get count of milliseconds.
long millisecondsSinceEpoch = instant.toEpochMilli() ;
By the way, I suggest you not track time by a count of milliseconds. Use ISO 8601 formatted text instead: easy to parse by machine, easy to read by humans across cultures. A count of milliseconds is neither.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
*
*Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
*
*Java 9 adds some minor features and fixes.
*Java SE 6 and Java SE 7
*
*Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
*Android
*
*Later versions of Android bundle implementations of the java.time classes.
*For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
A: When you parse a date it only uses the information you provide.
In this case it only knows MM-dd-yyyy HH:mm.
Creating a new date object returns the current system date/time (number of milliseconds since the epoch).
A: toString() of a Date object does not show you the milliseconds... But they are there
So new Date() is an object with milisecond resolution, as can be seen by:
System.out.printf( "ms = %d\n", myDate.getTime() % 1000 ) ;
However, when you construct your date with SimpleDateFormat, no milliseconds are passed to it
Am I missing the question here?
[edit] Hahaha...way too slow ;)
A: Date.getTime returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by the Date object. So "06-04-2007 07:05" - "01-01-1970 00:00" is equal to 1180955340000 milliseconds. Since the only concern of your question is about the time portion of the date, a rough way of thinking of this calculation is the number of milliseconds between 07:05 and 00:00 which is 25500000. This is evenly divisible by 1000 since neither time has any milliseconds.
In the second date it uses the current time when that line of code is executed. That will use whatever the current milliseconds past the current second are in the calculation. Therefore, Date.getTime will more than likely return a number that is not evenly divisible by 1000.
A: The getTime() method of Date returns the number of milliseconds since January 1, 1970 (this date is called the "epoch" because all computer dates are based off of this date). It should not be used to display a human-readable version of your Date.
Use the SimpleDateFormat.format() method instead. Here is a revised version of part of your code that I think may solve your problem:
String date = "06-04-2007 07:05:23:123";
SimpleDateFormat fmt = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss:S");
Date myDate = fmt.parse(date);
System.out.println(myDate); //Mon Jun 04 07:05:23 EDT 2007
String formattedDate = fmt.format(myDate);
System.out.println(formattedDate); //06-04-2007 07:05:23:123
A: import java.util.*;
public class Time {
public static void main(String[] args) {
Long l = 0L;
Calendar c = Calendar.getInstance();
//milli sec part of current time
l = c.getTimeInMillis() % 1000;
//current time without millisec
StringBuffer sb = new StringBuffer(c.getTime().toString());
//millisec in string
String s = ":" + l.toString();
//insert at right place
sb.insert(19, s);
//ENJOY
System.out.println(sb);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: What is the best way to force yourself to master vi? A good while ago, I read an article by the creator of viemu, clearing up a lot of the misconceptions about vi, as well as explaining why it's a good idea (and why it's been very popular for the last 30 years+). The same guy also has a great set of graphical cheat sheets that teach the basics a few bits at a time.
I'm convinced.
I've been convinced for the past 2 years in fact. But I still really haven't gotten around to force myself to learn vi as my primary editor, the learning curve is just too high. When I get down to work, acceptable but immediate productivity (using my current editor) has so far won over tremendous productivity farther down the line (using vi).
Does anybody have any good tips to help get past the learning curve? It can be straight out tips, some other tutorial or article, whatever.
Edit: Note that I'm aware of the vim/gVim, Cream and MacVim (etc.) variants of vi. I kept my question about vi to refer to the vi family as a whole. Thanks for all the great answers.
Update (April 2009)
I've been using Vim (more precisely, MacVim) in my day to day professional life since last December. I'm not going back :-)
Good luck to everyone in their Vim mastery.
A: The simplest way to force yourself might be just to remove all the other editors from your machine. Get rid of temptation :)
A: I wrote a guide to efficient editing with Vim a while back. You may find it helpful.
I'd step back for a minute and ask yourself "why do I want to learn this editor? What makes me think it'll be faster or better than my current text editor?" Then learn those features that will make Vi(m) indispensable to you.
For instance, Vim's CTags integration is completely indispensable for me. I work with a very, very large codebase, and the ability to jump to a function or class definition in one keystroke (regardless of which file it's in) is an absolutely killer feature, one I have trouble working without.
Use your .vimrc file to make macros that automate common tasks.
Your autopilot editor-chooser will pick the editor that will get the job done quickest and with the least amount of mental effort. A little prep-work will ensure that editor is Vim. :-)
A: EDIT: I've created a flashcard set over at the online spaced repetition site flashcarddb.com, in case you're interested ...
*
*Use a spaced repetition flash card program such as mnemosyne, supermemo, or anki to incorporate learning and retaining new commands into your daily routine. It's not enough to be using vim as your daily editor. To master it, you have to be storing those codes in your head, laying in wait for the time when they're the ideal solution to the task at hand.
*Maintain a .vimrc with customizations
*Write or edit a vim plugin
A: The first thing I'd do is lay a piece of paper or a book over your arrow keys and your ins/home/end/pgup/down keys. Those aren't needed in Vi.
Next I'd get used to hitting ctrl+[ whenever you're told to hit escape. It's much faster and you won't need to take your hands off the keyboard.
Then I'd watch my screencasts:
http://www.youtube.com/watch?v=FcpQ7koECgk
http://www.youtube.com/watch?v=c6WCm6z5msk
http://www.youtube.com/watch?v=BPDoI7gflxM
http://www.youtube.com/watch?v=J1_CfIb-3X4
Then, just practice practice practice.
edit
The reason for avoiding the arrow keys is that they slow you down. One of the largest benefits of Vim is the speed it allows you. The arrow keys also prevent you from really embracing the modal nature, which is very powerful when mastered.
A: Two things that will greatly improve your vi skills:
*
*Practice, practice, practice
*Nethack
A: My suggestion: start small. Just start by memorizing a small set of most useful commands. When I started vi, these were my top 10:
*
*(Esc) to return to command mode (most important!)
*a to add text after cursor
*A to add text at end of current line
*x to delete 1 character
*dd to delete 1 line
*R to replace text (overwrite)
*u to undo
*:q! (Enter) to quit without saving
*:w (Enter) to save
*ZZ to save and quit
A lot of basic editing can be done using only these commands. Once you get comfortable, the rest don't look too difficult.
BTW, I'd like to add that I used to rely on vi for my primary text editor, but now only if I have to. In my case, productivity is better when I use tools like Emacs or Visual Studio (please note: "in my case"). Try more than one tool and choose the one that helps your productivity the most. Good luck!
A: It sounds silly, but playing roguelike games (such as Nethack or Angband) is a fun way to get comfortable with using the h/j/k/l keys for cursor navigation.
A: Step 0: learn to touch type. Seriously - if your fingers don't know where the keys are then vim is going to be a pain. And even if you reject vim, touch typing will improve your programming (ask Steve Yegge ) by making the mind to monitor link friction free. There is a lot of software that can help you improve your typing.
Step 1: use vimtutor to get you started. It is in gvim (under
the help menu I think) or you can just type 'vimtutor' at the command
line. It will take 30-45 minutes of your time and then your fingers will
know the basics of vi/vim and you should be able to edit files without
wanting to hurl your keyboard out of the window.
Step 2: use vim everywhere. See this
question
for tips and links for using vim and vi key bindings at the command
line, from your web browser, for composing emails, in your IDE ... You
need to use vim to embed the key bindings in your muscle memory.
Step 3: learn more about vim. You will only have scratched the
surface with vimtutor. You can watch this
video or
read this article (both about
the "Seven habits of effective text editing". You can
read
about
tips
and
tricks
on
StackOverflow.
You can browse vimtips. Learn a
litle often would be my advice - there is so much out there that
sticking to bite-size chunks will be the best way to make the knowledge
stick.
Step 4: Profit :)
A: Write down all the short-cuts and features that you use in your current editor while you're using it at work. Then sit down on Saturday morning and using Google and stack overflow find out how to do each one of those in vi. Probably best if you use a sheet (or sheets) of paper for this.
Now disable/delete the other editors at work so that it'll take you longer to find and re-install them than look at your comparison sheet and do it in vi - i.e. you have no choice.
Lastly, publish your list of crossover shortcuts from your old editor to your new one on your blog.
Good luck!
A: Don't use X11?
$ sudu rm /usr/local/bin/emacs
Change your login shell to vi?
First, force yourself to use ed, then vi will seem like a luxury?
Use the vi key bindings in bash?
Just start using vi all the time?
It seems to me that learning an editor isn't terribly different from learning a language. Immersion works best.
I use vi for really quick edits or when I can't use X11 for some reason, but I live in emacs. Really powerful editors are worth taking the time to learn.
A: My recommendation is to come up with some simple programs and write them, start to finish, using VI.
Odds are, you will be too frustrated at first by the learning curve to force yourself to use them at work or in any time-sensitive environment.
I've done this before to get familiar with environments/editors, and it works pretty well.
If you are having problems coming up with things to write, I recommend redoing projects you did in school (or anything else that you've done previously). This method has the added bonus of letting you see how much of a better developer you have become. :)
Edit: forgot to mention that you should do this entirely from the console to avoid any temptation to use the mouse!
A: gVIM has a really good tutorial (link in the Start menu group).
I found working through that helped to get over the initial learning hump; and then switching my Visual Studio to ViEMU helped me hone my VI skills.
Also, the screencasts at http://vimcasts.org/ are great!
A: I remember when I first started learning emacs, it was after I was already very comfortable with Vim, and I was in the same or similar boat that you were, where I knew how to get a lot done in another editor, so as I started using emacs, it was always painfully slow.
However, I think what you'll have to do is just absorb a little bit of the pain, and always, always, ALWAYS make sure that you look up the documentation for doing something that you know you can do in your previous editor, such as moving to the end of a line, or selecting a region of text.
It also helps if you have a local vi-expert on hand that you can ask questions, or if you're like our company, you promote pair programming. That way when you're trying to do something that should be easy, you can simply ask someone, they'll show you how, and if you're using the editor regularly for a few weeks, you shouldn't have to ask more then a couple of times before it becomes second nature.
If you don't have any local resources, there are plenty of books/tutorials/reference sheets online that should be able to answer most of your questions.
Ultimately, learning Vi is like learning other skills, there's no silver bullet, and you'll have to accept that, for a while, you're going to be less productive in it then your current editor. Just keep telling yourself, "Other people have been able to learn Vi, and I'm at least as smart as them" (That's what I tell myself anyway :) )
A: The main reason for me to use vi is ssh (or Putty on Windows): When you're logged into a Unix server remotely, then vi is always available. And it works with VT100 when neither the cursor keys nor backspace/delete are mapped.
Also having a book like VI Editor Pocket Reference helps greatly.
A: I've been a on-again, off-again user of vim throughout the years (doing the occasional sys admin job). I just recently started spending more time doing my programming work in it. I'd suggest starting with gvim too. It integrates well with most OS environments, and (even better), you can fall back to the mouse when you need to :).
To get going with vim, run through the vimtutor (bundled with gVim) once or twice (takes an hour or so). I can't overstate how helpful it was for me! Especially the first parts about the different ways to move through a document, and how edit actions are recorded with motion commands, etc, etc. After that, things will be MUCH clearer.
Then, start doing quick, minor edits with it (notepad-replacement stuff) 'till you are comfortable enough to do useful editing at a rapid clip. Then try doing your day-to-day work in it. You'll find yourself pining for the "repeat last action" command in other editors in no time!
A: You asked for good tips to help get past the learning curve on the vi text editor. Many of the previous answers suggest you use no other editors. I think that is good advice. Switching to vi from a more graphical editor requires a change in mindset. It requires thinking in terms of commands, rather than visual changes.
I used nothing but vi for many years and believe the only way you can be productive is to memorize the commands you regularly use. The way I did this was to make a short list of the most common keyboard commands. I grouped and color-coded these commands by function, i.e. Moving the Cursor, Editing, Searching, etc. I was careful to only include the most commonly used commands I did not know. The idea is to create a quick reference that is also an aid in memorization – not to replace the available help screens. Then I printed this list and taped it to the wall behind my monitor so I could see it easily. (The graphical cheat sheets you mentioned might work better for some, but are probably a better reference source than a memorization tool.)
Here's the key. As I became comfortable with one of the commands, I drew a line through it with a pencil. I could still see it if I needed it, but it was symbolic to me that I had mastered that command. That gave me confidence and motivation as I could see regular progress. Once I had most of them crossed off, I removed them and added some of the more rarely used commands. I continued this process until I was satisfied with my command of vi. I knew I had reached that point when I realized I had not crossed off any commands or even looked at the list in a long time.
A couple years ago I had need to work on a UNIX platform where vi was the only editor available. I bought a little pocket reference book on vi, but hardly used it. I ended up making lists and posting them on the wall as I did the first time I used vi. By the end of the first week, I was very comfortable even though it had been five years since I had used vi.
A: You could get your hands on one of the original Happy Hacker keyboards (no arrow keys) and place your (wireless) mouse out of reach each time you start editing.
A: It's easy to write out a big list of commands/shortcuts, but it's difficult to remember them all without practice.
Focus on one new command at a time. When it becomes automatic, say after using it for a week or two, add another to your repertoire.
You'll be taking the long way around to accomplish certain things in the short term - these are obvious opportunities for new shortcuts to learn.
In my experience it was easier when I tried not to take on too much at once.
A: My number one suggestion: learn to type fast, without needing to look at the keyboard.
If you can't touch type and are always hunting-and-pecking for the colon or the hjkl or :%s/foo/bar, forget about it. Typing can be faster than using the mouse, but if that's not the case for you, vi's not going to work.
But combine good typing skills, ssh and screen and vi will be natural.
A: Face the fact that it will create an immediate performance hit. When learning a new tool you need to be able to do something that you know how to do with other tools so the problem isn't your problem. After using the new tool a while it will disappear and you will be only focusing on the underlying problem.
With something like vim (as others have said, vim is vastly superior to vi) it is important to reread and browse the documentation periodically. The interface is completely undiscoverable without it. With each new reading you will see a feature and say, "ah ha, that would have solved this issue I was trying to figure out last week", and will file it away in your brain. Solutions connected to real-world problems that you've had are much easier for you to remember than random shortcuts.
In the end you can use vim with a fairly small subset of it's features, so don't be overwhelmed with all the bells and whistles. Think of all the features in Word, do 99% of the people use them?
A: ESC gg=G to reindent code and :retab to convert tabs to spaces or spaces to tabs was what hooked me to vim. So actually you don't need to be forced to use it, you just have to learn when it can help you increase your speed.
Go through vimtutor.
Start using vim for simple editing, like config files or html. Learn the commands as you need them.
Search google for a good .vimrc used by someone who uses a toolchain that resembles yours. Turn on syntax highlighting. Find a nice color scheme.
Learn macros because Vim is the best for automated tasks and snippet insertion, like formatting a few words into a complex XML tag or converting a CSV to an HTML table.
A: You might want to start out with Cream. Cream describes itself as "a modern configuration" of vim. Basically, it is a special version of vim which looks and feels like any other text editor for all practical purposes. But enable the "expert mode" and you have all the power and behavior of vim.
So you can start using Cream as a regular text editor and then experiment with the "expert mode" until you are comfortable enough to fully switch to vim.
A: Install gVim on all platforms you use.
Then run through the the vimtutor (:help vimtutor or vimtutor at the command line).
Watch the following lecture and follow its advice: 7 Habits For Effective Text Editing 2.0
I say you definitely want to start using it for all your editing. If you fear a loss of productivity then take a weekend to practice it solid (I once did this to switch to dvorak from qwerty and had my productivity high enough by Monday and managed to stick with it after).
It's worth the effort and you won't look back!
A: force yourself not. the path to mastery love is.
A: First of all, you may want to pick up Vim; it has a vastly superior feature set along with everything vi has.
That said, it takes discipline to learn. If you have a job and can't afford the productivity hit (without getting fired), I'd suggest taking on a weekend project for the sole purpose of learning the editor. Keep its documentation open as you work, and be disciplined enough not to chicken out. As you learn more, become efficient and start relying on muscle memory, it won't be as hard to stick with it.
I've been using Vim for so long that I don't even think about what keys to press to search or navigate or save. And my hands never leave the keyboard. To use Vim is one of the best choices I've made in my programming career.
A: You should start with vim (Vi IMproved) and especially its GUI - gVim. The GUI has menus and on Windows you can use the copy, cut and paste shortcuts, so you can replace Notepad immediately. And since the menus display the shortcuts (vim commands) you could learn a lot.
Another thing that you should do from the beginning is to configure vi for your needs. For example, you can transform vim into a Python IDE. By doing this, you'll have no excuse for using another editor, because vi will offer you everything you need.
A: For me VI is a good emergency editor, but not something I want to use if there is any other alternative available. I realize this is not for everyone though, I'm not saying it's horrid or anything, I just personally prefer a discoverable UI.
But you really have to know VI if you do anything significant in Linux!
So just learn the basics:
i=insert mode
esc=leave insert mode
:wq=save and quit
:q!=don't save and quit
x=when not in insert mode, delete the character.
/=search
That will get you through any editing emergency. There is nothing you can't do with those few commands (and navigation of course). The rest you can "Tack on" as you need them.
Keep a reference or book available though--when you NEED to use VI, you probably won't be able to browse the web--but the man page may be somewhat useful.
A: Every time you're doing a complex editing task, keep wondering if there is a more efficient way to do it. Most times, when it's something that you can describe in simple terms (like "swap paragraphs of text" or "delete everything after the X character in commented lines"), it's something you can do in just a couple of keystrokes in vim.
There are some key features that are extremely useful, and you'll end using all the time. The ones I love the most are:
*
*Block selection (Ctrl-V)
*Macro recording (q)
*Virtual editing (:set ve=all)
*Regular expressions
*Piping to external Unix programs
*Key mappings
*Autocompletion (C-p, C-x C-p, C-x C-f)
*The operation+movement combination (this is amazingly powerful)
Ask other programmers what features they find most useful and adopt the ones that fit better your brain. Steal ideas from other people's .vimrcs (here's mine)
A: delete all other text editor apps.
Then you will have to learn it.
A: Personally, what I had to do was make sure that I could use the Vim key-bindings (or at least, close enough) in several applications. Having to completely switch how I edited text whenever I changed editors made it too hard to get the Vim editing style committed to muscle memory.
In my case, Viemu + vimperator did the trick.
A: Use the post-it note method :-)
When using gvim, allow your self to use the menus.
Read a book/tutorial about vim so you know the basics.
(insert and command mode)
Select some really cool functions you think you need and write those on post-it notes
and then stick those on the lower part off your monitor.
A good start is probably
i, a, o, gg, G, :10 ,/something
and some cut and paste like
yy, dd, p
and just top off with
v, V (the visual mode) + cut and paste
Then when you know them, replace on post-it with a new one that has a even cooler function,
and repeat until you are happy.
/Johan
A: When I was a lot younger (eleven), my family moved to Germany for a couple of years. I was able to learn the language through immersion - I simply had no choice but to speak the language (although if I was in a dire situation I could find an English speaker).
My suggestion is that you do the same - unless you're in an absolutely desperate situation (e.g. "ok, I just deleted /etc/passwd and need to put back root"), make the conscious decision to do your best with vi. It actually doesn't take that long to learn the basics, if you're willing.
As others have suggested,
vim-tutor
can be a really good starting point, as can this image.
A: How to force yourself ? My advice is to be in a work environment where you have to maintain 10 unix boxes by telnetting/puttying into them from windows. You will quickly realise that the only way to efficiently edit text on multiple variants of *nix is to use a standard editor that comes with almost every distro I know. Also, when X11 does not start up on a fresh install, vi is your only friend :)
A: I learnt vim/vi over ten years ago when I was doing my masters. Back then the only machine I have access to are Sun Sparc stations (Sparc 20 I think). And vi is the only thing that's on it. So one thing you can do to "force" yourself is to uninstall any other editor you have!
A: delete notepad.exe and create a shortcut to vim called notepad instead :)
or do all your coding via ssh or on a machine that has no GUI ;)
A: I've tried keeping a small cheat sheet or sticky notes of common vi commands. I do the same thing for an IDE I use. I find if I put sticky notes of keyboard shortcuts or commands on my monitor(s) it helps me learn them. Once I've used the shortcut enough and think I remember it well, I'll remove the sticky note.
A: umm, the is more of a physcology question than a programming question, but the best way I have been able to do things that I really didn't want to do is to just do it, and stop trying to thing of ways to motivate myself to do it.
Just think of it as brushing your teeth. Do you have to motivate yourself to do it? No, you just do it.
A: Spend ten years posting to Usenet from a machine where only vi and emacs were available (and where emacs had an annoying long startup time when invoked from 'rn').
That's how I learned it.
But for a quicker approach, all I can recommend is that you just commit yourself to learning it, and spend a few hours working on some source code. Install vim if you don't have it already - it has wonderful syntax highlighting features.
It's well worth it. I know that I can go to just about any Unix machine, anywhere in the western world, perhaps even through a slow dialup connection or on a GUI-less machine, and be fully productive within minutes.
A: Wait until you have to debug a wierd and wondeful problem in a live environment where all you can do is get to the command line. You might not end up liking VI, but it will save you a lot of time and you'll learn loads of tricks to step through massive (log) files.
A: Print out one of the many Vi/Vim cheat sheets you can find on the internet and force yourself to stick with it for a few weeks.
Once you learn some basic commands you can be pretty efficient. From there, just keep plugging away and learn a new command every once in a while. There is no way you can learn ALL the vi commands. I believe there are more vi commands than there are atoms in the universe!! :)
A: The best way? Set your terminal to use vi keybindings.
A: I only learned vi when I started working for an ISP where the scripts for editing domains only opened vi on a terminal. I had no choice but to learn it, but I've never regretted it.
In short, put yourself in a situation where you have no choice but to learn it.
A: I learned vi from the excellent O'Reilly book "Learning the vi editor".
A: Google is your friend. Keep a window or tab handy and when you have something that you need to do several times, say indent code or search with a regex, look it up. The best hints sites will become familar, bookmark some and perhaps print out a cheat sheet.
A: I would start with argdo, and once you fall in love with that, the rest is easy...
A: Spend a couple hours at the vi lover's site http://nereida.deioc.ull.es/html/vilovers.html - loads of tutorials, links, etc. with enthusiastic fans of vi.
A: I've started using VI because it's the default editor on pretty much every operating system except for Windows. Then again I don't do a lot of coding on Windows so that helps.
If you want to force yourself on a *NIX/OSX system just remove the other editors or alias them. For the rest it's up to yourself. Everytime you don't use VI to edit a file you won't get a cookie.
A: I used it to edit files on the webserver which was linux instead of using FTP. That was 9 years ago and I have since mastered the skills.
The other thing is find something great you can do in VI such as global search and replace or something even more powerful, and use VI whenever you need to do that.
A: One thing that I found really confusing in modern vi (vim?) is the input mode that allows for some, but not all features of command mode. I feel much more comfortable when input mode is fully dumbed down to "overwrite only, no cursor movement possible" kind of thing that old Solaris vi has. The true vi requires you to stay in command mode most of the time.
That being said, there is no need to learn vi nowadays - emacs is just as ubiquitous. :)
A: symlink every terminal editor on your system to vim and symlink every graphical editor on your system to a script that opens a new terminal window with vim running.
A: The way I did it was to take a few minutes initially to go over the most basic stuff -- moving the cursor around, searching forwards and back, jumping to next and previous words/sentences/paragraphs, etc. Inserting, appending. Whatever you can fit in your head. Then, when you've got something to do that doesn't have to be done in the next 15 seconds, make yourself use it.
When you're pretty comfortable with the basics, slowly learn the more advanced commands -- especially those that leverage your previous learning (like replacing the next 3 words, or deleting to the next search target)
I love using VI, once I learned how. The advanced commands are far more powerful than what most of the GUI editors seem to offer, and the fact that it's ubiquitous and text-based, and so available over ssh, is all the better.
A: If you force yourself to use it for a few days you will see that the commands soon become second-nature. If you are on a posix system, I recommend you start with the BSD-licensed nvi, a classical 1:1 vi clone, and then move on to vim. If you start with vim, it is likely you only use a subset of the editing commands because its INSERT mode is very similar to GUI editors.
A: I have VI on Windows, the version I use is listed below, if I am in a console window I always default to VI, then regardless of what OS I am running on I know I can edit the file. Conversely if I am in UI mode, I use Notepad++ go figure.
NT VI - Version 0.23
Developed by:
Tony Andrews
Based on a program by:
Tim Thompson
A: Play lots of nethack. That's what I did when I was in college, and I found out later that the cursor movement was the same. Although at this point you may need to change the setting to use the vi style keymap.
A: I made myself a handy one-page cheat sheet and used it to learn all the non-basic features. However, practice is about the only way to master anything.
vi is nice because it's on every UNIX-type computer, Mac OS X, Solaris, Linux. Find an old decstation box on eBay? It's got vi. How about Sun OS 4? vi again.
A: While i'm a great fan of vi in general, and vim in particular, there are many powerful editors, and you shouldn't feel you need to use vi, or it in some way is some absolute perfect editor, because it's not.
If you have to force yourself to use vi, I would be concerned that you don't feel productive using it. However, if you insist on persisting, I would probably just make sure I used vi for every single editing task. Whenever I need to do something and I don't quite no the best way to do it, I'd try to find the optimal (in terms of minimal keystrokes) to do it in vi after I did it a non-optimal normal way. I'd then make a post-it note with this little tip (or maybe just a text file) so I would remember it for next time.
Over time, your productivity with vi will dramatically improve.
A: Why don't I pitch in with my very own low-friction way to force myself? :-)
What I do is simple: I try to make my git commit messages with vim (default editor when you don't specify a message at the command-line).
Of course a commit message is so short that it barely helps. But when re-editing a message with git commit --amend it's more helpful.
A: Do what I did. Use it for everything, and hang out in #vim on freenode.
A: When you need to quickly search for something, having it all on one page can help.
A: I was forced to learn Vim for my first programming job when I was 16 (the boss wouldn't let us use anything else), but I didn't make any real progress until I read Steve Oualline's Vim Book - it is highly recommended as a starting point if you want to get serious with vim.
Vim actually takes more time to master than do some programming languages (the features are that complex). Trying to 'master' Vim by printing cheat sheets would be like trying to master Haskell by reading a couple of blog posts. Be prepared to invest some serious time and you will be well rewarded.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "208"
} |
Q: How do you force a CIFS connection to unmount I have a CIFS share mounted on a Linux machine. The CIFS server is down, or the internet connection is down, and anything that touches the CIFS mount now takes several minutes to timeout, and is unkillable while you wait. I can't even run ls in my home directory because there is a symlink pointing inside the CIFS mount and ls tries to follow it to decide what color it should be. If I try to umount it (even with -fl), the umount process hangs just like ls does. Not even sudo kill -9 can kill it. How can I force the kernel to unmount?
A: umount -a -t cifs -l
worked like a charm for me on CentOS 6.3. It saved me a server reboot.
A: I had this issue for a day until I found the real resolution. Instead of trying to force unmount an smb share that is hung, mount the share with the "soft" option. If a process attempts to connect to the share that is not available it will stop trying after a certain amount of time.
soft Make the mount soft. Fail file system calls after a number of seconds.
mount -t smbfs -o soft //username@server/share /users/username/smb/share
stat /users/username/smb/share/file
stat: /users/username/smb/share/file: stat: Operation timed out
May not be a real answer to your question but it is a solution to the problem
A: I use lazy unmount: umount -l (that's a lowercase L)
Lazy unmount. Detach the filesystem
from the filesystem hierarchy now, and
cleanup all references to the
filesystem as soon as it is not busy
anymore. (Requires kernel 2.4.11 or
later.)
A: There's a -f option to umount that you can try:
umount -f /mnt/fileshare
Are you specifying the '-t cifs' option to mount? Also make sure you're not specifying the 'hard' option to mount.
You may also want to consider fusesmb, since the filesystem will be running in userspace you can kill it just like any other process.
A: Try umount -f /mnt/share. Works OK with NFS, never tried with cifs.
Also, take a look at autofs, it will mount the share only when accessed, and will unmount it afterworlds.
There is a good tutorial at www.howtoforge.net
A: I had a very similar problem with davfs. In the man page of umount.davfs, I found that the -f -l -n -r -v options are ignored by umount.davfs. To force-unmount my davfs mount, I had to use umount -i -f -l /media/davmount.
A: On RHEL 6 this worked:
umount -f -a -t cifs -l
A: This works for me (Ubuntu 13.10 Desktop to an Ubuntu 14.04 Server) :-
sudo umount -f /mnt/my_share
Mounted with
sudo mount -t cifs -o username=me,password=mine //192.168.0.111/serv_share /mnt/my_share
where serv_share is that set up and pointed to in the smb.conf file.
A: umount -f -t cifs -l /mnt &
Be careful of &, let umount run in background.
umount will detach filesystem first, so you will find nothing abount /mnt. If you run df command, then it will umount /mnt forcibly.
A: Approaching this problem sideways:
If you can't unmount because the filesystem is busy, is your ssh/terminal session cd'd into the mount directory, therefore making the filesystem busy?
For me, the solution was to cd into my home, then sudo umount worked flawlessly.
cd ~
umount /path/to/my/share
I would post this as a comment, but I have insufficient reputation. Hoping to spare someone else the forehead slap.
A: I experienced very different results regarding unmounting a dead cifs mount and found several tricks to bypass the problem temporarily.
Let's start with the mountpoint command. It can be useful to analyze the status of a mount:
mountpoint /mnt/smb_share
Usually it returns is a mountpoint or / is not a mountpoint.
But it can even return:
*
*No such device
*Transport endpoint is not connected
*<nothing / stale>
For every result expect of is not a mountpoint there is a chance of unmounting.
You could try the usual way:
umount /mnt/smb_share
or force mode:
umount /mnt/smb_share -f
But often the force does not help. It simply returns the same nasty device is busy message.
Then the only option is to use the lazy mode:
umount /mnt/smb_share -l
BUT: This does not unmount anything. It only "moves" the mount to the root of the system, which can be seen as follows:
# lsof | grep mount | grep cwd
mount.cif 3125 root cwd unknown / (stat: No such device)
mount.cif 3150 root cwd unknown / (stat: No such device)
It is even noted in the documentation:
Lazy unmount. Detach the filesystem from the file hierarchy
now, and clean up all references to this filesystem as soon
as it is not busy anymore.
Now if you are unlucky, it will stay there forever. Even killing the process probably does not help:
kill -9 $pid
But why is this a problem? Because mount /mnt/smb_share does not work until the lazy unmounted path is really cleaned up by the Linux Kernel. And this is even mentioned in the documentation of umount. "lazy" should only be used to avoid a long shutdown / reboot times:
A system reboot would be expected in near future if you’re
going to use this option for network filesystem or local
filesystem with submounts. The recommended use-case for
umount -l is to prevent hangs on shutdown due to an
unreachable network share where a normal umount will hang due
to a downed server or a network partition. Remounts of the
share will not be possible.
Workarounds
Use a different SMB version
If you still have hopes that the lazy unmounted path will ever be not busy anymore and cleaned up by the Linux Kernel or you can't reboot at the moment, then you are maybe lucky and your SMB server supports different protocol versions. By that we can use the following trick:
Lets say you mounted your share as follows:
mount.cifs //smb.server/share /mnt/smb_share -o username=smb_user,password=smb_pw
By that Linux automatically tries the maximum support SMB protocol version. Maybe 3.1. Now, you can force this version and it won't mount as expected:
mount.cifs //smb.server/share /mnt/smb_share -o username=smb_user,password=smb_pw,vers=3.1
But then simply try a different version:
mount.cifs //smb.server/share /mnt/smb_share -o username=smb_user,password=smb_pw,vers=3.0
or maybe 2.1:
mount.cifs //smb.server/share /mnt/smb_share -o username=smb_user,password=smb_pw,vers=2.1
Change the IP of the SMB server
If you are able to change the IP address or add a second IP to your SMB server, you can use this to mount the same server.
Dirty: Forward the traffic
Lets say the SMB server has the IP address 10.0.0.1 and the mount is really dead. Then create this iptables rule:
iptables -t nat -A OUTPUT -d 10.0.0.250 -j DNAT --to-destination 10.0.0.1
Now change your mount rule accordingly, so it mounts the samba server through IP 10.0.0.250 instead of 10.0.0.1 and voila, its mounted without server reboot. Dirty, but it works. PS This rule does not survive a reboot, so you should mount the SMB server manually and leave the /etc/fstab as usual.
More debugging
If you want to check if samba connection itself is theoretically working, you could try to list all SMB shares of the server through SMB3 as follows:
smbclient //smb.server -U "smb_user" -m SMB3 -L
or to view the content of a share with SMB1:
smbclient //smb.server -U "smb_user" -m NT1 -c ls
A: A lazy unmount will do the job for you.
umount -l <mount path>
A: On RHEL 6 this worked for me also:
umount -f -a -t cifs -l FOLDER_NAME
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74626",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "166"
} |
Q: Modify an xml files in a jar file with Java I currently am tasked with updating an XML file (persistance.xml) within a jar at a customers site. I can of course unjar the file, update the xml, then rejar the file for redeployment. I would like to kind these command line operations in a Swing App so that the person doing it does not have to drop to the command line. Any thoughts on a way to do this programatically?
A: The Java API has classes for manipulating JAR files.
A: Sure:
File tmp = new File ("tmp");
tmp.mkdirs();
Process unjar = new ProcessBuilder ("jar", "-xf", "myjar.jar", tmp.getName ()).start();
unjar.waitFor();
// TODO read and update persistence.xml
Process jar = new ProcessBuilder ("jar", "-cf", "myjar.jar", tmp.getName()).start();
jar.waitFor();
A: You can use Java's ZipFile and ZipEntry classes to read the contents of a JAR file, then use ZipOutputStream to create a new one.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74641",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: what is the flex (ActionScript3) syntax for a function valued function's type? What is the syntax to declare a type for my compare-function generator in code like the following?
var colName:String = ""; // actually assigned in a loop
gc.sortCompareFunction = function() : ??WHAT_GOES_HERE??
{
var tmp:String = colName;
return function(a:Object,b:Object):int { return compareGeneral(a,b,tmp); };
}();
A: Isn't "Function" a data type?
A: In order to understand what the data type is, we must know what the intended outcome of the return is. I need to see the code block for compareGeneral, and I still don't believe this will help. You have two returns withing the same function "gc.sortCompareFunction", I believe this is incorrect as return gets a value and then acts as a break command meaning the rest of the anything withing the same function block is ignored. The problem is that I don't know which return is the intended return, and I don't know that flash knows either. You can use * as a data type, but this should only really be used in specific situations. In this situation I believe you need only the one return value that merely returns whatever the value of compareGeneral.
Now if this is a compareGenerator it really should either return a Boolean TRUE or FALSE, or a int 0 or 1, lets use the former. Also I believe we can use one less function. Since I have not seen all of your code and I am not exactly sure what your trying to accomplish, the following is hypothetical.
function compareGeneral(a:object,b:object):Boolean
{
//Check some property associated to each object for likeness.
if(a.someAssignedPropery == b.someAssignedPropery)
{
return true;
}
return false;
}
var objA:Object = new Object();
objA.someAssignedProperty = "AS3";
objB.someAssignedProperty = "AS3";
compareGeneral(objA,objB);
In this case compareGeneral(objA,objB); returns true, though we haven't done anything useful with it yet. Here is a way you may use it. Remember that it either returns a value of true or false so we can treat it like a variable.
if(compareGeneral(objA,objB)) //same as if(compareGeneral(objA,objB)) == true)
{
trace("You have found a match!");
//Here you can call some other function or set a variable or whatever you require functionality wise based on a match being found.
}
else
{
trace("No match could be found!");
}
I hope that this is able to help you understand data types and return values. I do not know what you were doing with tmp, but generally functions that return a value deal with that one thing and only that thing, so it is best that the compare function compare one thing against the other and that be the extent of the call. Whatever functionality you require with tmp can go inside its own function or method, and be called when needed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74649",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Has anyone hooked up BizTalk and Fogbugz? We have an intranet system that schedules routine tasks. We also have Fogbugz for bug tracking. When an urgent bug comes in, we track that task in the bugtracker. However, I need to write back to both the Intranet and our CMS. I'm thinking Biztalk as the middle piece, but am not sure the best way to go about it. Database adapter? Web services?
I know I can use the CMS adapter for Microsoft CMS. I'd love to hear your experiences with Fogbugz.
A: I'm guessing that watching the database for changes would be the best way to do it. That way, you could post any changes you saw happen in the FogBugz database through other Biztalk adapters.
Please keep us updated with what you decide to do - I'd be interested to hear about it.
A: Version 6 of the FogBugz API is pretty well documented at http://www.fogcreek.com/FogBugz/docs/60/topics/advanced/API.html. The API is implemented as an ASP page that accepts GET or POST params and returns XML after a user has been authenticated.
So, we can use the HTTP Send Adapter to POST requests to the FogBugz system, either updating bug records or retrieving information. The response from the API call is basic Xml that will be returned in the response body that can be read by BizTalk as necessary.
Be aware that the HTTP Send Adapter can only POST data - it cannot use the GET verb (http://msdn.microsoft.com/en-us/library/aa561642.aspx)
A: Isn't FogBugz based on a SQL Server Database? Or do you use a hosted alternative?
If it's using a SQL Server you're controlling I'd just tie up two send ports to the process that read and handles the "FixBugMessage". One send port that uses the CMS Adapter and writes to the CMS and another that just uses the SQL Adapter and via an Stored Procedure writes to the FogBugz database.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74662",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I check CPU and Memory Usage in Java? I need to check CPU and memory usage for the server in java, anyone know how it could be done?
A: If you are looking specifically for memory in JVM:
Runtime runtime = Runtime.getRuntime();
NumberFormat format = NumberFormat.getInstance();
StringBuilder sb = new StringBuilder();
long maxMemory = runtime.maxMemory();
long allocatedMemory = runtime.totalMemory();
long freeMemory = runtime.freeMemory();
sb.append("free memory: " + format.format(freeMemory / 1024) + "<br/>");
sb.append("allocated memory: " + format.format(allocatedMemory / 1024) + "<br/>");
sb.append("max memory: " + format.format(maxMemory / 1024) + "<br/>");
sb.append("total free memory: " + format.format((freeMemory + (maxMemory - allocatedMemory)) / 1024) + "<br/>");
However, these should be taken only as an estimate...
A: For memory usage, the following will work,
long total = Runtime.getRuntime().totalMemory();
long used = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
For CPU usage, you'll need to use an external application to measure it.
A: Since Java 1.5 the JDK comes with a new tool: JConsole wich can show you the CPU and memory usage of any 1.5 or later JVM. It can do charts of these parameters, export to CSV, show the number of classes loaded, the number of instances, deadlocks, threads etc...
A: If you use the runtime/totalMemory solution that has been posted in many answers here (I've done that a lot), be sure to force two garbage collections first if you want fairly accurate/consistent results.
For effiency Java usually allows garbage to fill up all of memory before forcing a GC, and even then it's not usually a complete GC, so your results for runtime.freeMemory() always be somewhere between the "real" amount of free memory and 0.
The first GC doesn't get everything, it gets most of it.
The upswing is that if you just do the freeMemory() call you will get a number that is absolutely useless and varies widely, but if do 2 gc's first it is a very reliable gauge. It also makes the routine MUCH slower (seconds, possibly).
A: Java's Runtime object can report the JVM's memory usage. For CPU consumption you'll have to use an external utility, like Unix's top or Windows Process Manager.
A: import java.io.File;
import java.text.NumberFormat;
public class SystemInfo {
private Runtime runtime = Runtime.getRuntime();
public String info() {
StringBuilder sb = new StringBuilder();
sb.append(this.osInfo());
sb.append(this.memInfo());
sb.append(this.diskInfo());
return sb.toString();
}
public String osName() {
return System.getProperty("os.name");
}
public String osVersion() {
return System.getProperty("os.version");
}
public String osArch() {
return System.getProperty("os.arch");
}
public long totalMem() {
return Runtime.getRuntime().totalMemory();
}
public long usedMem() {
return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
}
public String memInfo() {
NumberFormat format = NumberFormat.getInstance();
StringBuilder sb = new StringBuilder();
long maxMemory = runtime.maxMemory();
long allocatedMemory = runtime.totalMemory();
long freeMemory = runtime.freeMemory();
sb.append("Free memory: ");
sb.append(format.format(freeMemory / 1024));
sb.append("<br/>");
sb.append("Allocated memory: ");
sb.append(format.format(allocatedMemory / 1024));
sb.append("<br/>");
sb.append("Max memory: ");
sb.append(format.format(maxMemory / 1024));
sb.append("<br/>");
sb.append("Total free memory: ");
sb.append(format.format((freeMemory + (maxMemory - allocatedMemory)) / 1024));
sb.append("<br/>");
return sb.toString();
}
public String osInfo() {
StringBuilder sb = new StringBuilder();
sb.append("OS: ");
sb.append(this.osName());
sb.append("<br/>");
sb.append("Version: ");
sb.append(this.osVersion());
sb.append("<br/>");
sb.append(": ");
sb.append(this.osArch());
sb.append("<br/>");
sb.append("Available processors (cores): ");
sb.append(runtime.availableProcessors());
sb.append("<br/>");
return sb.toString();
}
public String diskInfo() {
/* Get a list of all filesystem roots on this system */
File[] roots = File.listRoots();
StringBuilder sb = new StringBuilder();
/* For each filesystem root, print some info */
for (File root : roots) {
sb.append("File system root: ");
sb.append(root.getAbsolutePath());
sb.append("<br/>");
sb.append("Total space (bytes): ");
sb.append(root.getTotalSpace());
sb.append("<br/>");
sb.append("Free space (bytes): ");
sb.append(root.getFreeSpace());
sb.append("<br/>");
sb.append("Usable space (bytes): ");
sb.append(root.getUsableSpace());
sb.append("<br/>");
}
return sb.toString();
}
}
A: If you are using the Sun JVM, and are interested in the internal memory usage of the application (how much out of the allocated memory your app is using) I prefer to turn on the JVMs built-in garbage collection logging. You simply add -verbose:gc to the startup command.
From the Sun documentation:
The command line argument -verbose:gc prints information at every
collection. Note that the format of the -verbose:gc output is subject
to change between releases of the J2SE platform. For example, here is
output from a large server application:
[GC 325407K->83000K(776768K), 0.2300771 secs]
[GC 325816K->83372K(776768K), 0.2454258 secs]
[Full GC 267628K->83769K(776768K), 1.8479984 secs]
Here we see two minor collections and one major one. The numbers
before and after the arrow
325407K->83000K (in the first line)
indicate the combined size of live objects before and after garbage
collection, respectively. After minor collections the count includes
objects that aren't necessarily alive but can't be reclaimed, either
because they are directly alive, or because they are within or
referenced from the tenured generation. The number in parenthesis
(776768K) (in the first line)
is the total available space, not counting the space in the permanent
generation, which is the total heap minus one of the survivor spaces.
The minor collection took about a quarter of a second.
0.2300771 secs (in the first line)
For more info see: http://java.sun.com/docs/hotspot/gc5.0/gc_tuning_5.html
A: JConsole is an easy way to monitor a running Java application or you can use a Profiler to get more detailed information on your application. I like using the NetBeans Profiler for this.
A: Here is some simple code to calculate the current memory usage in megabytes:
double currentMemory = ( (double)((double)(Runtime.getRuntime().totalMemory()/1024)/1024))- ((double)((double)(Runtime.getRuntime().freeMemory()/1024)/1024));
A: I would also add the following way to track CPU Load:
import java.lang.management.ManagementFactory;
import com.sun.management.OperatingSystemMXBean;
double getCpuLoad() {
OperatingSystemMXBean osBean =
(com.sun.management.OperatingSystemMXBean) ManagementFactory.
getPlatformMXBeans(OperatingSystemMXBean.class);
return osBean.getProcessCpuLoad();
}
You can read more here
A: From here
OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
int availableProcessors = operatingSystemMXBean.getAvailableProcessors();
long prevUpTime = runtimeMXBean.getUptime();
long prevProcessCpuTime = operatingSystemMXBean.getProcessCpuTime();
double cpuUsage;
try
{
Thread.sleep(500);
}
catch (Exception ignored) { }
operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
long upTime = runtimeMXBean.getUptime();
long processCpuTime = operatingSystemMXBean.getProcessCpuTime();
long elapsedCpu = processCpuTime - prevProcessCpuTime;
long elapsedTime = upTime - prevUpTime;
cpuUsage = Math.min(99F, elapsedCpu / (elapsedTime * 10000F * availableProcessors));
System.out.println("Java CPU: " + cpuUsage);
A: JMX, The MXBeans (ThreadMXBean, etc) provided will give you Memory and CPU usages.
OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
operatingSystemMXBean.getSystemCpuLoad();
A: If you are using Tomcat, check out Psi Probe, which lets you monitor internal and external memory consumption as well as a host of other areas.
A: The YourKit Java profiler is an excellent commercial solution. You can find further information in the docs on CPU profiling and memory profiling.
A: For Eclipse, you can use TPTP (Test and Performance Tools Platform) for analyse memory usage and etc. more information
A: I want to add a note to the existing answers:
These methods only keep track of JVM Memory. The actual process may consume more memory.
java.nio.ByteBuffer.allocateDirect() is a function/library, that is easily missed, and indeed allocated native memory, that is not part of the Java memory management.
On Linux, you may use something like this to get the actually consumed memory: https://linuxhint.com/check_memory_usage_process_linux/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74674",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "110"
} |
Q: Tools to effectively manage the information? How do you guys manage the information overflow?
What are the tools that you guys use?
One of the usefull tool is RSS feed reader.
Does Any body uses any other tools or any other ways to effectively manage the information?
A: Be an information snob.
If the blog doesn't absolutely rock your world, don't read it. It's so easy to get bogged down, even obsessed, with too much information. No matter what tools you have, you're still human and can only read so many words per day.
A: I use Evernote to keep notes and search through them.
A: I use Google Reader for the feeds. Split it up in multiple categories, 'A' with the more unique stuff, 'B' with the spam (Digg for example, easy to ignore because the important stuff shows up in 'A'), 'C' for my webcomics.
I always read the stuff in 'A', when bored I read 'C' and 'B' when I have spare time. It happens a lot of time that I'll mark 'B' as read just to get rid of it.
For work I'm stuck with Outlook, so I use the 'Tasks' function of Outlook a lot to get things sorted. Also a big believer of 'Inbox Zero' (http://www.43folders.com/izero).
A: I use a small number of tools and techniques, because it is easy to get distracted managing the information management tools, rather than managing the information.
*
*Google Reader - The key for me was creating @work and @home labels, for the appropriate location.
*TiddlyWiki - I keep track of all my notes for work projects in a TiddlyWiki file.
*Delicious - I keep my bookmarks here. When I come across a link I want to read later (usually in my RSS Reader), I tag it @readreview. When I read it, I delete it unless it is useful reference, then I retag appropriately.
*Local bookmarks - I store bookmarks on the browser toolbar in folders so I can middle-click and open all in tabs. Obviously these would be limited in number :-). I also have a bookmarklets folder.
I don't have a PDA. I have a pad of graph paper on my desk that I use for writing temporary notes and diagrams (permanent notes go into the TiddlyWiki). A lot of "productivity blogs" like to promote various tools, and some of these caught on for people, but I find my system is pretty simple and easy for me to manage. This makes it useful.
A: Well, this is an obvious one, but iGoogle seems to do a great job for me.
A: Depends on what information you are looking to manage. Can you be more specific?
I use google reader to handle things i read, RememberTheMilk to remind me of what i have to do, and gmail overall to quickly store and search data/correspondences.
Oh and i use the hipster PDA too!
You should probably check out Lifehacker for more tools and Getting Things Done apps.
A: Like you say most sites have a RSS feed today. Get a RSS Reader that sync between computers if you use more than one computer, so you don't have to mark alot of post as read. A good program is FeedDeamon, its free and sync between computers, there is even a online version as well, if you are on the road. FeedDeamon also have tools to help you identify the feeds, that you dont really read, and gives you a top 10 of feeds that you look on alot. This can help you delete bad RSS-Feeds, and also help you organize you're feeds.
I also use Delicious, to keep my bookmarks in sync, and is very handy if you bookmark alot.
Other than that, I don't really use any more tools - just the common sence that there is only 24 hours in the day, so dont use it to just read information that you don't need - bookmark interesting blog post from RSS, and read them later when you need to.
A: I've been using Delicious quite a bit over the past 2 years and it's been a great help.
A: If you're primarily interested in blogs, what I think we need is a way to prioritize the information that we, personally, are interested in. There used to be an RSS reader called wTicker (now demised) that used Bayesian filtering to rate articles for you. Another product under development, Particls, would similarly watch what you read and highlight similar content.
What about other types of information, though? For example, the tasks that OneNote or EverNote, or more obscure tools like Zoot aim to facilitate?
A: It depends on the type of information you meant. The answers above contain most of the tools. But if you use ms office you shall explore Office OneNote.
A: *
*iGoogle: News, RSS, Wether, New Films, E-Mail widgets
*ToDoList: every day work aspects
*Local MediaWiki, for local company knowleges
*Smartphone MS Excel for personal finances.
A: *
*I still read news and blogs from RSS feeds. Feedly is the best tool for that right now.
*When I find something interesting in Feedly, I add it to Pocket and read later. A Premium account allows me to highlight paragraphs I would like to save.
*I also set up a receipt on IFTTT that monitors my likes on Twitter and adds links from the liked tweets to Pocket too.
*As Substack grows, there is the new email newsletter boom. But my inbox is also a place where I do my work. So, I wrote an apps script file to receive newsletters once or twice a day and prevent them from distracting me from work. And then, I published it as Silent Inbox add-on that plugs into your Gmail.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74689",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How do I store the window size between sessions in Qt? I have a QMainWindow in a Qt application. When I close it I want it to store its current restore size (the size of the window when it is not maximized). This works well when I close the window in restore mode (that is, not maximized). But if I close the window if it is maximized, then next time i start the application and restore the application (because it starts in maximized mode), then it does not remember the size it should restore to. Is there a way to do this?
A: I've encountered this problem as well.
What you can do: in addition to the window's size, save whether it's maximized or not (QWidget::isMaximized()).
Then next time you start the application, first set the size (QWidget::resize()) and then maximize it if appropriate (QWidget::showMaximized()). When it's restored, it should return to the correct size.
A: I found that a combination of all the previous answers here was necessary on Fedora 14. Be careful not to save the size and position when the window is maximized!
void MainWindow::writePositionSettings()
{
QSettings qsettings( "iforce2d", "killerapp" );
qsettings.beginGroup( "mainwindow" );
qsettings.setValue( "geometry", saveGeometry() );
qsettings.setValue( "savestate", saveState() );
qsettings.setValue( "maximized", isMaximized() );
if ( !isMaximized() ) {
qsettings.setValue( "pos", pos() );
qsettings.setValue( "size", size() );
}
qsettings.endGroup();
}
void MainWindow::readPositionSettings()
{
QSettings qsettings( "iforce2d", "killerapp" );
qsettings.beginGroup( "mainwindow" );
restoreGeometry(qsettings.value( "geometry", saveGeometry() ).toByteArray());
restoreState(qsettings.value( "savestate", saveState() ).toByteArray());
move(qsettings.value( "pos", pos() ).toPoint());
resize(qsettings.value( "size", size() ).toSize());
if ( qsettings.value( "maximized", isMaximized() ).toBool() )
showMaximized();
qsettings.endGroup();
}
In main(), the position settings are read before showing the window the first time...
MainWindow mainWindow;
mainWindow.readPositionSettings();
mainWindow.show();
...and these event handlers update the settings as necessary. (This causes a writes to the settings file for every mouse movement during the move and resize which is not ideal.)
void MainWindow::moveEvent( QMoveEvent* )
{
writePositionSettings();
}
void MainWindow::resizeEvent( QResizeEvent* )
{
writePositionSettings();
}
void MainWindow::closeEvent( QCloseEvent* )
{
writePositionSettings();
}
Still, the vertical component of the position is not quite right, it seems to be ignoring the height of the window title bar... if anyone knows how to deal with that let me know :)
A: Use the QWidget::saveGeometry feature to write the current settings into the registry.(The registry is accessed using QSettings). Then use restoreGeometry() upon startup to return to the previous state.
A: The image at http://qt-project.org/doc/qt-4.8/application-windows.html shows, that geometry.x() and geometry.y() are not equal to x() and y(), which are the same as pos().
In my case, I use:
x()
y()
width()
height()
and restore these successfully with:
move()
resize()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: Is there a platform independent way (Java?) to read an audio CD's TOC? I would like to avoid using native libaries if at all possible. Surely there is a better way to solve this issue for Linux, Windows and Mac OS X.
A: Sorry, you're out of luck. You'll need JNI, and it'll be obnoxiously different for different platforms. The base java libraries cover tasks and hardware that are pretty much universal. CD drives weren't and aren't considered so.
A: You can use the Java Sound API. I believe this is part of java 5. This may allow you to do what you want to do.
http://java.sun.com/products/java-media/sound/
here are some examples:
http://www.jsresources.org/examples/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74693",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: On Windows Mobile device, what is the best way to display an OK button instead of the X button? I have a C++ program that when run, by default, displays the X in the upper right corner. Clicking X, minimizes the program. I've added code using the SHInitDialog function to change the X to OK, so that clicking OK exits the program.
My question: Is there a better method that applies to the window, since SHInitDialog works best with Dialog Boxes?
A: Take a look at SHDoneButton API.
A: With Windows Mobile 5.0 and higher, using the CreateWindowEx function passing it WS_EX_CAPTIONOKBTN for the extended style works.
@ctacke SHDoneButton may have also worked but I wanted to change the main window without handling it like a dialogbox, which is basically what SHInitDialog is doing.
A: Not sure how it's done in C++, but in .NET if you set the MinimizeBox property to false, you get an OK button. Since .NET Windows code is fancy wrapper code, there should be a C++ equivalent
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74696",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can you send a signal to Windows Explorer to make it refresh the systray icons? This problem has been afflicting me for quite a while and it's been really annoying.
Every time I login after a reboot/power cycle the explorer takes some time to show up.
I've taken the step of waiting for all the services to boot up and then I login, but it doesn't make any difference.
The result is always the same: Some of the icons do not show up even if the applications have started.
I've dug a bit on the code that makes one application "stick" an icon in there, but is there an API call that one can perform so explorer re-reads all that icon info? Like invalidate or redraw or something of the sort?
Apparently, it looks like Jon was right and it's not possible to do it.
I've followed Bob Dizzle and Mark Ransom code and build this (Delphi Code):
procedure Refresh;
var
hSysTray: THandle;
begin
hSysTray := GetSystrayHandle;
SendMessage(hSysTray, WM_PAINT, 0, 0);
end;
function GetSystrayHandle: THandle;
var
hTray, hNotify, hSysPager: THandle;
begin
hTray := FindWindow('Shell_TrayWnd', '');
if hTray = 0 then
begin
Result := hTray;
exit;
end;
hNotify := FindWindowEx(hTray, 0, 'TrayNotifyWnd', '');
if hNotify = 0 then
begin
Result := hNotify;
exit;
end;
hSyspager := FindWindowEx(hNotify, 0, 'SysPager', '');
if hSyspager = 0 then
begin
Result := hSyspager;
exit;
end;
Result := FindWindowEx(hSysPager, 0, 'ToolbarWindow32', 'Notification Area');
end;
But to no avail.
I've even tried with InvalidateRect() and still no show.
Any other suggestions?
A: Include following code with yours to refresh System Tray.
public const int WM_PAINT = 0xF;
[DllImport("USER32.DLL")]
public static extern int SendMessage(IntPtr hwnd, int msg, int character,
IntPtr lpsText);
Send WM_PAINT Message to paint System Tray which will refresh it.
SendMessage(traynotifywnd, WM_PAINT, 0, IntPtr.Zero);
A: As far as I know that isn't possible Gustavo - it's up to each application to put its notifyicon in the systray, and ensure it's kept in the right state.
You'll notice sometimes when explorer.exe crashes that certain icons don't reappear - this isn't because their process has crashed, simply that their application hasn't put the notifyicon in the systray when the new instance of explorer.exe started up. Once again, it's the application that's responsible.
Sorry not to have better news for you!
A: I covered this issue last year on my Codeaholic weblog in an article entitled [Delphi] Updating SysTray.
My solution is a Delphi ActiveX/COM DLL. The download link still works (though for how much longer I don't know as my PLUG membership has lapsed.)
A: Take a look at this blog entry: REFRESHING THE TASKBAR NOTIFICATION AREA. I am using this code to refresh the system tray to get rid of orphaned icons and it works perfectly.
The blog entry is very informative and gives a great explanation of the steps the author performed to discover his solution.
#define FW(x,y) FindWindowEx(x, NULL, y, L"")
void RefreshTaskbarNotificationArea()
{
HWND hNotificationArea;
RECT r;
GetClientRect(
hNotificationArea = FindWindowEx(
FW(FW(FW(NULL, L"Shell_TrayWnd"), L"TrayNotifyWnd"), L"SysPager"),
NULL,
L"ToolbarWindow32",
// L"Notification Area"), // Windows XP
L"User Promoted Notification Area"), // Windows 7 and up
&r);
for (LONG x = 0; x < r.right; x += 5)
for (LONG y = 0; y < r.bottom; y += 5)
SendMessage(
hNotificationArea,
WM_MOUSEMOVE,
0,
(y << 16) + x);
}
A: Two important details for anyone using Louis's answer (from REFRESHING THE TASKBAR NOTIFICATION AREA) on Windows 7 or Windows 8:
First, as the answer was reflected to show, the window titled "Notification Area" in XP is now titled "User Promoted Notification Area" in Windows 7 (actually probably Vista) and up.
Second, this code does not clear icons that are currently hidden. These are contained in a separate window. Use the original code to refresh visible icons, and the following to refresh hidden icons.
//Hidden icons
GetClientRect(
hNotificationArea = FindWindowEx(
FW(NULL, L"NotifyIconOverflowWindow"),
NULL,
L"ToolbarWindow32",
L"Overflow Notification Area"),
&r);
for (LONG x = 0; x < r.right; x += 5)
for (LONG y = 0; y < r.bottom; y += 5)
SendMessage(
hNotificationArea,
WM_MOUSEMOVE,
0,
(y << 16) + x);
For anyone who just needs a utility to run to accomplish this, rather than code, I built a simple exe with this update: Refresh Notification Area
A: I use the following C++ code to get the window handle to the tray window. Note: this has only been tested on Windows XP.
HWND FindSystemTrayIcons(void)
{
// the system tray icons are contained in a specific window hierarchy;
// use the Spy++ utility to see the chain
HWND hwndTray = ::FindWindow("Shell_TrayWnd", "");
if (hwndTray == NULL)
return NULL;
HWND hwndNotifyWnd = ::FindWindowEx(hwndTray, NULL, "TrayNotifyWnd", "");
if (hwndNotifyWnd == NULL)
return NULL;
HWND hwndSysPager = ::FindWindowEx(hwndNotifyWnd, NULL, "SysPager", "");
if (hwndSysPager == NULL)
return NULL;
return ::FindWindowEx(hwndSysPager, NULL, "ToolbarWindow32", "Notification Area");
}
A: After lots of times trying I found that there are three issues you must to know:
*
*The parent of hidden tray window is NotifyIconOverflowWindow, other than Shell_TrayWnd.
*You shouldn't use caption parameter of FindWindowEx to find a window, because these is lots of langue versions of Windows OS, they are not always be the same title Obviously.
*Use spy++ of Visual Studio to find or make assurance what you want.
So, I changed code from @Stephen Klancher and @Louis Davis, thank you guys.
The following code worked for me.
#define FW(x,y) FindWindowEx(x, NULL, y, L"")
void RefreshTaskbarNotificationArea()
{
HWND hNotificationArea;
RECT r;
GetClientRect(hNotificationArea = FindWindowEx(FW(NULL, L"NotifyIconOverflowWindow"), NULL, L"ToolbarWindow32", NULL), &r);
for (LONG x = 0; x < r.right; x += 5)
{
for (LONG y = 0; y < r.bottom; y += 5)
{
SendMessage(hNotificationArea, WM_MOUSEMOVE, 0, (y << 16) + x);
}
}
}
A: @Skip R, and anyone else wanting to do this in C, with this code verified compiled in a recent (most recent) mingw on Windows 10 64 bit (but with the mingw 32 bit package installed), this seems to work in Windows XP / 2003 to get rid of stale notification area icons.
I installed mingw via Chocolatey, like this:
choco install mingw --x86 --force --params "/exception:sjlj"
(your mileage may vary on that, on my system, the compiler was then installed here:
C:\ProgramData\chocolatey\lib\mingw\tools\install\mingw32\bin\gcc.exe
and then a simple
gcc refresh_notification_area.c
yielded an a.exe which solved a stale notification area icon problem I was having on Windows 2003 (32 bit).
The code, adapted from @Stephen Klancher above is (note this may only work on Windows XP/2003, which fulfilled my purposes):
#include <windows.h>
#define FW(x,y) FindWindowEx(x, NULL, y, "")
int main ()
{
HWND hNotificationArea;
RECT r;
//WinXP
// technique found at:
// https://stackoverflow.com/questions/74723/can-you-send-a-signal-to-windows-explorer-to-make-it-refresh-the-systray-icons#18038441
GetClientRect(
hNotificationArea = FindWindowEx(
FW(FW(FW(NULL, "Shell_TrayWnd"), "TrayNotifyWnd"), "SysPager"),
NULL,
"ToolbarWindow32",
"Notification Area"),
&r);
for (LONG x = 0; x < r.right; x += 5)
for (LONG y = 0; y < r.bottom; y += 5)
SendMessage(
hNotificationArea,
WM_MOUSEMOVE,
0,
(y << 16) + x);
return 0;
}
A: Powershell solution, put this in your script
Add-Type -AssemblyName System.Windows.Forms
Add-Type @"
using System;
using System.Runtime.InteropServices;
public struct RECT {
public int left;
public int top;
public int right;
public int bottom;
}
public class pInvoke {
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
[DllImport("user32.dll")]
public static extern bool GetClientRect(IntPtr hWnd, out RECT lpRect);
[DllImport("user32.dll")]
public static extern IntPtr SendMessage(IntPtr hWnd, uint msg, int wParam, int lParam);
public static void RefreshTrayArea() {
IntPtr systemTrayContainerHandle = FindWindow("Shell_TrayWnd", null);
IntPtr systemTrayHandle = FindWindowEx(systemTrayContainerHandle, IntPtr.Zero, "TrayNotifyWnd", null);
IntPtr sysPagerHandle = FindWindowEx(systemTrayHandle, IntPtr.Zero, "SysPager", null);
IntPtr notificationAreaHandle = FindWindowEx(sysPagerHandle, IntPtr.Zero, "ToolbarWindow32", "Notification Area");
if (notificationAreaHandle == IntPtr.Zero) {
notificationAreaHandle = FindWindowEx(sysPagerHandle, IntPtr.Zero, "ToolbarWindow32", "User Promoted Notification Area");
IntPtr notifyIconOverflowWindowHandle = FindWindow("NotifyIconOverflowWindow", null);
IntPtr overflowNotificationAreaHandle = FindWindowEx(notifyIconOverflowWindowHandle, IntPtr.Zero, "ToolbarWindow32", "Overflow Notification Area");
RefreshTrayArea(overflowNotificationAreaHandle);
}
RefreshTrayArea(notificationAreaHandle);
}
private static void RefreshTrayArea(IntPtr windowHandle) {
const uint wmMousemove = 0x0200;
RECT rect;
GetClientRect(windowHandle, out rect);
for (var x = 0; x < rect.right; x += 5)
for (var y = 0; y < rect.bottom; y += 5)
SendMessage(windowHandle, wmMousemove, 0, (y << 16) + x);
}
}
"@
Then use [pInvoke]::RefreshTrayArea() to reset
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74723",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Deploying VSTO Project to Server Is it possible to place an application using vsto if the office is not installed? It doesn't appear to be so, but I was wondering if anyone had a work-around.
A: VSTO wraps Office's Automation interfaces. Office is doing the work under the covers, so must be installed.
A: Just to compare with Web Office Extensions, did it also need Office installed on the server?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74728",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Which to use, eruby or erb? What's the difference between eruby and erb? What considerations would drive me to choose one or the other?
My application is generating config files for network devices (routers, load balancers, firewalls, etc.). My plan is to template the config files, using embedded ruby (via either eruby or erb) within the source files to do things like iteratively generate all the interface config blocks for a router (these blocks are all very similar, differing only in a label and an IP address). For example, I might have a config template file like this:
hostname sample-router
<%=
r = String.new;
[
["GigabitEthernet1/1", "10.5.16.1"],
["GigabitEthernet1/2", "10.5.17.1"],
["GigabitEthernet1/3", "10.5.18.1"]
].each { |tuple|
r << "interface #{tuple[0]}\n"
r << " ip address #{tuple[1]} netmask 255.255.255.0\n"
}
r.chomp
%>
logging 10.5.16.26
which, when run through an embedded ruby interpreter (either erb or eruby), produces the following output:
hostname sample-router
interface GigabitEthernet1/1
ip address 10.5.16.1 netmask 255.255.255.0
interface GigabitEthernet1/2
ip address 10.5.17.1 netmask 255.255.255.0
interface GigabitEthernet1/3
ip address 10.5.18.1 netmask 255.255.255.0
logging 10.5.16.26
A: Doesn't really matter, they're both the same. erb is pure ruby, eruby is written in C so it's a bit faster.
erubis (a third one) is pure ruby, and faster than both the ones listed above. But I doubt the speed of that is the bottleneck for you, so just use erb. It's part of Ruby Standard Library.
A: Eruby is an external executable, while erb is a library within Ruby. You would use the former if you wanted independent processing of your template files (e.g. quick-and-dirty PHP replacement), and the latter if you needed to process them within the context of some other Ruby script. It is more common to use ERB simply because it is more flexible, but I'll admit that I have been guilty of dabbling in eruby to execute .rhtml files for quick little utility websites.
A: I'm doing something similar using erb, and the performance is fine for me.
As Jordi said though, it depends what context you want to run this in - if you're literally going to use templates like the one you listed, eruby would probably work better, but I'd guess you're actually going to be passing variables to the template, in which case you want erb.
Just for reference, when using erb you'll need to pass it the binding for the object you want to take variables from, something like this:
device = Device.new
device.add_interface("GigabitEthernet1/1", "10.5.16.1")
device.add_interface("GigabitEthernet1/2", "10.5.17.1")
template = File.read("/path/to/your/template.erb")
config = ERB.new(template).result(device.binding)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74782",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Are there any projects for replacing HTML and the current javascript? Google created protocol buffers as a replacement for the bulky XML method of data transition. Faster XML processing was just not good enough. Most of the web has grown up as a hodge podge of different technologies that have been integrated to work within the browser or to generate html. JavaScript is separate from HTML. Flash and Silverlight are plugged in the mix as well. We can get the job done with the tools we have but can we do better?
Before you mention standards, (which are a good thing to have), think about evolutionary change versus revolutionary change. If Henry Ford asked people about a better way to get around they would have said they wanted a faster horse. (Webkit is a faster horse.)
I am hoping there is a project and I just haven’t read of it.
A: There are all sorts of "replacements", and have been since before the web existed. The problem with talking about a "replacement" for HTML+JS is that the conversation generally starts out of frustration with one or more specific aspects of the current implementations:
*
*"i hate the lack of presentation-specific tags, can we replace it?"
*"i hate the lack of semantic tags, can we replace it?"
*"i hate the CSS box model, can we replace it?"
*"i hate the sub-par printing support, can we replace it?"
*"i hate the hacks required to get glitzy animation, can we replace it?"
*...
Someone wants a faster horse, someone wants a tireless horse, someone wants a stronger horse, someone wants a horse that smells like burning petroleum instead of, uh, horse... Put all the ideas together and you might get a Model-T... or you might get something out of a Jules Verne / steampunk nightmare.
For every revolution that results in something better, there are scores that produce bloodshed followed by more of the same. Be careful what you wish for...
A: HTML+CSS+JS will be replaced by HTML+CSS+SVG+JS, which will be replaced by incrementally more modern versions of the former, sometimes with something new added in the mix. The web technologies of today are very different of the web technologies of 10 years ago. You can expect the landscape will still be different in ten years.
Look where the alpha geeks look. Well, they are all looking at REST designs with lots of Javascript and CSS.
The various "web replacement" technologies promoted by Microsoft, Adobe, Sun, etc. are only here because those companies hope to get people back into lock-in. Pray that they do not succeed.
The web technologies are not be themselve a "hodge-podge". The hodge-podge aspect comes from multiple implementations with their own bugs and quirks. In other words, it comes from open formats implemented in a competitive market.
A: You mentioned two alternatives already: Silverlight and Flash. It's safe to assume that ~95% people have Flash Player installed; Silverlight has also seen quite good adoption in this short amount of time.
But jumping on the eye-candy bandwagon isn't necessarily going to make your site better. There will be issues with accessibility, search engines not being to properly index your content, users not being to bookmark pages they want to get back to. Rich graphics pages, although vector, take more to load and can often turn out just annoying (where the goal was visual appeal, the opposite happened). All these things can be worked around or even fixed, but it takes much more resources compared to using standards.
All these things would apply even if there was some new technology that we "haven't read of".
HTTP is as slow as network connection is, not by poor design. It's actually very efficient. HTML processing is also blazing fast, considering browsers performed well enough for people using them even on sites with terrible, fat table-based markup. JavaScript scene is looking very bright; there is increased attention on the new version of the specs, multiple implementations, incredible speed advantages in modern browsers over the course of last year. And don't think only WebKit is fast -- Opera and Mozilla have never fallen behind.
If you observe what was happening on the Internet in the last 20 years, you would have noticed that proprietary, vendor-dictated technologies eventually got pushed out by open standards. The only reason Flash Player survived was that JavaScript and open video codecs needed some time to get developed. Now that they are here, I think the same thing is going to happen all over again.
A: You might be interested in Sun's Lively.
There will also probably be more tools that compile to HTML+JavaScript, so you won't have to deal with them directly (like GWT.) There are also projects that try compile other languages to work in the browser (like HotRuby).
A: so what you're looking for is a paradigm shift in web technology. it's always tough to imagine how that will look - maybe new tech will become a more immersive experience, incorporating more senses then just sight and sound (touch is a good candidate), as well as something that allows for full-range-motion interaction rather then the 2D 'point and click' mouse interface.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74786",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there a way for my binary to react to some global hotkeys in Linux? Is it possible to listen for a certain hotkey (e.g:Ctrl-I) and then perform a specific action? My application is written in C, will only run on Linux, and it doesn't have a GUI. Are there any libraries that help with this kind of task?
EDIT: as an example, amarok has global shortcuts, so for example if you map a combination of keys to an action (let's say Ctrl-+, Ctrl and +) you could execute that action when you press the keys. If I would map Ctrl-+ to the volume increase action, each time I press ctrl-+ the volume should increase by a certain amount.
Thanks
A: How global do your hotkeys need to be? Is it enough for them to be global for a X session? In that case you should be able to open an Xlib connection and listen for the events you need.
Ordinarily keyboard events in X are delivered to the window that currently has the focus, and propagated up the hierarchy until they are handled. Clearly this is not what we want. We need to process the event before any other window can get to it. We need to call XGrabKey on the root window with the keycode and modifiers of our hotkey to accomplish this.
I found a good example here.
A: I think smoofra is on the right track here; you're looking to register a global hotkey with X so that you can intercept keypresses and take appropriate action. Xlib is probably what you want, and XGrabKey is the function, i think.
It's not easy to learn, I'm afraid; I did locate this example that seems useful: TinyWM. I also found an example using Java/JNI (accessing the same underlying Xlib function).
A: You should look at the source code of xbindkeys.
Xlib programming is pretty arcane, documentation is hard to find, and there are subtle portability issues. You'll be better off copying some battle-hardened code.
A: One way to do it is to have your application listen on a certain port, or socket file, for incoming requests.
Then you can write a small client application that connects to that port or socket file and sends commands to the running application.
Then you can configure your window manager to bind certain key combinations to launch your small client app.
A: In UNIX, your access to a commandline shell is via a terminal. This harks back to the days when folks accessed their big shared computers literally via terminals connected directly to the machines (e.g. by a serial cable).
In fact, the 'xterm' program or whatever derivative you use on your UNIX box is properly referred to as a terminal emulator - it behaves (from both your point of view and that of the operating system) much like one of those old-fashioned terminal machines.
This makes it slightly complicated to handle input in interesting ways, since there are lots of different kinds of terminals, and your UNIX system has to know about the capabilities of each kind. These capabilities were traditionally stored in a termcap file, and I think more modern systems use terminfo instead. Try
man 5 terminfo
on a Linux system for more information.
Now, the good news is that you don't need to do too much messing about with terminal capabilities, etc. to have a commandline application that does interesting things with input or windowing features. There's a library, curses, that will help. Lookup
man 3 ncurses
on your Linux system for more information. You will probably be able to find a decent tutorial on using curses online.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74790",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: What causes a velocity Template.merge() failure? How does one avoid it? Our team has been experiencing a recurring problem with velocity templates. Upon rendering, some throw a RuntimeException with the message "Template.merge() failure - Unable to render Velocity Template, '/template.vm'". We have not been able to reproduce the problem and the documentation on the web is pretty insufficient. The problem is not consistently reproducible - the same templates whose rendering sometimes causes the error also manage to display without problems at other times. The Template class source code is also of little help. Thank you in advance.
Edit: Based on Nathan Bubna's response I need to clarify that we are using Velocity version 1.4.
Edit: Since it was pointed out that a stack trace would be beneficial, here it is:
2008-09-15 11:07:57,336 ERROR velocity - Template.merge() failure. The document is null, most likely due to parsing error.
2008-09-15 11:07:57,336 ERROR VelocityResult - Unable to render Velocity Template, '/search/[template-redacted].vm'
java.lang.Exception: Template.merge() failure. The document is null, most likely due to parsing error.
at org.apache.velocity.Template.merge(Template.java:277)
at com.opensymphony.webwork.dispatcher.VelocityResult.doExecute(VelocityResult.java:91)
at com.opensymphony.webwork.dispatcher.WebWorkResultSupport.execute(WebWorkResultSupport.java:109)
at com.opensymphony.xwork.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:258)
at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:182)
at com.opensymphony.xwork.interceptor.AroundInterceptor.intercept(AroundInterceptor.java:35)
at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:164)
at com.opensymphony.xwork.interceptor.AroundInterceptor.intercept(AroundInterceptor.java:35)
at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:164)
at com.opensymphony.xwork.interceptor.AroundInterceptor.intercept(AroundInterceptor.java:35)
at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:164)
at com.opensymphony.xwork.interceptor.AroundInterceptor.intercept(AroundInterceptor.java:35)
at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:164)
at com.opensymphony.xwork.interceptor.AroundInterceptor.intercept(AroundInterceptor.java:35)
at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:164)
at com.opensymphony.xwork.interceptor.AroundInterceptor.intercept(AroundInterceptor.java:35)
at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:164)
at com.opensymphony.xwork.DefaultActionProxy.execute(DefaultActionProxy.java:116)
at com.opensymphony.webwork.dispatcher.ServletDispatcher.serviceAction(ServletDispatcher.java:272)
at com.opensymphony.webwork.dispatcher.ServletDispatcher.service(ServletDispatcher.java:237)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
at com.opensymphony.module.sitemesh.filter.PageFilter.doFilter(PageFilter.java:39)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
at org.nanocontainer.nanowar.webwork2.PicoObjectFactoryFilter.doFilter(PicoObjectFactoryFilter.java:46)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
at org.nanocontainer.nanowar.ServletRequestContainerFilter.doFilter(ServletRequestContainerFilter.java:44)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
at com.bostoncapital.stuyvesant.RememberUserNameFilter.doFilter(RememberUserNameFilter.java:30)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:214)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:482)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:526)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:825)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:738)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:526)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
at java.lang.Thread.run(Unknown Source)
A: What version of Velocity are you using? There were some race conditions in old versions that caused this. Most were squashed in the Velocity 1.5 release. Though i would personally recommend using Velocity 1.6-beta1. It has vastly improved performance (memory and speed) and a lot of minor bug fixes that didn't make it into 1.5.
Edit: Since you say you are using 1.4, then, yes, i'm sure this is the race condition we fixed. Please consider upgrading. 1.6 is definitely your best bet, as it has the fix for your bug and improved performance. 1.6 final should be out very soon.
A: I am working on the same bug right now, on our website.
It does appear to be a race condition: I can reproduce it consistently using multiple processes fetching the same page, but never reproduce it if I serialize the requests.
I am using velocity-1.5; I tried migrating to 1.6-beta1 but see other errors.
RESOLVED: see comments below
A: Since the comments in the source already state this shouldn't happen, I think it's a bug in the Template software. Submit a bug report to whoever wrote it.
A: You need to get the full stack trace of the RuntimeException and its causes.
Please edit your answer to add that information.
A: I have emailed the authors of the code to see if they can provide some insight. I'll make sure to share anything I've learned.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74818",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: where can I find vim-enhanced resources? I recently installed vim-enhanced , but I can't find any article/tutorial related to it.All I could find is a page that briefly describes it's new features , along with several RPM's to download .
What exactly does it have to offer to scripting languages that regular vi/vim can't ?
Thanks
A: According to this, vim-enhanced is just vim "with the perl, python, tcl, and cscope options compiled in." You should be able to find everything you need to know about these compile options in the documentation.
A: If you're new to vim, then run vimtutor
You may also want to start out by reading :help and learning how to use the help system. In particular :help topic (control-D) and :help topic (more useful if you have :set wildmenu) will help you find topics in vim's built-in help (which is notably superior to trying to Google for things). If all else fails there's also :helpgrep topic and then use the quickfix buffer to see the hits (:cn, :cp, :cl, etc).
The #vim channel on Freenode IRC network is also a good place to get help.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74821",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to run a script as root on Mac OS X? What should I type on the Mac OS X terminal to run a script as root?
A: As in any unix-based environment, you can use the sudo command:
$ sudo script-name
It will ask for your password (your own, not a separate root password).
A: sudo ./scriptname
A: In order for sudo to work the way everyone suggest, you need to be in the admin group.
A: Or you can access root terminal by typing sudo -s
A: sudo ./scriptname
sudo bash will basically switch you over to running a shell as root, although it's probably best to stay as su as little as possible.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74829",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "39"
} |
Q: Bash or KornShell (ksh)? I am not new to *nix, however lately I have been spending a lot of time at the prompt. My question is what are the advantages of using KornShell (ksh) or Bash Shell? Where are the pitfalls of using one over the other?
Looking to understand from the perspective of a user, rather than purely scripting.
A: This is a bit of a Unix vs Linux battle. Most if not all Linux distributions have bash installed and ksh optional. Most Unix systems, like Solaris, AIX and HPUX have ksh as default.
Personally I always use ksh, I love the vi completion and I pretty much use Solaris for everything.
A: For scripts, I always use ksh because it smooths over gotchas.
But I find bash more comfortable for interactive use. For me the emacs key bindings and tab completion are the main benefits. But that's mostly force of habit, not any technical issue with ksh.
A: I don't have experience with ksh, but I have used both bash and zsh. I prefer zsh over bash because of its support for very powerful file globbing, variable expansion modifiers, and faster tab completion.
Here's a quick intro: http://friedcpu.wordpress.com/2007/07/24/zsh-the-last-shell-youll-ever-need/
A: Bash.
The various UNIX and Linux implementations have various different source level implementations of ksh, some of which are real ksh, some of which are pdksh implementations and some of which are just symlinks to some other shell that has a "ksh" personality. This can lead to weird differences in execution behavior.
At least with bash you can be sure that it's a single code base, and all you need worry about is what (usually minimum) version of bash is installed. Having done a lot of scripting on pretty much every modern (and not-so-modern) UNIX, programming to bash is more reliably consistent in my experience.
A: For one thing, bash has tab completion. This alone is enough to make me prefer it over ksh.
Z shell has a good combination of ksh's unique features with the nice things that bash provides, plus a lot more stuff on top of that.
A: I'm a korn-shell veteran, so know that I speak from that perspective.
However, I have been comfortable with Bourne shell, ksh88, and ksh93, and for the most I know which features are supported in which. (I should skip ksh88 here, as it's not widely distributed anymore.)
For interactive use, take whatever fits your need. Experiment. I like being able to use the same shell for interactive use and for programming.
I went from ksh88 on SVR2 to tcsh, to ksh88sun (which added significant internationalisation support) and ksh93. I tried bash, and hated it because
it flattened my history. Then I discovered shopt -s lithist and all was well.
(The lithist option assures that newlines are preserved in your command
history.)
For shell programming, I'd seriously recommend ksh93 if you want a consistent programming language, good POSIX conformance, and good performance, as many common unix commands can be available as builtin functions.
If you want portability use at least both. And make sure you have a good test suite.
There are many subtle differences between shells. Consider for example reading from a pipe:
b=42 && echo one two three four |
read a b junk && echo $b
This will produce different results in different shells. The korn-shell runs pipelines from back to front; the last element in the pipeline runs in the current process. Bash did not support this useful behaviour until v4.x, and even then, it's not the default.
Another example illustrating consistency: The echo command itself, which was made obsolete by the split between BSD and SYSV unix, and each introduced their own convention for not printing newlines (and other behaviour). The result of this can still be seen in many 'configure' scripts.
Ksh took a radical approach to that - and introduced the print command, which actually supports both methods (the -n option from BSD, and the trailing \c special character from SYSV)
However, for serious systems programming I'd recommend something other than a shell, like python, perl. Or take it a step further, and use a platform like puppet - which allows you to watch and correct the state of whole clusters of systems, with good auditing.
Shell programming is like swimming in uncharted waters, or worse.
Programming in any language requires familiarity with its syntax, its interfaces and behaviour. Shell programming isn't any different.
A: @foxxtrot
Actually, the standard shell is Bourne shell (sh). /bin/sh on Linux is actually bash, but if you're aiming for cross-platform scripts, you're better off sticking to features of the original Bourne shell or writing it in something like perl.
A: My answer would be 'pick one and learn how to use it'. They're both decent shells; bash probably has more bells and whistles, but they both have the basic features you'll want. bash is more universally available these days. If you're using Linux all the time, just stick with it.
If you're programming, trying to stick to plain 'sh' for portability is good practice, but then with bash available so widely these days that bit of advice is probably a bit old-fashioned.
Learn how to use completion and your shell history; read the manpage occasionally and try to learn a few new things.
A: Available in most UNIX system, ksh is standard-comliant, clearly designed, well-rounded.
I think books,helps in ksh is enough and clear, especially the O'Reilly book.
Bash is a mass. I keep it as root login shell for Linux at home only.
For interactive use, I prefer zsh on Linux/UNIX. I run scripts in zsh, but I'll test most of my scripts, functions in AIX ksh though.
A: The difference between Kornshell and Bash are minimal. There are certain advantages one has over the other, but the differences are tiny:
*
*BASH is much easier to set a prompt that displays the current directory. To do the same in Kornshell is hackish.
*Kornshell has associative arrays and BASH doesn't. Now, the last time I used Associative arrays was... Let me think... Never.
*Kornshell handles loop syntax a bit better. You can usually set a value in a Kornshell loop and have it available after the loop.
*Bash handles getting exit codes from pipes in a cleaner way.
*Kornshell has the print command which is way better than the echo command.
*Bash has tab completions. In older versions
*Kornshell has the r history command that allows me to quickly rerun older commands.
*Kornshell has the syntax cd old new which replaces old with new in your directory and CDs over there. It's convenient when you have are in a directory called /foo/bar/barfoo/one/bar/bar/foo/bar and you need to cd to /foo/bar/barfoo/two/bar/bar/foo/bar In Kornshell, you can simply do cd one two and be done with it. In BASH, you'd have to cd ../../../../../two/bar/bar/foo/bar.
I'm an old Kornshell guy because I learned Unix in the 1990s, and that was the shell of choice back then. I can use Bash, but I get frustrated by it at times because in habit I use some minor feature that Kornshell has that BASH doesn't and it doesn't work. So, whenever possible, I set Kornshell as my default.
However, I am going to tell you to learn BASH. Bash is now implemented on most Unix systems as well as on Linux, and there are simply more resources available for learning BASH and getting help than Kornshell. If you need to do something exotic in BASH, you can go on Stackoverflow, post your question, and you'll get a dozen answers in a few minutes -- and some of them will even be correct!.
If you have a Kornshell question and post it on Stackoverflow, you'll have to wait for some old past their prime hacker like me wake up from his nap before you get an answer. And, forget getting any response if they're serving pudding up in the old age home that day.
BASH is simply the shell of choice now, so if you've got to learn something, might as well go with what is popular.
A: Bash is the standard for Linux.
My experience is that it is easier to find help for bash than for ksh or csh.
A: Bash is the benchmark, but that's mostly because you can be reasonably sure it's installed on every *nix out there. If you're planning to distribute the scripts, use Bash.
I can not really address the actual programming differences between the shells, unfortunately.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74844",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "69"
} |
Q: What is the recommended error_reporting() setting for development? What about E_STRICT? Typically I use E_ALL to see anything that PHP might say about my code to try and improve it.
I just noticed a error constant E_STRICT, but have never used or heard about it, is this a good setting to use for development? The manual says:
Run-time notices. Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code.
So I'm wondering if I'm using the best error_reporting level with E_ALL or would that along with E_STRICT be the best? Or is there any other combination I've yet to learn?
A: In my opinion, the higher you set the error reporting level in development phase, the better.
In a live environment, you want a slightly (but only slightly) reduced set, but you want them logged somewhere that they can't be seen by the user (I prefer syslog).
http://php.net/error_reporting
E_ALL | E_STRICT for development with PHP before 5.2.0.
5.2 introduces E_RECOVERABLE_ERROR and 5.3 introduces E_DEPRECATED and E_USER_DEPRECATED. You'll probably want to turn those on if you're running one of those versions.
If you wanted to use magic numbers you could just set the error_reporting value to some fairly high value of 2^n-1 - say, 16777215, and that would really just turn on all the bits between 1..n. But I don't think using magic numbers is a good idea...
In my opinion, PHP has dropped the ball a bit by having E_ALL not really be all. But apparently it's going to be fixed in PHP 6...
A: In PHP 5, the things covered by E_STRICT are not covered by E_ALL, so to get the most information, you need to combine them:
error_reporting(E_ALL | E_STRICT);
In PHP 5.4, E_STRICT will be included in E_ALL, so you can use just E_ALL.
You can also use
error_reporting(-1);
which will always enable all errors. Which is more semantically correct as:
error_reporting(~0);
A: In newer PHP versions, E_ALL includes more classes of errors. Since PHP 5.3, E_ALL includes everything except E_STRICT. In PHP 6 it will alledgedly include even that. This is a good hint: it's better to see more error messages rather than less.
What's included in E_ALL is documented in the PHP predefined constants page in the online manual.
Personally, I think it doesn't matter all that much if you use E_STRICT. It certainly won't hurt you, especially since it may prevent you from writing scripts that have a small chance of getting broken in future versions of PHP. On the other hand, in some cases strict messages may be too noisy, perhaps especially if you're in a hurry. I suggest that you turn it on by default and turn it off when it gets annoying.
A: You may use error_reporting = -1
It will always consist of all bits (even if they are not in E_ALL)
A: Use the following in php.ini:
error_reporting = E_ALL | E_STRICT
Also you should install Xdebug, it can highlight your errors in blinding bright colors and print useful detailed information.
Never let any error or notice in your code, even if it's harmless.
A: Depending on your long term support plans for this code, debugging with E_STRICT enabled may help your code to continue working in the distant future, but it is probably overkill for day-to-day use. There are two important things about E_STRICT to keep in mind:
*
*Per the manual, most E_STRICT errors are generated at compile time, not runtime. If you are increasing the error level to E_ALL within your code (and not via php.ini), you may never see E_STRICT errors anyway.
*E_STRICT is contained within E_ALL under PHP 6, but not under PHP 5. If you upgrade your server to PHP6, and have E_ALL configured as described in #1 above, you will begin to see E_STRICT errors without requiring any additional changes on your part.
A: Not strictly speaking of error_reporting, I'd strongly suggest using any IDE that automatically shows parsing errors and common glitches (eg, assignment in condition).
Zend Studio for Eclipse has this feature enabled by default, and since I started using it, it has been helping me a lot at catching errors before they occur.
For example, I had this piece of code where I was caching some data in the $GLOBALS variable, but I inadvertently wrote $_GLOBALS instead. The data never got cached up, and I'd never knew if Zend didn't tell me: "Hey, this $_GLOBALS thingy appears only once, that might be an error".
A: ini_set("display_errors","2");
ERROR_REPORTING(E_ALL);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74847",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "29"
} |
Q: How can I cause subversion to check out projects from other repositories? I recently was working with a subversion project that checked out code not only from the repository I was working with, but also from a separate repository on a different server.
How can I configure my repository to do this?
I'm using the subversion client version 1.3.2 on Linux, and I also have access to TortoiseSVN version 1.4.8 (built on svn version 1.4.6) in Windows.
A: Try svn:externals
http://svnbook.red-bean.com/en/1.0/ch07s03.html
A: I think you should take a look at the svn:externals property
A: Search for the svn:externals property in the documentation.
A: See svn:externals:
Sometimes it is useful to construct a working copy that is made out of a number of different checkouts. For example, you may want different subdirectories to come from different locations in a repository, or perhaps from different repositories altogether. You could certainly setup such a scenario by hand—using svn checkout to create the sort of nested working copy structure you are trying to achieve. But if this layout is important for everyone who uses your repository, every other user will need to perform the same checkout operations that you did.
Fortunately, Subversion provides support for externals definitions. An externals definition is a mapping of a local directory to the URL—and possibly a particular revision—of a versioned resource. In Subversion, you declare externals definitions in groups using the svn:externals property. You can create or modify this property using svn propset or svn propedit (see the section called “Why Properties?”). It can be set on any versioned directory, and its value is a multi-line table of subdirectories (relative to the versioned directory on which the property is set) and fully qualified, absolute Subversion repository URLs...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74865",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Any tools to generate an XSD schema from an XML instance document? I am looking for a tool which will take an XML instance document and output a corresponding XSD schema.
I certainly recognize that the generated XSD schema will be limited when compared to creating a schema by hand (it probably won't handle optional or repeating elements, or data constraints), but it could at least serve as a quick starting point.
A: If all you want is XSD, LiquidXML has a free version that does XSDs, and its got a GUI to it so you can tweak the XSD if you like. Anyways nowadays I write my own XSDs by hand, but its all thanks to this app.
http://www.liquid-technologies.com/
A: the Microsoft XSD inference tool is a good, free solution. Many XML editing tools, such as XmlSpy (mentioned by @Garth Gilmour) or OxygenXML Editor also have that feature. They're rather expensive, though. BizTalk Server also has an XSD inferring tool as well.
edit: I just discovered the .net XmlSchemaInference class, so if you're using .net you should consider that
A: You can use an open source and cross-platform option: inst2xsd from Apache's XMLBeans. I find it very useful and easy.
Just download, unzip and play (it requires Java).
A: Trang is the best option here. Open source and cross platform (although Java is required)
From the Trang Website:
Trang converts between different schema languages for XML. It supports the following languages
*
*RELAX NG (XML syntax)
*RELAX NG compact syntax
*XML 1.0 DTDs
*W3C XML Schema
A schema written in any of the supported schema languages can be converted into any of the other supported schema languages, except that W3C XML Schema is supported for output only, not for input.
Trang can also infer a schema from one or more example XML documents.
Download Link
A: if you are working in the java world - intelliJ idea has also extensive xml support, including xsd generation and samle xml from xsd generation, and with plugins you can get xslt debuggers. - especially nice if you plan to use tools such as jaxb afterwards.
A: Altova XmlSpy does this well - you can find an overview here
A: This is an old thread but I thought it could be useful to post this link: just found this tool:
xsd-gen Generate XML Schema from XML
and it just did what I needed.
A: In VS2010 if you load an XML file into the editor, click the XML menu >> Create Schema.
A: There also is XML schema learner which is available on Github.
It can take multiple xml files and extract a common XSD from all of those files.
A: If you have .Net installed, a tool to generate XSD schemas and classes is already included by default.
For me, the XSD tool is installed under the following structure. This may differ depending on your installation directory.
C:\Program Files\Microsoft Visual Studio 8\VC>xsd
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 2.0.50727.42]
Copyright (C) Microsoft Corporation. All rights reserved.
xsd.exe -
Utility to generate schema or class files from given source.
xsd.exe <schema>.xsd /classes|dataset [/e:] [/l:] [/n:] [/o:] [/s] [/uri:]
xsd.exe <assembly>.dll|.exe [/outputdir:] [/type: [...]]
xsd.exe <instance>.xml [/outputdir:]
xsd.exe <schema>.xdr [/outputdir:]
Normally the classes and schemas that this tool generates work rather well, especially if you're going to be consuming them in a .Net language
I typically take the XML document that I'm after, push it through the XSD tool with the /o:<your path> flag to generate a schema (xsd) and then push the xsd file back through the tool using the /classes /L:VB (or CS) /o:<your path> flags to get classes that I can import and use in my day to day .Net projects
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74879",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "151"
} |
Q: Delegating a task in and getting notified when it completes (in C#) Conceptually, I would like to accomplish the following but have had trouble understand how to code it properly in C#:
SomeMethod { // Member of AClass{}
DoSomething;
Start WorkerMethod() from BClass in another thread;
DoSomethingElse;
}
Then, when WorkerMethod() is complete, run this:
void SomeOtherMethod() // Also member of AClass{}
{ ... }
Can anyone please give an example of that?
A: In .Net 2 the BackgroundWorker was introduced, this makes running async operations really easy:
BackgroundWorker bw = new BackgroundWorker { WorkerReportsProgress = true };
bw.DoWork += (sender, e) =>
{
//what happens here must not touch the form
//as it's in a different thread
};
bw.ProgressChanged += ( sender, e ) =>
{
//update progress bars here
};
bw.RunWorkerCompleted += (sender, e) =>
{
//now you're back in the UI thread you can update the form
//remember to dispose of bw now
};
worker.RunWorkerAsync();
In .Net 1 you have to use threads.
A: You have to use AsyncCallBacks. You can use AsyncCallBacks to specify a delegate to a method, and then specify CallBack Methods that get called once the execution of the target method completes.
Here is a small Example, run and see it for yourself.
class Program
{
public delegate void AsyncMethodCaller();
public static void WorkerMethod()
{
Console.WriteLine("I am the first method that is called.");
Thread.Sleep(5000);
Console.WriteLine("Exiting from WorkerMethod.");
}
public static void SomeOtherMethod(IAsyncResult result)
{
Console.WriteLine("I am called after the Worker Method completes.");
}
static void Main(string[] args)
{
AsyncMethodCaller asyncCaller = new AsyncMethodCaller(WorkerMethod);
AsyncCallback callBack = new AsyncCallback(SomeOtherMethod);
IAsyncResult result = asyncCaller.BeginInvoke(callBack, null);
Console.WriteLine("Worker method has been called.");
Console.WriteLine("Waiting for all invocations to complete.");
Console.Read();
}
}
A: Although there are several possibilities here, I would use a delegate, asynchronously called using BeginInvoke method.
Warning : don't forget to always call EndInvoke on the IAsyncResult to avoid eventual memory leaks, as described in this article.
A: The BackgroundWorker class was added to .NET 2.0 for this exact purpose.
In a nutshell you do:
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += delegate { myBClass.DoHardWork(); }
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(SomeOtherMethod);
worker.RunWorkerAsync();
You can also add fancy stuff like cancellation and progress reporting if you want :)
A: Check out BackgroundWorker.
A: Use Async Delegates:
// Method that does the real work
public int SomeMethod(int someInput)
{
Thread.Sleep(20);
Console.WriteLine(”Processed input : {0}”,someInput);
return someInput+1;
}
// Method that will be called after work is complete
public void EndSomeOtherMethod(IAsyncResult result)
{
SomeMethodDelegate myDelegate = result.AsyncState as SomeMethodDelegate;
// obtain the result
int resultVal = myDelegate.EndInvoke(result);
Console.WriteLine(”Returned output : {0}”,resultVal);
}
// Define a delegate
delegate int SomeMethodDelegate(int someInput);
SomeMethodDelegate someMethodDelegate = SomeMethod;
// Call the method that does the real work
// Give the method name that must be called once the work is completed.
someMethodDelegate.BeginInvoke(10, // Input parameter to SomeMethod()
EndSomeOtherMethod, // Callback Method
someMethodDelegate); // AsyncState
A: Ok, I'm unsure of how you want to go about this. From your example, it looks like WorkerMethod does not create its own thread to execute under, but you want to call that method on another thread.
In that case, create a short worker method that calls WorkerMethod then calls SomeOtherMethod, and queue that method up on another thread. Then when WorkerMethod completes, SomeOtherMethod is called. For example:
public class AClass
{
public void SomeMethod()
{
DoSomething();
ThreadPool.QueueUserWorkItem(delegate(object state)
{
BClass.WorkerMethod();
SomeOtherMethod();
});
DoSomethingElse();
}
private void SomeOtherMethod()
{
// handle the fact that WorkerMethod has completed.
// Note that this is called on the Worker Thread, not
// the main thread.
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74880",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How do I compile mod_dontdothat on Windows I cannot seem to compile mod_dontdothat on Windows. Has anybody managed to achieve this?
Edit:
I've tried compiling the file according to the readme on the site and I've tried to add extra libs to reduce the link errors. Ive got the following installed:
*
*Apache 2.2.9
*Visual Studio 2008
*ActivePerl
*apxs-win32 from ApacheLounge
*Subversion libs and headers
I run the following command line:
C:\Program Files\Apache Software Foundation\Apache2.2\bin>apxs -c -I ..\include\
svn_config.h -L ..\lib -L C:\Progra~1\Micros~1.0\VC\lib -l apr-1.lib -l aprutil-
1.lib -l svn_subr-1.lib -l libapr-1.lib -l libaprutil-1.lib -l libhttpd.lib -l l
ibsvn_subr-1.lib -l mod_dav.lib mod_dontdothat.c
Then I get the following errors:
cl /nologo /MD /W3 /O2 /D WIN32 /D _WINDOWS /D NDEBUG -I"C:\PROGRA~1\APACHE~
1\Apache2.2\include" /I"..\include\svn_config.h" /c /Fomod_dontdothat.lo mod_d
ontdothat.c
mod_dontdothat.c
link kernel32.lib /nologo /subsystem:windows /dll /machine:I386 /libpath:"C:\PRO
GRA~1\APACHE~1\Apache2.2\lib" /out:mod_dontdothat.so /libpath:"..\lib" /libpat
h:"C:\Progra~1\Micros~1.0\VC\lib" apr-1.lib aprutil-1.lib svn_subr-1.lib libapr
-1.lib libaprutil-1.lib libhttpd.lib libsvn_subr-1.lib mod_dav.lib mod_dontdot
hat.lo
Creating library mod_dontdothat.lib and object mod_dontdothat.exp
mod_dontdothat.lo : error LNK2019: unresolved external symbol _dav_svn_split_uri
@32 referenced in function _is_this_legal
svn_subr-1.lib(io.obj) : error LNK2001: unresolved external symbol __imp__libint
l_dgettext
svn_subr-1.lib(subst.obj) : error LNK2001: unresolved external symbol __imp__lib
intl_dgettext
svn_subr-1.lib(config_auth.obj) : error LNK2001: unresolved external symbol __im
p__libintl_dgettext
svn_subr-1.lib(time.obj) : error LNK2001: unresolved external symbol __imp__libi
ntl_dgettext
svn_subr-1.lib(nls.obj) : error LNK2001: unresolved external symbol __imp__libin
tl_dgettext
svn_subr-1.lib(dso.obj) : error LNK2001: unresolved external symbol __imp__libin
tl_dgettext
svn_subr-1.lib(path.obj) : error LNK2001: unresolved external symbol __imp__libi
ntl_dgettext
svn_subr-1.lib(prompt.obj) : error LNK2001: unresolved external symbol __imp__li
bintl_dgettext
svn_subr-1.lib(error.obj) : error LNK2019: unresolved external symbol __imp__lib
intl_dgettext referenced in function _print_error
svn_subr-1.lib(config.obj) : error LNK2001: unresolved external symbol __imp__li
bintl_dgettext
svn_subr-1.lib(utf.obj) : error LNK2001: unresolved external symbol __imp__libin
tl_dgettext
svn_subr-1.lib(cmdline.obj) : error LNK2001: unresolved external symbol __imp__l
ibintl_dgettext
svn_subr-1.lib(utf.obj) : error LNK2019: unresolved external symbol __imp__libin
tl_sprintf referenced in function _fuzzy_escape
svn_subr-1.lib(path.obj) : error LNK2001: unresolved external symbol __imp__libi
ntl_sprintf
svn_subr-1.lib(cmdline.obj) : error LNK2019: unresolved external symbol __imp__l
ibintl_fprintf referenced in function _svn_cmdline_init
svn_subr-1.lib(config_win.obj) : error LNK2019: unresolved external symbol __imp
__SHGetFolderPathA@20 referenced in function _svn_config__win_config_path
svn_subr-1.lib(config_win.obj) : error LNK2019: unresolved external symbol __imp
__SHGetFolderPathW@20 referenced in function _svn_config__win_config_path
svn_subr-1.lib(config_win.obj) : error LNK2019: unresolved external symbol __imp
__RegCloseKey@4 referenced in function _svn_config__parse_registry
svn_subr-1.lib(config_win.obj) : error LNK2019: unresolved external symbol __imp
__RegEnumKeyExA@32 referenced in function _svn_config__parse_registry
svn_subr-1.lib(config_win.obj) : error LNK2019: unresolved external symbol __imp
__RegOpenKeyExA@20 referenced in function _svn_config__parse_registry
svn_subr-1.lib(config_win.obj) : error LNK2019: unresolved external symbol __imp
__RegQueryValueExA@24 referenced in function _parse_section
svn_subr-1.lib(config_win.obj) : error LNK2019: unresolved external symbol __imp
__RegEnumValueA@32 referenced in function _parse_section
svn_subr-1.lib(win32_xlate.obj) : error LNK2019: unresolved external symbol __im
p__CoUninitialize@0 referenced in function _svn_subr__win32_xlate_open
svn_subr-1.lib(win32_xlate.obj) : error LNK2019: unresolved external symbol __im
p__CoInitializeEx@8 referenced in function _svn_subr__win32_xlate_open
svn_subr-1.lib(win32_xlate.obj) : error LNK2019: unresolved external symbol __im
p__CoCreateInstance@20 referenced in function _get_page_id_from_name
svn_subr-1.lib(nls.obj) : error LNK2019: unresolved external symbol __imp__libin
tl_bindtextdomain referenced in function _svn_nls_init
svn_subr-1.lib(stream.obj) : error LNK2019: unresolved external symbol _inflate
referenced in function _read_handler_gz
svn_subr-1.lib(stream.obj) : error LNK2019: unresolved external symbol _inflateI
nit_ referenced in function _read_handler_gz
svn_subr-1.lib(stream.obj) : error LNK2019: unresolved external symbol _deflate
referenced in function _write_handler_gz
svn_subr-1.lib(stream.obj) : error LNK2019: unresolved external symbol _deflateI
nit_ referenced in function _write_handler_gz
svn_subr-1.lib(stream.obj) : error LNK2019: unresolved external symbol _deflateE
nd referenced in function _close_handler_gz
svn_subr-1.lib(stream.obj) : error LNK2019: unresolved external symbol _inflateE
nd referenced in function _close_handler_gz
mod_dontdothat.so : fatal error LNK1120: 21 unresolved externals
apxs:Error: Command failed with rc=6291456
.
I'm not too much of a C guru, so any help in finding these unresolved external symbols will be much appreciated!
A: I managed to compile the module. Prerequisites:
*
*Apache 2.2.11
*apxs-win32 from www.apachelounge.com
*Visual Studio 2005
*Active Perl 5.8.8 (you need perl for apxs-win32 installation)
Here is a step-by-step guide.
Download these packages:
*
*http://subversion.tigris.org/files/documents/15/44595/svn-win32-1.5.5_dev.zip (we need the libraries and header files from this package)
*http://subversion.tigris.org/downloads/subversion-1.5.5.zip (we will be using the mod_dav_svn sources to compile a static lib)
Unpack the dev package to c:\temp\svn and the other package to c:\temp\svn-src and the mod_dontdothat files to C:\Temp\dontdothat.
One of the dependencies of mod_dontdothat module is mod_dav_svn module. Unfortunately you'll find the mod_dav_svn binary only as a shared library (DLL). You cannot link against
a DLL. So the first step is to build a static mod_dav_svn library:
cd C:\Temp\svn-src\subversion\mod_dav_svn
apxs -c -I ..\include -L C:\Temp\svn\lib -l libsvn_delta-1.lib -l libsvn_diff-1.lib -l libsvn_fs-1.lib -l libsvn_fs_base-1.lib -l libsvn_fs_fs-1.lib -l libsvn_fs_util-1.lib -l libsvn_repos-1.lib -l libsvn_subr-1.lib -l libapr-1.lib -l libaprutil-1.lib -l libhttpd.lib -l mod_dav.lib -l xml.lib -n mod_dav_svn mod_dav_svn.c activity.c authz.c deadprops.c liveprops.c lock.c merge.c mirror.c repos.c util.c version.c reports\dated-rev.c reports\file-revs.c reports\get-locations.c reports\get-location-segments.c reports\get-locks.c reports\log.c reports\mergeinfo.c reports\replay.c reports\update.c
The apxs call will print the commands it executes. The last command is a link call which builds the DLL. Copy it replace "link" by "lib", remove the "/dll" param, and change the "out" param file name to "libmod_dav_svn.lib". You should get something similar to:
lib kernel32.lib /nologo /subsystem:windows /machine:I386 /libpath:"C:\PROGRA~1\APACHE~1\Apache2.2\lib" /out:libmod_dav_svn.lib /libpath:"C:\Temp\svn\lib" libsvn_delta-1.lib libsvn_diff-1.lib libsvn_fs-1.lib libsvn_fs_base-1.lib libsvn_fs_fs-1.lib libsvn_fs_util-1.lib libsvn_repos-1.lib libsvn_subr-1.lib libapr-1.lib libaprutil-1.lib libhttpd.lib mod_dav.lib xml.lib reports\update.lo reports\replay.lo reports\mergeinfo.lo reports\log.lo reports\get-locks.lo reports\get-location-segments.lo reports\get-locations.lo reports\file-revs.lo reports\dated-rev.lo version.lo util.lo repos.lo mirror.lo merge.lo lock.lo liveprops.lo deadprops.lo authz.lo activity.lo mod_dav_svn.lo
You will get some link warnings. You can ignore them. Copy the libmod_dav_svn.lib to the mod_dontdothat directory. Now start the compilation process for mod_dontdothat:
C:\Temp\dontdothat
apxs -c -I C:\Temp\svn\include -L C:\Temp\svn\lib -l libsvn_subr-1.lib -l libapr-1.lib -l libaprutil-1.lib -l libhttpd.lib -l mod_dav.lib -l xml.lib -l libmod_dav_svn.lib mod_dontdothat.c
apxs -i -n dontdothat mod_dontdothat.so
This should do the trick.
A: Googling around I've got
*
*mod_dav_svn.lib for _dav_svn_split_uri
*intl3_svn.lib for all things _libintl
*shell32.lib for SHGetFolderPath
*advapi32.lib for Registry stuff
*ole32.lib for CoInitialize and it's ilk
*inflate and deflate smell like zlib1.lib or something like that
Hope that helps.
A: Thanks for revising the question.
It looks like a definite linker issue. I see that the first undefined symbol is related to webdav. Are you sure you have that library in the right place? I see you give a nice long path with lots of svn libs, maybe it's possible you overlooked just one?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74883",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How can I create a command line (unix/linux) instruction that uses variables to execute numerous commands? I need to rearrange some content in various directories but it's a bit of a pain. In order to debug the application I'm working on (a ruby app) I need to move my gems into my gem folder one at a time (long story; nutshell: one is broken and I can't figure out which one).
So I need to do something like:
sudo mv backup/gem/foo gem/
sudo mv backup/doc/foo doc/
sudo mv backup/specification/foo.gemspec specification/
replacing "foo" each time. How can I author a simple shell script to let me do something like: gemMove("foo") and it fill in the blanks for me?
A: Put the following into a file named gemmove:
#!/bin/bash
if [ "x$1" == x ]; then
echo "Must have an arg"
exit 1
fi
for d in gem doc specification ; do
mv "backup/$d/$1" "$d"
done
then do
chmod a+x gemmove
and then call sudo /path/to/gemmove foo to move the foo gem from the backup dirs into the real ones
A: You could simply use the bash shell arguments, like this:
#!/bin/bash
# This is move.sh
mv backup/gem/$1 gem/
mv backup/doc/$1 doc/
# ...
and then execute it as:
sudo ./move.sh foo
Be sure make the script executable, with
chmod +x move.sh
A: in bash, something like:
function gemMove()
{
filename=$1
mv backup/gem/$filename gem/$filename
mv backup/doc/$filename doc/$filename
mv backup/specification/$filename.spec specification
}
then you can just call gemMove("foo") elsewhere in the script.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74886",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there a quality, file-size, or other benefit to JPEG sizes being multiples of 8px or 16px? The JPEG compression encoding process splits a given image into blocks of 8x8 pixels, working with these blocks in future lossy and lossless compressions. [source]
It is also mentioned that if the image is a multiple 1MCU block (defined as a Minimum Coded Unit, 'usually 16 pixels in both directions') that lossless alterations to a JPEG can be performed. [source]
I am working with product images and would like to know both if, and how much benefit can be derived from using multiples of 16 in my final image size (say, using an image with size 480px by 360px) vs. a non-multiple of 16 (such as 484x362). In this example I am not interested in further alterations, editing, or recompression of the final image.
To try to get closer to a specific answer where I know there must be largely generalities: Given a 480x360 image that is 64k and saved at maximum quality in Photoshop [example]:
*
*Can I expect any quality loss from an image that is 484x362
*What amount of file size addition can I expect (for this example, the additional space would be white pixels)
*Are there any other disadvantages to growing larger than the 8px grid?
I know it's arbitrary to use that specific example, but it would still be helpful (for me and potentially any others pondering an image size) to understand what level of compromise I'd be dealing with in breaking the non-8px grid.
The key issue here is a debate I've had is whether 8-pixel divisible images are higher quality than images that are not divisible by 8-pixels.
A: Sometimes you need to use 16 pixel boundaries rather than 8 because of subsampling; every 2nd pixel is thrown away during the encoding process, and those 8x8 DCT blocks started out as 16x16 and will decode back to 16x16. This won't be a problem at the highest quality settings.
A: A JPG with sizes being multiplies of 8 can also be rotated/flipped with no quality loss. For example gthumb can do this on Linux.
A: 8 pixels is the cutoff. The reason is because JPEG images are simply an array of 8x8 DCT blocks; if the image resolution isn't mod8 in both directions, the encoder has to pad the sides up to the next mod8 resolution. This in practice is not very expensive bit-wise; what's much worse are the cases when an image has sharp black lines (such as a letterboxed image) that don't lie on block boundaries. This is especially problematic in video encoding. The reason for this being a problem is that the frequency transform of a sharp line is a Gaussian distribution of coefficients--resulting in an enormous number of bits to code.
For those curious, the most common method of padding edges in intra compression (such as JPEG images) is to mirror the lines of pixels before the edge. For example, if you need to pad three lines and line X is the edge, line X+1 is equal to line X, line X+2 is equal to line X-1, and line X+3 is equal to line X-2. This quite effectively minimizes the cost in transform coefficients of the extra lines.
In inter coding, however, the padding algorithms generally simply duplicate the last line, because the mirror method does not work well for inter compression, such as in video compression.
A: The image dimensions being multiples of 8 or 16 is not going to affect the size on disk very much, but you can get dramatic savings if you can line up the visual contents to the 8x8 pixel grid, such as if there is a repeating pattern or texture in the image.
A: What Tometzky said. If you don't have the correct multiple, the lossless flip and rotate algorithms don't work. That's because the padding on the right/bottom that can be safely ignored now ends up on the left/top, where it can't.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74892",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Uninstall Mono from Mac OS X v10.5 Leopard I installed Mono on my iMac last night and I immidiately had a change of heart! I don't think Mono is ready for prime time.
The Mono website says to run the following script to uninstall:
#!/bin/sh -x
#This script removes Mono from an OS X System. It must be run as root
rm -r /Library/Frameworks/Mono.framework
rm -r /Library/Receipts/MonoFramework-SVN.pkg
cd /usr/bin
for i in `ls -al | grep Mono | awk '{print $9}'`; do
rm ${i}
done
Has anyone had to uninstall Mono? Was it as straight forward as running the above script or do I have to do more? How messy was it? Any pointers are appreciated.
A: Seems the uninstall script has been slightly modified as today (2011-07-12):
#!/bin/sh -x
#This script removes Mono from an OS X System. It must be run as root
rm -r /Library/Frameworks/Mono.framework
rm -r /Library/Receipts/MonoFramework-*
for dir in /usr/bin /usr/share/man/man1 /usr/share/man/man3 /usr/share/man/man5; do
(cd ${dir};
for i in `ls -al | grep /Library/Frameworks/Mono.framework/ | awk '{print $9}'`; do
rm ${i}
done);
done
You can find the current version here.
By the way: it's the same exact thing that runs the uninstaller mentioned by joev (although as jochem noted it is not located in the /Library/Receipts, it must be found in the installation package=.
A: To expand on feelingsofwhite.com's answer, the Mono installer for Mac OS puts the uninstall script in the /Library/Receipts directory, not in the installer image as it says in the Notes.rtf file. The Receipts directory is what the Mac OS Installer.app uses to keep track of which packages were responsible for installing which files. Usually, a list of these is kept in a .bom ("Bill of Materials") file, which can be explored with the lsbom command.
In the case of Mono, they also add a whole bunch of links from your /usr/bin and man directories. Their uninstall scripts finds these and removes them. Since the uninstall script lives in a place the uninstaller deletes, you should probably copy the uninstall script somewhere else before running it:
cd
cp /Library/Receipts/MonoFramework-2.4_7.macos10.novell.universal.pkg/Contents/Resources/uninstallMono.sh .
sudo ./uninstallMono.sh
rm uninstallMono.sh
A: The above script simply deletes everything related to Mono on your system -- and since the developers wrote it, I'm sure they didn't miss anything :) Unlike some other operating systems made by software companies that rhyme with "Macrosoft", uninstalling software in OS X is as simple as deleting the files, 99% of the time.. no registry or anything like that.
So, long story short, yes, that script is probably the only thing you need to do.
A: Year 2017 answer for those, like myself, looking at SE first and official docs later (FYI I know the question was for OS Leopard). Run these commands in the terminal:
sudo rm -rf /Library/Frameworks/Mono.framework
sudo pkgutil --forget com.xamarin.mono-MDK.pkg
sudo rm -rf /etc/paths.d/mono-commands
A: Mono doesn't contain a lot of fluff, so just running those commands will be fine. It's as simple as deleting all the data folders, and the binaries.
A: http://dragthor.wordpress.com/2007/07/24/uninstall-mono-on-mac-os-x/
Work for me, OSX, But I Use the uninstall script file (.sh) from the Mono Installer Package.
A: I just deleted the mono.frameworks folder. I got tired of answering "yes" billions of times...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74902",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: Tool to parse a file I'm trying to figure out the best way to parse a GE Logician MEL trace file to make it easier to read.
It has segments like
>{!gDYNAMIC_3205_1215032915_810 = (clYN)}
execute>GDYNAMIC_3205_1215032915_810 = "Yes, No"
results>"Yes, No"
execute>end
results>"Yes, No"
>{!gDYNAMIC_3205_1215032893_294 = (clYN)}
execute>GDYNAMIC_3205_1215032893_294 = "Yes, No"
results>"Yes, No"
execute>end
results>"Yes, No"
and
>{IF (STR(F3205_1220646638_285, F3205_1220646638_301) == "") THEN "" ELSE (\par\tab fnHeadingFormat("Depression") + CFMT(F3205_1220646638_285, "", "Have you often been bothered by feeling down, depressed or hopeless? ", "B", "\par ") + CFMT(F3205_1220646638_301, "", "Have you often been bothered by little interest or pleasure in doing things? ", "B", "\par ") ) ENDIF}
execute>call STR("No", "No")
results>"NoNo"
execute>"NoNo" == ""
results>FALSE
execute>if FALSE
results>FALSE
execute>call FNHEADINGFORMAT("Depression")
execute>call CFMT("Depression", "B,2")
results>"\fs24\b Depression\b0\fs20 "
execute>"\r\n" + "\fs24\b Depression\b0\fs20 "
results>"\r\n\fs24\b Depression\b0\fs20 "
execute>"\r\n\fs24\b Depression\b0\fs20 " + "\r\n"
results>"\r\n\fs24\b Depression\b0\fs20 \r\n"
results>return "\r\n\fs24\b Depression\b0\fs20 \r\n"
execute>call CFMT("No", "", "Have you often been bothered by feeling down, depressed or hopeless? ", "B", "\par ")
results>"\b Have you often been bothered by feeling down, depressed or hopeless? \b0 No\par "
execute>"\r\n\fs24\b Depression\b0\fs20 \r\n" + "\b Have you often been bothered by feeling down, depressed or hopeless? \b0 No\par "
results>"\r\n\fs24\b Depression\b0\fs20 \r\n\b Have you often been bothered by feeling down, depressed or hopeless? \b0 No\par "
execute>call CFMT("No", "", "Have you often been bothered by little interest or pleasure in doing things? ", "B", "\par ")
results>"\b Have you often been bothered by little interest or pleasure in doing things? \b0 No\par "
execute>"\r\n\fs24\b Depression\b0\fs20 \r\n\b Have you often been bothered by feeling down, depressed or hopeless? \b0 No\par " + "\b Have you often been bothered by little interest or pleasure in doing things? \b0 No\par "
results>"\r\n\fs24\b Depression\b0\fs20 \r\n\b Have you often been bothered by feeling down, depressed or hopeless? \b0 No\par \b Have you often been bothered by little interest or pleasure in doing things? \b0 No\par "
I could grovel through doing it procedurally, but after all the regexps I've worked with, I find it hard to believe there's nothing out there that will let me define the rules for parsing the file in a similar manner. Am I wrong?
A: Make a grammar using ANTLR. If you're using C, lex/yacc are native. ANTLR creates native parsers in Java, Python and .NET. Your output looks like a repl; try asking the vendor for a spec on the input language.
A: Antlr would do the trick.
A: In case you're using Perl for parsing. The Perl equivalent of YACC would be the Parse::Yapp module. When I translated a yacc grammar for use with my Perl code, the translation was mostly mechanic. There's also a recursive descent parser generator, which is slow but powerful: Parse::RecDescent.
A: You could try ANTLR or lex/yacc.
A: If it were me, I would derive a context-free grammar and plug it into a parser generator, probably Scala's combinator library. However, this grammar looks reasonably easy to parse by hand, just bear in mind the automata theory and it shouldn't be a problem.
A: I would imagine you could use tools like LEX, FLEX, CUP, ANTLR or YACC (or their equivalents for whatever programming language you are using. Any mainstream programming language has some flavor of these available.) to parse the files if they have a specific structure [more accurately, if they could be represented by a grammar]. These might not work for finer points though.
A: There's a programming language called Haskell that has a great parsing library you might try. www.haskell.org and http://legacy.cs.uu.nl/daan/parsec.html for more details
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74928",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How can i combine two columns containing Richtext data/files What is the best way to maniupulate richtext / *.rtf data in SQL server 2005 / 2008
I have looked at ocx solutions. Maybe creating some CLR stored procs??
The problem is that I have several notes written in richtext that need to be combined for ease of reporting.
Like
SELECT @Notes = @Notes + RTFColumn FROM Notestable WHERE ...
A: I think you are probably better off creating a simple application to read the two files, merge the data and save if that is where you are heading. Its sounds like you are expecting the database to do something outside of its store/retrieve job functions...
A: CLR would be the equivalent of writing a program and might not work as efficiently.
The database isn't really designed to do what you are asking of it and, a CLR sproc that handled it would be blocking, on many levels. So you would be better off writing a program that manually processed through the rows to do what you want it to do.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I implement custom drag functionality in a Flex list control? Flex has built in drag-n-drop for list controls, and allows you to override this. But they don't cover this in examples. The built-in functionality automatically drags the list-item, if you want to override this you find the handlers are being set up on the list itself.
What I specifically want to do, is my TileList shows small thumbnails of items I can drag onto a large Canvas. As I drag an item from the list, the drag proxy should be a different image.
So, I followed the technique suggested and it only works if I explicitly set the width/height on the proxy Image. Why?
A: It's not obvious until you've tried it =) I struggled with the same thing just a few weeks ago. This was my solution:
The list:
<List>
<mouseDown>onListMouseDown(event)</mouseDown>
</Tree>
The mouse down handler:
private function onMouseDown( event : MouseEvent ) : void {
var list : List = List(event.currentTarget);
// the data of the clicked row, change the name of the class to your own
var item : MyDataType = MyDataType(list.selectedItem);
var source : DragSource = new DragSource();
// MyAwsomeDragFormat is the key that you will retrieve the data by in the
// component that handles the drop
source.addData(item, "MyAwsomeDragFormat");
// this is the component that will be shown as the drag proxy image
var dragView : UIComponent = new Image();
// set the source of the image to a bigger version here
dragView.source = getABiggerImage(item);
// get hold of the renderer of the clicked row, to use as the drag initiator
var rowRenderer : UIComponent = UIComponent(list.indexToItemRenderer(list.selectedIndex));
DragManager.doDrag(
rowRenderer,
source,
event,
dragView
);
}
That will start the drag when the user clicks an item in the list. Notice that I don't set dragEnabled and the other drag-related properties on the list since I handle all that myself.
It can be useful to add this to the beginning of the event handler:
if ( event.target is ScrollThumb || event.target is Button ) {
return;
}
Just to short circuit if the user clicks somewhere in the scrollbar. It's not very elegant but it does the job.
A: I found a simpler answer here. That example extends a DataGrid control, but you can do the same with a List control. In my case, I use an image source instead of Class:
public class CustomDragList extends List {
[Bindable]
public var dragProxyImageSource:Object;
override protected function get dragImage():IUIComponent {
var image:Image = new Image();
image.width = 50;
image.height = 50;
image.source = dragProxyImageSource;
image.owner = this;
return image;
}
}
Then use that custom list like this:
<control:CustomDragList
allowMultipleSelection="true"
dragEnabled="true"
dragProxyImageSource="{someImageSource}"
dragStart="onDragStart(event)"/>
Where 'someImageSource' can be anything you'd normally use for an image source (embedded, linked, etc.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74951",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there a PowerShell "string does not contain" cmdlet or syntax? In PowerShell I'm reading in a text file. I'm then doing a Foreach-Object over the text file and am only interested in the lines that do NOT contain strings that are in $arrayOfStringsNotInterestedIn.
What is the syntax for this?
Get-Content $filename | Foreach-Object {$_}
A: If $arrayofStringsNotInterestedIn is an [array] you should use -notcontains:
Get-Content $FileName | foreach-object { `
if ($arrayofStringsNotInterestedIn -notcontains $_) { $) }
or better (IMO)
Get-Content $FileName | where { $arrayofStringsNotInterestedIn -notcontains $_}
A: To exclude the lines that contain any of the strings in $arrayOfStringsNotInterestedIn, you should use:
(Get-Content $FileName) -notmatch [String]::Join('|',$arrayofStringsNotInterestedIn)
The code proposed by Chris only works if $arrayofStringsNotInterestedIn contains the full lines you want to exclude.
A: You can use the -notmatch operator to get the lines that don't have the characters you are interested in.
Get-Content $FileName | foreach-object {
if ($_ -notmatch $arrayofStringsNotInterestedIn) { $) }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74957",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "32"
} |
Q: How do I add a namespace reference to a SOAP response with Apache Axis2 and WSDL2Java I'm looking at the SOAP output from a web service I'm developing, and I noticed something curious:
<soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
<soapenv:Body>
<ns1:CreateEntityTypesResponse xmlns:ns1="http://somedomain.com/wsinterface">
<newKeys>
<value>1234</value>
</newKeys>
<newKeys>
<value>2345</value>
</newKeys>
<newKeys>
<value>3456</value>
</newKeys>
<newKeys xsi:nil="1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
<newKeys xsi:nil="1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
<errors>Error1</errors>
<errors>Error2</errors>
</ns1:CreateEntityTypesResponse>
</soapenv:Body>
</soapenv:Envelope>
I have two newKeys elements that are nil, and both elements insert a namespace reference for xsi. I'd like to include that namespace in the soapenv:Envelope element so that the namespace reference is only sent once.
I am using WSDL2Java to generate the service skeleton, so I don't directly have access to the Axis2 API.
A: Using WSDL2Java
If you have used the Axis2 WSDL2Java tool you're kind of stuck with what it generates for you. However you can try to change the skeleton in this section:
// create SOAP envelope with that payload
org.apache.axiom.soap.SOAPEnvelope env = null;
env = toEnvelope(
getFactory(_operationClient.getOptions().getSoapVersionURI()),
methodName,
optimizeContent(new javax.xml.namespace.QName
("http://tempuri.org/","methodName")));
//adding SOAP soap_headers
_serviceClient.addHeadersToEnvelope(env);
To add the namespace to the envelope add these lines somewhere in there:
OMNamespace xsi = getFactory(_operationClient.getOptions().getSoapVersionURI()).
createOMNamespace("http://www.w3.org/2001/XMLSchema-instance", "xsi");
env.declareNamespace(xsi);
Hand-coded
If you are "hand-coding" the service you might do something like this:
SOAPFactory fac = OMAbstractFactory.getSOAP11Factory();
SOAPEnvelope envelope = fac.getDefaultEnvelope();
OMNamespace xsi = fac.createOMNamespace("http://www.w3.org/2001/XMLSchema-instance", "xsi");
envelope.declareNamespace(xsi);
OMNamespace methodNs = fac.createOMNamespace("http://somedomain.com/wsinterface", "ns1");
OMElement method = fac.createOMElement("CreateEntityTypesResponse", methodNs);
//add the newkeys and errors as OMElements here...
Exposing service in aar
If you are creating a service inside an aar you may be able to influence the SOAP message produced by using the target namespace or schema namespace properties (see this article).
Hope that helps.
A: Other option is that the variable MY_QNAME has the prefix empty.
public static final QName MY_QNAME = new QName("http://www.hello.com/Service/",
"tagname",
"prefix");
So, if you fill it, then it works.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: XBAP Application, can these work in Google Chrome? I'm developing a .NET 3.5 XBAP application that runs perfectly fine in FF3 and IE6/7 etc. I'm just wondering if its possible to get these to run under other browsers, specifically (as its in the limelight at the moment) Google Chrome.
A: At the moment, XBAPs do not work in Google Chrome. I've gotten it to run once, somehow, but every time there after I've received an error that the browser cannot locate xpcom.dll. Apparently this error occurs for more than just XBAP applications. From what I've read users will have to wait for a fix seeing as Chrome is still in beta.
Update:
Looks like it's not going to be fixed: http://code.google.com/p/chromium/issues/detail?id=4051
A: XBAP applications do work in google chrome, however you have to set your environments PATH variable to the directory where xpcom.dll is located.
for example SET PATH=PATH;"C:\Program Files\Mozilla Firefox"
A: Here is another alternative solution that still requires Firefox to be installed, but you copy DLLs instead of modifying the PATH:
http://adrianbega.blogspot.com/2009/04/execute-xbap-in-google-chrome.html
A: First thing required here is to make the .Net framework 3.5 installed, once its done check whether the application is working in Mozilla Firefox, because it uses the plugin of Mozilla, if there is some issue in Mozilla, execute the aspnet_regiis.exe -iru from Visual Studio command prompt with administrative priviledge, then set Path variable to C:\Program Files\Mozilla Firefox and add the following DLLs to the location C:\Users\[Username]\AppData\Local\Google\Chrome\Application
*
*mozalloc.dll
*mozcpp19.dll
*mozcrt19.dll
*mozjs.dll
*mozsqlite3.dll
*nspr4.dll
*nss3.dll
*nssutil3.dll
*plc4.dll
*plds4.dll
*smime3.dll
*ssl3.dll
*test.txt
*xpcom.dll
*xul.dll
and restart the browser, and check the application, if it still shows the plugin crashed, try re-installing the framework first and then Mozilla, also for Windows 7, mozilla requires to put the NPWPF.dll to the location C:\Program Files (x86)\Mozilla Firefox\plugins.
After this whole lot of hell, the application may still not debug, then publish the XBAP application and check with file and keep your finger crossed as it may work this time, this is how I made my application work in my system and checked for 5 more systems, so hope it resolve your problem too.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74986",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
} |
Q: Which resources should one monitor on a Linux server running a web-server or database When running any kind of server under load there are several resources that one would like to monitor to make sure that the server is healthy. This is specifically true when testing the system under load.
Some examples for this would be CPU utilization, memory usage, and perhaps disk space.
What other resource should I be monitoring, and what tools are available to do so?
A: As many as you can afford to, and can then graph/understand/look at the results. Monitoring resources is useful for not only capacity planning, but anomaly detection, and anomaly detection significantly helps your ability to detect security events.
You have a decent start with your basic graphs. I'd want to also monitor the number of threads, number of connections, network I/O, disk I/O, page faults (arguably this is related to memory usage), context switches.
I really like munin for graphing things related to hosts.
A: I use Zabbix extensively in production, which comes with a stack of useful defaults. Some examples of the sorts of things we've configured it to monitor:
*
*Network usage
*CPU usage (% user,system,nice times)
*Load averages (1m, 5m, 15m)
*RAM usage (real, swap, shm)
*Disc throughput
*Active connections (by port number)
*Number of processes (by process type)
*Ping time from remote location
*Time to SSL certificate expiry
*MySQL internals (query cache usage, num temporary tables in RAM and on disc, etc)
Anything you can monitor with Zabbix, you can also attach triggers to - so it can restart failed services; or page you to alert about problems.
Collect the data now, before performance becomes an issue. When it does, you'll be glad of the historical baselines, and the fact you'll be able to show what date and time problems started happening for when you need to hunt down and punish exactly which developer made bad changes :)
A: I ended up using dstat which is vmstat's nicer looking cousin.
This will show most everything you need to know about a machine's health,
including:
*
*CPU
*Disk
*Memory
*Network
*Swap
A: "df -h" to make sure that no partition runs full which can lead to all kinds of funky problems, watching the syslog is of course also useful, for that I recommend installing "logwatch" (Logwatch Website) on your server which sends you an email if weird things start showing up in your syslog.
A: Cacti is a good web-based monitoring/graphing solution. Very complete, very easy to use, with a large userbase including many large Enterprise-level installations.
If you want more 'alerting' and less 'graphing', check out nagios.
As for 'what to monitor', you want to monitor systems at both the system and application level, so yes: network/memory/disk i/o, interrupts and such over the system level. The application level gets more specific, so a webserver might measure hits/second, errors/second (non-200 responses), etc and a database might measure queries/second, average query fulfillment time, etc.
A: Beware the afore-mentioned slowquerylog in mysql. It should only be used when trying to figure out why some queries are slow. It has the side-effect of making ALL your queries slow while it's enabled. :P It's intended for debugging, not logging.
Think 'passive monitoring' whenever possible. For instance, sniff the network traffic rather than monitor it from your server -- have another machine watch the packets fly back and forth and record statistics about them.
(By the way, that's one of my favorites -- if you watch connections being established and note when they end, you can find a lot of data about slow queries or slow anything else, without putting any load on the server you care about.)
A: In addition to top and auth.log, I often look at mtop, and enable mysql's slowquerylog and watch mysqldumpslow.
I also use Nagios to monitor CPU, Memory, and logged in users (on a VPS or dedicated server). That last lets me know when someone other than me has logged in.
A: network of course :) Use MRTG to get some nice bandwidth graphs, they're just pretty most of the time.. until a spammer finds a hole in your security and it suddenly increases.
Nagios is good for alerting as mentioned, and is easy to get setup. You can then use the mrtg plugin to get alerts for your network traffic too.
I also recommend ntop as it shows where your network traffic is going.
A good link to get you going with Munin and Monit: link text
A: I typically watch top and tail -f /var/log/auth.log.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74993",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Why isn't there a viable mod_ruby for Apache yet? As popular as Ruby and Rails are, it seems like this problem would already be solved. JRuby and mod_rails are all fine and dandy, but why isn't there an Apache mod for just straight Ruby?
A: It's perhaps worth double-clarifying mislav's point that mod_rails isn't actually limited to Rails code at all. The new name, mod_rack, is way better. Trivially small apps can be rackable -- their example being:
class HelloWorld
def call(env)
[200, {"Content-Type" => "text/plain"}, ["Hello world!"]]
end
end
A: There is one: mod_ruby, but it hasn't been maintained in about 2 years.
A: There is Phusion Passenger, a robust Apache module that can run Rack applications with minimum configuration. It's becoming appealing to shared hosts, and turning any program into a Rack application is ridiculously easy:
A Rack application is an Ruby object
(not a class) that responds to call.
It takes exactly one argument, the
environment and returns an Array of
exactly three values: The status, the
headers, and the body.
A: The basic problem is this: for a long time, MRI was the only feasible Ruby Implementation. MRI has a number of problems that make it hard to embed it into another application (which is basically what mod_ruby does: it embeds MRI in Apache), especially a multi-threaded one (which Apache is). It is not particularly thread-safe and it has quite a bit of global state.
This global state means for example that if one Rails application modifies some class, then all other Rails applications that run on the same Apache server, will also see this modified class.
Another problem is that the MRI source code is not easily hackable. MRI is now more than 15 years old, and it's starting to show.
As a result of these problems, mod_ruby has never really properly worked, and at some point the maintainers simply gave up.
The C based PHP interpreter, on the other hand, was designed from day one to be run as mod_php inside Apache. Indeed, for the first couple of versions, there wasn't even a commandline version of the interpreter, mod_php was the only way to run PHP.
Phusion Passenger (aka mod_rack aka mod_rails) solves this problem by basically giving up and sidestepping the problem: they simply run a seperate copy of MRI in a seperate process for every application. It works great, and not only for Ruby. It supports WSGI (standard interface for Python Web Frameworks), Rack (standard interface for Ruby Web Frameworks) and direct support for Ruby on Rails.
My hopes are on mod_rubinius, which unfortunately doesn't exist yet. Rubinius was designed from the beginning to be thread-safe, embeddable, free of global state, not use the C stack and so on. It was designed to be able to run multiple Rubinius VMs inside one Rubinius process. This makes mod_rubinius infinitely easier to implement and maintain than mod_ruby. Unfortunately, of course, Rubinius is not released yet, and the real work on mod_rubinius cannot even begin until Rubinius is released. The good news is that mod_rubinius already has more manpower behind it than mod_ruby ever had, because it has paid developers working on it by a Rails hosting company that desperately wants to use it themselves.
A: There is mod_rails and it can run Rack applications, what more can you need?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Does Scripting.Dictionary's RemoveAll() method release all of its elements first? In a VB6 application, I have a Dictionary whose keys are Strings and values are instances of a custom class. If I call RemoveAll() on the Dictionary, will it first free the custom objects? Or do I explicitly need to do this myself?
Dim d as Scripting.Dictionary
d("a") = New clsCustom
d("b") = New clsCustom
' Are these two lines necessary?
Set d("a") = Nothing
Set d("b") = Nothing
d.RemoveAll
A: Yes, all objects in the Dictionary will be released after a call to RemoveAll(). From a performance (as in speed) standpoint I would say those lines setting the variables to Nothing are unnecessary, because the code has to first look them up based on the key names whereas RemoveAll() will enumerate and release everything in one loop.
A: RemoveAll will remove all the associations from the Dictionary: both the keys and values.
It would be a reference leak for the Dictionary to keep a reference to the values in the Dictionary.
A: If there are no other variables that reference the items in the collection then those objects should be handed to the Garbage Collector to be cleaned up the next time the GC is run.
If you, for example do this where sObj is a static variable somewhere then the when the GC is invoked next by the system, the first object will be cleaned up but the second which still is referenced by sObj will not.
d("a") = New clsCustom
d("b") = New clsCustom code.
sObj = d("b")
d.RemoveAll()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75011",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Detecting concurrent modifications? In a multi-threaded application I'm working on, we occasionally see ConcurrentModificationExceptions on our Lists (which are mostly ArrayList, sometimes Vectors). But there are other times when I think concurrent modifications are happening because iterating through the collection appears to be missing items, but no exceptions are thrown. I know that the docs for ConcurrentModificationException says you can't rely on it, but how would I go about making sure I'm not concurrently modifying a List? And is wrapping every access to the collection in a synchronized block the only way to prevent it?
Update: Yes, I know about Collections.synchronizedCollection, but it doesn't guard against somebody modifying the collection while you're iterating through it. I think at least some of my problem is happening when somebody adds something to a collection while I'm iterating through it.
Second Update If somebody wants to combine the mention of the synchronizedCollection and cloning like Jason did with a mention of the java.util.concurrent and the apache collections frameworks like jacekfoo and Javamann did, I can accept an answer.
A: Depending on your update frequency one of my favorites is the CopyOnWriteArrayList or CopyOnWriteArraySet. They create a new list/set on updates to avoid concurrent modification exception.
A: Your original question seems to be asking for an iterator that sees live updates to the underlying collection while remaining thread-safe. This is an incredibly expensive problem to solve in the general case, which is why none of the standard collection classes do it.
There are lots of ways of achieving partial solutions to the problem, and in your application, one of those may be sufficient.
Jason gives a specific way to achieve thread safety, and to avoid throwing a ConcurrentModificationException, but only at the expense of liveness.
Javamann mentions two specific classes in the java.util.concurrent package that solve the same problem in a lock-free way, where scalability is critical. These only shipped with Java 5, but there have been various projects that backport the functionality of the package into earlier Java versions, including this one, though they won't have such good performance in earlier JREs.
If you are already using some of the Apache Commons libraries, then as jacekfoo points out, the apache collections framework contains some helpful classes.
You might also consider looking at the Google collections framework.
A: Check out java.util.concurrent for versions of the standard Collections classes that are engineered to handle concurrency better.
A: Yes you have to synchronize access to collections objects.
Alternatively, you can use the synchronized wrappers around any existing object. See Collections.synchronizedCollection(). For example:
List<String> safeList = Collections.synchronizedList( originalList );
However all code needs to use the safe version, and even so iterating while another thread modifies will result in problems.
To solve the iteration problem, copy the list first. Example:
for ( String el : safeList.clone() )
{ ... }
For more optimized, thread-safe collections, also look at java.util.concurrent.
A: Usually you get a ConcurrentModificationException if you're trying to remove an element from a list whilst it's being iterated through.
The easiest way to test this is:
List<Blah> list = new ArrayList<Blah>();
for (Blah blah : list) {
list.remove(blah); // will throw the exception
}
I'm not sure how you'd get around it. You may have to implement your own thread-safe list, or you could create copies of the original list for writing and have a synchronized class that writes to the list.
A: You could try using defensive copying so that modifications to one List don't affect others.
A: Wrapping accesses to the collection in a synchronized block is the correct way to do this. Standard programming practice dictates the use of some sort of locking mechanism (semaphore, mutex, etc) when dealing with state that is shared across multiple threads.
Depending on your use case however you can usually make some optimizations to only lock in certain cases. For example, if you have a collection that is frequently read but rarely written, then you can allow concurrent reads but enforce a lock whenever a write is in progress. Concurrent reads only cause conflicts if the collection is in the process of being modified.
A: ConcurrentModificationException is best-effort because what you're asking is a hard problem. There's no good way to do this reliably without sacrificing performance besides proving that your access patterns do not concurrently modify the list.
Synchronization would likely prevent concurrent modifications, and it may be what you resort to in the end, but it can end up being costly. The best thing to do is probably to sit down and think for a while about your algorithm. If you can't come up with a lock-free solution, then resort to synchronization.
A: See the implementation. It basically stores an int:
transient volatile int modCount;
and that is incremented when there is a 'structural modification' (like remove). If iterator detects that modCount changed it throws Concurrent modification exception.
Synchronizing (via Collections.synchronizedXXX) won't do good since it does not guarantee iterator safety it only synchronizes writes and reads via put, get, set ...
See java.util.concurennt and apache collections framework (it has some classes that are optimized do work correctly in concurrent environment when there is more reads (that are unsynchronized) than writes - see FastHashMap.
A: You can also synchronize over iteratins over the list.
List<String> safeList = Collections.synchronizedList( originalList );
public void doSomething() {
synchronized(safeList){
for(String s : safeList){
System.out.println(s);
}
}
}
This will lock the list on synchronization and block all threads that try to access the list while you edit it or iterate over it. The downside is that you create a bottleneck.
This saves some memory over the .clone() method and might be faster depending on what you're doing in the iteration...
A: Collections.synchronizedList() will render a list nominally thread-safe and java.util.concurrent has more powerful features.
A: This will get rid of your concurrent modification exception. I won't speak to the efficiency however ;)
List<Blah> list = fillMyList();
List<Blah> temp = new ArrayList<Blah>();
for (Blah blah : list) {
//list.remove(blah); would throw the exception
temp.add(blah);
}
list.removeAll(temp);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75014",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: How to stop a mp3 file from being downloaded by flash when in streaming mode I have a flash player that has a set of songs loaded via an xml file.
The files dont start getting stream until you pick one.
If I quickly cycle through each of the 8 files, then flash starts trying to download each of the 8 files at the same time.
I'm wondering if there is a way to clear the file that is being downloaded. So that bandwidth is not eaten up if someone decides to click on lots of track names.
Something like mySound.clear would be great, or mySound.stopStreaming..
Has anyone had this problem before?
Regards,
Chris
A: Check out Sound.Close().
From the docs: "Closes the stream, causing any download of data to cease. No data may be read from the stream after the close() method is called."
This is the source code example from the linked docs:
package {
import flash.display.Sprite;
import flash.net.URLRequest;
import flash.media.Sound;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.events.MouseEvent;
import flash.errors.IOError;
import flash.events.IOErrorEvent;
public class Sound_closeExample extends Sprite {
private var snd:Sound = new Sound();
private var button:TextField = new TextField();
private var req:URLRequest = new URLRequest("http://av.adobe.com/podcast/csbu_dev_podcast_epi_2.mp3");
public function Sound_closeExample() {
button.x = 10;
button.y = 10;
button.text = "START";
button.border = true;
button.background = true;
button.selectable = false;
button.autoSize = TextFieldAutoSize.LEFT;
button.addEventListener(MouseEvent.CLICK, clickHandler);
this.addChild(button);
}
private function clickHandler(e:MouseEvent):void {
if(button.text == "START") {
snd.load(req);
snd.play();
snd.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
button.text = "STOP";
}
else if(button.text == "STOP") {
try {
snd.close();
button.text = "Wait for loaded stream to finish.";
}
catch (error:IOError) {
button.text = "Couldn't close stream " + error.message;
}
}
}
private function errorHandler(event:IOErrorEvent):void {
button.text = "Couldn't load the file " + event.text;
}
}
}
A: If you do something like:
MySoundObject = undefined;
That should do it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75052",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What is the best way to check the strength of a password? What is the best way of ensuring that a user supplied password is a strong password in a registration or change password form?
One idea I had (in python)
def validate_password(passwd):
conditions_met = 0
conditions_total = 3
if len(passwd) >= 6:
if passwd.lower() != passwd: conditions_met += 1
if len([x for x in passwd if x.isdigit()]) > 0: conditions_met += 1
if len([x for x in passwd if not x.isalnum()]) > 0: conditions_met += 1
result = False
print conditions_met
if conditions_met >= 2: result = True
return result
A: 1: Eliminate often used passwords
Check the entered passwords against a list of often used passwords (see e.g. the top 100.000 passwords in the leaked LinkedIn password list: http://www.adeptus-mechanicus.com/codex/linkhap/combo_not.zip), make sure to include leetspeek substitutions:
A@, E3, B8, S5, etc.
Remove parts of the password that hit against this list from the entered phrase, before going to part 2 below.
2: Don't force any rules on the user
The golden rule of passwords is that longer is better.
Forget about forced use of caps, numbers, and symbols because (the vast majority of) users will:
- Make the first letter a capital;
- Put the number 1 at the end;
- Put a ! after that if a symbol is required.
Instead check password strength
For a decent starting point see: http://www.passwordmeter.com/
I suggest as a minimum the following rules:
Additions (better passwords)
-----------------------------
- Number of Characters Flat +(n*4)
- Uppercase Letters Cond/Incr +((len-n)*2)
- Lowercase Letters Cond/Incr +((len-n)*2)
- Numbers Cond +(n*4)
- Symbols Flat +(n*6)
- Middle Numbers or Symbols Flat +(n*2)
- Shannon Entropy Complex *EntropyScore
Deductions (worse passwords)
-----------------------------
- Letters Only Flat -n
- Numbers Only Flat -(n*16)
- Repeat Chars (Case Insensitive) Complex -
- Consecutive Uppercase Letters Flat -(n*2)
- Consecutive Lowercase Letters Flat -(n*2)
- Consecutive Numbers Flat -(n*2)
- Sequential Letters (3+) Flat -(n*3)
- Sequential Numbers (3+) Flat -(n*3)
- Sequential Symbols (3+) Flat -(n*3)
- Repeated words Complex -
- Only 1st char is uppercase Flat -n
- Last (non symbol) char is number Flat -n
- Only last char is symbol Flat -n
Just following passwordmeter is not enough, because sure enough its naive algorithm sees Password1! as good, whereas it is exceptionally weak.
Make sure to disregard initial capital letters when scoring as well as trailing numbers and symbols (as per the last 3 rules).
Calculating Shannon entropy
See: Fastest way to compute entropy in Python
3: Don't allow any passwords that are too weak
Rather than forcing the user to bend to self-defeating rules, allow anything that will give a high enough score. How high depends on your use case.
And most importantly
When you accept the password and store it in a database, make sure to salt and hash it!.
A: The two simplest metrics to check for are:
*
*Length. I'd say 8 characters as a minimum.
*Number of different character classes the password contains. These are usually, lowercase letters, uppercase letters, numbers and punctuation and other symbols. A strong password will contain characters from at least three of these classes; if you force a number or other non-alphabetic character you significantly reduce the effectiveness of dictionary attacks.
A: Cracklib is great, and in newer packages there is a Python module available for it. However, on systems that don't yet have it, such as CentOS 5, I've written a ctypes wrapper for the system cryptlib. This would also work on a system that you can't install python-libcrypt. It does require python with ctypes available, so for CentOS 5 you have to install and use the python26 package.
It also has the advantage that it can take the username and check for passwords that contain it or are substantially similar, like the libcrypt "FascistGecos" function but without requiring the user to exist in /etc/passwd.
My ctypescracklib library is available on github
Some example uses:
>>> FascistCheck('jafo1234', 'jafo')
'it is based on your username'
>>> FascistCheck('myofaj123', 'jafo')
'it is based on your username'
>>> FascistCheck('jxayfoxo', 'jafo')
'it is too similar to your username'
>>> FascistCheck('cretse')
'it is based on a dictionary word'
A: after reading the other helpful answers, this is what i'm going with:
-1 same as username
+0 contains username
+1 more than 7 chars
+1 more than 11 chars
+1 contains digits
+1 mix of lower and uppercase
+1 contains punctuation
+1 non-printable char
pwscore.py:
import re
import string
max_score = 6
def score(username,passwd):
if passwd == username:
return -1
if username in passwd:
return 0
score = 0
if len(passwd) > 7:
score+=1
if len(passwd) > 11:
score+=1
if re.search('\d+',passwd):
score+=1
if re.search('[a-z]',passwd) and re.search('[A-Z]',passwd):
score+=1
if len([x for x in passwd if x in string.punctuation]) > 0:
score+=1
if len([x for x in passwd if x not in string.printable]) > 0:
score+=1
return score
example usage:
import pwscore
score = pwscore(username,passwd)
if score < 3:
return "weak password (score="
+ str(score) + "/"
+ str(pwscore.max_score)
+ "), try again."
probably not the most efficient, but seems reasonable.
not sure FascistCheck => 'too similar to username' is
worth it.
'abc123ABC!@£' = score 6/6 if not a superset of username
maybe that should score lower.
A: Depending on the language, I usually use regular expressions to check if it has:
*
*At least one uppercase and one
lowercase letter
*At least one number
*At least one special character
*A length of at least six characters
You can require all of the above, or use a strength meter type of script. For my strength meter, if the password has the right length, it is evaluated as follows:
*
*One condition met: weak password
*Two conditions met: medium password
*All conditions met: strong password
You can adjust the above to meet your needs.
A: The object-oriented approach would be a set of rules. Assign a weight to each rule and iterate through them. In psuedo-code:
abstract class Rule {
float weight;
float calculateScore( string password );
}
Calculating the total score:
float getPasswordStrength( string password ) {
float totalWeight = 0.0f;
float totalScore = 0.0f;
foreach ( rule in rules ) {
totalWeight += weight;
totalScore += rule.calculateScore( password ) * rule.weight;
}
return (totalScore / totalWeight) / rules.count;
}
An example rule algorithm, based on number of character classes present:
float calculateScore( string password ) {
float score = 0.0f;
// NUMBER_CLASS is a constant char array { '0', '1', '2', ... }
if ( password.contains( NUMBER_CLASS ) )
score += 1.0f;
if ( password.contains( UPPERCASE_CLASS ) )
score += 1.0f;
if ( password.contains( LOWERCASE_CLASS ) )
score += 1.0f;
// Sub rule as private method
if ( containsPunctuation( password ) )
score += 1.0f;
return score / 4.0f;
}
A: Well this is what I use:
var getStrength = function (passwd) {
intScore = 0;
intScore = (intScore + passwd.length);
if (passwd.match(/[a-z]/)) {
intScore = (intScore + 1);
}
if (passwd.match(/[A-Z]/)) {
intScore = (intScore + 5);
}
if (passwd.match(/\d+/)) {
intScore = (intScore + 5);
}
if (passwd.match(/(\d.*\d)/)) {
intScore = (intScore + 5);
}
if (passwd.match(/[!,@#$%^&*?_~]/)) {
intScore = (intScore + 5);
}
if (passwd.match(/([!,@#$%^&*?_~].*[!,@#$%^&*?_~])/)) {
intScore = (intScore + 5);
}
if (passwd.match(/[a-z]/) && passwd.match(/[A-Z]/)) {
intScore = (intScore + 2);
}
if (passwd.match(/\d/) && passwd.match(/\D/)) {
intScore = (intScore + 2);
}
if (passwd.match(/[a-z]/) && passwd.match(/[A-Z]/) && passwd.match(/\d/) && passwd.match(/[!,@#$%^&*?_~]/)) {
intScore = (intScore + 2);
}
return intScore;
}
A: I don't know if anyone will find this useful, but I really liked the idea of a ruleset as suggested by phear so I went and wrote a rule Python 2.6 class (although it's probably compatible with 2.5):
import re
class SecurityException(Exception):
pass
class Rule:
"""Creates a rule to evaluate against a string.
Rules can be regex patterns or a boolean returning function.
Whether a rule is inclusive or exclusive is decided by the sign
of the weight. Positive weights are inclusive, negative weights are
exclusive.
Call score() to return either 0 or the weight if the rule
is fufilled.
Raises a SecurityException if a required rule is violated.
"""
def __init__(self,rule,weight=1,required=False,name=u"The Unnamed Rule"):
try:
getattr(rule,"__call__")
except AttributeError:
self.rule = re.compile(rule) # If a regex, compile
else:
self.rule = rule # Otherwise it's a function and it should be scored using it
if weight == 0:
return ValueError(u"Weights can not be 0")
self.weight = weight
self.required = required
self.name = name
def exclusive(self):
return self.weight < 0
def inclusive(self):
return self.weight >= 0
exclusive = property(exclusive)
inclusive = property(inclusive)
def _score_regex(self,password):
match = self.rule.search(password)
if match is None:
if self.exclusive: # didn't match an exclusive rule
return self.weight
elif self.inclusive and self.required: # didn't match on a required inclusive rule
raise SecurityException(u"Violation of Rule: %s by input \"%s\"" % (self.name.title(), password))
elif self.inclusive and not self.required:
return 0
else:
if self.inclusive:
return self.weight
elif self.exclusive and self.required:
raise SecurityException(u"Violation of Rule: %s by input \"%s\"" % (self.name,password))
elif self.exclusive and not self.required:
return 0
return 0
def score(self,password):
try:
getattr(self.rule,"__call__")
except AttributeError:
return self._score_regex(password)
else:
return self.rule(password) * self.weight
def __unicode__(self):
return u"%s (%i)" % (self.name.title(), self.weight)
def __str__(self):
return self.__unicode__()
I hope someone finds this useful!
Example Usage:
rules = [ Rule("^foobar",weight=20,required=True,name=u"The Fubared Rule"), ]
try:
score = 0
for rule in rules:
score += rule.score()
except SecurityException e:
print e
else:
print score
DISCLAIMER: Not unit tested
A: Password strength checkers, and if you have time+resources (its justified only if you are checking for more than a few passwords) use Rainbow Tables.
A: With a series of checks to ensure it meets minimum criteria:
*
*at least 8 characters long
*contains at least one non-alphanumeric symbol
*does not match or contain username/email/etc.
*etc
Here's a jQuery plugin that reports password strength (not tried it myself):
http://phiras.wordpress.com/2007/04/08/password-strength-meter-a-jquery-plugin/
And the same thing ported to PHP:
http://www.alixaxel.com/wordpress/2007/06/09/php-password-strength-algorithm/
A:
What is the best way of ensuring that a user supplied password is a strong password in a registration or change password form?
Don't evaluate complexity and or strength, users will find a way to fool your system or get so frustrated that they will leave. That will only get you situations like this. Just require certain length and that leaked passwords aren't used. Bonus points: make sure whatever you implement allows the use of password managers and/or 2FA.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75057",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "45"
} |
Q: Beginning Java EE I know something about Java but completely new to Enterprise Java. I'm trying my hand with NetBeans 6.1 and GlassFish Application Server.
Please guide me to some resources which tell me actually what java enterprise applications are, how they are different from normal java classes etc.
Also which is the best application server to use (on Linux)?
A: The Java EE 5 Tutorial - read online or as pdf
EJB 3 in Action - great book that covers everything you need to know
I have also recently started with Java EE and I have only used Glassfish/Sun Application Server so far, but from what I understad from my colleagues at work and what I have seen so far Glassfish seems to be the the best choice at the moment.
A: "what java enterprise applications are, how they are different from normal java classes etc"
Well they are normal classes. They are ran by an application server. The "application server" is often just a JVM, but sometimes enhanced or modified or extended by the vendor. But that shouldn't be any concern to you. The application server (ie: JVM) uses a class loader (probably customized by vendor) to load your servlet (any class that implements the HttpServlet interface). Any other classes (not just J2EE classes, but all classes) will be loaded by the class loader. From there on it is your same java code. I hope this gives you the kind of answer you want. Reading J2EE documents (even aimed towards developers) usually entails meaningless buzzwords.
I would recommend that you look over the J2EE Tutorial from Sun. It's free, and goes over the basics that you should know before moving onto a framework (Struts for example). And of course must need to know if you are just going to use just straight J2EE.
You may wish to familiarize yourself with some of this:
*
*http://java.sun.com/j2ee/1.4/docs/api/
*You may also wish to go over HTTP specification (RFC or elsewhere) as well in case you don't understand how http requests and responses are processed by a standalone webserver.
*http://java.sun.com/j2ee/1.4/docs/tutorial/doc/Overview3.html (web containers in particular)
A couple of helpful facts:
*
*A JSP is compiled into a servlet. These were created so that your Servlets wouldn't have to be developed using an Output Writer to handle every write to page content (the JSP will be compiled into that for you). ie: out.println("<html>etcetc...")
*the request (HttpServletRequest) object represents the request.
*the response (HttpServletRespone) object will build the response. (both the http headers and content).
*Session and Context objects are also important. The former is for carrying session scoped objects (managed by the app server) and mapped to a jsessionid cookie on the client side (so it knows what client (ie: request) has what objects on the server side). The context object is used for initial settings.
*You will want to go over web containers to fit it all together.
A: Glassfish on Linux is an excellent choice.
A: I always like to start with wikipedia: http://en.wikipedia.org/wiki/Java_Platform,_Enterprise_Edition
Mastering a good IDE like Eclipse is worthwhile.
Last but not least, YouTube has nice how-to vids:
http://www.youtube.com/watch?v=_-IDpzC0n9Y
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75064",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Obtain parameter values from a stack frame in .NET? I would like to be able to obtain all the parameter values from the stack frame in .NET. A bit like how you're able to see the values in the call stack when in the Visual Studio debugger. My approach has concentrated on using the StackFrame class and then to reflect over a ParameterInfo array. I've had success with reflection and properties, but this is proving a bit trickier.
Is there an approach for achieving this?
The code so far looks like this:
class Program
{
static void Main(string[] args)
{
A a = new A();
a.Go(1);
}
}
public class A
{
internal void Go(int x)
{
B b = new B();
b.Go(4);
}
}
public class B
{
internal void Go(int y)
{
Console.WriteLine(GetStackTrace());
}
public static string GetStackTrace()
{
StringBuilder sb = new StringBuilder();
StackTrace st = new StackTrace(true);
StackFrame[] frames = st.GetFrames();
foreach (StackFrame frame in frames)
{
MethodBase method = frame.GetMethod();
sb.AppendFormat("{0} - {1}",method.DeclaringType, method.Name);
ParameterInfo[] paramaters = method.GetParameters();
foreach (ParameterInfo paramater in paramaters)
{
sb.AppendFormat("{0}: {1}", paramater.Name, paramater.ToString());
}
sb.AppendLine();
}
return sb.ToString();
}
}
The output looks like this:
SfApp.B - GetStackTrace
SfApp.B - Go
y: Int32 y
SfApp.A - Go
x: Int32 x
SfApp.Program - Main
args: System.String[] args
I'd like it to look more like this:
SfApp.B - GetStackTrace
SfApp.B - Go
y: 4
SfApp.A - Go
x: 1
SfApp.Program - Main
Just for a bit of context, my plan was to try and use this when I throw my own exceptions. I'll look at your suggestions in more detail and see if I can see it fitting.
A: It seems it can't be done that way. It will only provide meta information about the method and its parameters. Not the actual value at the time of the callstack.
Some suggest deriving your classes from ContextBoundObject and use IMessageSink to be notified off all method calls and the values of the parameters. This is normally used for .NET Remoting.
Another suggestion might be to write a debugger. This is how the IDE gets its information. Microsoft has Mdbg of which you can get the source code. Or write a CLR profiler.
A: I am quite sure this is possible somehow, but I am not competent enough to give you the answer you wish. I am suggesting a different approach, less flexible but still useful if you have a stack trace in advance and you would like to see the arguments passed to each frame.
Typically you would scatter log messages at the start of each method present in your stack trace, but that is pretty cumbersome and not always possible: what if you call methods defined in an external library?
While I was searching for an inspiration on how to tackle this problem, I found a library called Harmony, that allows you to patch methods at runtime. Basically a method can be decorated with a prefix, a postfix and/or a finalizer. It is all very well explained in the documentation, but the idea you could use in order to provide details about methods in a stack trace is to create a prefix that prints the parameters of each frame.
Unfortunately, with Harmony only, I do not think it is possible to do this for the methods in the current StackTrace, as you would like to do, even using a postfix/finalizer. Nonetheless it can be done before the target method is called.
I have created a very simple library called DebugLogger that internally uses Harmony and that simplifies the procedure. Here is the repository, but you can also find it on Nuget:
dotnet add package DebugLogger --version 1.0.0
It still has many limitations, in part because of Harmony, there are just a bunch of tests and is not ready to be considered a library, but it is a good starting point in my opinion. I have prepared a Fiddle showing the initialization of DebugLogger and a couple of dummy classes to make the demo "meaningful".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75076",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: What datatype should be used for storing phone numbers in SQL Server 2005? I need to store phone numbers in a table. Please suggest which datatype should I use?
Wait. Please read on before you hit reply..
This field needs to be indexed heavily as Sales Reps can use this field for searching (including wild character search).
As of now, we are expecting phone numbers to come in a number of formats (from an XML file). Do I have to write a parser to convert to a uniform format? There could be millions of data (with duplicates) and I dont want to tie up the server resources (in activities like preprocessing too much) every time some source data comes through..
Any suggestions are welcome..
Update: I have no control over source data. Just that the structure of xml file is standard. Would like to keep the xml parsing to a minimum.
Once it is in database, retrieval should be quick. One crazy suggestion going on around here is that it should even work with Ajax AutoComplete feature (so Sales Reps can see the matching ones immediately). OMG!!
A: Does this include:
*
*International numbers?
*Extensions?
*Other information besides the actual number (like "ask for bobby")?
If all of these are no, I would use a 10 char field and strip out all non-numeric data. If the first is a yes and the other two are no, I'd use two varchar(50) fields, one for the original input and one with all non-numeric data striped and used for indexing. If 2 or 3 are yes, I think I'd do two fields and some kind of crazy parser to determine what is extension or other data and deal with it appropriately. Of course you could avoid the 2nd column by doing something with the index where it strips out the extra characters when creating the index, but I'd just make a second column and probably do the stripping of characters with a trigger.
Update: to address the AJAX issue, it may not be as bad as you think. If this is realistically the main way anything is done to the table, store only the digits in a secondary column as I said, and then make the index for that column the clustered one.
A: We use varchar(15) and certainly index on that field.
The reason being is that International standards can support up to 15 digits
Wikipedia - Telephone Number Formats
If you do support International numbers, I recommend the separate storage of a World Zone Code or Country Code to better filter queries by so that you do not find yourself parsing and checking the length of your phone number fields to limit the returned calls to USA for example
A: Use CHAR(10) if you are storing US Phone numbers only. Remove everything but the digits.
A: I'm probably missing the obvious here, but wouldn't a varchar just long enough for your longest expected phone number work well?
If I am missing something obvious, I'd love it if someone would point it out...
A: I would use a varchar(22). Big enough to hold a north american phone number with extension. You would want to strip out all the nasty '(', ')', '-' characters, or just parse them all into one uniform format.
Alex
A: nvarchar with preprocessing to standardize them as much as possible. You'll probably want to extract extensions and store them in another field.
A: SQL Server 2005 is pretty well optimized for substring queries for text in indexed varchar fields. For 2005 they introduced new statistics to the string summary for index fields. This helps significantly with full text searching.
A: using varchar is pretty inefficient. use the money type and create a user declared type "phonenumber" out of it, and create a rule to only allow positive numbers.
if you declare it as (19,4) you can even store a 4 digit extension and be big enough for international numbers, and only takes 9 bytes of storage. Also, indexes are speedy.
A: Normalise the data then store as a varchar. Normalising could be tricky.
That should be a one-time hit. Then as a new record comes in, you're comparing it to normalised data. Should be very fast.
A: Use a varchar field with a length restriction.
A: Since you need to accommodate many different phone number formats (and probably include things like extensions etc.) it may make the most sense to just treat it as you would any other varchar. If you could control the input, you could take a number of approaches to make the data more useful, but it doesn't sound that way.
Once you decide to simply treat it as any other string, you can focus on overcoming the inevitable issues regarding bad data, mysterious phone number formating and whatever else will pop up. The challenge will be in building a good search strategy for the data and not how you store it in my opinion. It's always a difficult task having to deal with a large pile of data which you had no control over collecting.
A: Use SSIS to extract and process the information. That way you will have the processing of the XML files separated from SQL Server. You can also do the SSIS transformations on a separate server if needed. Store the phone numbers in a standard format using VARCHAR. NVARCHAR would be unnecessary since we are talking about numbers and maybe a couple of other chars, like '+', ' ', '(', ')' and '-'.
A: It is fairly common to use an "x" or "ext" to indicate extensions, so allow 15 characters (for full international support) plus 3 (for "ext") plus 4 (for the extension itself) giving a total of 22 characters. That should keep you safe.
Alternatively, normalise on input so any "ext" gets translated to "x", giving a maximum of 20.
A: I realize this thread is old, but it's worth mentioning an advantage of storing as a numeric type for formatting purposes, specifically in .NET framework.
IE
.DefaultCellStyle.Format = "(###)###-####" // Will not work on a string
A: It is always better to have separate tables for multi valued attributes like phone number.
As you have no control on source data so, you can parse the data from XML file and convert it into the proper format so that there will not be any issue with formats of a particular country and store it in a separate table so that indexing and retrieval both will be efficient.
Thank you.
A: Use data type long instead.. dont use int because it only allows whole numbers between -32,768 and 32,767 but if you use long data type you can insert numbers between -2,147,483,648 and 2,147,483,647.
A: For most cases, it will be done with bigint
Just save unformatted phone numbers like: 19876543210, 02125551212, etc.
Check the topic about bigint vs varchar
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75105",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "96"
} |
Q: Remove columns from DataTable in C# I have a DataSet which I get a DataTable from that I am being passed back from a function call. It has 15-20 columns, however I only want 10 columns of the data.
Is there a way to remove those columns that I don't want, copy the DataTable to another that has only the columns defined that I want or is it just better to iterate the collection and just use the columns I need.
I need to write the values out to a fixed length data file.
A: The question has already been marked as answered, But I guess the question states that the person wants to remove multiple columns from a DataTable.
So for that, here is what I did, when I came across the same problem.
string[] ColumnsToBeDeleted = { "col1", "col2", "col3", "col4" };
foreach (string ColName in ColumnsToBeDeleted)
{
if (dt.Columns.Contains(ColName))
dt.Columns.Remove(ColName);
}
A: Aside from limiting the columns selected to reduce bandwidth and memory:
DataTable t;
t.Columns.Remove("columnName");
t.Columns.RemoveAt(columnIndex);
A: To remove all columns after the one you want, below code should work. It will remove at index 10 (remember Columns are 0 based), until the Column count is 10 or less.
DataTable dt;
int desiredSize = 10;
while (dt.Columns.Count > desiredSize)
{
dt.Columns.RemoveAt(desiredSize);
}
A: How about you just select the columns you want like this:
Dim Subjects As String = "Math, English"
Dim SubjectData As DataTable = Table.AsDataView.ToTable(True, Subjects.Split(","))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75123",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "142"
} |
Q: How to make a web app appear at the root of the site? I have a bulletin board (punBB based) that I was running out of the root directory for a couple of years. I foolishly decided to do a little gardening and in the process moved the punbb code into it's own subdirectory. The code works great; as long as you point the browser at the new subdirectory. The issue is that the users expect to see it at the root...
I tried an index file in the root that had the following:
<?php chdir('punbb');
include('index.php');
But that didn't seem to do the trick. So, I tried using the "damn cool voodoo" of mod_rewrite in .htaccess but I can't seem to figure out the right combination of rules to make it work.
Here is what I would like to make happen:
User enters:
http://guardthe.net
Browser displays:
http://guardthe.net/punbb/
or
http://punbb.guardthe.net/
Is this possible, or should I just move the code base back into the root?
A: Something like this in .htacces should do it:
RewriteEngine On
RewriteRule ^/?$ /punbb/ [R=301,L]
The 301 return code is to mark the move as permanentm making it posible for the browser to update bookmarks.
A: a PHP file with a 301 HTTP permenant redirect.
Put the following into index.php in the root directory of guardthe.net
<?php
Header( "HTTP/1.1 301 Moved Permanently" );
Header( "Location: http://guardthe.net/punbb/" );
?>
browser will re-direct with search engine friendliness.
A: Your example code is missing but here's one way to do it using mod_rewrite:
RewriteEngine on
RewriteRule ^$ http://guardthe.net/punbb/ [L,R=301]
A: You could write a small redirect script to take care of this simply and quickly.
<?php
header( 'Location: http://guardthe.net/punbb/' );
?>
Enter that as the only content in your index.php in your root directory, and any requests sent to that folder will then redirect the user to the forum.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75127",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to make jQuery effects run in sequence, not simultaneously? How do I have two effects in jQuery run in sequence, not simultaneously? Take this piece of code for example:
$("#show-projects").click(function() {
$(".page:visible").fadeOut("normal");
$("#projects").fadeIn("normal");
});
The fadeOut and the fadeIn run simultaneously, how do I make them run one after the other?
A: You can supply a callback to the effects functions that run after the effect has completed.
$("#show-projects").click(function() {
$(".page:visible").fadeOut("normal", function() {
$("#projects").fadeIn("normal");
});
});
A: What you want is a queue.
Check out the reference page http://api.jquery.com/queue/ for some working examples.
A: $( "#foo" ).fadeOut( 300 ).delay( 800 ).fadeIn( 400 );
A: Does there have to be a target? surely you can use a random target to queue events sequentially so long as the target is constant...below I'm using the parent of an animation target to store the queue.
//example of adding sequential effects through
//event handlers and a jquery event trigger
jQuery( document ).unbind( "bk_prompt_collapse.slide_up" );
jQuery( document ).bind( "bk_prompt_collapse.slide_up" , function( e, j_obj ) {
jQuery(j_obj).queue(function() {
//running our timed effect
jQuery(this).find('div').slideUp(400);
//adding a fill delay to the parent
jQuery(this).delay(400).dequeue();
});
});
//the last action removes the content from the dom
//if its in the queue then it will fire sequentially
jQuery( document ).unbind( "bk_prompt_collapse.last_action" );
jQuery( document ).bind( "bk_prompt_collapse.last_action" , function( e, j_obj ) {
jQuery(j_obj).queue(function() {
//Hot dog!!
jQuery(this).remove().dequeue();
});
});
jQuery("tr.bk_removing_cart_row").trigger(
"bk_prompt_collapse" ,
jQuery("tr.bk_removing_cart_row")
);
Not sure if its possible but it seems like you could bind .dequeue() to fire when another jquery event fires, instead of firing inline in my example above? effectively halting an animation queue?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75134",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: Best way to implement Google Custom Search on an aspx page Google custom search code is provided as a form tag. However, Asp.net only allows a single form tag on a page. What is the best way to implement their code so you can include it on an aspx page (say as part of a Masterpage or navigation element).
A: You can have multiple form tags on an ASP.NET page. The limitation is on server-side (runat="server") form tags.
You can implement two form tags (or more) as long as only one has the runat="server" attribute and one is not contained in the other. Example:
<body>
<form action="http://www.google.com/cse" id="cse-search-box"> ... </form>
<form runat="server" id="aspNetform"> ... </form>
<body>
A: You may be able to have multiple form tags, but note that they cannot be nested. You'll run into all kinds of weirdness in that scenario (e.g., I've seen cases where the opening tag for the nested form apparently gets ignored and then its closing tag winds up closing the "parent" form out).
A: You'll need to remove the form tag and use javascript send the query. Have a look at
http://my6solutions.com/post/2009/04/19/Fixing-Google-Custom-Search-nested-form-tags-in-asp-net-pages.aspx
I have included the before and after code as well. So you can see what I've done to integrate it with blogengine .net.
A: You could use Javascript:
<input name="Query" type="text" class="searchField" id="Query" value="Search" size="15" onfocus="if(this.value == 'Search') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Search'; }" onkeydown="var event = event || window.event; var key = event.which || event.keyCode; if(key==13) window.open('http://www.google.com/search?q=' + getElementById('Query').value ); " /><input name="" type="button" class="searchButton" value="go" onclick="window.open('http://www.google.com/search?q=' + getElementById('Query').value );" />
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75139",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do you quickly find the URL for a .NET framework method on MSDN? How to you find the URL that represents the documentation of a .NET framework method on the MSDN website?
For example, I want to embed the URL for the .NET framework method into some comments in some code. The normal "mangled" URL that one gets searching MSDN isn't very friendly looking: http://msdn.microsoft.com/library/xd12z8ts.aspx. Using a Google search URL isn't all that pretty looking either.
What I really want a URL that can be embedded in comments that is plain and easy to read. For example,
// blah blah blah. See http://<....>/System.Byte.ToString for more information
A: A lot of the time you can merely append the lowercase namespace reference to the domain:
http://msdn.microsoft.com/en-us/library/system.windows.application_events.aspx
Moreover, for say the .Net 2.0 version (or any specific version) you can add "(VS.80)":
http://msdn.microsoft.com/en-us/library/system.windows.forms.button(VS.80).aspx
Other versions:
*
*.Net 1.1 -> (VS.71)
*.Net 2.0 -> (VS.80)
*.Net 3.0 -> (VS.85)
*.Net 3.5 -> (VS.90)
Try it for a method (Control.IsInputChar) like so:
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.isinputchar.aspx
A: It's probably quickest to just type it into Google in my experience.
EDIT:
Now that you've edited your post to clarify what you actually meant I would say that embedding URLs in your comments is nice but you really have no guarantees that either the mangled URL or the pretty one will exist in future.
A: It's simple -- just add the name of the method to the end of http://msdn.microsoft.com//library/.
For example, to find the URL for the System.Byte.ToString method go to http://msdn.microsoft.com//library/System.Byte.ToString
A: In my experiecne, googling it works faster than msdn search.
A: I find that googling "msdn " does it.
ie - msdn System.Web.UI.WebControls.Repeater.ItemDataBound
A: Create a Search engine for MSDN Library in Firefox
Like this perhaps?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75145",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: General Development Notes During a typical day programming, I implement functions in a way that I would like to remember. For instance, say I tuned a DB insert function that, when I come across the situation again, I want to find what I did to resuse.
I need a place to keep the solution(what I did), and I need to find it somehow, which may be months or a year later. Using a mind map sort of idea, I was thinking about a personal wiki, but then I heard the stackoverflow podcast mention using this site for such a reason. Does anybody else keep track of slick things they've done so that they may find it sometime in the future. If so, what did you use, and in general, how do you use it?
i like to personal blog idea and using the stack for it. i'll try the idea of posting at the stack and then answering it myself, with the benefit of other people potentially giving their opinion.
As long a the stack will be around for a while :)
A: Jeff Atwood recommends using Stack Overflow for this kind of thing. Post a question (your problem) and then post an answer (the solution you found). This lets you share the information with the world, and maybe get some valuable feedback or better solutions.
(Wow, I got downvoted for repeating what Jeff Atwood said. I won't do that again, I promise.)
A: I use neomem all the time. I write notes to myself. Then I can later search for it.
A: You may find these questions useful
*
*Where do you store your code snippets?
*Tracking useful information
*What is you preferred site for code snippets?
A: I use a personal Wiki, my del.icio.us bookmarks and my own blog for that. Usually my blog: When I learn something that I know I might stumble on again I write a short post in my blog.
A: I use WikiDPad or Wiki-On-A-Stick. It works not only for code snippets but also to take notes, record typical problems you get and how to solve them and documentation. Take my word for it, it makes your job a LOT more easier if you have proper notes... and add the power of interlinking to it and you have a killer resource. I have very bad memory and taking notes has improved my performance by an order of magnitude. It also saves you from having to ask someone the same question twice or thrice. Also, if anyone asks the same question, you can just helpfully point them to the wiki and they can read it and add to it if they need to.
A: The technical term for what you are thinking of is "code snippets", and googling for that will find you many programs designed to store them for a variety of platforms, including entirely web-based ones such as this one.
A: I set up dekiwiki on a server at work that my coworkers and I use for company specifics stuff but also for general programming tips that arise as well.
A: A simple wiki, may be useful. SeeTiki Wiki
A: I always put it on my blog. Not only am I able to get back to it later, there is also a chance that it can help someone else as well.
A: It's oldschool, but I keep notes in a notebook. Makes remembering solutions (or the problems that caused them) a bit easier. Usually I make 1-2 pages of notes a day.
The digital equivalent of this would be keeping a private blog or journal. Easy enough to add a search program to help you find stuff.
Worthwhile things that my boss might be interested in, like bugs and user calls all get entered into bug tracking software where it is more formally handled.
A: I use the excellent Trac project management system for my personal projects, and I use it's wiki as a brainstorming and note-taking tool. And, because it also hooks into the Subversion repository and the bug tracking system, I can link from my notes right to a particular section of code or a bug report.
A: I keep my personal projects on assembla. Wiki, Issue Tracking, Source Control... very useful.
A: Check to see if your editor has some kind of annotations feature. Ideally you could link a particular location in code with a small note, and store it in a centralized place. If it doesn't, that kind of plugin wouldn't be too hard to build, your biggest hurdle is going to be how to link the piece of code to a file (due to the volatile nature of code) and even that one isn't insurmountable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75153",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How can I limit execution time for a Perl script in IIS? This is a shared hosting environment. I control the server, but not necessarily the content. I've got a client with a Perl script that seems to run out of control every now and then and suck down 50% of the processor until the process is killed.
With ASP scripts, I'm able to restrict the amount of time the script can run, and IIS will simply shut it down after, say, 90 seconds. This doesn't work for Perl scripts, since it's running as a cgi process (and actually launches an external process to execute the script).
Similarly, techniques that look for excess resource consumption in a worker process will likely not see this, since the resource that's being consumed (the processor) is being chewed up by a child process rather than the WP itself.
Is there a way to make IIS abort a Perl script (or other cgi-type process) that's running too long? How??
A: On a UNIX-style system, I would use a signal handler trapping ALRM events, then use the alarm function to start a timer before starting an action that I expected might timeout. If the action completed, I'd use alarm(0) to turn off the alarm and exit normally, otherwise the signal handler should pick it up to close everything up gracefully.
I have not worked with perl on Windows in a while and while Windows is somewhat POSIXy, I cannot guarantee this will work; you'll have to check the perl documentation to see if or to what extent signals are supported on your platform.
More detailed information on signal handling and this sort of self-destruct programming using alarm() can be found in the Perl Cookbook. Here's a brief example lifted from another post and modified a little:
eval {
# Create signal handler and make it local so it falls out of scope
# outside the eval block
local $SIG{ALRM} = sub {
print "Print this if we time out, then die.\n";
die "alarm\n";
};
# Set the alarm, take your chance running the routine, and turn off
# the alarm if it completes.
alarm(90);
routine_that_might_take_a_while();
alarm(0);
};
A: The ASP script timeout applies to all scripting languages. If the script is running in an ASP page, the script timeout will close the offending page.
A: An update on this one...
It turns out that this particular script apparently is a little buggy, and that the Googlebot has the uncanny ability to "press it's buttons" and drive it crazy. The script is an older, commercial application that does calendaring. Apparently, it displays links for "next month" and "previous month", and if you follow the "next month" too many times, you'll fall off a cliff. The resulting page, however, still includes a "next month" link. Googlebot would continuously beat the script to death and chew up the processor.
Curiously, adding a robots.txt with Disallow: / didn't solve the problem. Either the Googlebot had already gotten ahold of the script and wouldn't let loose, or else it simply was disregarding the robots.txt.
Anyway, Microsoft's Process Explorer (http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx) was a huge help, as it allowed me to see the environment for the perl.exe process in more detail, and I was able to determine from it that it was the Googlebot causing my problems.
Once I knew that (and determined that robots.txt wouldn't solve the problem), I was able to use IIS directly to block all traffic to this site from *.googlebot.com, which worked well in this case, since we don't care if Google indexes this content.
Thanks much for the other ideas that everyone posted!
Eric Longman
A: Googling for "iis cpu limit" gives these hits:
http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/38fb0130-b14b-48d5-a0a2-05ca131cf4f2.mspx?mfr=true
"The CPU monitoring feature monitors and automatically shuts down worker processes that consume large amounts of CPU time. CPU monitoring is enabled for individual application pools."
http://technet.microsoft.com/en-us/library/cc728189.aspx
"By using CPU monitoring, you can monitor worker processes for CPU usage and optionally shut down the worker processes that consume large amounts of CPU time. CPU monitoring is only available in worker process isolation mode."
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75156",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: What is the easiest way to get total number for lines of code (LOC) in SQL Server? I need to provide statistics on how many lines of code (LOC) associated with a system. The application part is easy but I need to also include any code residing within the SQL Server database. This would apply to stored procedures, functions, triggers, etc.
How can I easily get that info? Can it be done (accurately) with TSQL by querying the system tables\sprocs, etc?
A: In Management Studio, right click the database you want a line count for... select Tasks -> Generate Scripts, you can select script options in the Scripts Wizard to include or exclude objects, when you have it set the way you like it can generate to a new query window
A: Just select all the text from syscomments and count how many lines you have. The text column is text, which you can't really see in Management studio, so I would write a program or power shell script like this:
$conn = new-object System.Data.SqlClient.SqlConnection("Server=server;Database=database;Integrated Security=SSPI")
$cmd = new-object System.Data.SqlClient.SqlCommand("select text from syscomments", $conn)
$conn.Open()
$reader = $cmd.ExecuteReader()
$reader.Read() | out-null
$reader.GetString(0) | clip
$reader.Close()
$conn.Close()
Paste into an editor that has a line count, and you're done.
A: Personally you might just script the objects to file using SQL Server Management tools, it will get a few extras in there for the checks to do the drop first incase the object exists.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75159",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is there a working on-the-fly compilation in NetBeans 6.5 and how well is it doing? I learned today that NetBeans 6.5 should have an on-the-fly compilation of (single) Java files. This feature is well known from Eclipse: Simply store the file and the compiled class is stored, too. Is NetBeans working the same way? If not, how is it ticking?
A: Yes, it's the same I believe...
Here's a video showing it in action
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75168",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Create instance of generic type in Java? Is it possible to create an instance of a generic type in Java? I'm thinking based on what I've seen that the answer is no (due to type erasure), but I'd be interested if anyone can see something I'm missing:
class SomeContainer<E>
{
E createContents()
{
return what???
}
}
EDIT: It turns out that Super Type Tokens could be used to resolve my issue, but it requires a lot of reflection-based code, as some of the answers below have indicated.
I'll leave this open for a little while to see if anyone comes up with anything dramatically different than Ian Robertson's Artima Article.
A: You'll need some kind of abstract factory of one sort or another to pass the buck to:
interface Factory<E> {
E create();
}
class SomeContainer<E> {
private final Factory<E> factory;
SomeContainer(Factory<E> factory) {
this.factory = factory;
}
E createContents() {
return factory.create();
}
}
A: When you are working with E at compile time you don't really care the actual generic type "E" (either you use reflection or work with base class of generic type) so let the subclass provide instance of E.
abstract class SomeContainer<E>
{
abstract protected E createContents();
public void doWork(){
E obj = createContents();
// Do the work with E
}
}
class BlackContainer extends SomeContainer<Black>{
protected Black createContents() {
return new Black();
}
}
A: Here is an option I came up with, it may help:
public static class Container<E> {
private Class<E> clazz;
public Container(Class<E> clazz) {
this.clazz = clazz;
}
public E createContents() throws Exception {
return clazz.newInstance();
}
}
EDIT: Alternatively you can use this constructor (but it requires an instance of E):
@SuppressWarnings("unchecked")
public Container(E instance) {
this.clazz = (Class<E>) instance.getClass();
}
A: If you want not to type class name twice during instantiation like in:
new SomeContainer<SomeType>(SomeType.class);
You can use factory method:
<E> SomeContainer<E> createContainer(Class<E> class);
Like in:
public class Container<E> {
public static <E> Container<E> create(Class<E> c) {
return new Container<E>(c);
}
Class<E> c;
public Container(Class<E> c) {
super();
this.c = c;
}
public E createInstance()
throws InstantiationException,
IllegalAccessException {
return c.newInstance();
}
}
A: Java unfortunatly does not allow what you want to do. See the official workaround :
You cannot create an instance of a type parameter. For example, the following code causes a compile-time error:
public static <E> void append(List<E> list) {
E elem = new E(); // compile-time error
list.add(elem);
}
As a workaround, you can create an object of a type parameter through reflection:
public static <E> void append(List<E> list, Class<E> cls) throws Exception {
E elem = cls.newInstance(); // OK
list.add(elem);
}
You can invoke the append method as follows:
List<String> ls = new ArrayList<>();
append(ls, String.class);
A: You can use:
Class.forName(String).getConstructor(arguments types).newInstance(arguments)
But you need to supply the exact class name, including packages, eg. java.io.FileInputStream. I used this to create a math expressions parser.
A: Hope this's not too late to help!!!
Java is type-safe, meaning that only Objects are able to create instances.
In my case I cannot pass parameters to the createContents method. My solution is using extends unlike the answer below.
private static class SomeContainer<E extends Object> {
E e;
E createContents() throws Exception{
return (E) e.getClass().getDeclaredConstructor().newInstance();
}
}
This is my example case in which I can't pass parameters.
public class SomeContainer<E extends Object> {
E object;
void resetObject throws Exception{
object = (E) object.getClass().getDeclaredConstructor().newInstance();
}
}
Using reflection create run time error, if you extends your generic class with none object type. To extends your generic type to object convert this error to compile time error.
A: Use the TypeToken<T> class:
public class MyClass<T> {
public T doSomething() {
return (T) new TypeToken<T>(){}.getRawType().newInstance();
}
}
A: You are correct. You can't do new E(). But you can change it to
private static class SomeContainer<E> {
E createContents(Class<E> clazz) {
return clazz.newInstance();
}
}
It's a pain. But it works. Wrapping it in the factory pattern makes it a little more tolerable.
A: I thought I could do that, but quite disappointed: it doesn't work, but I think it still worths sharing.
Maybe someone can correct:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
interface SomeContainer<E> {
E createContents();
}
public class Main {
@SuppressWarnings("unchecked")
public static <E> SomeContainer<E> createSomeContainer() {
return (SomeContainer<E>) Proxy.newProxyInstance(Main.class.getClassLoader(),
new Class[]{ SomeContainer.class }, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Class<?> returnType = method.getReturnType();
return returnType.newInstance();
}
});
}
public static void main(String[] args) {
SomeContainer<String> container = createSomeContainer();
[*] System.out.println("String created: [" +container.createContents()+"]");
}
}
It produces:
Exception in thread "main" java.lang.ClassCastException: java.lang.Object cannot be cast to java.lang.String
at Main.main(Main.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Line 26 is the one with the [*].
The only viable solution is the one by @JustinRudd
A: An imporovement of @Noah's answer.
Reason for Change
a] Is safer if more then 1 generic type is used in case you changed the order.
b] A class generic type signature changes from time to time so that you will not be surprised by unexplained exceptions in the runtime.
Robust Code
public abstract class Clazz<P extends Params, M extends Model> {
protected M model;
protected void createModel() {
Type[] typeArguments = ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments();
for (Type type : typeArguments) {
if ((type instanceof Class) && (Model.class.isAssignableFrom((Class) type))) {
try {
model = ((Class<M>) type).newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
}
Or use the one liner
One Line Code
model = ((Class<M>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1]).newInstance();
A: what you can do is -
*
*First declare the variable of that generic class
2.Then make a constructor of it and instantiate that object
*Then use it wherever you want to use it
example-
1
private Class<E> entity;
2
public xyzservice(Class<E> entity) {
this.entity = entity;
}
public E getEntity(Class<E> entity) throws InstantiationException, IllegalAccessException {
return entity.newInstance();
}
3.
E e = getEntity(entity);
A: package org.foo.com;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
/**
* Basically the same answer as noah's.
*/
public class Home<E>
{
@SuppressWarnings ("unchecked")
public Class<E> getTypeParameterClass()
{
Type type = getClass().getGenericSuperclass();
ParameterizedType paramType = (ParameterizedType) type;
return (Class<E>) paramType.getActualTypeArguments()[0];
}
private static class StringHome extends Home<String>
{
}
private static class StringBuilderHome extends Home<StringBuilder>
{
}
private static class StringBufferHome extends Home<StringBuffer>
{
}
/**
* This prints "String", "StringBuilder" and "StringBuffer"
*/
public static void main(String[] args) throws InstantiationException, IllegalAccessException
{
Object object0 = new StringHome().getTypeParameterClass().newInstance();
Object object1 = new StringBuilderHome().getTypeParameterClass().newInstance();
Object object2 = new StringBufferHome().getTypeParameterClass().newInstance();
System.out.println(object0.getClass().getSimpleName());
System.out.println(object1.getClass().getSimpleName());
System.out.println(object2.getClass().getSimpleName());
}
}
A: If you need a new instance of a type argument inside a generic class then make your constructors demand its class...
public final class Foo<T> {
private Class<T> typeArgumentClass;
public Foo(Class<T> typeArgumentClass) {
this.typeArgumentClass = typeArgumentClass;
}
public void doSomethingThatRequiresNewT() throws Exception {
T myNewT = typeArgumentClass.newInstance();
...
}
}
Usage:
Foo<Bar> barFoo = new Foo<Bar>(Bar.class);
Foo<Etc> etcFoo = new Foo<Etc>(Etc.class);
Pros:
*
*Much simpler (and less problematic) than Robertson's Super Type Token (STT) approach.
*Much more efficient than the STT approach (which will eat your cellphone for breakfast).
Cons:
*
*Can't pass Class to a default constructor (which is why Foo is final). If you really do need a default constructor you can always add a setter method but then you must remember to give her a call later.
*Robertson's objection... More Bars than a black sheep (although specifying the type argument class one more time won't exactly kill you). And contrary to Robertson's claims this does not violate the DRY principal anyway because the compiler will ensure type correctness.
*Not entirely Foo<L>proof. For starters... newInstance() will throw a wobbler if the type argument class does not have a default constructor. This does apply to all known solutions though anyway.
*Lacks the total encapsulation of the STT approach. Not a big deal though (considering the outrageous performance overhead of STT).
A: You can do this now and it doesn't require a bunch of reflection code.
import com.google.common.reflect.TypeToken;
public class Q26289147
{
public static void main(final String[] args) throws IllegalAccessException, InstantiationException
{
final StrawManParameterizedClass<String> smpc = new StrawManParameterizedClass<String>() {};
final String string = (String) smpc.type.getRawType().newInstance();
System.out.format("string = \"%s\"",string);
}
static abstract class StrawManParameterizedClass<T>
{
final TypeToken<T> type = new TypeToken<T>(getClass()) {};
}
}
Of course if you need to call the constructor that will require some reflection, but that is very well documented, this trick isn't!
Here is the JavaDoc for TypeToken.
A: From Java Tutorial - Restrictions on Generics:
Cannot Create Instances of Type Parameters
You cannot create an instance of a type parameter. For example, the following code causes a compile-time error:
public static <E> void append(List<E> list) {
E elem = new E(); // compile-time error
list.add(elem);
}
As a workaround, you can create an object of a type parameter through reflection:
public static <E> void append(List<E> list, Class<E> cls) throws Exception {
E elem = cls.getDeclaredConstructor().newInstance(); // OK
list.add(elem);
}
You can invoke the append method as follows:
List<String> ls = new ArrayList<>();
append(ls, String.class);
A: Think about a more functional approach: instead of creating some E out of nothing (which is clearly a code smell), pass a function that knows how to create one, i.e.
E createContents(Callable<E> makeone) {
return makeone.call(); // most simple case clearly not that useful
}
A: In Java 8 you can use the Supplier functional interface to achieve this pretty easily:
class SomeContainer<E> {
private Supplier<E> supplier;
SomeContainer(Supplier<E> supplier) {
this.supplier = supplier;
}
E createContents() {
return supplier.get();
}
}
You would construct this class like this:
SomeContainer<String> stringContainer = new SomeContainer<>(String::new);
The syntax String::new on that line is a constructor reference.
If your constructor takes arguments you can use a lambda expression instead:
SomeContainer<BigInteger> bigIntegerContainer
= new SomeContainer<>(() -> new BigInteger(1));
A: I don't know if this helps, but when you subclass (including anonymously) a generic type, the type information is available via reflection. e.g.,
public abstract class Foo<E> {
public E instance;
public Foo() throws Exception {
instance = ((Class)((ParameterizedType)this.getClass().
getGenericSuperclass()).getActualTypeArguments()[0]).newInstance();
...
}
}
So, when you subclass Foo, you get an instance of Bar e.g.,
// notice that this in anonymous subclass of Foo
assert( new Foo<Bar>() {}.instance instanceof Bar );
But it's a lot of work, and only works for subclasses. Can be handy though.
A: Here's an implementation of createContents that uses TypeTools (which I authored) to resolve the raw class represented by E:
E createContents() throws Exception {
return TypeTools.resolveRawArgument(SomeContainer.class, getClass()).newInstance();
}
This approach only works if SomeContainer is subclassed so the actual value of E is captured in a type definition:
class SomeStringContainer extends SomeContainer<String>
Otherwise the value of E is erased at runtime and is not recoverable.
A: As you said, you can't really do it because of type erasure. You can sort of do it using reflection, but it requires a lot of code and lot of error handling.
A: If you mean
new E()
then it is impossible. And I would add that it is not always correct - how do you know if E has public no-args constructor?
But you can always delegate creation to some other class that knows how to create an instance - it can be Class<E> or your custom code like this
interface Factory<E>{
E create();
}
class IntegerFactory implements Factory<Integer>{
private static int i = 0;
Integer create() {
return i++;
}
}
A: return (E)((Class)((ParameterizedType)this.getClass().getGenericSuperclass()).getActualTypeArguments()[0]).newInstance();
A: You can achieve this with the following snippet:
import java.lang.reflect.ParameterizedType;
public class SomeContainer<E> {
E createContents() throws InstantiationException, IllegalAccessException {
ParameterizedType genericSuperclass = (ParameterizedType)
getClass().getGenericSuperclass();
@SuppressWarnings("unchecked")
Class<E> clazz = (Class<E>)
genericSuperclass.getActualTypeArguments()[0];
return clazz.newInstance();
}
public static void main( String[] args ) throws Throwable {
SomeContainer< Long > scl = new SomeContainer<>();
Long l = scl.createContents();
System.out.println( l );
}
}
A: Here is an improved solution, based on ParameterizedType.getActualTypeArguments, already mentioned by @noah, @Lars Bohl, and some others.
First small improvement in the implementation. Factory should not return instance, but a type. As soon as you return instance using Class.newInstance() you reduce a scope of usage. Because only no-arguments constructors can be invoke like this. A better way is to return a type, and allow a client to choose, which constructor he wants to invoke:
public class TypeReference<T> {
public Class<T> type(){
try {
ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
if (pt.getActualTypeArguments() == null || pt.getActualTypeArguments().length == 0){
throw new IllegalStateException("Could not define type");
}
if (pt.getActualTypeArguments().length != 1){
throw new IllegalStateException("More than one type has been found");
}
Type type = pt.getActualTypeArguments()[0];
String typeAsString = type.getTypeName();
return (Class<T>) Class.forName(typeAsString);
} catch (Exception e){
throw new IllegalStateException("Could not identify type", e);
}
}
}
Here is a usage examples. @Lars Bohl has shown only a signe way to get reified geneneric via extension. @noah only via creating an instance with {}. Here are tests to demonstrate both cases:
import java.lang.reflect.Constructor;
public class TypeReferenceTest {
private static final String NAME = "Peter";
private static class Person{
final String name;
Person(String name) {
this.name = name;
}
}
@Test
public void erased() {
TypeReference<Person> p = new TypeReference<>();
Assert.assertNotNull(p);
try {
p.type();
Assert.fail();
} catch (Exception e){
Assert.assertEquals("Could not identify type", e.getMessage());
}
}
@Test
public void reified() throws Exception {
TypeReference<Person> p = new TypeReference<Person>(){};
Assert.assertNotNull(p);
Assert.assertEquals(Person.class.getName(), p.type().getName());
Constructor ctor = p.type().getDeclaredConstructor(NAME.getClass());
Assert.assertNotNull(ctor);
Person person = (Person) ctor.newInstance(NAME);
Assert.assertEquals(NAME, person.name);
}
static class TypeReferencePerson extends TypeReference<Person>{}
@Test
public void reifiedExtenension() throws Exception {
TypeReference<Person> p = new TypeReferencePerson();
Assert.assertNotNull(p);
Assert.assertEquals(Person.class.getName(), p.type().getName());
Constructor ctor = p.type().getDeclaredConstructor(NAME.getClass());
Assert.assertNotNull(ctor);
Person person = (Person) ctor.newInstance(NAME);
Assert.assertEquals(NAME, person.name);
}
}
Note: you can force the clients of TypeReference always use {} when instance is created by making this class abstract: public abstract class TypeReference<T>. I've not done it, only to show erased test case.
A: Note that a generic type in kotlin could come without a default constructor.
implementation("org.objenesis","objenesis", "3.2")
val fooType = Foo::class.java
var instance: T = try {
fooType.newInstance()
} catch (e: InstantiationException) {
// Use Objenesis because the fooType class has not a default constructor
val objenesis: Objenesis = ObjenesisStd()
objenesis.newInstance(fooType)
}
*
*Withou default constructor
*Objenesis
A: I was inspired with Ira's solution and slightly modified it.
abstract class SomeContainer<E>
{
protected E createContents() {
throw new NotImplementedException();
}
public void doWork(){
E obj = createContents();
// Do the work with E
}
}
class BlackContainer extends SomeContainer<Black>{
// this method is optional to implement in case you need it
protected Black createContents() {
return new Black();
}
}
In case you need E instance you can implement createContents method in your derived class (or leave it not implemented in case you don't need it.
A: As you mentioned, you can't get an instance from generics. IMO, you have to change the design and make use of FACTORY METHOD design pattern. In this manner you don't need your class or method to be generics:
class abstract SomeContainer{
Parent execute(){
return method1();
}
abstract Parent method1();
}
class Child1 extends Parent{
Parent method1(){
return new Parent();
}
}
class Child2 extends Parent{
Parent method1(){
return new Child2();
}
}
A: You can with a classloader and the class name, eventually some parameters.
final ClassLoader classLoader = ...
final Class<?> aClass = classLoader.loadClass("java.lang.Integer");
final Constructor<?> constructor = aClass.getConstructor(int.class);
final Object o = constructor.newInstance(123);
System.out.println("o = " + o);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75175",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "643"
} |
Q: How to display a dynamically allocated array in the Visual Studio debugger? If you have a statically allocated array, the Visual Studio debugger can easily display all of the array elements. However, if you have an array allocated dynamically and pointed to by a pointer, it will only display the first element of the array when you click the + to expand it. Is there an easy way to tell the debugger, show me this data as an array of type Foo and size X?
A: For,
int **a; //row x col
add this to watch
(int(**)[col])a,row
A: Yet another way to do this is specified here in MSDN.
In short, you can display a character array as several types of string. If you've got an array declared as:
char *a = new char[10];
You could print it as a unicode string in the watch window with the following:
a,su
See the tables on the MSDN page for all of the different conversions possible since there are quite a few. Many different string variants, variants to print individual items in the array, etc.
A: There are two methods to view data in an array m4x4:
float m4x4[16]={
1.f,0.f,0.f,0.f,
0.f,2.f,0.f,0.f,
0.f,0.f,3.f,0.f,
0.f,0.f,0.f,4.f
};
One way is with a Watch window (Debug/Windows/Watch). Add watch =
m4x4,16
This displays data in a list:
Another way is with a Memory window (Debug/Windows/Memory). Specify a memory start address =
m4x4
This displays data in a table, which is better for two and three dimensional matrices:
Right-click on the Memory window to determine how the binary data is visualized. Choices are limited to integers, floats and some text encodings.
A: In a watch window, add a comma after the name of the array, and the amount of items you want to be displayed.
A: Yes, simple.
say you have
char *a = new char[10];
writing in the debugger:
a,10
would show you the content as if it were an array.
A: You can find a list of many things you can do with variables in the watch window in this gem in the docs:
https://msdn.microsoft.com/en-us/library/75w45ekt.aspx
For a variable a, there are the things already mentioned in other answers like
a,10
a,su
but there's a whole lot of other specifiers for format and size, like:
a,en (shows an enum value by name instead of the number)
a,mb (to show 1 line of 'memory' view right there in the watch window)
A: a revisit:
let's assume you have a below pointer:
double ** a; // assume 5*10
then you can write below in Visual Studio debug watch:
(double(*)[10]) a[0],5
which will cast it into an array like below, and you can view all contents in one go.
double[5][10] a;
A: For MFC arrays (CArray, CStringArray, ...)
following the next link in its Tip #4
http://www.codeproject.com/Articles/469416/10-More-Visual-Studio-Debugging-Tips-for-Native-De
For example for "CArray pArray", add in the Watch windows
pArray.m_pData,5
to see the first 5 elements .
If pArray is a two dimensional CArray you can look at any of the elements of the second dimension using the next syntax:
pArray.m_pData[x].m_pData,y
A: I haven't found a way to use this with a multidimensional array. But you can at least (if you know the index of your desired entry) add a watch to a specific value. Simply use the index-operator.
For an Array named current, which has an Array named Attribs inside, which has an Array named Attrib inside, it should look like this if you like to have to position 26:
((*((*current).Attribs)).Attrib)[26]
You can also use an offset
((*((*current).Attribs)).Attrib)+25
will show ne "next" 25 elements.
(I'm using VS2008, this shows only 25 elements maximum).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75180",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "154"
} |
Q: Problem accessing the content of a div when that content came from an Ajax call Here's a very simple Prototype example.
All it does is, on window load, an ajax call which sticks some html into a div.
<html>
<head>
<script type="text/javascript" src="scriptaculous/lib/prototype.js"></script>
<script type="text/javascript">
Event.observe(window, 'load', function(){
new Ajax.Request('get-table.php', {
method: 'get',
onSuccess: function(response){
$('content').innerHTML = response.responseText;
//At this call, the div has HTML in it
click1();
},
onFailure: function(){
alert('Fail!');
}
});
//At this call, the div is empty
click1();
});
function click1(){if($('content').innerHTML){alert('Found content');}else{alert('Empty div');}}
</script>
</head>
<body><div id="content"></div></body>
</html>
The thing that's confusing is the context in which Prototype understands that the div actually has stuff in it.
If you look at the onSuccess part of the ajax call, you'll see that at that point $('content').innerHTML has stuff in it.
However when I check $('content').innerHTML right after the ajax call, it appears to be empty.
This has to be some fundamental misunderstanding on my part. Anyone care to explain it to me?
Edit
I just want to clarify something. I realize that the Ajax call is asynchronous.
Here's the actual order that things are being executed and why it's confusing to me:
*
*The page loads.
*The Ajax request to get-table.php is made.
*The call to click1() INSIDE onSuccess happens. I see an alert that the div has content.
*The call to click1() AFTER the Ajax call happens. I see an alert that the div is empty.
So it's like the code is executing in the order it's written but the DOM is not updating in the same order.
Edit 2
So the short answer is that putting the code in onSuccess is the correct place.
Another case to consider is the one where you do an Ajax call and then do another Ajax call from the onSuccess of the first call like this:
new Ajax.Request('foo.php',{
method: 'get',
onSuccess: function(response){
doAnotherAjaxCall();
}
});
function doAnotherAjaxCall(){
new Ajax.Request('foo.php',{
method: 'get',
onSuccess: function(response){
//Anything that needs to happen AFTER the call to doAnotherAjaxCall() above
//needs to happen here!
}
});
}
A: The first letter of AJAX stands for "asynchronous". This means that the AJAX call is performed in the background, i.e. the AJAX request call immediately returns. This means that the code immediately after it is normally actually executed before the onSuccess handler gets called (and before the AJAX request has even finished).
Taking into account your edited question: in some browsers (e.g. Firefox), alert boxes are not as modal as you might think. Asynchronous code may pop up an alert box even if another one is already open. In that case, the newer alert box (the one from the asynchronous code) gets displayed on top of the older one. This creates the illusion that the asynchronous code got executed first.
A: Without having tried your code: The AJAX call is executed asynchronously. Meaning that your Ajax.Request fires, then goes on to the click1() call that tells you the div is empty. At some point after that the Ajax request is finished and content is actually put into the div. At this point the onSuccess function is executed and you get the content you expected.
A: It's Ajax call, which is asynchronous. That means right after that request call, response hasn't come back yet, that's why $('content') is still empty.
A: The onSuccess element of the function call you are making to handle the AJAX call is executed at the time you receive a response from get-table.php. This is a separate Javascript function which you are telling the browser to call when you get an answer from get-table.php. The code below your AJAX.Request call is accessed as soon as the AJAX.Request call is made, but not necessarily before get-table.php is called. So yes I think there is a bit of a fundamental misunderstanding of how AJAX works, likely due to using a library to hide the details.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75181",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Detecting a chroot jail from within How can one detect being in a chroot jail without root privileges? Assume a standard BSD or Linux system. The best I came up with was to look at the inode value for "/" and to consider whether it is reasonably low, but I would like a more accurate method for detection.
[edit 20080916 142430 EST] Simply looking around the filesystem isn't sufficient, as it's not difficult to duplicate things like /boot and /dev to fool the jailed user.
[edit 20080916 142950 EST] For Linux systems, checking for unexpected values within /proc is reasonable, but what about systems that don't support /proc in the first place?
A: On Linux with root permissions, test if the root directory of the init process is your root directory. Although /proc/1/root is always a symbolic link to /, following it leads to the “master” root directory (assuming the init process is not chrooted, but that's hardly ever done). If /proc isn't mounted, you can bet you're in a chroot.
[ "$(stat -c %d:%i /)" != "$(stat -c %d:%i /proc/1/root/.)" ]
# With ash/bash/ksh/zsh
! [ -x /proc/1/root/. ] || [ /proc/1/root/. -ef / ]
This is more precise than looking at /proc/1/exe because that could be different outside a chroot if init has been upgraded since the last boot or if the chroot is on the main root filesystem and init is hard linked in it.
If you do not have root permissions, you can look at /proc/1/mountinfo and /proc/$$/mountinfo (briefly documented in filesystems/proc.txt in the Linux kernel documentation). This file is world-readable and contains a lot of information about each mount point in the process's view of the filesystem. The paths in that file are restricted by the chroot affecting the reader process, if any. If the process reading /proc/1/mountinfo is chrooted into a filesystem that's different from the global root (assuming pid 1's root is the global root), then no entry for / appears in /proc/1/mountinfo. If the process reading /proc/1/mountinfo is chrooted to a directory on the global root filesystem, then an entry for / appears in /proc/1/mountinfo, but with a different mount id. Incidentally, the root field ($4) indicates where the chroot is in its master filesystem. Again, this is specific to Linux.
[ "$(awk '$5=="/" {print $1}' </proc/1/mountinfo)" != "$(awk '$5=="/" {print $1}' </proc/$$/mountinfo)" ]
A: If you are not in a chroot and the root filesystem is ext2/ext3/ext4, the inode for / will always be 2. You may check that using
stat -c %i /
or
ls -id /
Interresting, but let's try to find path of chroot directory. Ask to stat on which device / is located:
stat -c %04D /
First byte is major of device and lest byte is minor. For example, 0802, means major 8, minor 1. If you check in /dev, you will see this device is /dev/sda2. If you are root you can directly create correspondong device in your chroot:
mknode /tmp/root_dev b 8 1
Now, let's find inode associated to our chroot. debugfs allows list contents of files using inode numbers. For exemple, ls -id / returned 923960:
sudo debugfs /tmp/root_dev -R 'ls <923960>'
923960 (12) . 915821 (32) .. 5636100 (12) var
5636319 (12) lib 5636322 (12) usr 5636345 (12) tmp
5636346 (12) sys 5636347 (12) sbin 5636348 (12) run
5636349 (12) root 5636350 (12) proc 5636351 (12) mnt
5636352 (12) home 5636353 (12) dev 5636354 (12) boot
5636355 (12) bin 5636356 (12) etc 5638152 (16) selinux
5769366 (12) srv 5769367 (12) opt 5769375 (3832) media
Interesting information is inode of .. entry: 915821. I can ask its content:
sudo debugfs /tmp/root_dev -R 'ls <915821>'
915821 (12) . 2 (12) .. 923960 (20) debian-jail
923961 (4052) other-jail
Directory called debian-jail has inode 923960. So last component of my chroot dir is debian-jail. Let's see parent directory (inode 2) now:
sudo debugfs /tmp/root_dev -R 'ls <2>'
2 (12) . 2 (12) .. 11 (20) lost+found 1046529 (12) home
130817 (12) etc 784897 (16) media 3603 (20) initrd.img
261633 (12) var 654081 (12) usr 392449 (12) sys 392450 (12) lib
784898 (12) root 915715 (12) sbin 1046530 (12) tmp
1046531 (12) bin 784899 (12) dev 392451 (12) mnt
915716 (12) run 12 (12) proc 1046532 (12) boot 13 (16) lib64
784945 (12) srv 915821 (12) opt 3604 (3796) vmlinuz
Directory called opt has inode 915821 and inode 2 is root of filesystem. So my chroot directory is /opt/debian-jail. Sure, /dev/sda1 may be mounted on another filesystem. You need to check that (use lsof or directly picking information /proc).
A: Preventing stuff like that is the whole point. If it's your code that's supposed to run in the chroot, have it set a flag on startup. If you're hacking, hack: check for several common things in known locations, count the files in /etc, something in /dev.
A: On BSD systems (check with uname -a), proc should always be present. Check if the dev/inode pair of /proc/1/exe (use stat on that path, it won't follow the symlink by text but by the underlying hook) matches /sbin/init.
Checking the root for inode #2 is also a good one.
On most other systems, a root user can find out much faster by attempting the fchdir root-breaking trick. If it goes anywhere you are in a chroot jail.
A: I guess it depends why you might be in a chroot, and whether any effort has gone into disguising it.
I'd check /proc, these files are automatically generated system information files. The kernel will populate these in the root filesystem, but it's possible that they don't exist in the chroot filesystem.
If the root filesystem's /proc has been bound to /proc in the chroot, then it is likely that there are some discrepancies between that information and the chroot environment. Check /proc/mounts for example.
Similrarly, check /sys.
A: I wanted the same information for a jail running on FreeBSD (as Ansible doesn't seem to detect this scenario).
On the FreeNAS distribution of FreeBSD 11, /proc is not mounted on the host, but it is within the jail. Whether this is also true on regular FreeBSD I don't know for sure, but procfs: Gone But Not Forgotten seems to suggest it is. Either way, you probably wouldn't want to try mounting it just to detect jail status and therefore I'm not certain it can be used as a reliable predictor of being within a jail.
I also ruled out using stat on / as certainly on FreeNAS all jails are given their own file system (i.e. a ZFS dataset) and therefore the / node on the host and in the jail both have inode 4. I expect this is common on FreeBSD 11 in general.
So the approach I settled on was using procstat on pid 0.
[root@host ~]# procstat 0
PID PPID PGID SID TSID THR LOGIN WCHAN EMUL COMM
0 0 0 0 0 1234 - swapin - kernel
[root@host ~]# echo $?
0
[root@host ~]# jexec guest tcsh
root@guest:/ # procstat 0
procstat: sysctl(kern.proc): No such process
procstat: procstat_getprocs()
root@guest:/ # echo $?
1
I am making an assumption here that pid 0 will always be the kernel on the host, and there won't be a pid 0 inside the jail.
A: The inode for / will always be 2 if it's the root directory of an ext2/ext3/ext4 filesystem, but you may be chrooted inside a complete filesystem. If it's just chroot (and not some other virtualization), you could run mount and compare the mounted filesystems against what you see. Verify that every mount point has inode 2.
A: If you entered the chroot with schroot, then you can check the value of $debian_chroot.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75182",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
} |
Q: What is an unsigned char? In C/C++, what an unsigned char is used for? How is it different from a regular char?
A: In terms of direct values a regular char is used when the values are known to be between CHAR_MIN and CHAR_MAX while an unsigned char provides double the range on the positive end. For example, if CHAR_BIT is 8, the range of regular char is only guaranteed to be [0, 127] (because it can be signed or unsigned) while unsigned char will be [0, 255] and signed char will be [-127, 127].
In terms of what it's used for, the standards allow objects of POD (plain old data) to be directly converted to an array of unsigned char. This allows you to examine the representation and bit patterns of the object. The same guarantee of safe type punning doesn't exist for char or signed char.
A: unsigned char is the heart of all bit trickery. In almost all compilers for all platforms an unsigned char is simply a byte and an unsigned integer of (usually) 8 bits that can be treated as a small integer or a pack of bits.
In addition, as someone else has said, the standard doesn't define the sign of a char. So you have 3 distinct char types: char, signed char, unsigned char.
A: If you like using various types of specific length and signedness, you're probably better off with uint8_t, int8_t, uint16_t, etc simply because they do exactly what they say.
A: In C++, there are three distinct character types:
*
*char
*signed char
*unsigned char
If you are using character types for text, use the unqualified char:
*
*it is the type of character literals like 'a' or '0' (in C++ only, in C their type is int)
*it is the type that makes up C strings like "abcde"
It also works out as a number value, but it is unspecified whether that value is treated as signed or unsigned. Beware character comparisons through inequalities - although if you limit yourself to ASCII (0-127) you're just about safe.
If you are using character types as numbers, use:
*
*signed char, which gives you at least the -127 to 127 range. (-128 to 127 is common)
*unsigned char, which gives you at least the 0 to 255 range.
"At least", because the C++ standard only gives the minimum range of values that each numeric type is required to cover. sizeof (char) is required to be 1 (i.e. one byte), but a byte could in theory be for example 32 bits. sizeof would still be report its size as 1 - meaning that you could have sizeof (char) == sizeof (long) == 1.
A: Because I feel it's really called for, I just want to state some rules of C and C++ (they are the same in this regard). First, all bits of unsigned char participate in determining the value if any unsigned char object. Second, unsigned char is explicitly stated unsigned.
Now, I had a discussion with someone about what happens when you convert the value -1 of type int to unsigned char. He refused the idea that the resulting unsigned char has all its bits set to 1, because he was worried about sign representation. But he didn't have to be. It's immediately following out of this rule that the conversion does what is intended:
If the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type. (6.3.1.3p2 in a C99 draft)
That's a mathematical description. C++ describes it in terms of modulo calculus, which yields to the same rule. Anyway, what is not guaranteed is that all bits in the integer -1 are one before the conversion. So, what do we have so we can claim that the resulting unsigned char has all its CHAR_BIT bits turned to 1?
*
*All bits participate in determining its value - that is, no padding bits occur in the object.
*Adding only one time UCHAR_MAX+1 to -1 will yield a value in range, namely UCHAR_MAX
That's enough, actually! So whenever you want to have an unsigned char having all its bits one, you do
unsigned char c = (unsigned char)-1;
It also follows that a conversion is not just truncating higher order bits. The fortunate event for two's complement is that it is just a truncation there, but the same isn't necessarily true for other sign representations.
A: Some googling found this, where people had a discussion about this.
An unsigned char is basically a single byte. So, you would use this if you need one byte of data (for example, maybe you want to use it to set flags on and off to be passed to a function, as is often done in the Windows API).
A: An unsigned char uses the bit that is reserved for the sign of a regular char as another number. This changes the range to [0 - 255] as opposed to [-128 - 127].
Generally unsigned chars are used when you don't want a sign. This will make a difference when doing things like shifting bits (shift extends the sign) and other things when dealing with a char as a byte rather than using it as a number.
A: unsigned char takes only positive values: 0 to 255 while
signed char takes positive and negative values: -128 to +127.
A: As for example usages of unsigned char:
unsigned char is often used in computer graphics, which very often (though not always) assigns a single byte to each colour component. It is common to see an RGB (or RGBA) colour represented as 24 (or 32) bits, each an unsigned char. Since unsigned char values fall in the range [0,255], the values are typically interpreted as:
*
*0 meaning a total lack of a given colour component.
*255 meaning 100% of a given colour pigment.
So you would end up with RGB red as (255,0,0) -> (100% red, 0% green, 0% blue).
Why not use a signed char? Arithmetic and bit shifting becomes problematic. As explained already, a signed char's range is essentially shifted by -128. A very simple and naive (mostly unused) method for converting RGB to grayscale is to average all three colour components, but this runs into problems when the values of the colour components are negative. Red (255, 0, 0) averages to (85, 85, 85) when using unsigned char arithmetic. However, if the values were signed chars (127,-128,-128), we would end up with (-99, -99, -99), which would be (29, 29, 29) in our unsigned char space, which is incorrect.
A: quoted frome "the c programming laugage" book:
The qualifier signed or unsigned may be applied to char or any integer. unsigned numbers
are always positive or zero, and obey the laws of arithmetic modulo 2^n, where n is the number
of bits in the type. So, for instance, if chars are 8 bits, unsigned char variables have values
between 0 and 255, while signed chars have values between -128 and 127 (in a two' s
complement machine.) Whether plain chars are signed or unsigned is machine-dependent,
but printable characters are always positive.
A: signed char and unsigned char both represent 1byte, but they have different ranges.
Type | range
-------------------------------
signed char | -128 to +127
unsigned char | 0 to 255
In signed char if we consider char letter = 'A', 'A' is represent binary of 65 in ASCII/Unicode, If 65 can be stored, -65 also can be stored. There are no negative binary values in ASCII/Unicode there for no need to worry about negative values.
Example
#include <stdio.h>
int main()
{
signed char char1 = 255;
signed char char2 = -128;
unsigned char char3 = 255;
unsigned char char4 = -128;
printf("Signed char(255) : %d\n",char1);
printf("Unsigned char(255) : %d\n",char3);
printf("\nSigned char(-128) : %d\n",char2);
printf("Unsigned char(-128) : %d\n",char4);
return 0;
}
Output -:
Signed char(255) : -1
Unsigned char(255) : 255
Signed char(-128) : -128
Unsigned char(-128) : 128
A: signed char has range -128 to 127; unsigned char has range 0 to 255.
char will be equivalent to either signed char or unsigned char, depending on the compiler, but is a distinct type.
If you're using C-style strings, just use char. If you need to use chars for arithmetic (pretty rare), specify signed or unsigned explicitly for portability.
A: unsigned char takes only positive values....like 0 to 255
where as
signed char takes both positive and negative values....like -128 to +127
A: This is implementation dependent, as the C standard does NOT define the signed-ness of char. Depending on the platform, char may be signed or unsigned, so you need to explicitly ask for signed char or unsigned char if your implementation depends on it. Just use char if you intend to represent characters from strings, as this will match what your platform puts in the string.
The difference between signed char and unsigned char is as you'd expect. On most platforms, signed char will be an 8-bit two's complement number ranging from -128 to 127, and unsigned char will be an 8-bit unsigned integer (0 to 255). Note the standard does NOT require that char types have 8 bits, only that sizeof(char) return 1. You can get at the number of bits in a char with CHAR_BIT in limits.h. There are few if any platforms today where this will be something other than 8, though.
There is a nice summary of this issue here.
As others have mentioned since I posted this, you're better off using int8_t and uint8_t if you really want to represent small integers.
A: An unsigned char is an unsigned byte value (0 to 255). You may be thinking of char in terms of being a "character" but it is really a numerical value. The regular char is signed, so you have 128 values, and these values map to characters using ASCII encoding. But in either case, what you are storing in memory is a byte value.
A: char and unsigned char aren't guaranteed to be 8-bit types on all platforms—they are guaranteed to be 8-bit or larger. Some platforms have 9-bit, 32-bit, or 64-bit bytes. However, the most common platforms today (Windows, Mac, Linux x86, etc.) have 8-bit bytes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75191",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "532"
} |
Q: scope resolution operator without a scope In C++, what is the purpose of the scope resolution operator when used without a scope? For instance:
::foo();
A: It means global scope. You might need to use this operator when you have conflicting functions or variables in the same scope and you need to use a global one. You might have something like:
void bar(); // this is a global function
class foo {
void some_func() { ::bar(); } // this function is calling the global bar() and not the class version
void bar(); // this is a class member
};
If you need to call the global bar() function from within a class member function, you should use ::bar() to get to the global version of the function.
A: Also you should note, that name resolution happens before overload resolution. So if there is something with the same name in your current scope then it will stop looking for other names and try to use them.
void bar() {};
class foo {
void bar(int) {};
void foobar() { bar(); } // won't compile needs ::bar()
void foobar(int i) { bar(i); } // ok
}
A: When you already have a function named foo() in your local scope but you need to access the one in the global scope.
A: My c++ is rusty but I believe if you have a function declared in the local scope, such as foo() and one at global scope, foo() refers to the local one. ::foo() will refer to the global one.
A: A name that begins with the scope resolution operator (::) is looked up in the global namespace. We can see this by looking at the draft C++ standard section 3.4.3 Qualified name lookup paragraph 4 which says (emphasis mine):
A name prefixed by the unary scope operator :: (5.1) is looked up in global scope, in the translation unit where it is used. The name shall be declared in global namespace scope or shall be a name whose declaration is visible in global scope because of a using-directive (3.4.3.2). The use of :: allows a global name to be referred to even if its identifier has been hidden (3.3.10).
As the standard states this allows us to use names from the global namespace that would otherwise be hidden, the example from the linked document is as follows:
int count = 0;
int main(void) {
int count = 0;
::count = 1; // set global count to 1
count = 2; // set local count to 2
return 0;
}
The wording is very similar going back to N1804 which is the earliest draft standard available.
A: referring to the global scope
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75213",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "72"
} |
Q: How can I detect when an Exception's been thrown globally in Java? How can I detect when an Exception has been thrown anywhere in my application?
I'm try to auto-magically send myself an email whenever an exception is thrown anywhere in my Java Desktop Application. I figure this way I can be more proactive.
I know I could just explicitly log and notify myself whenever an exception occurs, but I'd have to do it everywhere and I might(more likely will) miss a couple.
Any suggestions?
A: The new debugging hooks in Java 1.5 let you do this. It enables e.g. "break on any exception" in debuggers.
Here's the specific Javadoc you need.
A: Check out Thread.UncaughtExceptionHandler. You can set it per thread or a default one for the entire VM.
This would at least help you catch the ones you miss.
A: You probobly don't want to mail on any exception. There are lots of code in the JDK that actaully depend on exceptions to work normally. What I presume you are more inerested in are uncaught exceptions. If you are catching the exceptions you should handle notifications there.
In a desktop app there are two places to worry about this, in the event-dispatch-thread (EDT) and outside of the EDT. Globaly you can register a class implementing java.util.Thread.UncaughtExceptionHandler and register it via java.util.Thread.setDefaultUncaughtExceptionHandler. This will get called if an exception winds down to the bottom of the stack and the thread hasn't had a handler set on the current thread instance on the thread or the ThreadGroup.
The EDT has a different hook for handling exceptions. A system property 'sun.awt.exception.handler' needs to be registerd with the Fully Qualified Class Name of a class with a zero argument constructor. This class needs an instance method handle(Throwable) that does your work. The return type doesn't matter, and since a new instance is created every time, don't count on keeping state.
So if you don't care what thread the exception occurred in a sample may look like this:
class ExceptionHandler implements Thread.UncaughtExceptionHandler {
public void uncaughtException(Thread t, Throwable e) {
handle(e);
}
public void handle(Throwable throwable) {
try {
// insert your e-mail code here
} catch (Throwable t) {
// don't let the exception get thrown out, will cause infinite looping!
}
}
public static void registerExceptionHandler() {
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());
System.setProperty("sun.awt.exception.handler", ExceptionHandler.class.getName());
}
}
Add this class into some random package, and then call the registerExceptionHandler method and you should be ready to go.
A: If you're using a web framework such as Spring then you can delegate in your web.xml to a page and then use the controller to send the email. For example:
In web.xml:
<error-page>
<error-code>500</error-code>
<location>/error/500.htm</location>
</error-page>
Then define /error/500.htm as a controller. You can access the exception from the parameter javax.servlet.error.exception:
Exception exception = (Exception) request.getAttribute("javax.servlet.error.exception");
If you're just running a regular Java program, then I would imagine you're stuck with public static void main(String[] args) { try { ... } catch (Exception e) {} }
A: If you are using java 1.3/1.4, Thread.UncaughtExceptionHandler is not available.
In this case you can use a solution based on AOP to trigger some code when an exception is thrown. Spring and/or aspectJ might be helpful.
A: In my current project I faced the similar requirement regarding the errors detection. For this purpose I have applied the following approach: I use log4j for logging across my app, and everywhere, where the exception is caught I do the standard thing: log.error("Error's description goes here", e);, where e is the Exception being thrown (see log4j documentation for details regarding the initialization of the "log").
In order to detect the error, I use my own Appender, which extends the log4j AppenderSkeleton class:
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;
public class ErrorsDetectingAppender extends AppenderSkeleton {
private static boolean errorsOccured = false;
public static boolean errorsOccured() {
return errorsOccured;
}
public ErrorsDetectingAppender() {
super();
}
@Override
public void close() {
// TODO Auto-generated method stub
}
@Override
public boolean requiresLayout() {
return false;
}
@Override
protected void append(LoggingEvent event) {
if (event.getLevel().toString().toLowerCase().equals("error")) {
System.out.println("-----------------Errors detected");
this.errorsOccured = true;
}
}
}
The log4j configuration file has to just contain a definition of the new appender and its attachement to the selected logger (root in my case):
log4j.rootLogger = OTHER_APPENDERS, ED
log4j.appender.ED=com.your.package.ErrorsDetectingAppender
You can either call the errorsOccured() method of the ErrorsDetectingAppender at some significant point in your programs's execution flow or react immidiately by adding functionality to the if block in the append() method. This approach is consistent with the semantics: things that you consider errors and log them as such, are detected. If you will later consider selected errors not so important, you just change the logging level to log.warn() and report will not be sent.
A: In this case I think your best bet might be to write a custom classloader to handle all classloading in your application, and whenever an exception class is requested you return a class that wraps the requested exception class. This wrapper calls through to the wrapped exception but also logs the exception event.
A: I assume you don't mean any Exception but rather any uncaught Exception.
If this is the case this article on the Sun Website has some ideas. You need to wrap your top level method in a try-catch block and also do some extra work to handle other Threads.
A: Sending an email may not be possible if you are getting a runtime exception like OutOfMemoryError or StackOverflow. Most likely you will have to spawn another process and catch any exceptions thrown by it (with the various techniques mentioned above).
A: There is simply no good reason to be informed of every thrown exception. I guess you are assuming that a thrown exception indicates a "problem" that your "need" to know about. But this is wrong. If an exception is thrown, caught and handled, all is well. The only thing you need to be worried about is an exception that is thrown but not handled (not caught). But you can do that in a try...catch clause yourself.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75218",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
} |
Q: How do you quickly find the URL for a Win32 API on MSDN? How do you quickly find the URL for a Win32 API on MSDN? It's easy for .NET methods -- just add the method name (for example, System.Byte.ToString) to http://msdn.microsoft.com/library/.
However, for Win32 APIs (say GetLongPathName), this doesn't work: http://msdn.microsoft.com/en-us/library/GetLongPathName.
I want to be able to use the URL in code comments or documentation. So the URL one gets with an MSDN or Google search (for example, http://msdn.microsoft.com/library/aa364980.aspx) isn't really what I'm looking for. I'd really like my code comments to look something like:
// blah blah blah. See http://msdn.microsoft.com/en-us/library/GetLongPathName for more information.
What's the magic pixie dust for Win32 APIs? Or does it only work for .NET methods?
A: Google might be your best bet. I know the msdn site search has time and again pointed me in the wrong direction, but a quick switch to Google ("GetLongPathName site:msdn.microsoft.com") never steers me wrong.
A: FWIW if you have the MSDN installed locally on your machine the Zeus editor has a feature to search the local copy of the MSDN.
For example, placing the cursor on the GetLongPathName word within a text document and using the Zeus Help, Quick Help, Current Word menu, the following MSDN page gets loaded:
ms-help://MS.VSCC.v80/MS.MSDN.vAug06.en/fileio/fs/getlongpathname.htm
A: I am using Linkify by cough me, which lets you link
// see msdn:GetLongPathName
to the google search japollock mentions.
A: You could use MSDN search.
http://social.msdn.microsoft.com/Search/en-US/?Refinement=86&Query=GetLongPathName
Refinement=86 stands for Win32 search.
A: MSDN GET api (I don't know how new this is)
"https://learn.microsoft.com/api/search?locale=en-us&scoringprofile=semantic-captions&%24top=1&search=" functionName
returns json like such:
{
"results": [
{
"title": "KeClearEvent function (wdm.h) - Windows drivers",
"url": "https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-keclearevent",
"displayUrl": {
"content": "/windows-hardware/drivers/ddi/wdm/nf-wdm-keclearevent",
"hitHighlights": [
{
"start": 41,
"length": 12
}
]
},
"description": "The KeClearEvent routine sets an event to a not-signaled state.",
"descriptions": [
{
"content": "KeClearEvent function (wdm.h) Article 04/18/2022 2 minutes to read In this article The KeClearEvent routine sets an event to a not-signaled state.",
"hitHighlights": [
{
"start": 0,
"length": 12
},
{
"start": 87,
"length": 12
}
]
},
{
"content": "For better performance, use KeClearEvent unless the caller uses the value returned by KeResetEvent to determine what to do next.",
"hitHighlights": [
{
"start": 28,
"length": 12
}
]
}
],
"lastUpdatedDate": "2022-04-18T04:31:00+00:00",
"breadcrumbs": []
}
],
"spellingCorrection": [],
"scopeRemoved": false,
"count": 18,
"nextLink": "https://learn.microsoft.com/api/Search?locale=en-us\u0026search=KeClearEvent\u0026$skip=1\u0026$top=1",
"srcheng": "02"
}
if you want really fast, you can bind it to a hotkey
AutohotkeyV2
#SingleInstance force
ListLines 0
KeyHistory 0
SendMode "Input" ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir A_ScriptDir ; Ensures a consistent starting directory.
linkFromName(functionName) {
json:=downloadToVar("https://learn.microsoft.com/api/search?locale=en-us&scoringprofile=semantic-captions&%24top=1&search=" functionName)
obj:=JSON_parse(json)
if (obj.results.Length) {
RegExMatch(obj.results[1].title, ".*?(?=\s|$)", &OutputVar)
if (OutputVar.0 = functionName) {
validUrl:=obj.results[1].url
} else if (OutputVar.0 = functionName "W" || OutputVar.0 = functionName "A") {
validUrl:=SubStr(obj.results[1].url, 1, -1) "w"
}
; A_Clipboard:=validUrl
Run validUrl
}
}
; linkFromName("GetLongPathNameW") ;works
; linkFromName("GetLongPathName") ;works
linkFromName(A_Clipboard)
Exitapp
f3::Exitapp
downloadToVar(url) {
whr := ComObject("WinHttp.WinHttpRequest.5.1")
whr.Open("GET", url, true)
whr.SetRequestHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)")
whr.Send()
; Using 'true' above and the call below allows the script to remain responsive.
whr.WaitForResponse()
return whr.ResponseText
}
JSON_parse(str) {
c_:=1
return JSON_value()
JSON_value() {
char_:=SubStr(str, c_, 1)
Switch char_ {
case "{":
obj_:=Map()
;object
c_++
loop {
skip_s()
if (SubStr(str, c_, 1) == "}") {
c_++
return obj_
}
; key_:=JSON_objKey()
; a or "a"
if (SubStr(str, c_, 1) == "`"") {
RegExMatch(str, "(?:\\.|.)*?(?=`")", &OutputVar, c_ + 1)
key_:=RegExReplace(OutputVar.0, "\\(.)", "$1")
c_+=OutputVar.Len
} else {
RegExMatch(str, ".*?(?=[\s:])", &OutputVar, c_)
key_:=OutputVar.0
c_+=OutputVar.Len
}
c_:=InStr(str, ":", true, c_) + 1
skip_s()
value_:=JSON_value()
obj_[key_]:=value_
obj_.DefineProp(key_, {Value: value_})
skip_s()
if (SubStr(str, c_, 1) == ",") {
c_++, skip_s()
}
}
case "[":
arr_:=[]
;array
c_++
loop {
skip_s()
if (SubStr(str, c_, 1) == "]") {
c_++
return arr_
}
value_:=JSON_value()
arr_.Push(value_)
skip_s()
char_:=SubStr(str, c_, 1)
if (char_ == ",") {
c_++, skip_s()
}
}
case "`"":
RegExMatch(str, "(?:\\.|.)*?(?=`")", &OutputVar, c_ + 1)
unquoted:=RegExReplace(OutputVar.0, "\\(.)", "$1")
c_+=OutputVar.Len + 2
return unquoted
case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9":
RegExMatch(str, "[0-9.]*", &OutputVar, c_)
c_+=OutputVar.Len
return Number(OutputVar.0)
case "t":
;"true"
c_+=4
return {a:1}
case "f":
;"false"
c_+=5
return {a:0}
case "n":
;"null"
c_+=4
return {a:-1}
}
}
skip_s() {
RegExMatch(str, "\s*", &OutputVar, c_)
c_+=OutputVar.Len
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75230",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: HQL querying columns in a set Is it possible to reach the individual columns of table2 using HQL with a configuration like this?
<hibernate-mapping>
<class table="table1">
<set name="table2" table="table2" lazy="true" cascade="all">
<key column="result_id"/>
<many-to-many column="group_id"/>
</set>
</class>
</hibernate-mapping>
A: They're just properties of table1's table2 property.
select t1.table2.property1, t1.table2.property2, ... from table1 as t1
You might have to join, like so
select t2.property1, t2.property2, ...
from table1 as t1
inner join t1.table2 as t2
Here's the relevant part of the hibernate doc.
A: You can query on them, but you can't make it part of the where clause. E.g.,
select t1.table2.x from table1 as t1
would work, but
select t1 from table1 as t1 where t1.table2.x = foo
would not.
A: Let's say table2 has a column "color varchar(128)" and this column is properly mapped to Hibernate.
You should be able to do something like this:
from table1 where table2.color = 'red'
This will return all table1 rows that are linked to a table2 row whose color column is 'red'. Note that in your Hibernate mapping, your set has the same name as the table it references. The above query uses the name of the set, not the name of the table.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75245",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What are the implications of running a Microsoft access database in both 2003 and 2007? What are the implications of running a Microsoft Access Database in both 2003 and 2007?
Is there some class I forgot to take?
The program was originally built in office 2003, and then run in 2007. Issues seem to happen when the machine it is being run on has both 2003 and 2007 on it. The issue would also appear to stem from reference from the "Microsoft Access 12.0 Object Library" (or the "Microsoft Access 11.0 Object Library" in 2003). To see this, just look at the Tools: Refrences menu on the VBA screen.
The error's symptom is basically the code not be recognized (almost like it doesn’t recognize the programming language I’m using). It usually follows this with a box that says "The expression On Load you entered as the event property settings produced the following error: Object or class does not support the set of events". You can also replace “On Load” with “On Click” for buttons or “On Change” for text boxes.
I personally suspect that the computer is taking parts of the Microsoft Access 11.0/12.0 Object Library and then mixes the two into a useless VBA reference. What further confirms my suspicion is the box that pops up when going between the two that says "Configuring Microsoft Access" Another issue that further confirms my suspicion is it will run on whichever one it is opened on first (2007, for example) and then not run on the other (2003 continuing the example)
The only other issue is I have had to fix was changing the last part of the DoCmd.OpenForm ,,,,, acFormReadOnly (or acReadOnly, depending on how the machine seems to feel on that particular day - yes it would work with one, one day and then want me to switch it another) to simply locking the individual text boxes
Maybe it’s not quite coding, but I think it might be able to be fixed by coding.
Hopefully that’s enough for someone to come up with something.
A: Microsoft's official position is that installing multiple office versions on the same pc is not supported and not recommended, and Access 2007 seems to be designed to prove that to us!
That said, you can avoid most issues by doing the following:
1 - Splitting the db into a back end and front end. Place the back end (tables and relationships) in a network folder, and place a copy of the front end (all other objects) on each user's desktop.
2 - It's best to make the front end an mde to avoid the references shuffle every time you open the db in the other version of Access.
3 - Create a shortcut to open the front end with the desired version of Access so it's always opened with that version. (And remember to use the shortcut!) In the shortcut's target:
"path to Access 12 msaccess.exe" "path to db.mdb"
A: We have an MS-Acces application, developped with Access 2003 and used on either full or runtime version of Access 2003 and Access 2007 (Access 2007 Runtime being free, we are making a great use of it!). There is no particular issue except the references management. Our code analyses the Office version installed on the computer and automatically updates corresponding references (not only Access but also Excel, Outlook, Word, etc.: code is very tricky but of great interest!)
To my own knowledge, no major objects, properties or methods available in Office 2003/VBA were deprecated in Office 2007. Office 2003 code will then run with Access 2007 once these references issues solved. Some new objects were introduced in Office 2007 so I would not advise any developer to use it to develop code to be further used with Access 2003.
But the main & real issue of your question is: why should one run both Access versions on the same computer? This is what I'd do if I want to make sure to crash my apps. I think that if your objectives were to develop software, you should definitely find a better configuration for your machine!
A: In general, having multiple versions of Access installed on the one machine is unsupported and will result in the issues you are seeing with the object references.
If the database is authored in Access 2003, compiled to an .MDE, and then deployed onto a separate Windows instance running Access 2007, you should not have any significant issues (other than UI changes such as custom toolbars being thrown into the Add-Ins ribbon).
For testing on multiple versions of Access you will need some form of isolation between each version. I use multiple virtual machines to accomplish this. My primary Windows VM runnings Office 2007 and IE7 and I have a second VM which has Office 2003 and IE6 for testing.
Note that if you wish to simply use Word, Excel and Outlook 2007 with Access 2003, you can install Access 2003 first by itself and then do a custom install of Office 2007 and deselect Access 2007.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75246",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do you start running the program over again in gdb with 'target remote'? When you're doing a usual gdb session on an executable file on the same computer, you can give the run command and it will start the program over again.
When you're running gdb on an embedded system, as with the command target localhost:3210, how do you start the program over again without quitting and restarting your gdb session?
A: Presumably you are running gdbserver on the embedded system.
You can ask it to restart your program instead of exiting with target extended-remote
A: "jump _start" is the usual way.
A: Step-by-step procedure
Remote:
# pwd contains cross-compiled ./myexec
gdbserver --multi :1234
Local:
# pwd also contains the same cross-compiled ./myexec
gdb -ex 'target extended-remote 192.168.0.1:1234' \
-ex 'set remote exec-file ./myexec' \
--args ./myexec arg1 arg2
(gdb) r
[Inferior 1 (process 1234) exited normally]
(gdb) r
[Inferior 1 (process 1235) exited normally]
(gdb) monitor exit
Tested in Ubuntu 14.04.
It is also possible to pass CLI arguments to the program as:
gdbserver --multi :1234 ./myexec arg1 arg2
and the ./myexec part removes the need for set remote exec-file ./myexec, but this has the following annoyances:
*
*undocumented: https://sourceware.org/bugzilla/show_bug.cgi?id=21981
*does not show on show args and does not persist across restarts: https://sourceware.org/bugzilla/show_bug.cgi?id=21980
Pass environment variables and change working directory without restart: How to modify the environment variables and working directory of gdbserver --multi without restarting it?
A: If you are running regular gdb you can type 'run' shortcut 'r' and gdb asks you if you wish to restart the program
A: For me the method described in 21.2 Sample GDB session startup works great. When I enter monitor reset halt later at the “(gdb)” prompt the target hardware is reset and I can re-start the application with c (= continue).
The load command can be omitted between the runs because there is no need to flash the program again and again.
A: You are looking for Multi-Process Mode for gdbserver and set remote exec-file filename
A: Unfortunately, I don't know of a way to restart the application and still maintain your session. A workaround is to set the PC back to the entry point of your program. You can do this by either calling:
jump function
or
set $pc=address.
If you munged the arguments to main you may need set them up again.
Edit:
There are a couple of caveats with the above method that could cause problems.
*
*If you are in a multi-threaded program jumping to main will jump the current thread to main, all other threads remain. If the current thread held a lock...then you have some problems.
*Memory leaks, if you program flow allocates some stuff during initialization then you just leaked a bunch of memory with the jump.
*Open files will still remain open. If you mmap some files or an address, the call will most likely fail.
So, using jump isn't the same thing as restarting the program.
A: You can use jump gdb command. For that, you can check your startup script.
My startup script has a symbol.
.section .text.Reset_Handler
.weak Reset_Handler
.type Reset_Handler, %function
Reset_Handler:
ldr r0, =_estack
mov sp, r0 /* set stack pointer */
I wanted to jump to start. That's why I used:
jump Reset_Handler
A: On EFM32 Happy Gecko none of the suggestions would work for me, so here is what I have learned from the documentation on integrating GDB into the Eclipse environment.
(gdb) mon reset 0
(gdb) continue
(gdb) continue
This puts me in the state that I would have expected when hitting reset from the IDE.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75255",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "36"
} |
Q: How to make a Side-by-Side Compiler for .NET Nikhil Kothari's Script# is quite possibly one of the most amazing concepts I've seen in the JavaScript arena for quite some time. This question isn't about JavaScript, but rather about language compilation in the .NET runtime.
I've been rather interested in how, using the .NET platform, one can write a compiler for a language that already has a compiler (like C#) that will generate separate output from the original compiler while allowing the original compiler to generate output for the same source during the same build operation, all the while referencing/using the output of the other compiler as well.
I'm not entirely sure I even understand the process well enough to ask the question with the right details, but this is the way I currently see the process, as per diagrams in the Script# docs. I've thought about many things involving complex language design and compilation that may be able to take advantage of concepts like this and I'm interested in what other people think about the concepts.
--
Edit: Thanks for commenting,so far; your information is, in it's own right, very intriguing and I should like to research it more, but my question is actually about how I would be able to write my own compiler/s that can be run on the same source at the same time producing multiple different types of (potentially) interdependent output using the CLR. Script# serves as an example since it generates JavaScript and an Assembly using the same C# source, all the while making the compiled Assembly cooperate with the JavaScript. I'm curious what the various approaches and theoretical concepts are in designing something of this nature.
A: It's important to realize that all a compiler does is take a source language (C# in this case), parse it so the compiler has a representation that makes sense to it and not humans (this is the abstract syntax tree), and then does a naive code generation to the target language (msil is the target for languages that run on the .NET runtime).
Now if the script# code is turned into an assembly and interacts with other .NET code, that means this compiler must be generating msil. script# is using csc.exe for this, which is just the standard c# comiler. Now to generate the javascript, it must take either c# or msil, parse it, and generate javascript to send to the browser. The docs says it has a custom c# -> js compiler called ssc.exe.
To make things interact consistently on both the client side and the server side it has a set of reference assemblies that are written in .NET but are also compiled to javascript. This is not a compiler specific issue though, those reference assemblies are the script# runtime. The runtime is probably responsible for a lot of the script# magic you're perceiving though.
A: So let's say you want to compile C# into Javascript. You are asking whether you can take advantage of the existing C# compilers, so instead of compiling C# into Javascript directly you actually convert the MSIL generated by the C# compiler into Javascript?
Sure, you can do that. Once you have the MSIL binary you can do whatever you want to it.
A: Microsoft has a research project called Volta which, amongst other things, compiles msil to JavaScript.
a developer toolset for building
multi-tier web applications using
existing and familiar tools,
techniques and patterns. Volta’s
declarative tier-splitting enables
developers to postpone architectural
decisions about distribution until the
last possible responsible moment.
Also, thanks to a shared programming
model across multiple-tiers, Volta
enables new end-to-end profiling and
testing for higher levels of
application performance, robustness,
and reliability. Using the declarative
tier-splitting, developers can refine
architectural decisions based on this
profiling data. This saves time and
costs associated with manual
refactoring. In effect, Volta extends
the .NET platform to further enable
the development of software+services
applications, using existing and
familiar tools and techniques.
You architect and build your
application as a .NET client
application, assigning the portions of
the application that run on the server
tier and client tier late in the
development process. You can target
either web browsers or the CLR as
clients and Volta handles the
complexities of tier-splitting. The
compiler creates cross-browser
JavaScript for the client tier, web
services for the server tier, and all
communication, serialization,
synchronization, security, and other
boilerplate code to tie the tiers
together. In effect, Volta offers a
best-effort experience in multiple
environments without requiring
tailoring of the application.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75258",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Why isn't Scalar::Util::Numeric installing correctly? I got this output when running sudo cpan Scalar::Util::Numeric
jmm@freekbox:~/bfwsandbox/sa/angel/astroportal/dtu8e/resources$ sudo cpan Scalar::Util::Numeric
[sudo] password for jmm:
CPAN: Storable loaded ok
Going to read /home/jmm/.cpan/Metadata
Database was generated on Tue, 09 Sep 2008 16:02:51 GMT
CPAN: LWP::UserAgent loaded ok
Fetching with LWP:
ftp://ftp.perl.org/pub/CPAN/authors/01mailrc.txt.gz
Going to read /home/jmm/.cpan/sources/authors/01mailrc.txt.gz
Fetching with LWP:
ftp://ftp.perl.org/pub/CPAN/modules/02packages.details.txt.gz
Going to read /home/jmm/.cpan/sources/modules/02packages.details.txt.gz
Database was generated on Tue, 16 Sep 2008 16:02:50 GMT
There's a new CPAN.pm version (v1.9205) available!
[Current version is v1.7602]
You might want to try
install Bundle::CPAN
reload cpan
without quitting the current session. It should be a seamless upgrade
while we are running...
Fetching with LWP:
ftp://ftp.perl.org/pub/CPAN/modules/03modlist.data.gz
Going to read /home/jmm/.cpan/sources/modules/03modlist.data.gz
Going to write /home/jmm/.cpan/Metadata
Running install for module Scalar::Util::Numeric
Running make for C/CH/CHOCOLATE/Scalar-Util-Numeric-0.02.tar.gz
CPAN: Digest::MD5 loaded ok
Checksum for /home/jmm/.cpan/sources/authors/id/C/CH/CHOCOLATE/Scalar-Util-Numeric-0.02.tar.gz ok
Scanning cache /home/jmm/.cpan/build for sizes
Scalar-Util-Numeric-0.02/
Scalar-Util-Numeric-0.02/Changes
Scalar-Util-Numeric-0.02/lib/
Scalar-Util-Numeric-0.02/lib/Scalar/
Scalar-Util-Numeric-0.02/lib/Scalar/Util/
Scalar-Util-Numeric-0.02/lib/Scalar/Util/Numeric.pm
Scalar-Util-Numeric-0.02/Makefile.PL
Scalar-Util-Numeric-0.02/MANIFEST
Scalar-Util-Numeric-0.02/META.yml
Scalar-Util-Numeric-0.02/Numeric.xs
Scalar-Util-Numeric-0.02/ppport.h
Scalar-Util-Numeric-0.02/README
Scalar-Util-Numeric-0.02/t/
Scalar-Util-Numeric-0.02/t/pod.t
Scalar-Util-Numeric-0.02/t/Scalar-Util-Numeric.t
Removing previously used /home/jmm/.cpan/build/Scalar-Util-Numeric-0.02
CPAN.pm: Going to build C/CH/CHOCOLATE/Scalar-Util-Numeric-0.02.tar.gz
Checking if your kit is complete...
Looks good
Writing Makefile for Scalar::Util::Numeric
cp lib/Scalar/Util/Numeric.pm blib/lib/Scalar/Util/Numeric.pm
AutoSplitting blib/lib/Scalar/Util/Numeric.pm (blib/lib/auto/Scalar/Util/Numeric)
/usr/bin/perl /usr/share/perl/5.8/ExtUtils/xsubpp -typemap /usr/share/perl/5.8/ExtUtils/typemap Numeric.xs > Numeric.xsc && mv Numeric.xsc Numeric.c
cc -c -D_REENTRANT -D_GNU_SOURCE -DTHREADS_HAVE_PIDS -DDEBIAN -fno-strict-aliasing -pipe -I/usr/local/include -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -O3 -DVERSION=\"0.02\" -DXS_VERSION=\"0.02\" -fPIC "-I/usr/lib/perl/5.8/CORE" Numeric.c
In file included from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/perl.h:420:24: error: sys/types.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:451:19: error: ctype.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:463:23: error: locale.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:480:20: error: setjmp.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:486:26: error: sys/param.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:491:23: error: stdlib.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:496:23: error: unistd.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:776:23: error: string.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:925:27: error: netinet/in.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:929:26: error: arpa/inet.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:939:25: error: sys/stat.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:961:21: error: time.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:968:25: error: sys/time.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:975:27: error: sys/times.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:982:19: error: errno.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:997:25: error: sys/socket.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:1024:21: error: netdb.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:1127:24: error: sys/ioctl.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:1156:23: error: dirent.h: No such file or directory
In file included from /usr/lib/gcc/i486-linux-gnu/4.2.3/include/syslimits.h:7,
from /usr/lib/gcc/i486-linux-gnu/4.2.3/include/limits.h:11,
from /usr/lib/perl/5.8/CORE/perl.h:1510,
from Numeric.xs:2:
/usr/lib/gcc/i486-linux-gnu/4.2.3/include/limits.h:122:61: error: limits.h: No such file or directory
In file included from /usr/lib/perl/5.8/CORE/perl.h:2120,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/handy.h:136:25: error: inttypes.h: No such file or directory
In file included from /usr/lib/perl/5.8/CORE/perl.h:2284,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/unixish.h:106:21: error: signal.h: No such file or directory
In file included from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/perl.h:2421:33: error: pthread.h: No such file or directory
In file included from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/perl.h:2423: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘perl_os_thread’
/usr/lib/perl/5.8/CORE/perl.h:2424: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘perl_mutex’
/usr/lib/perl/5.8/CORE/perl.h:2425: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘perl_cond’
/usr/lib/perl/5.8/CORE/perl.h:2426: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘perl_key’
In file included from /usr/lib/perl/5.8/CORE/iperlsys.h:51,
from /usr/lib/perl/5.8/CORE/perl.h:2733,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/perlio.h:65:19: error: stdio.h: No such file or directory
In file included from /usr/lib/perl/5.8/CORE/iperlsys.h:51,
from /usr/lib/perl/5.8/CORE/perl.h:2733,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/perlio.h:259: error: expected ‘)’ before ‘*’ token
/usr/lib/perl/5.8/CORE/perlio.h:262: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
/usr/lib/perl/5.8/CORE/perlio.h:265: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
/usr/lib/perl/5.8/CORE/perlio.h:268: error: expected declaration specifiers or ‘...’ before ‘FILE’
In file included from /usr/lib/perl/5.8/CORE/perl.h:2747,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/sv.h:389: error: expected specifier-qualifier-list before ‘DIR’
In file included from /usr/lib/perl/5.8/CORE/op.h:497,
from /usr/lib/perl/5.8/CORE/perl.h:2754,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/reentr.h:72:20: error: pwd.h: No such file or directory
/usr/lib/perl/5.8/CORE/reentr.h:75:20: error: grp.h: No such file or directory
/usr/lib/perl/5.8/CORE/reentr.h:85:26: error: crypt.h: No such file or directory
/usr/lib/perl/5.8/CORE/reentr.h:90:27: error: shadow.h: No such file or directory
In file included from /usr/lib/perl/5.8/CORE/op.h:497,
from /usr/lib/perl/5.8/CORE/perl.h:2754,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/reentr.h:612: error: field ‘_crypt_struct’ has incomplete type
/usr/lib/perl/5.8/CORE/reentr.h:620: error: field ‘_drand48_struct’ has incomplete type
/usr/lib/perl/5.8/CORE/reentr.h:624: error: field ‘_grent_struct’ has incomplete type
/usr/lib/perl/5.8/CORE/reentr.h:635: error: field ‘_hostent_struct’ has incomplete type
/usr/lib/perl/5.8/CORE/reentr.h:654: error: field ‘_netent_struct’ has incomplete type
/usr/lib/perl/5.8/CORE/reentr.h:669: error: field ‘_protoent_struct’ has incomplete type
/usr/lib/perl/5.8/CORE/reentr.h:684: error: field ‘_pwent_struct’ has incomplete type
/usr/lib/perl/5.8/CORE/reentr.h:695: error: field ‘_servent_struct’ has incomplete type
/usr/lib/perl/5.8/CORE/reentr.h:710: error: field ‘_spent_struct’ has incomplete type
/usr/lib/perl/5.8/CORE/reentr.h:721: error: field ‘_gmtime_struct’ has incomplete type
/usr/lib/perl/5.8/CORE/reentr.h:724: error: field ‘_localtime_struct’ has incomplete type
/usr/lib/perl/5.8/CORE/reentr.h:771: error: field ‘_random_struct’ has incomplete type
/usr/lib/perl/5.8/CORE/reentr.h:772: error: expected specifier-qualifier-list before ‘int32_t’
In file included from /usr/lib/perl/5.8/CORE/perl.h:2756,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/av.h:13: error: expected specifier-qualifier-list before ‘ssize_t’
In file included from /usr/lib/perl/5.8/CORE/perl.h:2759,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/scope.h:232: error: expected specifier-qualifier-list before ‘sigjmp_buf’
In file included from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/perl.h:2931: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘getuid’
/usr/lib/perl/5.8/CORE/perl.h:2932: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘geteuid’
/usr/lib/perl/5.8/CORE/perl.h:2933: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘getgid’
/usr/lib/perl/5.8/CORE/perl.h:2934: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘getegid’
In file included from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/perl.h:3238:22: error: math.h: No such file or directory
In file included from /usr/lib/perl/5.8/CORE/perl.h:3881,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/thrdvar.h:85: error: field ‘Tstatbuf’ has incomplete type
/usr/lib/perl/5.8/CORE/thrdvar.h:86: error: field ‘Tstatcache’ has incomplete type
/usr/lib/perl/5.8/CORE/thrdvar.h:91: error: field ‘Ttimesbuf’ has incomplete type
In file included from /usr/lib/perl/5.8/CORE/perl.h:3883,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/intrpvar.h:66: error: expected specifier-qualifier-list before ‘time_t’
In file included from /usr/lib/perl/5.8/CORE/perl.h:3950,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/proto.h:128: error: expected declaration specifiers or ‘...’ before ‘mode_t’
/usr/lib/perl/5.8/CORE/proto.h:128: error: expected declaration specifiers or ‘...’ before ‘uid_t’
/usr/lib/perl/5.8/CORE/proto.h:297: error: expected declaration specifiers or ‘...’ before ‘off64_t’
/usr/lib/perl/5.8/CORE/proto.h:299: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_do_sysseek’
/usr/lib/perl/5.8/CORE/proto.h:300: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_do_tell’
/usr/lib/perl/5.8/CORE/proto.h:411: error: expected declaration specifiers or ‘...’ before ‘gid_t’
/usr/lib/perl/5.8/CORE/proto.h:411: error: expected declaration specifiers or ‘...’ before ‘uid_t’
/usr/lib/perl/5.8/CORE/proto.h:736: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_my_fork’
/usr/lib/perl/5.8/CORE/proto.h:1020: error: expected declaration specifiers or ‘...’ before ‘pid_t’
/usr/lib/perl/5.8/CORE/proto.h:1300: error: expected declaration specifiers or ‘...’ before ‘pid_t’
/usr/lib/perl/5.8/CORE/proto.h:1456: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
/usr/lib/perl/5.8/CORE/proto.h:2001: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_PerlIO_read’
/usr/lib/perl/5.8/CORE/proto.h:2002: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_PerlIO_write’
/usr/lib/perl/5.8/CORE/proto.h:2003: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_PerlIO_unread’
/usr/lib/perl/5.8/CORE/proto.h:2004: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_PerlIO_tell’
/usr/lib/perl/5.8/CORE/proto.h:2005: error: expected declaration specifiers or ‘...’ before ‘off64_t’
In file included from /usr/lib/perl/5.8/CORE/perl.h:3988,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/perlvars.h:31: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘PL_thr_key’
/usr/lib/perl/5.8/CORE/perlvars.h:48: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘PL_op_mutex’
/usr/lib/perl/5.8/CORE/perlvars.h:52: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘PL_dollarzero_mutex’
/usr/lib/perl/5.8/CORE/perl.h:4485:24: error: sys/ipc.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:4486:24: error: sys/sem.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:4611:24: error: sys/file.h: No such file or directory
In file included from /usr/lib/perl/5.8/CORE/perlapi.h:38,
from /usr/lib/perl/5.8/CORE/XSUB.h:349,
from Numeric.xs:3:
/usr/lib/perl/5.8/CORE/intrpvar.h:66: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
/usr/lib/perl/5.8/CORE/intrpvar.h:237: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
/usr/lib/perl/5.8/CORE/intrpvar.h:238: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
/usr/lib/perl/5.8/CORE/intrpvar.h:239: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
/usr/lib/perl/5.8/CORE/intrpvar.h:240: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
In file included from /usr/lib/perl/5.8/CORE/perlapi.h:39,
from /usr/lib/perl/5.8/CORE/XSUB.h:349,
from Numeric.xs:3:
/usr/lib/perl/5.8/CORE/perlvars.h:31: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
/usr/lib/perl/5.8/CORE/perlvars.h:48: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
/usr/lib/perl/5.8/CORE/perlvars.h:52: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
In file included from Numeric.xs:4:
ppport.h:3042:1: warning: "PERL_UNUSED_DECL" redefined
In file included from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/perl.h:163:1: warning: this is the location of the previous definition
Numeric.c: In function ‘XS_Scalar__Util__Numeric_is_num’:
Numeric.c:20: error: invalid type argument of ‘unary *’
Numeric.c:20: error: invalid type argument of ‘unary *’
Numeric.c:20: error: invalid type argument of ‘unary *’
Numeric.c:22: error: invalid type argument of ‘unary *’
Numeric.c:24: error: invalid type argument of ‘unary *’
Numeric.xs:16: error: invalid type argument of ‘unary *’
Numeric.xs:17: error: invalid type argument of ‘unary *’
Numeric.xs:20: error: invalid type argument of ‘unary *’
Numeric.xs:20: error: invalid type argument of ‘unary *’
Numeric.xs:20: error: invalid type argument of ‘unary *’
Numeric.xs:20: error: invalid type argument of ‘unary *’
Numeric.xs:20: error: invalid type argument of ‘unary *’
Numeric.c:36: error: invalid type argument of ‘unary *’
Numeric.c:36: error: invalid type argument of ‘unary *’
Numeric.c: In function ‘XS_Scalar__Util__Numeric_uvmax’:
Numeric.c:43: error: invalid type argument of ‘unary *’
Numeric.c:43: error: invalid type argument of ‘unary *’
Numeric.c:43: error: invalid type argument of ‘unary *’
Numeric.c:45: error: invalid type argument of ‘unary *’
Numeric.xs:26: error: invalid type argument of ‘unary *’
Numeric.xs:26: error: invalid type argument of ‘unary *’
Numeric.xs:26: error: invalid type argument of ‘unary *’
Numeric.xs:26: error: invalid type argument of ‘unary *’
Numeric.xs:26: error: invalid type argument of ‘unary *’
Numeric.c:51: error: invalid type argument of ‘unary *’
Numeric.c:51: error: invalid type argument of ‘unary *’
Numeric.c: In function ‘boot_Scalar__Util__Numeric’:
Numeric.c:60: error: invalid type argument of ‘unary *’
Numeric.c:60: error: invalid type argument of ‘unary *’
Numeric.c:60: error: invalid type argument of ‘unary *’
Numeric.c:63: error: invalid type argument of ‘unary *’
Numeric.c:63: error: invalid type argument of ‘unary *’
Numeric.c:63: error: invalid type argument of ‘unary *’
Numeric.c:63: error: invalid type argument of ‘unary *’
Numeric.c:63: error: invalid type argument of ‘unary *’
Numeric.c:63: error: invalid type argument of ‘unary *’
Numeric.c:63: error: invalid type argument of ‘unary *’
Numeric.c:63: error: invalid type argument of ‘unary *’
Numeric.c:63: error: invalid type argument of ‘unary *’
Numeric.c:63: error: invalid type argument of ‘unary *’
Numeric.c:63: error: invalid type argument of ‘unary *’
Numeric.c:65: error: invalid type argument of ‘unary *’
Numeric.c:65: error: invalid type argument of ‘unary *’
Numeric.c:66: error: invalid type argument of ‘unary *’
Numeric.c:66: error: invalid type argument of ‘unary *’
Numeric.c:67: error: invalid type argument of ‘unary *’
Numeric.c:67: error: invalid type argument of ‘unary *’
Numeric.c:67: error: invalid type argument of ‘unary *’
Numeric.c:67: error: invalid type argument of ‘unary *’
make: *** [Numeric.o] Error 1
/usr/bin/make -- NOT OK
Running make test
Can't test without successful make
Running make install
make had returned bad status, install seems impossible
jmm@freekbox:~/bfwsandbox/sa/angel/astroportal/dtu8e/resources$
A: It can't find basic system headers. Either your include path is seriously messed up, or the headers are not installed.
A: Awfully hard to read without line breaks, but it looks like you are missing sys/types.h on your system. Do you have a full build environment installed (gcc, make, etc.)? What OS and distribution are you using?
In the future, you should bockquote output like this (select the text and click the quote button).
A: You're missing your C library development headers. You should install a package that has them. These are necessary to install this module because it has to compile some non-perl C code and needs to know more about your system.
I can't tell what kind of operating system you're on, but it looks like linux. If it's debian, you should be able to use apt-get to install the 'libc6-dev' package. That will contain the headers you need to compile this module. On other types of linux there will be a similarly named package.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75261",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: In how many languages is Null not equal to anything not even Null? In how many languages is Null not equal to anything not even Null?
A: In VB6 the expression Null = Null will produce Null instead of True as you would expect.
This will cause a runtime error if you try to assign it to a Boolean, however if you use it
as the condition of "If ... Then" it will act like False. Moreover Null <> Null will also
produce Null, so:
In VB6 you could say that Null is neither equal to itself (or anything else), nor unequal!
You're supposed to test for it using the IsNull() function.
VB6 also has other special values:
*
*Nothing for object references. Nothing = Nothing is a compile error. (you're supposed to compare it using "is")
*Missing for optional parameters which haven't been given. It has no literal representation so you can't even write Missing = Missing. (the test is IsMissing(foo))
*Empty for uninitialized variables. This one does test equal to itself although there's also a function IsEmpty().
*... let me know if I've forgotten one
I remember being a bit disgusted with VB.
A: Oracle is this way.
SELECT * FROM dual WHERE NULL=null; --no rows returned
A: MySQL has a null-safe equality operator, <=>, which returns true if both sides are equal or both sides are null. See MySQL Docs.
A: You can make ruby work that way:
class Null
def self.==(other);false;end
end
n=Null
print "Null equals nothing" if n!=Null
A: In C#, Nullable<bool> has interesting properties with respect to logical operators, but the equality operator is the same as other types in that language (i.e., ((bool?)null == (bool?)null) == true).
To preserve the short-circuited behavior of the short-circuited logical operators, and to preserve consistency with the non-short-circuited logical operators, the nullable boolean has some interesting properties. For example: true || null == true. false && null == false, etc. This stands in direct contradiction with other three-valued logic languages such as ANSI SQL.
A: It's this way in SQL (as a logic language) because null means unknown/undefined.
However, in programming languages (like say, C++ or C#), a null pointer/reference is a specific value with a specific meaning -- nothing.
Two nothings are equivilent, but two unknowns are not. The confusion comes from the fact that the same name (null) is used for both concepts.
A: In SQL you would have to do something like:
WHERE column is NULL
rather than
WHERE column = NULL
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75267",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Open Source Database Plugin For Eclipse? Does anyone know of a good open source plugin for database querying and exploring within Eclipse?
The active Database Exploring plugin within Eclipse is really geared around being associated with a Java project. While I am just trying to run ad-hoc queries and explore the schema. I am effectively looking for a just a common, quick querying tool without the overhead of having to create a code project. I have found a couple open source database plugins for Eclipse but these have not seen active development in over a year.
Any suggestions?
A: I use SQL Explorer.
It comes as an Eclipse plugin or standalone.
http://eclipsesql.sourceforge.net/
A: I use Quantum DB, and it seems to work quite well.
http://quantum.sourceforge.net/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75270",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: "Could not reformat the document" in ASP.NET, VS2008 I'm in an ASP.NET UserControl. When I type Control-K, Control-D to reformat all the markup, I get a series of messages from VS 2008:
"Could not reformat the document. The original format was restored."
"Could not complete the action."
"The operation could not be completed. The parameter is incorrect."
Anybody know what causes this?
Edit: OK, that is just...weird.
The problem is here:
<asp:TableCell>
<asp:Button Text="Cancel" runat="server" ID="lnkCancel" CssClass="CellSingleItem" />
</asp:TableCell>
Somehow that asp:Button line is causing the problem. But if I delete any individual attribute, the formatting works. Or if I add a new attribute, the formatting works. Or if I change the tag to be non-self-closing, it works. But if I undo and leave it as-is, it doesn't work.
All I can figure is that this is some sort of really obscure, bizarre bug.
A: There's probably some malformed markup somewhere in your document. Have you tried it on a fresh document?
A: Did get the problem today.
My solution: Restart Visual Studio
A: Usually this sort of behavior is caused by invalid code. It may only be invalid HTML causing it which would still allow the program to be compiled.
For example, if tags are mismatched like this the IDE cannot reformat it.
<div><h1>My Title</div></h1
Check your warnings to see if there are any entries pointing towards mismatched or unclosed tags.
A: select the entire suspicious codes segments and use Ctrl+k,Ctrl+F to format only the selected segments instead of whole document .
this way you can find the exact place of problems specially not closed or inappropriate closed tags and fix them .
after all scanning segment by segment is done you can format the whole document for sure
A: For me, it's usually as issue with whitespace. To fix it, I open Find and Replace (CTRL+H), set Look in to "Current Document", check Use and select "Regular expressions". For Find what I enter ":b|\n" (minus quotes), and for Replace with I enter a single space. Then I click Replace All.
The steps above will replace all whitespace—including line breaks—with a single space, and the next time you format the document, you shouldn't get any errors. That is assuming you don't have malformed HTML.
A: My problem was an extra ". Look carefully the html.
A: I encountered this for the first time a few weeks ago. I found it was down to invalid HTML. I had to cut out sections of content and paste it back in a little at a time to track down the problem.
A: For me, I had some bogus characters in my markup code. I only found this out by copy and pasting all my text into Notepad. After that, I saw the bogus characters (showed up as little squares). I just deleted those lines and retyped them and now everything is ok.
A: I had an unwanted semi-colon. But you may have quote ('), double quote ("), semi-colon (;) or any special character.
So, editing my answer with more details and a screenshot because it still very active.
Go to that line by double clicking the error and search for the extra (unwanted) quote ('), double quote ("), semi-colon (;) or any special character. Remove it because it is causing the error.
A: Just to add some more information. This issue is caused due to some invalid markup in html.
It won't cause any blocking while running the application.
Unfortunately the solutions mentioned here did not work for me.
1. Restarting visual studio
2. Replacing spaces using regex etc
The best solution to fix the issue is to go to the specific line where the issue is caused and check that line for any invalid symbols like , or ". Just remove it and it will work fine.
A: My issue is extra " in the value of html attribute, After removing this it is working fine for me.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75273",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: SelectedIndexChanged event handler getting old index I'm handling the onSelectIndexChanged event. An event is raised when the DropDownList selection changes. the problem is that the DropDownList still returns the old values for SelectedValue and SelectedIndex. What am I doing wrong?
Here is the DropDownList definition from the aspx file:
<div style="margin: 0px; padding: 0px 1em 0px 0px;">
<span style="margin: 0px; padding: 0px; vertical-align: top;">Route:</span>
<asp:DropDownList id="Select1" runat="server" onselectedindexchanged="index_changed" AutoPostBack="true">
</asp:DropDownList>
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
</div>
Here is the DropDownList OnSelectedIndexChanged event handler:
protected void index_changed(object sender, EventArgs e)
{
decimal d = Convert.ToDecimal( Select1.SelectedValue );
Literal1.Text = d.ToString();
}
A: If you are using AJAX you may also be doing a callback, not a full postback. In that case you may want to use this in your page load method:
if (!IsCallback && !IsPostBack)
{
// Do your page setup here
}
A: add this:
if page.isnotpostback {
}
around your code to bind the dropdownlist.
A: This may seem obvious, but anyway.
Do you initialize this dropdown with an initial value in some other event handler like OnLoad ?
If so you should check if that event is risen by a postback or by the first load. So you should have something like
if(!IsPostback) d.SelectedValue = "Default"
A: Do you have any code in page load that is by chance re-defaulting the value to the first value?
When the page reloads do you see the new value?
A: Is it possible that you have items copied throughout your datasource for the drop down list?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75282",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: What languages implement features from functional programming? Lisp developed a set of interesting language features quite early on in the academic world, but most of them never caught on in production environments.
Some languages, like JavaScript, adapted basic features like garbage collection and lexical closures, but all the stuff that might actually change how you write programs on a large scale, like powerful macros, the code-as-data thing and custom control structures, only seems to propagate within other functional languages, none of which are practical to use for non-trivial projects.
The functional programming community also came up with a lot of other interesting ideas (apart from functional programming itself), like referential transparency, generalised case-expressions (ie, pattern-matching, not crippled like C/C# switches) and curried functions, which seem obviously useful in regular programming and should be easy to integrate with existing programming practice, but for some reason seem to be stuck in the academic world forever.
Why do these features have such a hard time getting adopted? Are there any modern, practical languages that actually learn from Lisp instead of half-assedly copying "first class functions", or is there an inherent conflict that makes this impossible?
A: Scala is a cool functional/OO language with pattern matching, first class functions, and the like. It has the advantage of compiling to Java bytecode and inter-operates well with Java code.
A: I suggest you try Clojure. Syntactically beautiful dialect, functional (in the ML sense), and fast. You get immutability, software transactional memory, multiversion concurrency control, a REPL, SLIME support, and an inexhaustible FFI. It's the Lisp (& Haskell) for the Business Programmer. I'm having a great time using it daily in my real job.
A: There is no known correlation between a language "catching on" and whether or not is has powerful, well researched, well designed features.
A lot has been said on the subject. It exists all over the place in technology, and also the arts. We know artist A has more training and produces works of greater breadth and depth than artist B, yet artist B is far more successful in the marketplace. Is it because there's a zeitgeist? Is is because artist B has better marketing? Is it because most people won't take the time to understand artist A? Maybe artist B is secretly awful and we should mistrust experts who make judgements about artists? Probably all of the above, to some degree or another.
This drives people who study the arts, and people who study programming languages, crazy.
A: Common Lisp, used in the real-world albeit not wildely so, I guess.
A: Python or Ruby. See Paul Graham's thoughts on this in the question "I like Lisp but my company won't let me use it. What should I do?".
A: Scala is the absolute king of languages which have adopted significant academic features. Higher kinds, self types, polymorphic pattern matching, etc. All of these are bleeding-edge (or near to it) academic research topics that have been incorporated into Scala as fundamental features. Arguably, this has been to the detriment of the langauge's simplicity, but it does lead to some very interesting patterns.
C# is more mainstream than Scala, but it also has adopted fewer of these "out-there" functional features. LINQ is a limited implementation for Wadler's generalized list comprehensions, and everyone knows about lambdas. But for all that, C# (rightfully) remains a bit conservative in adopting research features from the academic world.
A: Erlang has recently gained renewed exposure not only through being used by Twitter, but also by the rise of XMPP driven messaging and implementations such as ejabberd. It sports many of the ideas coming from functional programming being a language designed with that in mind. Initially used to run Telephone switches and conceived by Ericson to run the first GSM networks. It is still around, it is fully functional (as a language) and used in many production environments.
A: Lua.
It's used as a scripting/extension language for a number of games (like World of Worcraft), and applications (Snort, NMAP, Wireshark, etc). In fact, according to an Adobe developer, Adobe's Lightroom is over 40% Lua.
The guys behind Lua have repeatedly listed Scheme and Lisp as major influences on Lua, and Lua has even been described as Scheme without the parentheses.
A:
Are there any modern, practical
languages that actually learn from
Lisp instead of half-assedly copying
"first class functions", or is there
an inherent conflict that makes this
impossible?
Why aren't lisp, haskell, ocaml, or f# modern?
You might just need to take it on yourself and look at them and realize that they are more robust, with libraries like java, then you'd think.
A lot of features have been adopted from functional languages to other languages. But vice versa -- (some) functional languages have objects, for example.
A: Have you checked out F#
A: Lot's of dynamic programming languages implement ideas from functional programming. The newer .Net languages (C# and VB) have what they call lambda's but these aren't side effect free.
It's not difficult combining concepts from functional programming and object oriented programming for example but it doesn't always make a lot of sense. Object oriented languages (try to) encapsulate state inside objects while functional languages encapsulate state inside functions. If you combine objects and functions in one language it gets harder to make sense of all this.
There have been a lot of languages that have combined these paradigms by just throwing them together (F#) and this can be usefull but I think we still need a couple of decades of playing with languages like this untill we can create a new paradigm that succesfully will combine the ideas from oo and functional programming.
A: C# 3.0 definitely does.
C# now has
*
*Lambda Expressions
*Higher Order Functions
*Map / Reduce + Filter ( Folding?) to lists and all types which implement IEnumerable.
*LINQ
*Object + Collection Initializers.
The last two list items may not fall under proper functional programming, anyways the answer is C# has implemented many useful concepts from Lisp etc.
A: In addition to what was said, a lot of LISP goodness is based on guaranteed lack of side-effects and using built-in data structures. Both rarely hold in real world. ML is probably better functional base.
A:
Lisp developed a set of interesting language features quite early on in the academic
world, but most of them never caught on in production environments.
Because the kind of people who manage software developers aren't the kinds of people who you can have an interesting chat comparing different language features with. Around 2000, I wanted to use LISP to implement XML-to-HTML transforms on our corporate website (this is around the time of Amazon implementing their backend in LISP). I didn't get to. This is mildly ironic seeing as the company I was working for made and sold a Common LISP environment.
A: Another "real-world" language that implements functional programming features is Javascript. Since absolutely everything has a value, then high-order functions are easily implemented. You also have other tenants of functional programming such as lambda functions, closures, and currying.
A: The features you refer to ("powerful" macros, the code-as-data thing and custom control structures) have not propagated within other functional languages. They died after Lisp taught us that they are a bad idea.
Modern functional languages (OCaml, Haskell, Erlang, Scala, F#, C# 3.0, JavaScript) do not have those features.
Cheers,
Jon Harrop.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75303",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Multicolor cursor in X X has the method XCreatePixmapCursor to create a cursor from a pixmap with a color depth of 1. The foreground and background colors can be other than black and white, but there are only two colors.
Is there a way to create a multicolored cursor in X?
A: You probably need to use the X Cursor Extensions. See the XCURSOR(3) manpage and the X11/Xcursor/Xcursor.h header file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75312",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Sys is undefined I have an ASP.Net/AJAX control kit project that i am working on. 80% of the time there is no problem. The page runs as it should. If you refresh the page it will sometimes show a javascript error "Sys is undefined".
It doesn't happen all the time, but it is reproducible. When it happens, the user has to shut down their browser and reopen the page.
This leads me to believe that it could be an IIS setting.
Another note. I looked at the page source both when I get the error, and when not. When the page throws errors the following code is missing:
<script src="/ScriptResource.axd?d=EAvfjPfYejDh0Z2Zq5zTR_TXqL0DgVcj_h1wz8cst6uXazNiprV1LnAGq3uL8N2vRbpXu46VsAMFGSgpfovx9_cO8tpy2so6Qm_0HXVGg_Y1&t=baeb8cc" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
if (typeof(Sys) === 'undefined') throw new Error('ASP.NET Ajax client-side framework failed to load.');
//]]>
</script>
A: Try setting your ScriptManager to this.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" />
A: Dean L's answer, https://stackoverflow.com/a/1718513/292060 worked for me, since my call to Sys was also too early. Since I'm using jQuery, instead of moving it down, I put the script inside a document.ready call:
$(document).ready(function () {
Sys. calls here
});
This seems to be late enough that Sys is available.
A: I was using telerik and had exactly same problem.
adding this to web.config resolved my issue :)
<location path="Telerik.Web.UI.WebResource.axd">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
maybe it will help you too. it was Authentication problem.
Source
A: Try one of this solutions:
1. The browser fails to load the compressed script
This is usually the case if you get the error on IE6, but not on other browsers.
The Script Resource Handler – ScriptResource.axd compresses the scripts before returning them to the browser. In pre-RTM releases, the handler did it all the time for all browsers, and it wasn’t configurable. There is an issue in one of the components of IE6 that prevents it from loading compressed scripts correctly. See KB article here. In RTM builds, we’ve made two fixes for this. One, we don’t compress if IE6 is the browser client. Two, we’ve now made compression configurable. Here’s how you can toggle the web.config.
How do you fix it? First, make sure you are using the AJAX Extensions 1.0 RTM release. That alone should be enough. You can also try turning off compression by editing your web.config to have the following:
<system.web.extensions>
<scripting>
<scriptResourceHandler enableCompression="false" enableCaching="true" />
</scripting>
</system.web.extensions>
2. The required configuration for ScriptResourceHandler doesn’t exist for the web.config for your application
Make sure your web.config contains the entries from the default web.config file provided with the extensions install. (default location: C:\Program Files\Microsoft ASP.NET\ASP.NET 2.0 AJAX Extensions\v1.0.61025)
3. The virtual directory you are using for your web, isn’t correctly marked as an application (thus the configuration isn’t getting loaded) - This would happen for IIS webs.
Make sure that you are using a Web Application, and not just a Virtual Directory
4. ScriptResource.axd requests return 404
This usually points to a mis-configuration of ASP.NET as a whole. On a default installation of ASP.NET, any web request to a resource ending in .axd is passed from IIS to ASP.NET via an isapi mapping. Additionally the mapping is configured to not check if the file exists. If that mapping does not exist, or the check if file exists isn't disabled, then IIS will attempt to find the physical file ScriptResource.axd, won't find it, and return 404.
You can check to see if this is the problem by coipy/pasting the full url to ScriptResource.axd from here, and seeing what it returns
<script src="/MyWebApp/ScriptResource.axd?[snip - long query string]" type="text/javascript"></script>
How do you fix this? If ASP.NET isn't properly installed at all, you can run the "aspnet_regiis.exe" command line tool to fix it up. It's located in C:\WINDOWS\Microsoft.Net\Framework\v2.0.50727. You can run "aspnet_regiis -i -enable", which does the full registration of ASP.NET with IIS and makes sure the ISAPI is enabled in IIS6. You can also run "aspnet_regiis -s w3svc/1/root/MyWebApp" to only fix up the registration for your web application.
5. Resolving the "Sys is undefined" error in ASP.NET AJAX RTM under IIS 7
Put this entry under <system.webServer/><handlers/>:
<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
and remove the one under <system.web/><httpHandlers/>.
References:
http://weblogs.asp.net/chrisri/demystifying-sys-is-undefined
http://geekswithblogs.net/lorint/archive/2007/03/28/110161.aspx
A: I hate adding to such a huge topic and so much later, but I've think I have a solution that works in VS2015 at the very least.
I was on a hunt to find a reason for the sys error, and the only solution that worked for me was to add EnableCdn="true" in a ScriptManager like this:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnableCdn="true" />
See the MSDN for more information.
Why do we need to do this?
When working on a asp.net web application, you have to enable CDN so that Microsoft can download the Sys. library.
There was probably a script in your page that was using the Sys function. Setting EnableCdn="true" would ensure that the Sys library is downloaded before it is used.
What's CDN?
It stands for "Content Delivery Network" and enabling it allows certain resources to download with simple references.
A quote from https://www.sitepoint.com/7-reasons-to-use-a-cdn/
Most CDNs are used to host static resources such as images, videos,
audio clips, CSS files and JavaScript. You’ll find common JavaScript
libraries, HTML5 shims, CSS resets, fonts and other assets available
on a variety of public and private CDN systems.
Both Google and Microsoft have CDNs. All you have to do is add a reference. Usually CDNs are added via a script resource:
<script src="https://ajax.aspnetcdn.com/ajax/4.5.1/1/MicrosoftAjax.js" type="text/javascript"></script>
Once you set EnableCdn="true" and Microsoft will add it's little CDN reference (like the one above) in the page which downloads the Sys library.
I hope that helps anybody that ran into the same issue.
A: I fixed my problem by moving the <script type="text/javascript"></script> block containing the Sys.* calls lower down (to the last item before the close of the body's <asp:Content/> section) in the HTML on the page. I originally had my the script block in the HEAD <asp:Content/> section of my page. I was working inside a page that had a MasterPageFile. Hope this helps someone out.
A: You must add these lines in the web.config
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
</httpHandlers>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpModules>
</system.web>
Hope this helps.
A: In addition to ensuring you have the ScriptManager on your page you need to ensure that your web.config is appropriately configured.
When ASP.NET AJAX 1.0 was released (for .NET 2.0) there was a lot of custom web.config settings which added handlers, controls, etc.
You'll find the config info here: http://www.asp.net/AJAX/documentation/live/ConfiguringASPNETAJAX.aspx
A: Make sure that any client scripts you have that interact with .NET AJAX have the following line at the end:
if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();
This tells the script manager that the whole script file has loaded and that it can begin to call client methods
A: I was having this same issue and after much wrangling I decided to try and isolate the problem and simply load the script manager in an empty page which still resulted in this same error. Having isolated the problem I discovered through a comparison of my site's web.config with a brand new (working) test site that changing <compilation debug="true"> to <compilation debug="false"> in the system.web section of my web.config fixes the problem.
I also had to remove the <xhtmlConformance mode="Legacy"/> entry from system.web to make the update panel work properly. Click here for a description of this issue.
A: When I experienced the errors
*
*Sys is undefined
*ASP.NET Ajax client-side framework failed to load
in IE when using ASP.NET Ajax controls in .NET 2.0, I needed to add the following to the web.config file within the <system.web> tags:
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add verb="GET" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler" validate="false"/>
</httpHandlers>
A: I solved this problem by creating separate asp.net ajax solution and copy and paste all ajax configuration from web.config to working project.
here are the must configuration you should set in web.config
<configuration>
<configSections>
<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
</sectionGroup>
</sectionGroup>
</configSections>
<assemblies>
<add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</assemblies>
</compilation>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
</httpHandlers>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpModules>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</modules>
<handlers>
<remove name="WebServiceHandlerFactory-Integrated"/>
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</handlers>
</system.webServer>
A: In case none of the above works for you, and you happen to be overriding OnPreRenderComplete, make sure you call base.OnPreRenderComplete. My therapist is going to be happy to see me back
A: I had the same problem after updating my AjaxControlToolkit.dll to the latest version 4.1.7.725 from 4.1.60623.0.
I've searched and came up to this page, but none of the answers help me.
After looking to the sample website of the Ajax Control Toolkit that is in the CodePlex zip file, I have realized that the <asp:ScriptManager> replaced by the new <ajaxtoolkit:ToolkitScriptManager>. I did so and there is no Sys.Extended is undefined any more.
A: In my case the problem was that I had putted the following code to keep the gridview tableheader after partial postback:
protected override void OnPreRenderComplete(EventArgs e)
{
if (grv.Rows.Count > 0)
{
grv.HeaderRow.TableSection = TableRowSection.TableHeader;
}
}
Removing this code stopped the issue.
A: Was having a similar issue, except that my page was consistently generating the Sys is undefined error.
For me the problem stems from the fact that I've just installed the AJAX 1.0 extension for .NET 2.0 but had already created my web project in Visual Studio.
When tried to create AJAX controls I kept encountering this error, I spotted Slace's and MadMax1138s posts here. And figured it was my web.config, I created a new project using the new "AJAX enabled web site" project type, and sure enough the web.config has a large number of customizations necessary to use the AJAX controls.
I just updated that web.config with the web.config updates I had already made myself and dropped it into my existing project and everything worked fine.
A: I have been seeing the exact same error today, but it was not a config or direct JavaScript issue.
An external .net project had been updated but the changes not picked up properly in the compilation of the web site. My presumption is that ASP.NET ajax was not able to construct the client representations of the .NET objects properly and so was failing to load correctly.
To resolve, I rebuilt the external project(s), and rebuilt my solution that was experiencing issues. The problem went away.
A: I found the error when using a combination of the Ajax Control Toolkit ToolkitScriptManager and URL Write 2.0.
In my <rewrite> <outboundRules> I had a precondition:
<preConditions>
<preCondition name="IsHTML">
<add input="{RESPONSE_CONTENT_TYPE}" pattern="^text/html"/>
</preCondition>
</preConditions>
But apparently some of my outbound rules weren't set to use the precondition.
Once I had that preCondition set on all my outbound rules:
<rule preCondition="IsHTML" name="MyOutboundRule">
No more problem.
A: Make sure you don't have any Rewrite rules that change your url.
In my case the application thought it was only level deeper then the url reached.
Example: http://mysite.com/app/page.aspx was the real url.
But i cut off /app/ this worked fine for ASP.net and WCF, but clearly not for Ajax.
A: I had similar problems and to my surprise what I found that one of my developer had saved web.config in the same folder/solution as web123.config and by mistake both of these files were uploaded.
As soon as I deleted the web123.config file, this error disappeared and ajax framework was loading correctly. even though I have
<compilation debug="true">
In my case I also have following segment. My project is using framework 3.5
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
</httpHandlers>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpModules>
</system.web>
A: This is going to sound stupid but I had a similar problem with a site being developed in VS2010 and hosted in the VS Dev Server. The page in question had a scriptmanager to create the connection to a wcf service. I added an extra method to the service and this error started appearing.
What fixed it for me was changing from 'Auto-assign Port' to 'Specific port' with a different port number in the oroject Web settings.
I wish I knew why...
A: Development Environment:
*
*Dev-Env: VS 2012
*FX: 4.0/4.5
*Implementations: Master(ScriptManager + UpdatePanel/Timer) + Content (UpdatePanel)
*Patterns: PageRouting.
Disclaimer:
If all the web.config solutions do not work for you and you have implemented PageRouting (IIS 7+), then the code snippet below will solve your problems.
Background:
Dont mean to Highjack this question but had the same problem as everyone else and implemented 100% of the suggestions here, with minor modifications for .Net 4.0/4.5, and none of them worked for me.
In my situation i had implemented Page Routing which was ghosting my problem. Basically it would work for about 20, or so, debug runs and then BAM would error out with the Sys is undefined error.
After reviewing a couple other posts, that got to talking about the Clean-URL logic, i remembered that i had done PageRouting setup's.
Here is the resource i used to build my patterns: Page Routing
My one-liner code fixed my VS2012 Debugging problem:
rts.Ignore("{resource}.axd/{*pathInfo}") 'Ignores any Resource cache references, used heavily in AJAX interactions.
A: Even after adding the correct entry for web config still getting this error ? most common reason for this error is JavaScript that references the Sys namespace too early.
Then most obvious fix would be move the java script block below the ScriptManager control:
A: I don't think this point has been added and since I just spent some time hunting this down I hope it can help.
I am working with IIS 7 and using the ASP.NET v4 Framework.
In my case it was important that an entry be added to both the and section of the entry in the web.config file.
My web.config file has a lot of handlers and in my case it was easiest to add the ScriptResources entry to the top of the handlers section. Most importantly, it needs to be placed before any entry that will act as a wildcard and capture the request. Adding it after a wildcard entry will cause it to be ignored and the error will still appear.The module can be added to the top or bottom of the section.
Web.config Sample:
<system.webServer>
<handlers>
<clear />
<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<!-- Make sure wildcard rules are below the ScriptResource tag -->
</handlers>
<modules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<!-- Other modules are added here -->
</modules>
</system.webServer>
A: I had same probleme but i fixed it by:
When putting a script file into a page, make sure it is
<script></script> and not <script />.
I have followed this:
http://forums.asp.net/t/1742435.aspx?An+element+with+id+form1+could+not+be+found+Script+error+on+page+load
Hope this will help
A: Add
if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();
Please check enter link description here
A: In my case, I've found a very hidden reason ... There was this page route with in Global.ascx.cs which doesn't appear in my tests in sub-folders but returns the question error all the time .. another day with strange issues.
routes.MapPageRoute("siteDefault", "{culture}/", "~/default.aspx", false, new RouteValueDictionary(new { culture = "(\\w{2})|(\\w{2}-\\w{2})" }));
A: I know this is an old thread but I found a somewhat unique solution. In my case I was getting the error because I am using both Webforms and MVC in the same ASP.NET web application. After mapping routes the issue showed up. I fixed it by adding the following code to ignore routes for both "{resource}.aspx/{*pathInfo}" and "{resource}.axd/{*pathInfo}"
private void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Test", action = "Index", id = UrlParameter.Optional }
);
}
A: Just create blank .axd files in your solutions root foder problem will be resolved. (2 file: scriptresouce.asx, webresource.asxd)
A: Please please please do check that the Server has the correct time and date set...
After about wasting 6 hours, i read it somewhere...
The date and time for the server must be updated to work correctly...
otherwise you will get 'Sys' is undefined error.
A: Hi thanx a lot it solved my issue ,
By default vs 2008 will add
<!--<add verb="*" path="*.asmx" validate="false" type="Microsoft.Web.Script.Services.ScriptHandlerFactory, Microsoft.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add verb="GET" path="ScriptResource.axd" type="Microsoft.Web.Handlers.ScriptResourceHandler" validate="false" />-->
Need to correct Default config(Above) to below code
FIX
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add verb="GET" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler" validate="false"/>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75322",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "65"
} |
Q: XSLT processing in/from ruby Can anyone recommend an efficient method to execute XSLT transforms of XML data within a Ruby application? The XSL gem (REXSL) is not available yet, and while I have seen a project or two that implement it, I'm wary of using them so early on. A friend had recommended a shell out call to Perl, but I'm worried about resources.
This is for a linux environment.
A: Try the "libxslt-ruby" gem. It depends on the "libxmlr-ruby" bindings for libxml library, which you probably already have installed if you're developing on Linux.
A: I would recomment to shell out call to "xsltproc", which comes with the libxslt libraries in linux and does the work.
Or if you are using JRuby by any chance, then you have several xslt parsers for java that you can really really easily use from your ruby program.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75340",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Execute an insert and then log in one SQL command I've been asked to implement some code that will update a row in a MS SQL Server database and then use a stored proc to insert the update in a history table. We can't add a stored proc to do this since we don't control the database. I know in stored procs you can do the update and then call execute on another stored proc. Can I set it up to do this in code using one SQL command?
A: Either run them both in the same statement (separate the separate commands by a semi-colon) or a use a transaction so you can rollback the first statement if the 2nd fails.
A: You don't really need a stored proc for this. The question really boils down to whether or not you have control over all the inserts. If in fact you have access to all the inserts, you can simply wrap an insert into datatable, and a insert into historytable in a single transasction. This will ensure that both are completed for 'success' to occur. However, when accessing to tables in sequence within a transaction you need to make sure you don't lock historytable then datatable, or else you could have a deadlock situation.
However, if you do not have control over the inserts, you can add a trigger to certain db systems that will give you access to the data that are modified, inserted or deleted. It may or may not give you all the data you need, like who did the insert, update or delete, but it will tell you what changed.
A: You can also create sql triggers.
A: Depending on your library, you can usually just put both queries in one Command String, separated by a semi-colon.
A: Insufficient information -- what SQL server? Why have a history table?
Triggers will do this sort of thing. MySQL's binlog might be more useful for you.
You say you don't control the database. Do you control the code that accesses it? Add logging there and keep it out of the SQL server entirely.
A: Thanks all for your reply, below is a synopsis of what I ended up doing. Now to test to see if the trans actually roll back in event of a fail.
sSQL = "BEGIN TRANSACTION;" & _
" Update table set col1 = @col1, col2 = @col2" & _
" where col3 = @col3 and " & _
" EXECUTE addcontacthistoryentry @parm1, @parm2, @parm3, @parm4, @parm5, @parm6; " & _
"COMMIT TRANSACTION;"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75347",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Force numerical order on a SQL Server 2005 varchar column, containing letters and numbers? I have a column containing the strings 'Operator (1)' and so on until 'Operator (600)' so far.
I want to get them numerically ordered and I've come up with
select colname from table order by
cast(replace(replace(colname,'Operator (',''),')','') as int)
which is very very ugly.
Better suggestions?
A: It's that, InStr()/SubString(), changing Operator(1) to Operator(001), storing the n in Operator(n) separately, or creating a computed column that hides the ugly string manipulation. What you have seems fine.
A: If you really have to leave the data in the format you have - and adding a numeric sort order column is the better solution - then consider wrapping the text manipulation up in a user defined function.
select colname from table order by dbo.udfSortOperator(colname)
It's less ugly and gives you some abstraction. There's an additional overhead of the function call but on a table containing low thousands of rows in a not-too-heavily hit database server it's not a major concern. Make notes in the function to optomise later as required.
A: My answer would be to change the problem. I would add an operatorNumber field to the table if that is possible. Change the update/insert routines to extract the number and store it. That way the string conversion hit is only once per record.
The ordering logic would require the string conversion every time the query is run.
A: Well, first define the meaning of that column. Is operator a name so you can justify using chars? Or is it a number?
If the field is a name then you will use chars, and then you would want to determine the fixed length. Pad all operator names with zeros on the left. Define naming rules for operators (I.E. No leters. Or the codes you would use in a series like "A001")
An index will sort the physical data in the server. And a properly define text naming will sort them on a query. You would want both.
If the operator is a number, then you got the data type for that column wrong and needs to be changed.
A: Indexed computed column
If you find yourself ordering on or otherwise querying operator column often, consider creating a computed column for its numeric value and adding an index for it. This will give you a computed/persistent column (which sounds like oxymoron, but isn't).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75361",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to make embedded servlet engine instantiate servlets eagerly? The problem is simple, but I'm struggling a bit already.
Server server = new Server(8080);
Context context = new Context(server, "/", Context.NO_SESSIONS);
context.addServlet(MainPageView.class, "/");
context.addServlet(UserView.class, "/signup");
server.start();
That's a pretty standard piece of code that you can find anywhere in Jetty world. I have an application that embeds Jetty as a servlet engine and has some servlets.
Instantiation of some of these servlets requires heavy work on startup. Say – reading additional config files, connecting to the database, etc. How can I make the servlet engine instantiate all servlets eagerly, so that I can do all the hard work upfront and not on the first user request?
A: I'm not sure why using Guice make's Justin's option not work for you. What exactly is getting injected in? I'm not sure if this would help you at all because it is very similar to what Justin wrote above but if you do it this way, Jetty will do the actually instantiating.
Context context = new Context(server, "/", Context.NO_SESSIONS);
ServletHolder mainPageViewHolder = new ServletHolder(MainPageView.class);
// Do this to force Jetty to instantiate the servlet
mainPageViewHolder.getServlet();
context.addServlet(mainPageViewHolder, "/");
A: Use the Context.addServlet overload that takes a ServletHolder. ServletHolder is a class that accepts either a Class or a Servlet instance.
Servlet myServlet = new MyServlet();
ServletHolder holder = new ServletHolder(myServlet);
context.addServlet(holder, "/");
This assumes Jetty 6. I think it will work for Jetty 7 as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75379",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Make VS compiler catch signed/unsigned assignments? The Visual Studio compiler does not seem to warn on signed/unsigned assignments, only on comparisons. For example the code below will generate a warning on the if statement but not the initial assignments.
Is there anyway to make it catch these? I'm already at W4 but thought (hoped) there may be another setting somewhere.
Thanks,
int foo(void)
{
unsigned int fooUnsigned = 0xffffffff;
int fooSigned = fooUnsigned; // no warning
if (fooSigned < fooUnsigned) // warning
{
return 0;
}
return fooSigned;
}
Update:
Quamrana is right, this is controlled by warning 4365 which appears to be off by default, even at W4. However you can explicitly enable it for a given warning level like so;
#pragma warning (4 : 4365)
Which results in;
warning C4365: 'initializing' : conversion from 'unsigned int' to 'int', signed/unsigned mismatch
A: You need to enable warning 4365 to catch the assignment.
That might be tricky - you need to enable ALL warnings - use /Wall which enables lots of warnings, so you may have some trouble seeing the warning occur, but it does.
A: You can change the level of any specific warning by using /W[level][code]. So in this case /W34365 will make warning 4365 into a level 3 warning. If you do this a lot you might find it useful to put these options in a text file and use the @[file] option to simplify the command line.
A: @quamrana:
There must be something beyond the /Wall option to enable warning 4365:
C:\Temp>cl /Wall /c foo.c
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.21022.08 for 80x86
Copyright (C) Microsoft Corporation. All rights reserved.
foo.c
foo.c(6) : warning C4018: '<' : signed/unsigned mismatch
I see that Andrew got it to work, but does anyone have an idea why it's not working here?
The Visual Studio docs indicate that it should, but I can't even get the example program in the docs to give the C4365 warning (though it does give the related C4245 warning - but that occurs with just a /W4 option anyway).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75385",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: NHibernate to not cache a property How can I configure NHibernate to not cache a file?
I know I can create a method that does an HSQL, but can I through a configuration setting in the <class>.xml file or the hibernate xml file itself to not cache a property?
A: You cannot set secondary caching settings at property level (as far as I know), but you can individually tune cache settings for each entity directly in their XML files.
For instance:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="ClassName" table="Table">
<cache usage="nonstrict-read-write" />
<id name="Id" type="Int64" ...
Where the cache "usage" property can be any of the following values:
*
*read-write: assures read committed isolation, makes sure data is consistent but doesn't reduce DB access as much as the other modes,
*nonstrict-read-write: objects with rare writes, slight chance of inconsistency between DB and cache,
*read-only: for data objects that never change, no chance of inconsistency.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75400",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What are the uses of "using" in C#? User kokos answered the wonderful Hidden Features of C# question by mentioning the using keyword. Can you elaborate on that? What are the uses of using?
A: Things like this:
using (var conn = new SqlConnection("connection string"))
{
conn.Open();
// Execute SQL statement here on the connection you created
}
This SqlConnection will be closed without needing to explicitly call the .Close() function, and this will happen even if an exception is thrown, without the need for a try/catch/finally.
A: Just adding a little something that I was surprised did not come up. The most interesting feature of using (in my opinion) is that no matter how you exit the using block, it will always dispose the object. This includes returns and exceptions.
using (var db = new DbContext())
{
if(db.State == State.Closed)
throw new Exception("Database connection is closed.");
return db.Something.ToList();
}
It doesn't matter if the exception is thrown or the list is returned. The DbContext object will always be disposed.
A: Another great use of using is when instantiating a modal dialog.
Using frm as new Form1
Form1.ShowDialog
' Do stuff here
End Using
A: The reason for the using statement is to ensure that the object is disposed as soon as it goes out of scope, and it doesn't require explicit code to ensure that this happens.
As in Understanding the 'using' statement in C# (codeproject) and Using objects that implement IDisposable (microsoft), the C# compiler converts
using (MyResource myRes = new MyResource())
{
myRes.DoSomething();
}
to
{ // Limits scope of myRes
MyResource myRes= new MyResource();
try
{
myRes.DoSomething();
}
finally
{
// Check for a null resource.
if (myRes != null)
// Call the object's Dispose method.
((IDisposable)myRes).Dispose();
}
}
C# 8 introduces a new syntax, named "using declarations":
A using declaration is a variable declaration preceded by the using keyword. It tells the compiler that the variable being declared should be disposed at the end of the enclosing scope.
So the equivalent code of above would be:
using var myRes = new MyResource();
myRes.DoSomething();
And when control leaves the containing scope (usually a method, but it can also be a code block), myRes will be disposed.
A: You can make use of the alias namespace by way of the following example:
using LegacyEntities = CompanyFoo.CoreLib.x86.VBComponents.CompanyObjects;
This is called a using alias directive as as you can see, it can be used to hide long-winded references should you want to make it obvious in your code what you are referring to
e.g.
LegacyEntities.Account
instead of
CompanyFoo.CoreLib.x86.VBComponents.CompanyObjects.Account
or simply
Account // It is not obvious this is a legacy entity
A: Interestingly, you can also use the using/IDisposable pattern for other interesting things (such as the other point of the way that Rhino Mocks uses it). Basically, you can take advantage of the fact that the compiler will always call .Dispose on the "used" object. If you have something that needs to happen after a certain operation ... something that has a definite start and end ... then you can simply make an IDisposable class that starts the operation in the constructor, and then finishes in the Dispose method.
This allows you to use the really nice using syntax to denote the explicit start and end of said operation. This is also how the System.Transactions stuff works.
A: In conclusion, when you use a local variable of a type that implements IDisposable, always, without exception, use using1.
If you use nonlocal IDisposable variables, then always implement the IDisposable pattern.
Two simple rules, no exception1. Preventing resource leaks otherwise is a real pain in the *ss.
1): The only exception is – when you're handling exceptions. It might then be less code to call Dispose explicitly in the finally block.
A: using can be used to call IDisposable. It can also be used to alias types.
using (SqlConnection cnn = new SqlConnection()) { /* Code */}
using f1 = System.Windows.Forms.Form;
A: When using ADO.NET you can use the keywork for things like your connection object or reader object. That way when the code block completes it will automatically dispose of your connection.
A: "using" can also be used to resolve namespace conflicts.
See http://www.davidarno.org/c-howtos/aliases-overcoming-name-conflicts/ for a short tutorial I wrote on the subject.
A: public class ClassA:IDisposable
{
#region IDisposable Members
public void Dispose()
{
GC.SuppressFinalize(this);
}
#endregion
}
public void fn_Data()
{
using (ClassA ObjectName = new ClassA())
{
// Use objectName
}
}
A: There are two usages of the using keyword in C# as follows.
*
*As a directive
Generally we use the using keyword to add namespaces in code-behind and class files. Then it makes available all the classes, interfaces and abstract classes and their methods and properties in the current page.
Example:
using System.IO;
*As a statement
This is another way to use the using keyword in C#. It plays a vital role in improving performance in garbage collection.
The using statement ensures that Dispose() is called even if an exception occurs when you are creating objects and calling methods, properties and so on. Dispose() is a method that is present in the IDisposable interface that helps to implement custom garbage collection. In other words if I am doing some database operation (Insert, Update, Delete) but somehow an exception occurs then here the using statement closes the connection automatically. No need to call the connection Close() method explicitly.
Another important factor is that it helps in Connection Pooling. Connection Pooling in .NET helps to eliminate the closing of a database connection multiple times. It sends the connection object to a pool for future use (next database call). The next time a database connection is called from your application the connection pool fetches the objects available in the pool. So it helps to improve the performance of the application. So when we use the using statement the controller sends the object to the connection pool automatically, there is no need to call the Close() and Dispose() methods explicitly.
You can do the same as what the using statement is doing by using try-catch block and call the Dispose() inside the finally block explicitly. But the using statement does the calls automatically to make the code cleaner and more elegant. Within the using block, the object is read-only and cannot be modified or reassigned.
Example:
string connString = "Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT CustomerId, CompanyName FROM Customers";
conn.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
Console.WriteLine("{0}\t{1}", dr.GetString(0), dr.GetString(1));
}
}
In the preceding code I am not closing any connection; it will close automatically. The using statement will call conn.Close() automatically due to the using statement (using (SqlConnection conn = new SqlConnection(connString)) and the same for a SqlDataReader object. And also if any exception occurs it will close the connection automatically.
For more information, see Usage and Importance of Using in C#.
A: using, in the sense of
using (var foo = new Bar())
{
Baz();
}
Is actually shorthand for a try/finally block. It is equivalent to the code:
var foo = new Bar();
try
{
Baz();
}
finally
{
foo.Dispose();
}
You'll note, of course, that the first snippet is much more concise than the second and also that there are many kinds of things that you might want to do as cleanup even if an exception is thrown. Because of this, we've come up with a class that we call Scope that allows you to execute arbitrary code in the Dispose method. So, for example, if you had a property called IsWorking that you always wanted to set to false after trying to perform an operation, you'd do it like this:
using (new Scope(() => IsWorking = false))
{
IsWorking = true;
MundaneYetDangerousWork();
}
You can read more about our solution and how we derived it here.
A: using is used when you have a resource that you want disposed after it's been used.
For instance if you allocate a File resource and only need to use it in one section of code for a little reading or writing, using is helpful for disposing of the File resource as soon as your done.
The resource being used needs to implement IDisposable to work properly.
Example:
using (File file = new File (parameters))
{
// Code to do stuff with the file
}
A: Since a lot of people still do:
using (System.IO.StreamReader r = new System.IO.StreamReader(""))
using (System.IO.StreamReader r2 = new System.IO.StreamReader("")) {
//code
}
I guess a lot of people still don't know that you can do:
using (System.IO.StreamReader r = new System.IO.StreamReader(""), r2 = new System.IO.StreamReader("")) {
//code
}
A: Microsoft documentation states that using has a double function (https://msdn.microsoft.com/en-us/library/zhdeatwt.aspx), both as a directive and in statements. As a statement, as it was pointed out here in other answers, the keyword is basically syntactic sugar to determine a scope to dispose an IDisposable object. As a directive, it is routinely used to import namespaces and types. Also as a directive, you can create aliases for namespaces and types, as pointed out in the book "C# 5.0 In a Nutshell: The Definitive Guide" (http://www.amazon.com/5-0-Nutshell-The-Definitive-Reference-ebook/dp/B008E6I1K8), by Joseph and Ben Albahari. One example:
namespace HelloWorld
{
using AppFunc = Func<IDictionary<DateTime, string>, List<string>>;
public class Startup
{
public static AppFunc OrderEvents()
{
AppFunc appFunc = (IDictionary<DateTime, string> events) =>
{
if ((events != null) && (events.Count > 0))
{
List<string> result = events.OrderBy(ev => ev.Key)
.Select(ev => ev.Value)
.ToList();
return result;
}
throw new ArgumentException("Event dictionary is null or empty.");
};
return appFunc;
}
}
}
This is something to adopt wisely, since the abuse of this practice can hurt the clarity of one's code. There is a nice explanation on C# aliases, also mentioning pros and cons, in DotNetPearls (http://www.dotnetperls.com/using-alias).
A: I've used it a lot in the past to work with input and output streams. You can nest them nicely and it takes away a lot of the potential problems you usually run into (by automatically calling dispose). For example:
using (FileStream fs = new FileStream("c:\file.txt", FileMode.Open))
{
using (BufferedStream bs = new BufferedStream(fs))
{
using (System.IO.StreamReader sr = new StreamReader(bs))
{
string output = sr.ReadToEnd();
}
}
}
A: When you use using, it will call the Dispose() method on the object at the end of the using's scope. So you can have quite a bit of great cleanup code in your Dispose() method.
A bullet point:
If you implement IDisposable, make sure you call GC.SuppressFinalize() in your Dispose() implementation, as otherwise automatic garbage collection will try to come along and Finalize it at some point, which at the least would be a waste of resources if you've already Dispose()d of it.
A: The using keyword defines the scope for the object and then disposes of the object when the scope is complete. For example.
using (Font font2 = new Font("Arial", 10.0f))
{
// Use font2
}
See here for the MSDN article on the C# using keyword.
A: Not that it is ultra important, but using can also be used to change resources on the fly.
Yes, disposable as mentioned earlier, but perhaps specifically you don't want the resources they mismatch with other resources during the rest of your execution. So you want to dispose of it so it doesn't interfere elsewhere.
A: Another example of a reasonable use in which the object is immediately disposed:
using (IDataReader myReader = DataFunctions.ExecuteReader(CommandType.Text, sql.ToString(), dp.Parameters, myConnectionString))
{
while (myReader.Read())
{
MyObject theObject = new MyObject();
theObject.PublicProperty = myReader.GetString(0);
myCollection.Add(theObject);
}
}
A: Everything outside the curly brackets is disposed, so it is great to dispose your objects if you are not using them. This is so because if you have a SqlDataAdapter object and you are using it only once in the application life cycle and you are filling just one dataset and you don't need it anymore, you can use the code:
using(SqlDataAdapter adapter_object = new SqlDataAdapter(sql_command_parameter))
{
// do stuff
} // here adapter_object is disposed automatically
A: The using statement provides a convenience mechanism to correctly use IDisposable objects. As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement.
The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned.
This comes from here.
A: For me the name "using" is a little bit confusing, because is can be a directive to import a Namespace or a statement (like the one discussed here) for error handling.
A different name for error handling would've been nice, and maybe a somehow more obvious one.
A: It also can be used for creating scopes for Example:
class LoggerScope:IDisposable {
static ThreadLocal<LoggerScope> threadScope =
new ThreadLocal<LoggerScope>();
private LoggerScope previous;
public static LoggerScope Current=> threadScope.Value;
public bool WithTime{get;}
public LoggerScope(bool withTime){
previous = threadScope.Value;
threadScope.Value = this;
WithTime=withTime;
}
public void Dispose(){
threadScope.Value = previous;
}
}
class Program {
public static void Main(params string[] args){
new Program().Run();
}
public void Run(){
log("something happend!");
using(new LoggerScope(false)){
log("the quick brown fox jumps over the lazy dog!");
using(new LoggerScope(true)){
log("nested scope!");
}
}
}
void log(string message){
if(LoggerScope.Current!=null){
Console.WriteLine(message);
if(LoggerScope.Current.WithTime){
Console.WriteLine(DateTime.Now);
}
}
}
}
A: The using statement tells .NET to release the object specified in the using block once it is no longer needed.
So you should use the 'using' block for classes that require cleaning up after them, like System.IO types.
A: The Rhino Mocks Record-playback Syntax makes an interesting use of using.
A:
using as a statement automatically calls the dispose on the specified
object. The object must implement the IDisposable interface. It is
possible to use several objects in one statement as long as they are
of the same type.
The CLR converts your code into CIL. And the using statement gets translated into a try and finally block. This is how the using statement is represented in CIL. A using statement is translated into three parts: acquisition, usage, and disposal. The resource is first acquired, then the usage is enclosed in a try statement with a finally clause. The object then gets disposed in the finally clause.
A: The using clause is used to define the scope for the particular variable.
For example:
Using(SqlConnection conn = new SqlConnection(ConnectionString)
{
Conn.Open()
// Execute SQL statements here.
// You do not have to close the connection explicitly
// here as "USING" will close the connection once the
// object Conn goes out of the defined scope.
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75401",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "354"
} |
Q: Deleting certain classes on running an external tool in eclipse? I've set an external tool (sablecc) in eclipse (3.4) that generates a bunch of classes in the current project. I need to run this tool and regenerate these classes fairly frequently. This means that every time I want to run sablecc, I have to manually delete the packages/classes that sablecc creates in order to ensure that I don't have conflicts between the old and new generated classes. Is there some easy way to automate this from within eclipse or otherwise?
A: Not sure if I understand your point right, I suppose you need to delete old classes before running sablecc because some of them would not be eventually created in new run.
It is probably best to write short Ant build.xml with the target, which first removes the classes (Ant delete task) and then runs sablecc (Ant exec task). It is also possible to preset eclipse so that it refreshes workspace after Ant finishes.
Put the build.xml anywhere to project, right click, Run As/Ant Build.
Just for the sake of the clean style, you could then call sablecc with its Ant task (implemented by org.sablecc.ant.taskdef), instead of running it externally in new process.
A: You can tell Eclipse to refresh the workspace (or parts of it) after an external tool has been run. This should force Eclipse to detect any new/deleted classes.
A: JesperE is referring to the option Refresh->Refresh resources on completion in your external tools configuration for running sablecc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75411",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.