qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
360,232 | <p>Building on <a href="https://stackoverflow.com/questions/318553/getting-emacs-to-untabify-when-saving-files">Getting Emacs to untabify when saving certain file types (and only those file types)</a> , I'd like to run a hook to untabify my C++ files when I start modifying the buffer. I tried adding hooks to untabify the buffer on load, but then it untabifies all my writable files that are autoloaded when emacs starts.</p>
<p>(For those that wonder why I'm doing this, it's because where I work enforces the use of tabs in files, which I'm happy to comply with. The problem is that I mark up my files to tell me when lines are too long, but the regexp matches the number of characters in the line, not how much space the line takes up. 4 tabs in a line can push it far over my 132 character limit, but the line won't be marked appropriately. Thus, I need a way to tabify and untabify automatically.)</p>
| [
{
"answer_id": 360396,
"author": "Alex B",
"author_id": 6180,
"author_profile": "https://Stackoverflow.com/users/6180",
"pm_score": 1,
"selected": false,
"text": "(defun untabify-buffer ()\n \"Untabify current buffer\"\n (interactive)\n (untabify (point-min) (point-max)))\n\n(defun untabify-hook ()\n (untabify-buffer))\n\n; Add the untabify hook to any modes you want untabified on load\n(add-hook 'nxml-mode-hook 'untabify-hook)\n"
},
{
"answer_id": 360413,
"author": "huaiyuan",
"author_id": 16240,
"author_profile": "https://Stackoverflow.com/users/16240",
"pm_score": 2,
"selected": false,
"text": "(add-hook 'before-change-functions \n (lambda (&rest args) \n (if (not (buffer-modified-p))\n (untabify (point-min) (point-max)))))\n"
},
{
"answer_id": 360523,
"author": "Trey Jackson",
"author_id": 6148,
"author_profile": "https://Stackoverflow.com/users/6148",
"pm_score": 0,
"selected": false,
"text": "\"^\\\\(?: \\\\|[^ \\n]\\\\{4\\\\}\\\\)\\\\{33\\\\}\\\\(.+\\\\)$\"\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45425/"
] |
360,234 | <p>I want to read an specific xml node and its value for example</p>
<pre><code><customers>
<name>John</name>
<lastname>fetcher</lastname>
</customer>
</code></pre>
<p>and my code behind should be some thing like this (I don't know how it should be though):</p>
<pre><code>Response.Write(xml.Node["name"].Value)
</code></pre>
<p>As I said it is just an example because I don't know how to do it.</p>
| [
{
"answer_id": 360250,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "document.Descendant(\"name\").Value\n document.SelectSingleNode(\"//name\").InnerText\n"
},
{
"answer_id": 360258,
"author": "Rich",
"author_id": 13449,
"author_profile": "https://Stackoverflow.com/users/13449",
"pm_score": 3,
"selected": true,
"text": "Response.Write(xml.SelectSingleNode(\"//name\").innerText)\n"
},
{
"answer_id": 360269,
"author": "Phil Corcoran",
"author_id": 45381,
"author_profile": "https://Stackoverflow.com/users/45381",
"pm_score": 1,
"selected": false,
"text": " 'Create the XML Document\n Dim l_xmld As XmlDocument\n'Create the XML Node\n Dim l_node As XmlNode\n\n l_xmld = New XmlDocument\n\n 'Load the Xml file\n l_xmld.LoadXml(\"XML Filename as String\")\n\n 'get the attributes\n l_node = l_xmld.SelectSingleNode(\"/customers/name\")\n\n Response.Write(l_node.InnerText)\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44852/"
] |
360,241 | <p>I have a visual studio 2005 solution which has a web application and a class library project. The web application has a reference to the library project. I'd like the library project's code documentation XML to output to the web application's bin folder, along with the library's DLL. I can't seem to find any easy way of doing this.</p>
| [
{
"answer_id": 369002,
"author": "Mike Strother",
"author_id": 21320,
"author_profile": "https://Stackoverflow.com/users/21320",
"pm_score": 0,
"selected": false,
"text": "copy \"$(TargetDir)$(TargetName).xml\" \"$(SolutionDir)MyWebProject1\\bin\\$(TargetName).xml\"\ncopy \"$(TargetDir)$(TargetName).xml\" \"$(SolutionDir)MyWebProject2\\bin\\$(TargetName).xml\"\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21320/"
] |
360,254 | <p>If I try to use a closure on an event handler the compiler complains with :</p>
<p>Incompatible types: "method pointer and regular procedure"</p>
<p>which I understand.. but is there a way to use a clouser on method pointers? and how to define if can?</p>
<p>eg : </p>
<pre><code>Button1.Onclick = procedure( sender : tobject ) begin ... end;
</code></pre>
<p>Thanks!</p>
| [
{
"answer_id": 388690,
"author": "Hans-Eric",
"author_id": 39348,
"author_profile": "https://Stackoverflow.com/users/39348",
"pm_score": 3,
"selected": false,
"text": "Button1.OnClick := procedure( sender : tobject ) of object begin\n ...\nend;\n Button1.OnClick := procedure( sender : tobject ) begin\n ...\nend;\n"
},
{
"answer_id": 410745,
"author": "dummzeuch",
"author_id": 49925,
"author_profile": "https://Stackoverflow.com/users/49925",
"pm_score": 2,
"selected": false,
"text": "procedure MyFakeMethod(_self: pointer; _Sender: TObject);\nbegin\n // do not access _self here! It is not valid\n ...\nend;\n\n...\n\nvar\n Meth: TMethod;\nbegin\n Meth.Data := nil;\n Meth.Code := @MyFakeMethod;\n Button1.OnClick := TNotifyEvent(Meth);\nend;\n"
},
{
"answer_id": 5647546,
"author": "Codenoid",
"author_id": 705615,
"author_profile": "https://Stackoverflow.com/users/705615",
"pm_score": 4,
"selected": true,
"text": "@Button1.OnClick := pPointer(Cardinal(pPointer( procedure (sender: tObject) \nbegin \n ((sender as TButton).Owner as TForm).Caption := 'Freedom to anonymous methods!' \n\nend )^ ) + $0C)^;\n"
},
{
"answer_id": 34360070,
"author": "William Egge",
"author_id": 655931,
"author_profile": "https://Stackoverflow.com/users/655931",
"pm_score": 2,
"selected": false,
"text": "procedure TForm36.Button2Click(Sender: TObject);\nvar\n Win: TForm;\nbegin\n Win:= TForm.Create(Self);\n Win.OnClick:= TEventComponent.NotifyEvent(Win, procedure begin ShowMessage('Hello'); Win.Free; end);\n Win.Show;\nend;\n unit AnonEvents;\n\ninterface\nuses\n SysUtils, Classes;\n\ntype\n TEventComponent = class(TComponent)\n protected\n FAnon: TProc;\n procedure Notify(Sender: TObject);\n class function MakeComponent(const AOwner: TComponent; const AProc: TProc): TEventComponent;\n public\n class function NotifyEvent(const AOwner: TComponent; const AProc: TProc): TNotifyEvent;\n end;\n\nimplementation\n\n{ TEventComponent }\n\nclass function TEventComponent.MakeComponent(const AOwner: TComponent;\n const AProc: TProc): TEventComponent;\nbegin\n Result:= TEventComponent.Create(AOwner);\n Result.FAnon:= AProc;\nend;\n\nprocedure TEventComponent.Notify(Sender: TObject);\nbegin\n FAnon();\nend;\n\nclass function TEventComponent.NotifyEvent(const AOwner: TComponent;\n const AProc: TProc): TNotifyEvent;\nbegin\n Result:= MakeComponent(AOwner, AProc).Notify;\nend;\n\nend.\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45439/"
] |
360,259 | <p>Can anyone recommend a decent SFTP library for use with Windows C++ apps? If a cross-platform one is available then all the better, but it's not essential. It's for use with a commercial application, so paying for something isn't an issue.</p>
<p>I am using the superb <a href="http://www.codeproject.com/KB/MFC/UltimateTCPIP.aspx" rel="noreferrer">Ultimate TCP/IP</a> library which supports FTP-S but not SFTP (yeh, I know, confusing isn't it!).</p>
<p>I've come across the <a href="http://www.chilkatsoft.com/ssh-sftp-c++.asp" rel="noreferrer">Chilkat</a> library, which looks very good, but wondered if there are any others that people have used.</p>
| [
{
"answer_id": 26006716,
"author": "Desphilboy",
"author_id": 2023625,
"author_profile": "https://Stackoverflow.com/users/2023625",
"pm_score": 3,
"selected": false,
"text": "main()\n{\npSFTPConnector sshc = new SFTPConnector(L\".\\\\\", L\"127.0.0.1\", 22, L\"sftpuser\",L\"sftppassword\"); // change the hostname , port , username, password to your sftp server, your credentials\n\nFILE *nullfile = fopen(\"null\", \"w\"); \nsshc->setLogFile(nullfile);\nsshc->setVerbosity(SSH_LOG_DEBUG); // you can change the verbosity as appropriate for you\n\nint i= sshc->InitSession();\nif (i != E_OK) wprintf(L\"%s\",sshc->errstring.c_str() );\ni=sshc->ConnectSession();\nif (i != E_OK) wprintf(L\"%s\", sshc->errstring.c_str());\n\ni = sshc->InitSFTP();\nif (i != E_OK) wprintf(L\"%s\", sshc->errstring.c_str());\n\ni = sshc->SFTPrename(\"renamed_myfile.txt\", \"myfile.txt\"); //change these file names\ni = sshc->Makedir(\"sftpdir\");\ni = sshc->testUploadFile(\"myfile2.txt\", \"1234567890testfile\");\n\n\n// change these file names to whatever appropriate\n\n\ni = sshc->SFTPreget(\"c:\\\\testdir\\\\reget_downloaded_CAR_HIRE_FINAL.jpg\", \"CAR_HIRE_FINAL.jpg\", 64 * 1024);\nsshc->setBlockTransferDelay(1);\n\ni = sshc->GetSessionStatus();\ni = sshc->SFTPreput(\"c:\\\\testdir\\\\CentOS-6.5-x86_64-bin-DVD1.iso\", \"reput_CentOS-6.5-x86_64-bin-DVD1.iso\", 64 * 1024);\ni = sshc->SFTPreput(\"c:\\\\testdir\\\\Reget_CentOS-6.5-x86_64-bin-DVD1.iso\", \"reput2_CentOS-6.5-x86_64-bin-DVD1.iso\", 64 * 1024);\n\nif (i != E_OK) wprintf(L\"%s\", sshc->errstring.c_str());\ndelete sshc;\ngetchar();\nreturn 0;\n}\n // filename ssh.h\n// SFTP Connection class with Pause/Resume largfiles capability\n// uses libssh for sftp functionality.\n// Author Desphilboy\n// Written 21 Sep 2014\n\n\n\n\n// needed include files on a windows system\n// for linux, native file open and read/write functions must be changed.\n\n\n#include <libssh\\libssh.h>\n#include <libssh\\sftp.h>\n#include <Windows.h>\n#include <string>\n#include <fcntl.h>\n#include <sys\\types.h>\n#include <sys\\stat.h>\n#include <time.h>\n#include <fstream>\n#include <iostream>\n#include <process.h>\nusing namespace std;\n\n\n// constant to limit length of character strings\n#define SHORT_BUFF_LEN 1024\n#define INITIALBLOCKTRANSDELAY 10 // mili seconds, this is the delay that we put after each block transfer to make it posssible for network to absorb the data.\n\n\n\n\n// these values will be returned by functions to report error or success\ntypedef enum sshconerr{\n E_OK = 1, E_SESSION_ALOC = -1, E_SSH_CONNECT_ERR = -2, E_SFTP_ALLOC = -3, E_INIT_SFTP = -4, E_CREATE_DIR = -5, E_FILEOPEN_WRITE = -6, E_WRITE_ERR = -7\n , E_FILE_CLOSE = -8, E_FILE_OPEN_READ = -9, E_INVALID_PARAMS = -10, E_SFTP_ERR = -11, E_SFTP_READ_ERR = -12, E_SFTP_READBYTES_ERR = -13, E_GET_FILEINF = -14\n , E_LOCAL_FILE_NOTFOUND = -15, E_RENAME_ERR = -16, E_MEM_ALLOC = -17, E_LOCAL_FILE_READ = -18, E_LOCAL_FILE_RDWR = -19, E_REMOTEFILE_SEEK = -20\n , E_REMOTE_FILE_OPEN = -21, E_DELETE_ERR = -22, E_RENAME_LOCAL_FILE = -23, E_LOCAL_DELETE_FILE = -24, E_FILEOPEN_RDONLY = -25, E_SFTP_READ_EOF=-26\n ,E_AUTHENTICATE=-27 ,E_UNKNOWN=-999 } ESSHERR;\n\n\n// status of transfers;\ntypedef enum sftpstat{ ES_DONE=0 , ES_INPROGRESS , ES_FAILED, ES_STARTING, ES_PAUSED, ES_RESUMING, ES_CANCELLED, ES_NONE } ESFTPSTAT;\n\nusing namespace std;\n\n\n\n\n// statistics about the transfer;\ntypedef struct transferstatstruct {\n string remote_file_name;\n string local_file_name;\n __int64 initially_transferred;\n __int64 total_size;\n __int64 transferred;\n __int64 averagebps;\n __int64 seconds_elapsed;\n __int64 seconds_remained;\n int percent; \n ESFTPSTAT transferstate;\n} TTransStat;\n\n\n#define E_SESSION_NEW -1\n\n\n\n// these libraries are required\n#pragma comment(lib, \"ssh.lib\") // for ex4ecution in windows, ssh.dll is needed\n\n\n\n\n// this is the main class that does the majority of the work\n\ntypedef class CSFTPConnector{\n\nprivate:\n\n ssh_session session; // ssh session\n sftp_session sftp; // sftp session\n sftp_file file; // structure for a remote file\n FILE *localfile; // not used in windows but could be local file pointer in UNIX\n FILE *logfile; // the file for writing logs, default is set to stderr\n string filename; // file name of the transfer;\n string localfilename; // file name of local file;\n string tempfilename; // a temporaty file name will be used during the transfer which is renamed when transfer is completed.\n ESFTPSTAT transferstatus; // state of the transfer which has one of the above values (ESFTPSTAT)\n\n __int64 transferstarttime; // time of start of the transfer\n wchar_t username[SHORT_BUFF_LEN];\n wchar_t password[SHORT_BUFF_LEN];\n wchar_t hostname[SHORT_BUFF_LEN]; // hostname of the sftp server\n wchar_t basedir[SHORT_BUFF_LEN]; // this base dir is the directory of public and private key structur ( NOT USED IN THIS VERSION)\n int port; // port of the server;\n int verbosity; // degree of verbosity of libssh\n __int64 filesize; // total number of bytes to be transfered;\n DWORD local_file_size_hiDWORD; // Bill Gates cannot accept the file size without twisting the programmers, so he accepts them in 2 separate words like this\n DWORD local_file_size_lowDWORD; // these 2 DWORDs when connected together comprise a 64 bit file size.\n __int64 lfilesize; // local file size\n __int64 rfilesize; // remote file size\n __int64 transfered; // number of bytes already transfered\n __int64 initially_was_transferred; // this is the number of bytes which was transferred before pause or interrupt of a transfer and used when resuming a transfer.\n bool pause; // pause flag\n TTransStat stats; // statistics of the transfer\n HANDLE localfilehandle; // windows uses handles to manipulate files. this is the handle to local file.\n int blocktransferdelay;\n\n ESSHERR CSFTPConnector::rwopen_existing_SFTPfile(char *fn); // open a file on remote ( server ) read/write for upload\n ESSHERR CSFTPConnector::rdopen_existing_SFTPfile(char *fn); // open a file on remote ( server ) read only for download\n ESSHERR createSFTPfile(char *fn); // create a file on server;\n ESSHERR writeSFTPfile(char *block, size_t blocksize); // write a block of data to the open remote file\n ESSHERR readSFTPfile(char *block, size_t len, size_t *bytesread); // read a block of data from the open remote file\n ESSHERR readSFTPfile(char *block, __int64 len, DWORD *bytesread);\n ESSHERR closeSFTPfile(); // closes the remote file;\n ESSHERR openSFTPfile(char *fn); // opens the remote file\n ESSHERR getSFTPfileinfo(); // gets information about the remote file\n\n\npublic:\n wstring errstring; // the string describing last error \n ESSHERR Err; // error code of last error\n CSFTPConnector(); // default constructor;\n CSFTPConnector(wchar_t *dir, wchar_t *hn, int hostport, wchar_t *un, wchar_t *pass); // constructor\n void setVerbosity(int v); \n int getVerbosity();\n ESSHERR InitSession(); // must be called befor doing any transfer\n ESSHERR ConnectSession(); // connnects to the ssh server\n ESSHERR InitSFTP(); // must be called befor doing any transfer\n ESSHERR Makedir(char *newdir);\n ESSHERR testUploadFile(char *fn, char *block); // do not use this , only for test purposes for myself\n ESSHERR SFTPput(char *lfn, char *rfn, size_t blocksize); // Upload a file from start\n ESSHERR SFTPreput(char *lfn, char *rfn, size_t blocksize); // checks for previouse interrupted transfer, then either continues the previouse transfer ( if there was any) or starts a new one (UPLOAD)\n ESSHERR SFTPrename(char *newname, char *oldname); // renames a remote file( must be closed)\n ESSHERR CSFTPConnector::SFTPdelete(char *remfile); // deletes a remote file\n TTransStat *getStatus(); // gets statistics of the transfer\n ESSHERR CSFTPConnector::SFTPget(char *lfn, char *rfn, size_t blocksize); // Downloads a file from sftp server\n ESSHERR CSFTPConnector::SFTPreget(char *lfn, char *rfn, size_t blocksize); // checks for previouse interrupted transfer, then either continues the previouse transfer ( if there was any) or starts a new one (DOWNLOAD)\n void CancelTransfer();\n void PauseTransfer();\n void setLogFile(FILE *logf); // sets the log file, if not set stderr will be used. by default.\n void CloseLocalFile();\n void CloseRemoteFile();\n int GetSessionStatus();\n bool IsConnected(); \n void setBlockTransferDelay(int miliseconds);\n ESFTPSTAT getTransferStatus();\n ~CSFTPConnector();\n\n\n\n\n} SFTPConnector, *pSFTPConnector ;\n\n\n\nsftpstat CSFTPConnector::getTransferStatus()\n{\n return transferstatus;\n}\n\n\nvoid CSFTPConnector::setBlockTransferDelay(int miliseconds)\n{\n blocktransferdelay = miliseconds;\n\n}\n\n\nbool CSFTPConnector::IsConnected()\n{\n if (ssh_is_connected(session) == 1) return true;\n return false;\n}\n\n\n\nint CSFTPConnector::GetSessionStatus()\n{\n return ssh_get_status(session);\n}\n\nvoid CSFTPConnector::CloseLocalFile()\n{\n CloseHandle(localfilehandle);\n}\n\n\nvoid CSFTPConnector::CloseRemoteFile()\n{\n sftp_close(file);\n}\n\n\n\nvoid CSFTPConnector::setLogFile(FILE *logf)\n{\n logfile = logf;\n}\n\n\nvoid CSFTPConnector::CancelTransfer()\n{\n transferstatus = ES_CANCELLED;\n\n}\nvoid CSFTPConnector::PauseTransfer()\n{\n transferstatus = ES_PAUSED;\n pause = true;\n}\n\n//----------------------------------------\n\n// SFTPreger starts or resumes a download.\nESSHERR CSFTPConnector::SFTPreget(char *lfn, char *rfn, size_t blocksize)\n{\n ESSHERR result;\n int rc;\n BOOL bresult;\n DWORD bytesread;\n DWORD byteswritten;\n filesize = 0;\n transfered = 0;\n initially_was_transferred = 0;\n lfilesize = rfilesize = 0;\n pause = false;\n transferstatus = ES_NONE;\n char *block;\n struct stat st;\n wchar_t temp[SHORT_BUFF_LEN];\n size_t tempsize;\n wstring wlfn;\n int loopcounter = 0;\n\n localfilename = lfn;\n filename = rfn;\n\n tempfilename = string(lfn) + \".sftp_temp\";\n mbstowcs_s(&tempsize, temp, tempfilename.c_str(), SHORT_BUFF_LEN);\n\n localfilehandle = CreateFile(temp, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);\n if (localfilehandle == INVALID_HANDLE_VALUE)\n {\n transferstatus = ES_FAILED;\n errstring = L\"Could not open local file:\" + wstring(temp) +L\" for read and write\";\n Err = E_LOCAL_FILE_RDWR;\n return E_LOCAL_FILE_RDWR;\n }\n local_file_size_lowDWORD = GetFileSize(localfilehandle, &local_file_size_hiDWORD);\n lfilesize = (local_file_size_hiDWORD * 0x100000000) + local_file_size_lowDWORD;\n\n if (lfilesize < 0) {\n transferstatus = ES_FAILED;\n Err = E_LOCAL_FILE_NOTFOUND;\n errstring = L\"Could not get size info for file:\" + wstring(temp); \n CloseLocalFile();\n return E_LOCAL_FILE_NOTFOUND;\n }\n\n transfered = lfilesize;\n initially_was_transferred = lfilesize;\n\n __int64 tempi64 = transfered & 0x00000000FFFFFFFF;\n DWORD dwlow = tempi64;\n tempi64 = (transfered & 0x7FFFFFFF00000000);\n tempi64 = tempi64 >> 32;\n long dwhi = tempi64;\n DWORD dwResult = SetFilePointer(localfilehandle, dwlow, &dwhi, FILE_BEGIN);\n if (dwResult == INVALID_SET_FILE_POINTER)\n {\n errstring = L\"could not set file pointer for localfile\" + wstring(temp);\n transferstatus = ES_FAILED; Err = result; \n CloseLocalFile();\n return result;\n }\n\n block = (char*)malloc(blocksize + 1);\n if (block == NULL) {\n Err = E_MEM_ALLOC;\n transferstatus = ES_FAILED;\n errstring = L\"Could not allocate memory for file block size\";\n CloseLocalFile();\n return E_MEM_ALLOC;\n }\n\n result = rdopen_existing_SFTPfile((char *)rfn);\n\n if (result == E_OK){\n getSFTPfileinfo();\n filesize = rfilesize; \n }\n else\n {\n Err = E_REMOTE_FILE_OPEN;\n transferstatus = ES_FAILED;\n errstring = L\"Could not open remote file\";\n CloseLocalFile();\n delete block;\n return E_REMOTE_FILE_OPEN;\n }\n\n\n rc=sftp_seek64(file, transfered);\n if (rc != SSH_OK)\n {\n Err = E_REMOTEFILE_SEEK;\n transferstatus = ES_FAILED;\n errstring = L\"Could not set pointer for remote file\";\n CloseRemoteFile();\n CloseLocalFile();\n delete block;\n return E_REMOTEFILE_SEEK;\n }\n\n transferstatus = ES_RESUMING;\n\n\n sftp_file_set_blocking(file);\n\n transferstarttime = time(NULL);\n transferstatus = ES_INPROGRESS;\n\n while (transferstatus != ES_FAILED && transferstatus != ES_PAUSED && transferstatus!=ES_CANCELLED &&transferstatus != ES_DONE)\n {\n loopcounter++;\n\n result = readSFTPfile(block,blocksize, (size_t *) &bytesread);\n if (result != E_OK && result != E_SFTP_READ_EOF)\n {\n errstring = L\"Error reading from remote sftp server file.\";\n Err = result;\n transferstatus = ES_FAILED;\n CloseRemoteFile();\n CloseLocalFile();\n delete block;\n return result;\n }\n if (result == E_SFTP_READ_EOF) transferstatus = ES_DONE;\n fprintf(logfile, \"Read %d bytes from input file. Number of packets: %d , %llu from %llu bytes\\n\", bytesread, loopcounter, transfered, filesize);\n\n bresult = WriteFile(localfilehandle, (LPVOID)block, bytesread, &byteswritten, NULL);\n if (byteswritten < bytesread)\n {\n if (bresult == FALSE)\n {\n errstring = L\"Error writing to local file.\";\n Err = E_LOCAL_FILE_RDWR;\n transferstatus = ES_FAILED;\n CloseRemoteFile();\n CloseLocalFile();\n delete block;\n return E_LOCAL_FILE_RDWR;\n }\n else if (bytesread == 0)\n {\n errstring = L\"Transfer done.\";\n Err = E_OK;\n transferstatus = ES_DONE;\n continue;\n }\n }\n\n\n Err = E_OK;\n\n if (pause == true) transferstatus = ES_PAUSED;\n if (bresult == TRUE && bytesread == 0)\n {\n // at the end of the file\n transferstatus = ES_DONE;\n }\n Sleep(blocktransferdelay);\n if (loopcounter % 71 == 0)Sleep(7 * blocktransferdelay);\n if (loopcounter % 331 == 0)Sleep(77 * blocktransferdelay);\n if (loopcounter % 3331 == 0)Sleep(777 * blocktransferdelay);\n\n }\n result = closeSFTPfile();\n CloseHandle(localfilehandle);\n Sleep(1000);\n\n if (transferstatus == ES_DONE)\n {\n wchar_t temp2[SHORT_BUFF_LEN];\n mbstowcs_s(&tempsize, temp2, lfn, SHORT_BUFF_LEN);\n bresult = MoveFile(temp, temp2);\n if (bresult != TRUE)\n {\n Err = E_RENAME_LOCAL_FILE;\n errstring = L\"Could not rename local file: \" + wstring(temp);\n transferstatus = ES_FAILED;\n delete block;\n return E_RENAME_LOCAL_FILE;\n }\n }\n\n if (transferstatus == ES_CANCELLED)\n {\n wchar_t temp2[SHORT_BUFF_LEN];\n mbstowcs_s(&tempsize, temp2, lfn, SHORT_BUFF_LEN);\n bresult = DeleteFile(temp);\n if (bresult != TRUE)\n {\n Err = E_LOCAL_DELETE_FILE;\n errstring = L\"Could not rename local file: \" + wstring(temp);\n transferstatus = ES_FAILED;\n delete block;\n return E_LOCAL_DELETE_FILE;\n }\n }\n\n delete block;\n return result;\n}\n\n\n\n\n//---------------------------------------\n\n\n\nTTransStat * CSFTPConnector::getStatus()\n{\n stats.seconds_elapsed = time(NULL); \n stats.seconds_elapsed -= transferstarttime;\n stats.averagebps = ((transfered- initially_was_transferred) * 8) / stats.seconds_elapsed;\n if (filesize > 0) {\n stats.percent = (transfered *100)/ filesize;\n stats.seconds_remained = ((filesize - transfered) * 8) / stats.averagebps;\n }\n else\n {\n stats.percent = -1;\n stats.seconds_remained = -1;\n }\n stats.total_size = filesize;\n stats.transferstate = transferstatus;\n stats.remote_file_name = filename;\n stats.local_file_name = localfilename;\n stats.transferred = transfered;\n stats.initially_transferred = initially_was_transferred;\n\n\n return &stats;\n}\n\n\nESSHERR CSFTPConnector::SFTPrename(char *newname, char *oldname)\n{\n\n int rc=sftp_rename(sftp, oldname, newname);\n if (rc !=SSH_OK){\n return E_RENAME_ERR;\n }\n\n return E_OK;\n}\n\n\n\nESSHERR CSFTPConnector::SFTPdelete(char *remfile)\n{\n\n int rc = sftp_unlink(sftp,remfile);\n if (rc != SSH_OK){\n return E_DELETE_ERR;\n }\n\n return E_OK;\n}\n\n// SFTPreput\nESSHERR CSFTPConnector::SFTPreput(char *lfn, char *rfn, size_t blocksize)\n{\n ESSHERR result;\n BOOL bresult;\n DWORD bytesread;\n filesize = 0;\n transfered = 0;\n\n pause = false;\n transferstatus = ES_NONE;\n char *block;\n struct stat st;\n wchar_t temp[SHORT_BUFF_LEN];\n size_t tempsize;\n wstring wlfn;\n int loopcounter = 0;\n\n localfilename = lfn;\n //wlfn = wstring(lfn);\n //localfile = fopen(lfn, L\"r\");\n filename = rfn;\n mbstowcs_s(&tempsize, temp, lfn, SHORT_BUFF_LEN);\n\n //filesize = getFileSize(localfilename);\n\n /*if(filesize < 0) {\n transferstatus = ES_FAILED;\n Err = E_LOCAL_FILE_NOTFOUND;\n return E_LOCAL_FILE_NOTFOUND;\n }*/\n\n localfilehandle = CreateFile(temp, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);\n if (localfilehandle == INVALID_HANDLE_VALUE)\n {\n transferstatus = ES_FAILED;\n Err = E_LOCAL_FILE_NOTFOUND;\n return E_LOCAL_FILE_NOTFOUND;\n }\n local_file_size_lowDWORD = GetFileSize(localfilehandle, &local_file_size_hiDWORD);\n filesize = (local_file_size_hiDWORD * 0x100000000) + local_file_size_lowDWORD;\n\n if (filesize < 0) {\n transferstatus = ES_FAILED;\n Err = E_LOCAL_FILE_NOTFOUND;\n CloseLocalFile();\n return E_LOCAL_FILE_NOTFOUND;\n }\n\n block = (char*)malloc(blocksize + 1);\n if (block == NULL) {\n Err = E_MEM_ALLOC;\n transferstatus = ES_FAILED;\n errstring = L\"Could not allocate memory for file block size\";\n CloseLocalFile();\n return E_MEM_ALLOC;\n }\n\n\n tempfilename = string(rfn) + \".sftp_temp\";\n\n result = rwopen_existing_SFTPfile((char *)tempfilename.c_str());\n if (result == E_OK){\n getSFTPfileinfo();\n sftp_seek64(file, rfilesize);\n __int64 tempi64 = rfilesize & 0x00000000FFFFFFFF;\n DWORD dwlow = tempi64;\n tempi64 = (rfilesize & 0x7FFFFFFF00000000);\n tempi64 = tempi64 >> 32;\n long dwhi = tempi64;\n DWORD dwResult=SetFilePointer(localfilehandle, dwlow,&dwhi , FILE_BEGIN);\n if (dwResult == INVALID_SET_FILE_POINTER)\n {\n transferstatus = ES_FAILED; Err = result; return result;\n }\n transferstatus = ES_RESUMING;\n transfered = rfilesize;\n initially_was_transferred = rfilesize;\n\n }\n else{\n result = createSFTPfile((char *)tempfilename.c_str());\n transferstatus = ES_STARTING;\n rfilesize = 0;\n initially_was_transferred = 0;\n if (result != E_OK) {\n transferstatus = ES_FAILED; \n Err = result;\n CloseLocalFile();\n return result;\n }\n }\n sftp_file_set_blocking(file);\n transferstarttime = time(NULL);\n transferstatus = ES_INPROGRESS;\n\n while (transferstatus != ES_FAILED && transferstatus != ES_PAUSED && transferstatus != ES_DONE)\n {\n loopcounter++;\n bresult = ReadFile(localfilehandle, (LPVOID)block, blocksize, &bytesread, NULL);\n fprintf(logfile, \"Read %d bytes from input file. Number of packets: %d , %llu from %llu bytes\\n\", bytesread, loopcounter, transfered, filesize);\n if (bytesread < blocksize)\n {\n if (bresult == FALSE)\n {\n errstring = L\"Error reading from local file.\";\n Err = E_LOCAL_FILE_READ;\n transferstatus = ES_FAILED;\n CloseRemoteFile();\n CloseLocalFile();\n return E_LOCAL_FILE_READ;\n }\n else if (bytesread == 0)\n {\n errstring = L\"Transfer done.\";\n Err = E_OK;\n transferstatus = ES_DONE;\n continue;\n }\n }\n\n result = writeSFTPfile(block, bytesread);\n if (result != E_OK && bytesread>0 )\n {\n errstring = L\"Error transmitting to remote sftp server file.\";\n Err = result;\n transferstatus = ES_FAILED;\n CloseRemoteFile();\n CloseLocalFile();\n return result;\n }\n\n\n Err = E_OK;\n //transfered = transfered + bytesread;\n if (pause == true) transferstatus = ES_PAUSED;\n if (bresult == TRUE && bytesread == 0)\n {\n // at the end of the file\n transferstatus = ES_DONE;\n }\n Sleep(blocktransferdelay);\n if (loopcounter % 71 == 0)Sleep(7 * blocktransferdelay);\n if (loopcounter % 331 == 0)Sleep(77 * blocktransferdelay);\n if (loopcounter % 3331 == 0)Sleep(777 * blocktransferdelay);\n\n }\n\n CloseRemoteFile();\n CloseLocalFile();\n Sleep(1000);\n\n if (transferstatus == ES_CANCELLED)\n {\n result = SFTPdelete((char *)tempfilename.c_str());\n if (bresult != E_OK)\n {\n Err = E_DELETE_ERR;\n errstring = L\"Could not delete remote file.\";\n transferstatus = ES_FAILED;\n return E_DELETE_ERR;\n }\n }\n if (transferstatus == ES_DONE) result = SFTPrename(rfn, (char *)tempfilename.c_str());\n delete block;\n return result;\n}\n\n\n\n\nESSHERR CSFTPConnector::getSFTPfileinfo()\n{\n sftp_attributes fileinf = sftp_fstat(file);\n\n if (fileinf == NULL){\n return E_GET_FILEINF;\n }\n\n rfilesize = fileinf->size;\n\n sftp_attributes_free(fileinf);\n return E_OK;\n}\n\nESSHERR CSFTPConnector::closeSFTPfile()\n{\n int rc = sftp_close(file);\n if (rc != SSH_OK)\n {\n fprintf(logfile, \"Can't close the written file: %s\\n\",\n ssh_get_error(session));\n return E_FILE_CLOSE;\n }\n return E_OK;\n}\n\n\n\n\nESSHERR CSFTPConnector::writeSFTPfile(char *block, size_t blocksize)\n{\n size_t nwritten = sftp_write(file, block, blocksize);\n if (nwritten != blocksize)\n {\n fprintf(logfile, \"Can't write data to file: %s\\n\",\n ssh_get_error(session));\n //sftp_close(file);\n transfered = transfered + nwritten;\n return E_WRITE_ERR;\n }\n\n transfered = transfered + nwritten;\n return E_OK;\n}\nESSHERR CSFTPConnector::readSFTPfile(char *block, __int64 len, DWORD *bytesread)\n{\n DWORD readbytes;\n *bytesread = 0;\n if (len <= 0) return E_INVALID_PARAMS;\n if (bytesread == NULL || block == NULL) return E_INVALID_PARAMS;\n\n readbytes = sftp_read(file, block, len);\n if (readbytes < 0)\n {\n fprintf(logfile, \"Can't read from remote file: %s %s\\n\", filename.c_str(), ssh_get_error(session));\n *bytesread = 0;\n return E_SFTP_READ_ERR;\n }\n\n\n if (readbytes < len)\n {\n *bytesread = readbytes;\n return E_SFTP_READ_EOF;\n }\n\n\n *bytesread = readbytes;\n transfered = transfered + readbytes;\n\n return E_OK;\n\n}\n\n\nESSHERR CSFTPConnector::createSFTPfile(char *fn)\n{\n\n int access_type = O_CREAT | O_RDWR | O_APPEND;\n int rc, nwritten;\n\n filename = string(fn);\n file = sftp_open(sftp, fn,access_type, S_IREAD | S_IWRITE);\n if (file == NULL)\n {\n fprintf(logfile, \"Can't open file for writing: %s\\n\",\n ssh_get_error(session));\n return E_FILEOPEN_WRITE;\n }\n return E_OK;\n}\n\n\n\n\n\nESSHERR CSFTPConnector::openSFTPfile(char *fn)\n{\n int access_type = O_RDONLY;\n int rc, nwritten;\n\n filename = string(fn);\n file = sftp_open(sftp, fn,\n access_type, S_IWRITE);\n if (file == NULL)\n {\n fprintf(logfile, \"Can't open file for writing: %s\\n\",\n ssh_get_error(session));\n return E_FILE_OPEN_READ;\n }\n return E_OK;\n\n}\n\nESSHERR CSFTPConnector::Makedir(char *newdir)\n{\n int rc;\n rc = sftp_mkdir(sftp, newdir, S_IFDIR);\n if (rc != SSH_OK)\n {\n if (sftp_get_error(sftp) != SSH_FX_FILE_ALREADY_EXISTS)\n {\n fprintf(logfile, \"Can't create directory: %s\\n\",\n ssh_get_error(session));\n return E_CREATE_DIR;\n }\n }\n\n return E_OK;\n}\n\n\n\n\nSFTPConnector::CSFTPConnector()\n{\n //libssh2_init(0);\n session = ssh_new();\n if (session == NULL)\n {\n Err = E_SESSION_ALOC;\n errstring = L\"Could not allocate a session.\";\n\n }\n wcscpy(hostname, L\"localhost\" );\n wcscpy(username, L\"User\");\n wcscpy(password, L\"Password\");\n wcscpy(basedir, L\".\\\\\");\n port = 22;\n verbosity = SSH_LOG_RARE;\n filesize = 0;\n transfered = 0;\n\n pause = false;\n transferstatus = ES_NONE;\n logfile = stderr;\n blocktransferdelay = INITIALBLOCKTRANSDELAY;\n\n}\n\n\n\n\nCSFTPConnector::CSFTPConnector(wchar_t *dir, wchar_t *hn, int hostport, wchar_t *un, wchar_t *pass)\n{\n\n //libssh2_init(0);\n session = ssh_new();\n\n if (session == NULL)\n {\n Err = E_SESSION_ALOC;\n errstring = L\"Could not allocate a session.\";\n\n }\n wcscpy(hostname, hn);\n wcscpy(username, un);\n wcscpy(password, pass);\n wcscpy(basedir, dir);\n port = hostport;\n verbosity = SSH_LOG_RARE;\n filesize=0;\n transfered=0;\n\n pause=false;\n transferstatus = ES_NONE;\n logfile = stderr;\n blocktransferdelay = INITIALBLOCKTRANSDELAY;\n\n}\n\n\nESSHERR CSFTPConnector::InitSFTP()\n{\n int rc;\n sftp= sftp_new(session);\n if (session == NULL)\n {\n Err = E_SFTP_ALLOC;\n errstring = L\"Could not allocate a sftp session.\";\n\n }\n\n rc = sftp_init(sftp);\n if (rc != SSH_OK)\n {\n fprintf(logfile, \"Error initializing SFTP session: %s.\\n\",\n sftp_get_error(sftp));\n sftp_free(sftp);\n return E_INIT_SFTP;\n }\n\n\n return E_OK;\n}\n\n\nESSHERR CSFTPConnector::ConnectSession()\n{\n char temp[SHORT_BUFF_LEN];\n size_t n_of_chars;\n wcstombs_s(&n_of_chars, temp, SHORT_BUFF_LEN, (const wchar_t *)password, SHORT_BUFF_LEN);\n int ir;\n\n ir=ssh_connect(session);\n if (ir != SSH_OK){\n errstring = L\"Could not connect the ssh session.\";\n return E_SSH_CONNECT_ERR;\n }\n\n ir=ssh_userauth_password(session, NULL, temp);\n if (ir != SSH_OK){\n errstring = L\"Could not authenticate with the ssh server.\\r\\n\";\n return E_AUTHENTICATE;\n }\n return E_OK;\n}\n\n\nESSHERR CSFTPConnector::InitSession()\n{\n char temp[SHORT_BUFF_LEN];\n size_t n_of_chars;\n wcstombs_s(&n_of_chars, temp,SHORT_BUFF_LEN, (const wchar_t *) hostname, SHORT_BUFF_LEN);\n ssh_options_set(session, SSH_OPTIONS_HOST,temp);\n ssh_options_set(session, SSH_OPTIONS_LOG_VERBOSITY, &verbosity);\n ssh_options_set(session, SSH_OPTIONS_PORT, &port);\n wcstombs_s(&n_of_chars, temp, SHORT_BUFF_LEN, (const wchar_t *)username, SHORT_BUFF_LEN);\n ssh_options_set(session, SSH_OPTIONS_USER,temp);\n wcstombs_s(&n_of_chars, temp, SHORT_BUFF_LEN, (const wchar_t *)basedir, SHORT_BUFF_LEN);\n ssh_options_set(session, SSH_OPTIONS_SSH_DIR, temp);\n\n return E_OK;\n}\n\n\nvoid CSFTPConnector::setVerbosity(int v)\n{\n verbosity = v;\n}\n\n\nint CSFTPConnector::getVerbosity()\n{\n return verbosity;\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
] |
360,265 | <p><a href="http://leepoint.net/notes-java/data/expressions/22compareobjects.html" rel="nofollow noreferrer">http://leepoint.net/notes-java/data/expressions/22compareobjects.html</a></p>
<blockquote>
<p>It turns out that defining equals()
isn't trivial; in fact it's moderately
hard to get it right, especially in
the case of subclasses. The best
treatment of the issues is in
Horstmann's Core Java Vol 1.</p>
</blockquote>
<p>If equals() must always be overridden, then what is a good approach for not being cornered into having to do object comparison? What are some good "design" alternatives?</p>
<p>EDIT:</p>
<p>I'm not sure this is coming across the way that I had intended. Maybe the question should be more along the lines of "Why would you want to compare two objects?" Based upon your answer to that question, is there an alternative solution to comparison? I don't mean, a different implementation of equals. I mean, not using equality at all. I think the key point is to start with that question, why would you want to compare two objects.</p>
| [
{
"answer_id": 360301,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 1,
"selected": false,
"text": "Integer a = Integer.valueOf( 2 );\nInteger b = Integer.valueOf( 2 );\n\na == b \n new Integer( 2 ) == new Integer( 2 ) \n"
},
{
"answer_id": 360305,
"author": "Pyrolistical",
"author_id": 21838,
"author_profile": "https://Stackoverflow.com/users/21838",
"pm_score": 2,
"selected": false,
"text": "@Override\npublic boolean equals(Object obj) {\n if(this == obj) {\n return true;\n }\n\n // only do this if you are a subclass and care about equals of parent\n if(!super.equals(obj)) {\n return false;\n }\n if(obj == null || getClass() != obj.getClass()) {\n return false;\n }\n final YourTypeHere other = (YourTypeHere) obj;\n if(!instanceMember1.equals(other.instanceMember1)) {\n return false;\n }\n ... rest of instanceMembers in same pattern as above....\n return true;\n }\n"
},
{
"answer_id": 360568,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 3,
"selected": true,
"text": "if (this.getClass() != other.getClass()) {\n return false; //inequal\n}\n public class Services {\n\n private static Map<String, Service> SERVICES = new HashMap<String, Service>();\n\n static interface Service {\n /** Services with the same name are considered equivalent */\n public String getName();\n }\n\n public static synchronized void installService(Service service) {\n SERVICES.put(service.getName(), service);\n }\n\n public static synchronized Service lookup(String name) {\n return SERVICES.get(name);\n }\n}\n"
},
{
"answer_id": 361184,
"author": "Chris B.",
"author_id": 45176,
"author_profile": "https://Stackoverflow.com/users/45176",
"pm_score": 0,
"selected": false,
"text": "Adding duplicates to a map (bad):\nResult of map.get(bean1):first\nResult of map.get(bean2):second\nResult of map.get(new NameBean(\"Alice\"): null\n\nAdding duplicates to a map (good):\nResult of map.get(bean1):second\nResult of map.get(bean2):second\nResult of map.get(new ImprovedNameBean(\"Alice\"): second\n // This bean cannot safely be used as a key in a Map\npublic class NameBean {\n private String name;\n public NameBean() {\n }\n public NameBean(String name) {\n this.name = name;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n @Override\n public String toString() {\n return name;\n }\n}\n\n// This bean can safely be used as a key in a Map\npublic class ImprovedNameBean extends NameBean {\n public ImprovedNameBean(String name) {\n super(name);\n }\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if(obj == null || getClass() != obj.getClass()) {\n return false;\n }\n return this.getName().equals(((ImprovedNameBean)obj).getName());\n }\n @Override\n public int hashCode() {\n return getName().hashCode();\n }\n}\n\npublic class MapDuplicateTest {\n public static void main(String[] args) {\n MapDuplicateTest test = new MapDuplicateTest();\n System.out.println(\"Adding duplicates to a map (bad):\");\n test.withDuplicates();\n System.out.println(\"\\nAdding duplicates to a map (good):\");\n test.withoutDuplicates();\n }\n public void withDuplicates() {\n NameBean bean1 = new NameBean(\"Alice\");\n NameBean bean2 = new NameBean(\"Alice\");\n\n java.util.Map<NameBean, String> map\n = new java.util.HashMap<NameBean, String>();\n map.put(bean1, \"first\");\n map.put(bean2, \"second\");\n System.out.println(\"Result of map.get(bean1):\"+map.get(bean1));\n System.out.println(\"Result of map.get(bean2):\"+map.get(bean2));\n System.out.println(\"Result of map.get(new NameBean(\\\"Alice\\\"): \"\n + map.get(new NameBean(\"Alice\")));\n }\n public void withoutDuplicates() {\n ImprovedNameBean bean1 = new ImprovedNameBean(\"Alice\");\n ImprovedNameBean bean2 = new ImprovedNameBean(\"Alice\");\n\n java.util.Map<ImprovedNameBean, String> map\n = new java.util.HashMap<ImprovedNameBean, String>();\n map.put(bean1, \"first\");\n map.put(bean2, \"second\");\n System.out.println(\"Result of map.get(bean1):\"+map.get(bean1));\n System.out.println(\"Result of map.get(bean2):\"+map.get(bean2));\n System.out.println(\"Result of map.get(new ImprovedNameBean(\\\"Alice\\\"): \"\n + map.get(new ImprovedNameBean(\"Alice\")));\n }\n}\n"
},
{
"answer_id": 364981,
"author": "Apocalisp",
"author_id": 3434,
"author_profile": "https://Stackoverflow.com/users/3434",
"pm_score": 0,
"selected": false,
"text": "equals hashCode Equal<A> Hash<A> Equal Equal<A> Hash<A> equals hashCode"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360265",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
360,273 | <p>Is there a built in way in SQL Server 2005 to audit things specifically like deleting a stored procedure? Is there a history table that I can query? We have a mystery sproc that has disappeared a few times now.</p>
| [
{
"answer_id": 28206602,
"author": "Daniel Calbimonte",
"author_id": 4504629,
"author_profile": "https://Stackoverflow.com/users/4504629",
"pm_score": 0,
"selected": false,
"text": " CREATE TRIGGER ddl_drop_procedure \n ON DATABASE \n FOR DROP_PROCEDURE\n AS \n RAISERROR ('You deleted a stored procedure',10, 1)\n\n GO\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12064/"
] |
360,277 | <p>So for viewing a current object's state at runtime, I really like what the Visual Studio Immediate window gives me. Just doing a simple</p>
<pre><code>? objectname
</code></pre>
<p>Will give me a nicely formatted 'dump' of the object. </p>
<p><strong>Is there an easy way to do this in code, so I can do something similar when logging?</strong></p>
| [
{
"answer_id": 360302,
"author": "Ricardo Villamil",
"author_id": 19314,
"author_profile": "https://Stackoverflow.com/users/19314",
"pm_score": 3,
"selected": false,
"text": "MyObject\n Property1 = value\n Property2 = value2\n OtherObject\n OtherProperty = value ...\n"
},
{
"answer_id": 360313,
"author": "Bernhard Hofmann",
"author_id": 39722,
"author_profile": "https://Stackoverflow.com/users/39722",
"pm_score": 5,
"selected": false,
"text": " private string ObjectToXml(object output)\n {\n string objectAsXmlString;\n\n System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(output.GetType());\n using (System.IO.StringWriter sw = new System.IO.StringWriter())\n {\n try\n {\n xs.Serialize(sw, output);\n objectAsXmlString = sw.ToString();\n }\n catch (Exception ex)\n {\n objectAsXmlString = ex.ToString();\n }\n }\n\n return objectAsXmlString;\n }\n"
},
{
"answer_id": 3514115,
"author": "mythz",
"author_id": 85785,
"author_profile": "https://Stackoverflow.com/users/85785",
"pm_score": 4,
"selected": false,
"text": "var model = new TestModel();\nConsole.WriteLine(model.Dump());\n {\n Int: 1,\n String: One,\n DateTime: 2010-04-11,\n Guid: c050437f6fcd46be9b2d0806a0860b3e,\n EmptyIntList: [],\n IntList:\n [\n 1,\n 2,\n 3\n ],\n StringList:\n [\n one,\n two,\n three\n ],\n StringIntMap:\n {\n a: 1,\n b: 2,\n c: 3\n }\n}\n"
},
{
"answer_id": 24150867,
"author": "Hot Licks",
"author_id": 581994,
"author_profile": "https://Stackoverflow.com/users/581994",
"pm_score": 4,
"selected": false,
"text": "using Newtonsoft.Json.Linq;\n\nDebug.WriteLine(\"The object is \" + JObject.FromObject(theObjectToDump).ToString());\n JObject.FromObject ToString ToString +"
},
{
"answer_id": 26181763,
"author": "Jason",
"author_id": 188567,
"author_profile": "https://Stackoverflow.com/users/188567",
"pm_score": 7,
"selected": false,
"text": "using Newtonsoft.Json;\n\npublic static class F\n{\n public static string Dump(object obj)\n {\n return JsonConvert.SerializeObject(obj);\n }\n}\n Immediate Window var lookHere = F.Dump(myobj);\n Locals Value"
},
{
"answer_id": 30999698,
"author": "Matas Vaitkevicius",
"author_id": 1509764,
"author_profile": "https://Stackoverflow.com/users/1509764",
"pm_score": 5,
"selected": false,
"text": "actual Newtonsoft.Json.JsonConvert.SerializeObject(actual);\n \\\" \" \\r\\n \" public static class Dumper\n{\n public static void Dump(this object obj)\n {\n Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(obj)); // your logger\n }\n}\n"
},
{
"answer_id": 35658387,
"author": "Ariful Islam",
"author_id": 4207533,
"author_profile": "https://Stackoverflow.com/users/4207533",
"pm_score": 2,
"selected": false,
"text": "public static void WriteLine<T>(T obj)\n {\n var t = typeof(T);\n var props = t.GetProperties();\n StringBuilder sb = new StringBuilder();\n foreach (var item in props)\n {\n sb.Append($\"{item.Name}:{item.GetValue(obj,null)}; \");\n }\n sb.AppendLine();\n Console.WriteLine(sb.ToString());\n }\n WriteLine(myObject);\n var ifaces = t.GetInterfaces();\n if (ifaces.Any(o => o.Name.StartsWith(\"ICollection\")))\n {\n\n dynamic lst = t.GetMethod(\"GetEnumerator\").Invoke(obj, null);\n while (lst.MoveNext())\n {\n WriteLine(lst.Current);\n }\n } \n public static void WriteLine<T>(T obj)\n {\n var t = typeof(T);\n var ifaces = t.GetInterfaces();\n if (ifaces.Any(o => o.Name.StartsWith(\"ICollection\")))\n {\n\n dynamic lst = t.GetMethod(\"GetEnumerator\").Invoke(obj, null);\n while (lst.MoveNext())\n {\n WriteLine(lst.Current);\n }\n } \n else if (t.GetProperties().Any())\n {\n var props = t.GetProperties();\n StringBuilder sb = new StringBuilder();\n foreach (var item in props)\n {\n sb.Append($\"{item.Name}:{item.GetValue(obj, null)}; \");\n }\n sb.AppendLine();\n Console.WriteLine(sb.ToString());\n }\n }\n if, else if"
},
{
"answer_id": 42264037,
"author": "engineforce",
"author_id": 767288,
"author_profile": "https://Stackoverflow.com/users/767288",
"pm_score": 3,
"selected": false,
"text": "public class ObjectDumper\n{\n public static string Dump(object obj)\n {\n return new ObjectDumper().DumpObject(obj);\n }\n\n StringBuilder _dumpBuilder = new StringBuilder();\n\n string DumpObject(object obj)\n {\n DumpObject(obj, 0);\n return _dumpBuilder.ToString();\n }\n\n void DumpObject(object obj, int nestingLevel = 0)\n {\n var nestingSpaces = \"\".PadLeft(nestingLevel * 4);\n\n if (obj == null)\n {\n _dumpBuilder.AppendFormat(\"{0}null\\n\", nestingSpaces);\n }\n else if (obj is string || obj.GetType().IsPrimitive)\n {\n _dumpBuilder.AppendFormat(\"{0}{1}\\n\", nestingSpaces, obj);\n }\n else if (ImplementsDictionary(obj.GetType()))\n {\n using (var e = ((dynamic)obj).GetEnumerator())\n {\n var enumerator = (IEnumerator)e;\n while (enumerator.MoveNext())\n {\n dynamic p = enumerator.Current;\n\n var key = p.Key;\n var value = p.Value;\n _dumpBuilder.AppendFormat(\"{0}{1} ({2})\\n\", nestingSpaces, key, value != null ? value.GetType().ToString() : \"<null>\");\n DumpObject(value, nestingLevel + 1);\n }\n }\n }\n else if (obj is IEnumerable)\n {\n foreach (dynamic p in obj as IEnumerable)\n {\n DumpObject(p, nestingLevel);\n }\n }\n else\n {\n foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(obj))\n {\n string name = descriptor.Name;\n object value = descriptor.GetValue(obj);\n\n _dumpBuilder.AppendFormat(\"{0}{1} ({2})\\n\", nestingSpaces, name, value != null ? value.GetType().ToString() : \"<null>\");\n DumpObject(value, nestingLevel + 1);\n }\n }\n }\n\n bool ImplementsDictionary(Type t)\n {\n return t.GetInterfaces().Any(i => i.Name.Contains(\"IDictionary\"));\n }\n}\n"
},
{
"answer_id": 53253744,
"author": "gianlucaparadise",
"author_id": 6155481,
"author_profile": "https://Stackoverflow.com/users/6155481",
"pm_score": 2,
"selected": false,
"text": "/// <summary>\n/// Based on: https://stackoverflow.com/a/42264037/6155481\n/// </summary>\npublic class ObjectDumper\n{\n public static string Dump(object obj)\n {\n return new ObjectDumper().DumpObject(obj);\n }\n\n StringBuilder _dumpBuilder = new StringBuilder();\n\n string DumpObject(object obj)\n {\n DumpObject(obj, 0);\n return _dumpBuilder.ToString();\n }\n\n void DumpObject(object obj, int nestingLevel)\n {\n var nestingSpaces = \"\".PadLeft(nestingLevel * 4);\n\n if (obj == null)\n {\n _dumpBuilder.AppendFormat(\"{0}null\\n\", nestingSpaces);\n }\n else if (obj is string || obj.GetType().GetTypeInfo().IsPrimitive || obj.GetType().GetTypeInfo().IsEnum)\n {\n _dumpBuilder.AppendFormat(\"{0}{1}\\n\", nestingSpaces, obj);\n }\n else if (ImplementsDictionary(obj.GetType()))\n {\n using (var e = ((dynamic)obj).GetEnumerator())\n {\n var enumerator = (IEnumerator)e;\n while (enumerator.MoveNext())\n {\n dynamic p = enumerator.Current;\n\n var key = p.Key;\n var value = p.Value;\n _dumpBuilder.AppendFormat(\"{0}{1} ({2})\\n\", nestingSpaces, key, value != null ? value.GetType().ToString() : \"<null>\");\n DumpObject(value, nestingLevel + 1);\n }\n }\n }\n else if (obj is IEnumerable)\n {\n foreach (dynamic p in obj as IEnumerable)\n {\n DumpObject(p, nestingLevel);\n }\n }\n else\n {\n foreach (PropertyInfo descriptor in obj.GetType().GetRuntimeProperties())\n {\n string name = descriptor.Name;\n object value = descriptor.GetValue(obj);\n\n _dumpBuilder.AppendFormat(\"{0}{1} ({2})\\n\", nestingSpaces, name, value != null ? value.GetType().ToString() : \"<null>\");\n\n // TODO: Prevent recursion due to circular reference\n if (name == \"Self\" && HasBaseType(obj.GetType(), \"NSObject\"))\n {\n // In ObjC I need to break the recursion when I find the Self property\n // otherwise it will be an infinite recursion\n Console.WriteLine($\"Found Self! {obj.GetType()}\");\n }\n else\n {\n DumpObject(value, nestingLevel + 1);\n }\n }\n }\n }\n\n bool HasBaseType(Type type, string baseTypeName)\n {\n if (type == null) return false;\n\n string typeName = type.Name;\n\n if (baseTypeName == typeName) return true;\n\n return HasBaseType(type.GetTypeInfo().BaseType, baseTypeName);\n }\n\n bool ImplementsDictionary(Type t)\n {\n return t is IDictionary;\n }\n}\n"
},
{
"answer_id": 58131398,
"author": "Tom Flídr",
"author_id": 7032987,
"author_profile": "https://Stackoverflow.com/users/7032987",
"pm_score": 2,
"selected": false,
"text": "Desharp.Debug.Log(anyException);\nDesharp.Debug.Log(anyCustomValueObject);\nDesharp.Debug.Log(anyNonserializableObject);\nDesharp.Debug.Log(anyFunc);\nDesharp.Debug.Log(anyFunc, Desharp.Level.EMERGENCY); // you can store into different files\n"
},
{
"answer_id": 67791709,
"author": "montonero",
"author_id": 7419215,
"author_profile": "https://Stackoverflow.com/users/7419215",
"pm_score": 2,
"selected": false,
"text": "YamlDotNet using YamlDotNet.Serialization;\n\nList<string> strings=new List<string>{\"a\",\"b\",\"c\"};\nnew Serializer().Serialize(strings)\n - a\n- b\n- c\n"
},
{
"answer_id": 72002963,
"author": "Leniel Maccaferri",
"author_id": 114029,
"author_profile": "https://Stackoverflow.com/users/114029",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Text.Json;\n\nnamespace MyCompany.Core.Extensions\n{\n public static class ObjectExtensions\n {\n public static string Dump(this object obj)\n {\n try\n {\n return JsonSerializer.Serialize(obj);\n }\n catch(Exception)\n {\n return string.Empty;\n }\n }\n }\n}\n JsonSerializerOptions new JsonSerializerOptions { WriteIndented = true }\n NewtonSoft.Json System.Text.Json"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19020/"
] |
360,288 | <p>Has anyone attempted this? Is it possible, and if so, what kind of problems will I run into if I try to accomplish it?</p>
| [
{
"answer_id": 18719053,
"author": "alecho",
"author_id": 1112785,
"author_profile": "https://Stackoverflow.com/users/1112785",
"pm_score": 2,
"selected": false,
"text": "$components $helpers protected $_mergeParent = 'YourParentClass' 'AppController'"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39086/"
] |
360,289 | <p>I a have a multithread application (MIDAS) that makes uses of windows messages to communicate with itself.</p>
<p>MAIN FORM</p>
<p>The main form receives windows messages sent by the RDM
LogData(‘DataToLog’) </p>
<p>Because windows messages are used they have the following attributes </p>
<ol>
<li>Received messages are Indivisible</li>
<li>Received messages are Queued in the order they are sent </li>
</ol>
<p><strong>QUESTION:</strong></p>
<p>Can you Suggest a better way doing this without using windows messages ?</p>
<p><strong>MAIN FORM CODE</strong> </p>
<pre><code>const
UM_LOGDATA = WM_USER+1002;
type
TLogData = Record
Msg : TMsgNum;
Src : Integer;
Data : String;
end;
PLogData = ^TLogData;
TfrmMain = class(TForm)
//
private
procedure LogData(var Message: TMessage); message UM_LOGDATA;
public
//
end;
procedure TfrmMain.LogData(var Message: TMessage);
var LData : PLogData;
begin
LData := PLogData(Message.LParam);
SaveData(LData.Msg,LData.Src,LData.Data);
Dispose(LData);
end;
</code></pre>
<p><strong>RDM CODE</strong></p>
<pre><code>procedure TPostBoxRdm.LogData(DataToLog : String);
var
WMsg : TMessage;
LData : PLogData;
Msg : TMsgNum;
begin
Msg := MSG_POSTBOX_RDM;
WMsg.LParamLo := Integer(Msg);
WMsg.LParamHi := Length(DataToLog);
new(LData);
LData.Msg := Msg;
LData.Src := 255;
LData.Data := DataToLog;
WMsg.LParam := Integer(LData);
PostMessage(frmMain.Handle, UM_LOGDATA, Integer(Msg), WMsg.LParam);
end;
</code></pre>
<p>EDIT:</p>
<p>Why I want to get rid of the windows messages:</p>
<ul>
<li>I would like to convert the application into a windows service </li>
<li>When the system is busy – the windows message buffer gets full and things slows down</li>
</ul>
| [
{
"answer_id": 360613,
"author": "gabr",
"author_id": 4997,
"author_profile": "https://Stackoverflow.com/users/4997",
"pm_score": 2,
"selected": false,
"text": "OtlComm.pas"
},
{
"answer_id": 360819,
"author": "Mick",
"author_id": 12458,
"author_profile": "https://Stackoverflow.com/users/12458",
"pm_score": 4,
"selected": true,
"text": "program CmdClient;\n{$APPTYPE CONSOLE}\n\nuses\n Windows, Messages, SysUtils, Pipes;\n\ntype\n TPipeEventHandler = class(TObject)\n public\n procedure OnPipeSent(Sender: TObject; Pipe: HPIPE; Size: DWORD);\n end;\n\nprocedure TPipeEventHandler.OnPipeSent(Sender: TObject; Pipe: HPIPE; Size: DWORD);\nbegin\n WriteLn('On Pipe Sent has executed!');\nend;\n\nvar\n lpMsg: TMsg;\n WideChars: Array [0..255] of WideChar;\n myString: String;\n iLength: Integer;\n pcHandler: TPipeClient;\n peHandler: TPipeEventHandler;\n\nbegin\n\n // Create message queue for application\n PeekMessage(lpMsg, 0, WM_USER, WM_USER, PM_NOREMOVE);\n\n // Create client pipe handler\n pcHandler:=TPipeClient.CreateUnowned;\n // Resource protection\n try\n // Create event handler\n peHandler:=TPipeEventHandler.Create;\n // Resource protection\n try\n // Setup clien pipe\n pcHandler.PipeName:='myNamedPipe';\n pcHandler.ServerName:='.';\n pcHandler.OnPipeSent:=peHandler.OnPipeSent;\n // Resource protection\n try\n // Connect\n if pcHandler.Connect(5000) then\n begin\n // Dispatch messages for pipe client\n while PeekMessage(lpMsg, 0, 0, 0, PM_REMOVE) do DispatchMessage(lpMsg);\n // Setup for send\n myString:='the message I am sending';\n iLength:=Length(myString) + 1;\n StringToWideChar(myString, wideChars, iLength);\n // Send pipe message\n if pcHandler.Write(wideChars, iLength * 2) then\n begin\n // Flush the pipe buffers\n pcHandler.FlushPipeBuffers;\n // Get the message\n if GetMessage(lpMsg, pcHandler.WindowHandle, 0, 0) then DispatchMessage(lpMsg);\n end;\n end\n else\n // Failed to connect\n WriteLn('Failed to connect to ', pcHandler.PipeName);\n finally\n // Show complete\n Write('Complete...');\n // Delay\n ReadLn;\n end;\n finally\n // Disconnect event handler\n pcHandler.OnPipeSent:=nil;\n // Free event handler\n peHandler.Free;\n end;\n finally\n // Free pipe client\n pcHandler.Free;\n end;\n\nend.\n"
},
{
"answer_id": 362607,
"author": "Mick",
"author_id": 12458,
"author_profile": "https://Stackoverflow.com/users/12458",
"pm_score": 0,
"selected": false,
"text": "unit uMain; \n\ninterface \n\nuses \n Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, \n Dialogs, ExtCtrls, StdCtrls, uallHook, uallProcess, uallUtil, uallKernel; \n\ntype \n TfrmMain = class(TForm) \n lbl1: TLabel; \n tmrSearchCondor: TTimer; \n mmo1: TMemo; \n procedure FormCreate(Sender: TObject); \n procedure tmrSearchCondorTimer(Sender: TObject); \n procedure FormDestroy(Sender: TObject); \n private \n { Private-Deklarationen } \n fCondorPID : DWord; \n fInjected : Boolean; \n fDontWork : Boolean; \n procedure SearchCondor; \n procedure InjectMyFunctions; \n procedure UnloadMyFunctions; \n function GetDebugPrivileges : Boolean; \n procedure WriteText(s : string); \n procedure WMNOTIFYCD(var Msg: TWMCopyData); message WM_COPYDATA; \n public \n { Public-Deklarationen } \n end; \n\nvar \n frmMain: TfrmMain; \n ChangeWindowMessageFilter: function (msg : Cardinal; dwFlag : Word) : BOOL; stdcall; \n\nimplementation \n\n{$R *.dfm} \n\ntype Tmydata = packed record \n datacount: integer; \n ind: boolean; \n end; \n\nconst cCondorApplication = 'notepad.exe'; \n cinjComFuntionsDLL = 'injComFunctions.dll'; \n\nvar myData : TMydata; \n\nprocedure TfrmMain.WMNOTIFYCD(var Msg: TWMCopyData); \nbegin \n if Msg.CopyDataStruct^.cbData = sizeof(TMydata) then \n begin \n CopyMemory(@myData,Msg.CopyDataStruct^.lpData,sizeof(TMyData)); \n WriteText(IntToStr(mydata.datacount)) \n end; \nend; \n\nprocedure TfrmMain.WriteText(s : string); \nbegin \n mmo1.Lines.Add(DateTimeToStr(now) + ':> ' + s); \nend; \n\nprocedure TfrmMain.InjectMyFunctions; \nbegin \n if not fInjected then begin \n if InjectLibrary(fCondorPID, PChar(GetExeDirectory + cinjComFuntionsDLL)) then fInjected := True; \n end; \nend; \n\nprocedure TfrmMain.UnloadMyFunctions; \nbegin \n if fInjected then begin \n UnloadLibrary(fCondorPID, PChar(GetExeDirectory + cinjComFuntionsDLL)); \n fInjected := False; \n end; \nend; \n\nprocedure TfrmMain.SearchCondor; \nbegin \n fCondorPID := FindProcess(cCondorApplication); \n if fCondorPID <> 0 then begin \n lbl1.Caption := 'Notepad is running!'; \n InjectMyFunctions; \n end else begin \n lbl1.Caption := 'Notepad isn''t running!'; \n end; \nend; \n\nprocedure TfrmMain.FormDestroy(Sender: TObject); \nbegin \n UnloadMyFunctions; \nend; \n\nfunction TfrmMain.GetDebugPrivileges : Boolean; \nbegin \n Result := False; \n if not SetDebugPrivilege(SE_PRIVILEGE_ENABLED) then begin \n Application.MessageBox('No Debug rights!', 'Error', MB_OK); \n end else begin \n Result := True; \n end; \nend; \n\nprocedure TfrmMain.FormCreate(Sender: TObject); \nbegin \n @ChangeWindowMessageFilter := GetProcAddress(LoadLibrary('user32.dll'), 'ChangeWindowMessageFilter'); \n ChangeWindowMessageFilter(WM_COPYDATA, 1); \n fInjected := False; \n fDontWork := not GetDebugPrivileges; \n tmrSearchCondor.Enabled := not fDontWork; \nend; \n\nprocedure TfrmMain.tmrSearchCondorTimer(Sender: TObject); \nbegin \n tmrSearchCondor.Enabled := False; \n SearchCondor; \n tmrSearchCondor.Enabled := True; \nend; \n\nend.\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17560/"
] |
360,307 | <p>I was reading a review of the new Intel Atom 330, where they noted that Task Manager shows 4 cores - two physical cores, plus two more simulated by Hyperthreading.</p>
<p>Suppose you have a program with two threads. Suppose also that these are the only threads doing any work on the PC, everything else is idle. What is the probability that the OS will put both threads on the same core? This has huge implications for program throughput.</p>
<p>If the answer is anything other than 0%, are there any mitigation strategies other than creating more threads?</p>
<p>I expect there will be different answers for Windows, Linux, and Mac OS X.
<hr>
Using <a href="https://stackoverflow.com/questions/360307/multicore-hyperthreading-how-are-threads-distributed#360326">sk's answer</a> as Google fodder, then following the links, I found the <a href="http://msdn.microsoft.com/en-us/library/ms683194(VS.85).aspx" rel="nofollow noreferrer">GetLogicalProcessorInformation</a> function in Windows. It speaks of "logical processors that share resources. An example of this type of resource sharing would be hyperthreading scenarios." This implies that <a href="https://stackoverflow.com/questions/360307/multicore-hyperthreading-how-are-threads-distributed#360385">jalf</a> is correct, but it's not quite a definitive answer. </p>
| [
{
"answer_id": 3358040,
"author": "bart",
"author_id": 230899,
"author_profile": "https://Stackoverflow.com/users/230899",
"pm_score": 3,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Diagnostics;\nusing System.Runtime.InteropServices;\nusing System.Threading.Tasks;\n\nclass Program\n{\n [DllImport(\"kernel32\")]\n static extern int GetCurrentThreadId();\n\n static void Main(string[] args)\n {\n Task task1 = Task.Factory.StartNew(() => ThreadFunc(1));\n Task task2 = Task.Factory.StartNew(() => ThreadFunc(2));\n Stopwatch time = Stopwatch.StartNew();\n Task.WaitAll(task1, task2);\n Console.WriteLine(time.Elapsed);\n }\n\n static void ThreadFunc(int cpu)\n {\n int cur = GetCurrentThreadId();\n var me = Process.GetCurrentProcess().Threads.Cast<ProcessThread>().Where(t => t.Id == cur).Single();\n //me.ProcessorAffinity = (IntPtr)cpu; //using this line of code binds a thread to each core\n //me.IdealProcessor = cpu; //seems to have no effect\n\n //do some CPU / memory bound work\n List<int> ls = new List<int>();\n ls.Add(10);\n for (int j = 1; j != 30000; ++j)\n {\n ls.Add((int)ls.Average());\n }\n }\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5987/"
] |
360,321 | <p>Do you write <code>createSomething()</code> or <code>addSomething()</code>?</p>
<p>Do you write <code>readSomething()</code>, <code>getSomething()</code> or <code>fetchSomething()</code>?</p>
<p>This is totally a petty gripe. In the meeting room we refer to it as CRUD, but in actual code, it's becoming AGUD.</p>
<p>What's your naming convention of preference? Does it matter?</p>
<p>thnx.</p>
| [
{
"answer_id": 7358359,
"author": "Bilal Ahmad",
"author_id": 936265,
"author_profile": "https://Stackoverflow.com/users/936265",
"pm_score": 2,
"selected": false,
"text": "readXXXX() getXXXX() getXXX() getter / setter bean"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45441/"
] |
360,334 | <p>Hey I was wondering if there were any way to upload images in ASP? I am working on my school's server and I don't really know what is installed and what isn't I Googled a little and came up with "Persits.Upload.1" I tried to instantiate the object with this line:</p>
<p><code>Set Upload = Server.CreateObject("Persits.Upload.1")</code></p>
<p>It gave me this error, </p>
<blockquote>
<p>Server object error 'ASP 0177 : 800401f3'<br>
Server.CreateObject Failed </p>
</blockquote>
<p>Am I to assume the component is not installed on the server and/or what should I do for uploading images?</p>
<p>Thanks</p>
| [
{
"answer_id": 360363,
"author": "Xetius",
"author_id": 274,
"author_profile": "https://Stackoverflow.com/users/274",
"pm_score": 1,
"selected": false,
"text": "<INPUT type=file name=filename>"
},
{
"answer_id": 15159844,
"author": "Matteo Bononi 'peorthyr'",
"author_id": 1225880,
"author_profile": "https://Stackoverflow.com/users/1225880",
"pm_score": 0,
"selected": false,
"text": "Server.CreateObject(\"Persist.Upload.1\")\n Server.CreateObject(\"Persits.Upload.1\")\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27620/"
] |
360,338 | <p>As the question states, i am a C#/Java programmer who is interested in (re)learning C++. As you know C#/Java have a somewhat strict project file structure (especially Java). I find this structure to be very helpful and was wondering if it is a) good practice to do a similar structure in a C++, b) if so, what is the best way to setup it up?</p>
<p>i know there is the basic 'headers' and 'source' folders, but is there a better way?</p>
| [
{
"answer_id": 360372,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 3,
"selected": true,
"text": "namespace foo { \nnamespace bar {\n // declare/define the stuff (classes, functions) here\n} } // foo::bar\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18811/"
] |
360,348 | <p>I have an existing bare git repository located in /home/myaccount/git/project. I am currently using it over ssh from my local machine without any problems. I want to add a second user on the server which only shall access to this git repository (maybe move the repo outside my account folder?). How? Using latest version of git and ubuntu on slicehost.</p>
<p>I have this setup:
user: sleepyhead
user: developer1
group: git. both sleepyhead and developer1 are members of this group
repository /home/sleepyhead/git/project1</p>
<p>I want to:
move repository to a proper place, either /home/git/project1 or /usr/local/git/project1. What is recommended?
developer1 should permissions to read and write project1 with git. no other permissions should be given.</p>
<p>I do not know how to properly set the permissions and to restrict developer1 to only have access using git to project1.</p>
| [
{
"answer_id": 361164,
"author": "orip",
"author_id": 37020,
"author_profile": "https://Stackoverflow.com/users/37020",
"pm_score": 4,
"selected": false,
"text": "~/.ssh/authorized_keys command=\"...\""
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/50718/"
] |
360,365 | <p>Currently I am saving a UIImage to the photos album using UIImageWriteToSavedPhotosAlbum, which works fine.</p>
<p>Is there a way to then open the Photos app showing the just-saved photo? (I assume my app must close before opening Photos, which is fine.)</p>
<p>Simply opening the Photos app to the Saved Photos Album would be a not-quite-as-good alternative if the above isn't possible.</p>
<p>Thanks.</p>
| [
{
"answer_id": 380862,
"author": "lostInTransit",
"author_id": 46297,
"author_profile": "https://Stackoverflow.com/users/46297",
"pm_score": 2,
"selected": false,
"text": "UIImagePickerViewController"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44003/"
] |
360,368 | <p>There must be an easy way to do this, but somehow I can wrap my head around it. The best way I can describe what I want is a lambda function for a class. I have a library that expects as an argument an uninstantiated version of a class to work with. It then instantiates the class itself to work on. The problem is that I'd like to be able to dynamically create versions of the class, to pass to the library, but I can't figure out how to do it since the library expects an uninstantiated version. The code below describes the problem:</p>
<pre><code>class Double:
def run(self,x):
return x*2
class Triple:
def run(self,x):
return x*3
class Multiply:
def __init__(self,mult):
self.mult = mult
def run(self,x):
return x*self.mult
class Library:
def __init__(self,c):
self.c = c()
def Op(self,val):
return self.c.run(val)
op1 = Double
op2 = Triple
#op3 = Multiply(5)
lib1 = Library(op1)
lib2 = Library(op2)
#lib3 = Library(op3)
print lib1.Op(2)
print lib2.Op(2)
#print lib3.Op(2)
</code></pre>
<p>I can't use the generic Multiply class, because I must instantiate it first which breaks the library "AttributeError: Multiply instance has no <strong>call</strong> method". Without changing the Library class, is there a way I can do this?</p>
| [
{
"answer_id": 360403,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "__call__ class Multiply:\n def __init__(self,mult):\n self.mult = mult\n def __call__(self):\n return self\n def run(self,x):\n return x*self.mult\n c() c.__call__()"
},
{
"answer_id": 360415,
"author": "Moe",
"author_id": 3051,
"author_profile": "https://Stackoverflow.com/users/3051",
"pm_score": 1,
"selected": false,
"text": "def mult(x):\n def f():\n return Multiply(x)\n return f\n\n\nop3 = mult(5)\nlib3 = Library(op3)\nprint lib3.Op(2)\n"
},
{
"answer_id": 360425,
"author": "Deestan",
"author_id": 6848,
"author_profile": "https://Stackoverflow.com/users/6848",
"pm_score": 4,
"selected": false,
"text": "lib3 = Library(lambda: Multiply(5))\n Multiply5 = lambda: Multiply(5)\nassert Multiply5().run(3) == Multiply(5).run(3)\n"
},
{
"answer_id": 360443,
"author": "Greg Case",
"author_id": 462,
"author_profile": "https://Stackoverflow.com/users/462",
"pm_score": 1,
"selected": false,
"text": "Library Library run def make_op(f):\n class MyOp(object):\n def run(self, x):\n return f(x)\n return MyOp\n\nop1 = make_op(lambda x: return x*2)\nop2 = make_op(lambda x: return x*3)\n\ndef multiply_op(y):\n return make_op(lambda x: return x*y)\n\nop3 = multiply_op(3)\n\nlib1 = Library(op1)\nlib2 = Library(op2)\nlib3 = Library(op3)\n\nprint( lib1.Op(2) )\nprint( lib2.Op(2) )\nprint( lib3.Op(2) )\n"
},
{
"answer_id": 360456,
"author": "Parker Coates",
"author_id": 4757,
"author_profile": "https://Stackoverflow.com/users/4757",
"pm_score": 4,
"selected": true,
"text": "class Double:\n def run(self,x):\n return x*2\n\nclass Triple:\n def run(self,x):\n return x*3\n\ndef createMultiplier(n):\n class Multiply:\n def run(self,x):\n return x*n\n return Multiply\n\nclass Library:\n def __init__(self,c):\n self.c = c()\n def Op(self,val):\n return self.c.run(val)\n\nop1 = Double\nop2 = Triple\nop3 = createMultiplier(5)\n\nlib1 = Library(op1)\nlib2 = Library(op2)\nlib3 = Library(op3)\n\nprint lib1.Op(2)\nprint lib2.Op(2)\nprint lib3.Op(2)\n"
},
{
"answer_id": 53599449,
"author": "Bachsau",
"author_id": 5029818,
"author_profile": "https://Stackoverflow.com/users/5029818",
"pm_score": 1,
"selected": false,
"text": "type type my_class = type(\"my_class\", (object,), {\"an_attribute\": 1})\n my_class object {\"an_attribute\": 1, \"a_method\": lambda self: print(\"Hello\")}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27478/"
] |
360,369 | <p>Hey. I have an object that has a string property called BackgroundColor. This string is the hexidecimal representation of a color. I cannot change this object.</p>
<p>I'm binding a collection of these objects to a listView. What I would like to do is bind the background of the listview's row to the BackgroundColor property of the object that is displayed in the row.</p>
<p>What is the best way to to this?</p>
| [
{
"answer_id": 360579,
"author": "Robert Macnee",
"author_id": 19273,
"author_profile": "https://Stackoverflow.com/users/19273",
"pm_score": 3,
"selected": false,
"text": "<Grid xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:sys=\"clr-namespace:System;assembly=mscorlib\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\">\n <Grid.Resources>\n <x:Array x:Key=\"colors\" Type=\"{x:Type sys:String}\">\n <sys:String>Red</sys:String>\n <sys:String>Yellow</sys:String>\n <sys:String>#0000FF</sys:String>\n </x:Array>\n </Grid.Resources>\n <ListView ItemsSource=\"{StaticResource colors}\">\n <ListView.Resources>\n <Style TargetType=\"{x:Type ListViewItem}\">\n <Setter Property=\"Background\" Value=\"{Binding .}\"/>\n </Style>\n </ListView.Resources>\n </ListView>\n</Grid>\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20518/"
] |
360,373 | <p>I remember seeing in a sample a while ago that it is possible to break up a windsor configuration file into multiple ones and reference them from the app.config in a way that they get parsed automatically.</p>
<p>Of course I didn't bookmark it and now I can't find it and my Windsor.Config.xml file is creeping up on 600 lines. Can anyone tell me how to do this?</p>
<p>Currently I just instantiate my container directly off the file:
IWindsorContainer container = new WindsorContainer("Windsor.Config.xml");</p>
<p>But I'd like to break it up, reference the xml in the app.config and have it included automatically. </p>
| [
{
"answer_id": 360394,
"author": "Watson",
"author_id": 25807,
"author_profile": "https://Stackoverflow.com/users/25807",
"pm_score": 2,
"selected": true,
"text": "<include uri=\"file://Configurations/facilities.xml\">\n<include uri=\"file://Configurations/services.xml\">\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] |
360,378 | <p>This relates to Composite Application Guidance for WPF, or Prism.</p>
<p>I have one "MainRegion" in my shell. My various modules will be loaded into this main region. I can populate a list of available modules in a menu and select them to load. On the click of the menu I do:</p>
<pre><code>var module = moduleEnumerator.GetModule(moduleName);
moduleLoader.Initialize(new[] { module });
</code></pre>
<p>At the first time all works ok, because the Initialize() methods of the modules are executed, but after Module1, Module2 and Module3 are initialized, nothing happens when I click to load Module2 again.</p>
<p>My question: how can I activate a module on demand, after its initialize method has been executed?</p>
<p>Thank you for your help!</p>
| [
{
"answer_id": 897219,
"author": "NJE",
"author_id": 90576,
"author_profile": "https://Stackoverflow.com/users/90576",
"pm_score": 3,
"selected": true,
"text": "// Get a view from the container.\nvar view = Container.Resolve<MyView>();\n\n// Get the region.\nvar region = RegionManager.Regions[\"MyRegion\"];\n\n// Activate the view.\nregion.Activate(view);\n"
},
{
"answer_id": 3453707,
"author": "skjagini",
"author_id": 185907,
"author_profile": "https://Stackoverflow.com/users/185907",
"pm_score": 2,
"selected": false,
"text": "public void RemoveViewFromRegion(string viewName, string regionName, object defaultView)\n {\n IRegion region = regionManager.Regions[regionName];\n object view = region.GetView(viewName);\n region.Remove(view);\n region.Activate(defaultView); \n }\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28029/"
] |
360,392 | <p>We are scheduling a task programatically. However, the executable to be scheduled could be installed in a path that has spaces. ie c:\program Files\folder\folder\folder program\program.exe</p>
<p>When we provide this path as a parameter to the Tasjk Scheduler it fails to start because it cannot find the executable. It obviously needs to be enclosed in quotes ("). </p>
<p>The problem we are having is that even when we enclosed the path in quotes when we pass it as a paramemter (cmd + "\" + path + "\") it still doesnt include the quotes in the path that is used to schedule the task.</p>
<p>Anyone have any idea how to force the quotes to be included in the path?</p>
<p><strong>EDIT: Answer to comment:</strong></p>
<p>We had the same idea, and here is the problem. the ~1 format is based on the index of the folder, so if say you had these 3 folders:</p>
<pre><code>Program Applications
Program Files
Program Zips
</code></pre>
<p>then the path would be: progra~2</p>
<p>Now if you say there are over 10 of those folders, the path could possibly look like: progr~12.</p>
<p>Now, not to say this is not a viable solution, but having to count the folders to find the right one and then use the index to build the path is a little cumbersome and not very clean IMO.</p>
<p>We are hoping there is a better way.</p>
<p><strong>EDIT 2: Added applicable code snippet</strong></p>
<p>You asked for the code: this is how we build the Args string that we pass to the scheduler:</p>
<pre><code>string args = "/CREATE /RU SYSTEM /SC " + taskSchedule + " /MO " + taskModifier + " /SD " + taskStartDate + " /ST " + taskStartTime + " /TN " + taskName + " /TR \"" + taskSource + "\"";
</code></pre>
<p>where taskSource is the path to the application.</p>
| [
{
"answer_id": 360690,
"author": "TheSoftwareJedi",
"author_id": 18941,
"author_profile": "https://Stackoverflow.com/users/18941",
"pm_score": 3,
"selected": true,
"text": "string args = \"/CREATE /RU SYSTEM /SC \" + taskSchedule + \" /MO \" + taskModifier + \" /SD \" + taskStartDate + \" /ST \" + taskStartTime + \" /TN \" + taskName + \" /TR \\\"\\\\\\\"\" + taskSource + \"\\\"\"\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42518/"
] |
360,402 | <p>I have a csv imported into my Hyperion v8.3 bqy file. I have some custom columns and a pivot already created. I just want to refresh the data. In the past, I would hit Process Current and it would direct me to my computer and I could select the csv file to update from. Now it will not do that. It doesn't go to my computer at all.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 360690,
"author": "TheSoftwareJedi",
"author_id": 18941,
"author_profile": "https://Stackoverflow.com/users/18941",
"pm_score": 3,
"selected": true,
"text": "string args = \"/CREATE /RU SYSTEM /SC \" + taskSchedule + \" /MO \" + taskModifier + \" /SD \" + taskStartDate + \" /ST \" + taskStartTime + \" /TN \" + taskName + \" /TR \\\"\\\\\\\"\" + taskSource + \"\\\"\"\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
360,409 | <p>I have a XML File like that</p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<Configurations>
<EmailConfiguration>
<userName>xxxx</userName>
<password>xxx</password>
<displayName>xxxxx</displayName>
<hostAddress>xxxx</hostAddress>
<sslEnable>xxx</sslEnable>
<port>xxx</port>
</EmailConfiguration>
<LogConfiguration>
<logEnable>true</logEnable>
<generalEnable>true</generalEnable>
<warningEnable>true</warningEnable>
<errorEnable>true</errorEnable>
</LogConfiguration>
</Configurations>
</code></pre>
<p>and I am using it as config file for my code and I want to retrieve their values (innerText) like that</p>
<pre><code>bool logEnable = value comes from XML (logEnable)
bool warningEnable = value comes from XML (warningEnable)
bool errorEnable = value comes from XML (errorEnable)
bool generalEnable = value comes from XML (generalEnable)
</code></pre>
<p>So how can I read their values to assign them to the boolean variables and if I wanted to change one of their values with false, How would I be able to do that ?</p>
<p>Thanks...</p>
<p>Regards...</p>
<p>P.s : If you wrote more explanatory codes, It would be so much appreciated.</p>
<p>Thanks again...</p>
| [
{
"answer_id": 360518,
"author": "NerdFury",
"author_id": 6146,
"author_profile": "https://Stackoverflow.com/users/6146",
"pm_score": 4,
"selected": true,
"text": "public class Options\n{\n public string UserName { get; set; }\n public string Password { get; set; }\n public string DisplayName { get; set; }\n public string HostAddress { get; set; }\n public bool SSL { get; set; }\n public string Port { get; set; }\n\n public bool LogEnable { get; set; }\n public bool GeneralEnable { get; set; }\n public bool WarningEnable { get; set; }\n public bool ErrorEnable { get; set; }\n\n public static Options Load(string path)\n {\n Options options = new Options();\n XmlDocument xml = new XmlDocument();\n xml.Load(path);\n\n XmlNodeReader input = new XmlNodeReader(xml);\n\n while (input.Read())\n {\n var elementname = input.Name.ToLower();\n\n switch (elementname)\n {\n case \"username\":\n options.UserName = input.Value;\n break;\n // all other cases\n case \"logenable\":\n options.LogEnable = Boolean.Parse(input.Value);\n break;\n // continue with other cases\n }\n }\n }\n\n public static void Save(Options options, string path)\n {\n XmlTextWriter writer = new XmlTextWriter(path);\n\n xmlWriter.WriteStartDocument(true);\n xmlWriter.WriteStartElement(\"configuration\");\n xmlWriter.WriteStartElement(\"emailConfiguration\");\n\n xmlWriter.WriteStartElement(\"userName\");\n xmlWriter.WriteString(options.UserName);\n xmlWriter.WriteEndElemement();\n\n // continue for all elements\n\n xmlWriter.WriteEndElement();\n xmlWriter.WriteStartElement(\"logConfiguration\");\n\n xmlWriter.WriteStartElement(\"logEnable\");\n xmlWriter.WriteString(options.LogEnable.ToString());\n xmlWriter.WriteEndElemement();\n\n // continue for all elements\n\n xmlWriter.WriteEndElement();\n xmlWriter.WriteEndElement();\n\n xmlWriter.Close();\n }\n}\n"
},
{
"answer_id": 360742,
"author": "Tarik",
"author_id": 44852,
"author_profile": "https://Stackoverflow.com/users/44852",
"pm_score": 0,
"selected": false,
"text": "XmlDocument doc = new XmlDocument();\n\n doc.Load(HttpContext.Current.Server.MapPath(\"config.xml\"));\n\n logEnable = Convert.ToBoolean(doc[\"Configurations\"][\"LogConfiguration\"][\"logEnable\"].InnerText);\n warningEnable = Convert.ToBoolean(doc[\"Configurations\"][\"LogConfiguration\"][\"warningEnable\"].InnerText);\n errorEnable = Convert.ToBoolean(doc[\"Configurations\"][\"LogConfiguration\"][\"errorEnable\"].InnerText);\n generalEnable = Convert.ToBoolean(doc[\"Configurations\"][\"LogConfiguration\"][\"generalEnable\"].InnerText);\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44852/"
] |
360,421 | <p>Is there a way to define styles for a combination of classes? For example, I'd like my HTML to look like this, but the output to render in the appropriate color:</p>
<pre><code><span class="red">Red Text</span><br/>
<span class="green">Green Text</span><br/>
<span class="red green">Yellow Text</span><br/>
</code></pre>
<p><strong>Edit:</strong> The above seems to be confusing people when it was just an example; so here is another example:</p>
<pre><code><style>
.style1 { background-color: #fff; }
.style2 { background-color: #eee; }
.style1.highlight { color: red; }
.style2.highlight { color: blue; }
</style>
<ul>
<li class="action style1">Do Action 1</li>
<li class="action style2">Do Action 2</li>
<li class="action style1 highlight">Do Action 1</li>
<li class="action style2 highlight">Do Action 2</li>
</ul>
<script language="javascript" type="text/javascript">
$("li.action").bind("click", function(e) {
e.preventDefault();
// Do some stuff
$(this).addClass("highlight");
$(this).unbind("click");
});
</script>
</code></pre>
<p>Again, this is just an <em>example</em>, so don't get hung up on alternating elements or anything like that. What I'm trying to avoid is having to duplicate the bind function for each different styleN or having to write an elseif structure that checks for each styleN class. Unfortunately this code doesn't work in IE 6 or 7 - the highlighted text for both .style1 and .style2 elements end up being blue.</p>
| [
{
"answer_id": 360450,
"author": "ieure",
"author_id": 45224,
"author_profile": "https://Stackoverflow.com/users/45224",
"pm_score": 4,
"selected": true,
"text": "span.red.green { color: yellow; }\n <span class=\"red green blue\">white</span>\n"
},
{
"answer_id": 360451,
"author": "Tarik",
"author_id": 44852,
"author_profile": "https://Stackoverflow.com/users/44852",
"pm_score": -1,
"selected": false,
"text": ".red\n{\ncolor: red;\n}\n\n.red_green\n{\ncolor: #AS8324;\n}\n <span class=\"red\">Red Text</span><br/>\n<span class=\"green\">Green Text</span><br/>\n<span class=\"red_green\">Yellow Text</span><br/>\n"
},
{
"answer_id": 360453,
"author": "stesch",
"author_id": 41860,
"author_profile": "https://Stackoverflow.com/users/41860",
"pm_score": 2,
"selected": false,
"text": ".red { color: red; }\n.green { color: green; }\n.red.green { color: yellow; }\n"
},
{
"answer_id": 360642,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 0,
"selected": false,
"text": "class=\"red green\"\n class=\"yellow\"\n"
},
{
"answer_id": 361817,
"author": "Soldarnal",
"author_id": 3420,
"author_profile": "https://Stackoverflow.com/users/3420",
"pm_score": 0,
"selected": false,
"text": "<style>\n .style1 { background-color: #fff; }\n .style2 { background-color: #eee; }\n .style1 .highlight { color: red; }\n .style2 .highlight { color: blue; }\n</style>\n\n<ul>\n <li class=\"action style1\"><span>Do Action 1</span></li>\n <li class=\"action style2\"><span>Do Action 2</span></li>\n <li class=\"action style1\"><span class=\"highlight\">Do Action 1</span></li>\n <li class=\"action style2\"><span class=\"highlight\">Do Action 2</span></li>\n</ul>\n\n<script language=\"javascript\" type=\"text/javascript\">\n$(\"li.action\").bind(\"click\", function(e) {\n e.preventDefault();\n\n // Do some stuff \n\n $(this).children(\"span\").addClass(\"highlight\");\n $(this).unbind(\"click\");\n});\n</script>\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3420/"
] |
360,422 | <p>I'm trying to use reflection to get a property from a class. Here is some sample code of what I'm seeing:</p>
<pre><code>
using System.Reflection;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
PropertyInfo[] tmp2 = typeof(TestClass).GetProperties();
PropertyInfo test = typeof(TestClass).GetProperty(
"TestProp", BindingFlags.Public | BindingFlags.NonPublic);
}
}
public class TestClass
{
public Int32 TestProp
{
get;
set;
}
}
}
</code></pre>
<p>When I trace through this, this is what I see:</p>
<ul>
<li>When I fetch all properties using <code>GetProperties()</code>, the resulting array has one entry, for property <code>TestProp</code>.</li>
<li>When I try to fetch <code>TestProp</code> using <code>GetProperty()</code>, I get null back.</li>
</ul>
<p>I'm a little stumped; I haven't been able to find anything in the MSDN regarding <code>GetProperty()</code> to explain this result to me. Any help?</p>
<p>EDIT:</p>
<p>If I add <code>BindingFlags.Instance</code> to the <code>GetProperties()</code> call, no properties are found, period. This is more consistent, and leads me to believe that <code>TestProp</code> is not considered an instance property for some reason. </p>
<p>Why would that be? What do I need to do to the class for this property to be considered an instance property?</p>
| [
{
"answer_id": 360427,
"author": "Andrew Rollings",
"author_id": 40410,
"author_profile": "https://Stackoverflow.com/users/40410",
"pm_score": 5,
"selected": true,
"text": "BindingFlags.Instance GetProperty using System.Reflection;\nnamespace ConsoleApplication\n{\n class Program\n {\n static void Main(string[] args)\n {\n PropertyInfo[] tmp2 = typeof(TestClass).GetProperties();\n PropertyInfo test = typeof(TestClass).GetProperty(\n \"TestProp\",\n BindingFlags.Instance | BindingFlags.Public |\n BindingFlags.NonPublic);\n\n Console.WriteLine(test.Name);\n }\n }\n\n public class TestClass\n {\n public Int32 TestProp\n {\n get\n {\n return 0;\n }\n set\n {\n }\n }\n }\n}\n"
},
{
"answer_id": 360438,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": 1,
"selected": false,
"text": "System.Reflection.BindingFlags.Instance\n PropertyInfo test = typeof(TestClass).GetProperty(\"TestProp\", BindingFlags.Public | BindingFlags.Instance);\n\nConsole.WriteLine(test.Name);\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8169/"
] |
360,431 | <p>For this dropdownlist in HTML:</p>
<pre><code><select id="countries">
<option value="1">Country</option>
</select>
</code></pre>
<p>I would like to open the list (the same as left-clicking on it). Is this possible using JavaScript (or more specifically jQuery)?</p>
| [
{
"answer_id": 360448,
"author": "Andreas Grech",
"author_id": 44084,
"author_profile": "https://Stackoverflow.com/users/44084",
"pm_score": 2,
"selected": false,
"text": "onclick multiple <select id=\"countries\" multiple=\"multiple\" size=\"10\">\n<option value=\"1\">Country</option>\n</select>\n"
},
{
"answer_id": 360474,
"author": "ieure",
"author_id": 45224,
"author_profile": "https://Stackoverflow.com/users/45224",
"pm_score": 5,
"selected": true,
"text": "<select>"
},
{
"answer_id": 360531,
"author": "Grant Wagner",
"author_id": 9254,
"author_profile": "https://Stackoverflow.com/users/9254",
"pm_score": 1,
"selected": false,
"text": "<select> <select>"
},
{
"answer_id": 360544,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 2,
"selected": false,
"text": "<select id=\"countries\" size=\"6\">\n <option value=\"1\">Country 1</option>\n <option value=\"2\">Country 2</option>\n <option value=\"3\">Country 3</option>\n <option value=\"4\">Country 4</option>\n <option value=\"5\">Country 5</option>\n <option value=\"6\">Country 6</option>\n</select>\n"
},
{
"answer_id": 4498360,
"author": "CommentLuv",
"author_id": 371225,
"author_profile": "https://Stackoverflow.com/users/371225",
"pm_score": 6,
"selected": false,
"text": "$('#countries').attr('size',6);\n $('#countries').attr('size',1);\n"
},
{
"answer_id": 8070377,
"author": "Czarek Tomczak",
"author_id": 623622,
"author_profile": "https://Stackoverflow.com/users/623622",
"pm_score": 4,
"selected": false,
"text": "<select> size"
},
{
"answer_id": 8932866,
"author": "mrperfect",
"author_id": 1159408,
"author_profile": "https://Stackoverflow.com/users/1159408",
"pm_score": 3,
"selected": false,
"text": "function down(what) {\n pos = $(what).offset(); // remember position\n $(what).css(\"position\",\"absolute\");\n $(what).offset(pos); // reset position\n $(what).attr(\"size\",\"10\"); // open dropdown\n}\n\nfunction up(what) {\n$(what).css(\"position\",\"static\");\n$(what).attr(\"size\",\"1\"); // close dropdown\n}\n <select onfocus=\"down(this)\" onblur=\"up(this)\">\n function down(was) {\na = $(was).clone().attr('id','down_man').attr('disabled',true).insertAfter(was);\n$(was).css(\"position\",\"absolute\").attr(\"size\",\"10\");\n}\n\nfunction up(was) {\n$('#down_man').remove();\n$(was).css(\"position\",\"static\");\n$(was).attr(\"size\",\"1\");\n}\n"
},
{
"answer_id": 10235046,
"author": "colinbashbash",
"author_id": 379215,
"author_profile": "https://Stackoverflow.com/users/379215",
"pm_score": 2,
"selected": false,
"text": "function down() {\n var pos = $(this).offset(); // remember position\n $(this).css(\"position\", \"absolute\");\n $(this).offset(pos); // reset position\n $(this).attr(\"size\", \"15\"); // open dropdown\n $(this).unbind(\"focus\", down);\n}\nfunction up() {\n $(this).css(\"position\", \"static\");\n $(this).attr(\"size\", \"1\"); // close dropdown\n $(this).unbind(\"change\", up);\n}\nfunction openDropdown(elementId) {\n $('#' + elementId).focus(down).blur(up).focus();\n}\n"
},
{
"answer_id": 10419589,
"author": "vipergtsrz",
"author_id": 97689,
"author_profile": "https://Stackoverflow.com/users/97689",
"pm_score": 2,
"selected": false,
"text": "$(\"option\").click(function(){\n $(this).parent().blur();\n});\n z-index: 100;\n"
},
{
"answer_id": 10844589,
"author": "Chris K",
"author_id": 1429898,
"author_profile": "https://Stackoverflow.com/users/1429898",
"pm_score": 3,
"selected": false,
"text": " function openDropdown(elementId) {\n function down() {\n var pos = $(this).offset(); // remember position\n var len = $(this).find(\"option\").length;\n if(len > 20) {\n len = 20;\n }\n\n $(this).css(\"position\", \"absolute\");\n $(this).css(\"zIndex\", 9999);\n $(this).offset(pos); // reset position\n $(this).attr(\"size\", len); // open dropdown\n $(this).unbind(\"focus\", down);\n $(this).focus();\n }\n function up() {\n $(this).css(\"position\", \"static\");\n $(this).attr(\"size\", \"1\"); // close dropdown\n $(this).unbind(\"change\", up);\n $(this).focus();\n }\n $(\"#\" + elementId).focus(down).blur(up).focus();\n }\n"
},
{
"answer_id": 16749663,
"author": "yckart",
"author_id": 1250044,
"author_profile": "https://Stackoverflow.com/users/1250044",
"pm_score": 2,
"selected": false,
"text": "var state = false;\n$(\"a\").click(function () {\n state = !state;\n $(\"select\").prop(\"size\", state ? $(\"option\").length : 1);\n});\n"
},
{
"answer_id": 18331027,
"author": "Johan Nordli",
"author_id": 2294456,
"author_profile": "https://Stackoverflow.com/users/2294456",
"pm_score": -1,
"selected": false,
"text": "$(document).ready(function() {\n fixSelect(document.getElementsByTagName(\"select\"));\n }); \n\n function fixSelect(selectList)\n {\n for (var i = 0; i != selectList.length; i++)\n {\n\n setActions(selectList[i]);\n }\n }\n\n\n function setActions(select)\n {\n $(select).click(function() {\n if (select.getElementsByTagName(\"option\").length == 1)\n {\n active(select);\n }\n });\n $(select).focus(function() {\n active(select);\n });\n $(select).blur(function() {\n inaktiv(select);\n });\n $(select).keypress(function(e) {\n if (e.which == 13) {\n\n inaktiv(select);\n }\n });\n var optionList = select.getElementsByTagName(\"option\");\n\n for (var i = 0; i != optionList.length; i++)\n {\n setActionOnOption(optionList[i], select);\n }\n }\n\n function setActionOnOption(option, select)\n {\n $(option).click(function() {\n inaktiv(select);\n });\n }\n\n function active(select)\n {\n var temp = $('<select/>');\n $('<option />', {value: 1,text:$(select).find(':selected').text()}).appendTo(temp);\n $(temp).insertBefore($(select));\n\n $(select).attr('size', select.getElementsByTagName('option').length);\n $(select).css('position', 'absolute');\n $(select).css('margin-top', '-6px');\n $(select).css({boxShadow: '2px 3px 4px #888888'});\n\n\n\n }\n\n function inaktiv(select)\n {\n if($(select).parent().children('select').length!=1)\n {\n select.parentNode.removeChild($(select).parent().children('select').get(0));\n }\n $(select).attr('size', 1);\n $(select).css('position', 'static');\n $(select).css({boxShadow: ''});\n $(select).css('margin-top', '0px');\n\n }\n"
},
{
"answer_id": 26297840,
"author": "Stuart.Sklinar",
"author_id": 664672,
"author_profile": "https://Stackoverflow.com/users/664672",
"pm_score": 3,
"selected": false,
"text": " var event;\n event = document.createEvent('MouseEvents');\n event.initMouseEvent('mousedown', true, true, window);\n countries.dispatchEvent(event); //we use countries as it's referred to by ID - but this could be any JS element var\n modal.find(\"select\").not(\"[readonly]\").on(\"keypress\", function(e) {\n\n if (e.keyCode == 13) {\n e.preventDefault();\n return false;\n }\n var event;\n event = document.createEvent('MouseEvents');\n event.initMouseEvent('mousedown', true, true, window);\n this.dispatchEvent(event);\n });\n"
},
{
"answer_id": 41117160,
"author": "Emmanuel",
"author_id": 3663967,
"author_profile": "https://Stackoverflow.com/users/3663967",
"pm_score": 0,
"selected": false,
"text": "select = $('#' + id);\nlength = $('#' + id + ' > option').length;\nif (length > 20)\n length = 20;\nselect.attr('size', length);\nselect.css('position', 'absolute');\nselect.focus();\n onchange=\"$(this).removeAttr('size');\"\nonblur=\"$(this).removeAttr('size');\"\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/343/"
] |
360,449 | <p>I'm trying to run a 3d array but the code just crashes in windows when i run it, here's my code;</p>
<pre><code>#include <iostream>
using namespace std;
int main(){
int myArray[10][10][10];
for (int i = 0; i <= 9; ++i){
for (int t = 0; t <=9; ++t){
for (int x = 0; x <= 9; ++t){
myArray[i][t][x] = i+t+x;
}
}
}
for (int i = 0; i <= 9; ++i){
for (int t = 0; t <=9; ++t){
for (int x = 0; x <= 9; ++t){
cout << myArray[i][t][x] << endl;
}
}
}
system("pause");
}
</code></pre>
<p>can someone throw me a quick fix / explanation</p>
| [
{
"answer_id": 360463,
"author": "David Norman",
"author_id": 34502,
"author_profile": "https://Stackoverflow.com/users/34502",
"pm_score": 5,
"selected": true,
"text": "for (int x = 0; x <= 9; ++t){\n for (int x = 0; x <= 9; ++x){\n"
},
{
"answer_id": 360595,
"author": "JohnMcG",
"author_id": 1674,
"author_profile": "https://Stackoverflow.com/users/1674",
"pm_score": 2,
"selected": false,
"text": "const std::size_t ARRAY_SIZE = 10;\n\nint myArray[ARRAY_SIZE][ARRAY_SIZE][ARRAY_SIZE];\n\nfor (std::size_t i = 0; i < ARRAY_SIZE; ++i) \n{\n for (std::size_t j = 0; j < ARRAY_SIZE; ++j)\n {\n for (std::size_t k = 0; k < ARRAY_SIZE; ++k)\n {\n std::assert (i < ARRAY_SIZE && j < ARRAY_SIZE && k < ARRAY_SIZE);\n // Do stuff\n }\n }\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33061/"
] |
360,454 | <p>Back in college, only the use of pseudo code was evangelized more than OOP in my curriculum. Just like commenting (and other preached 'best practices'), I found that in crunch time psuedocode was often neglected. So my question is...who actually uses it a lot of the time? Or do you only use it when an algorithm is really hard to conceptualize entirely in your head? I'm interested in responses from everyone: wet-behind-the-ears junior developers to grizzled vets who were around back in the punch card days.</p>
<p>As for me personally, I mostly only use it for the difficult stuff.</p>
| [
{
"answer_id": 360490,
"author": "Chris Cudmore",
"author_id": 18907,
"author_profile": "https://Stackoverflow.com/users/18907",
"pm_score": 1,
"selected": false,
"text": "public void doBigJob( params )\n{\n doTask1( params);\n doTask2( params);\n doTask3( params);\n}\nprivate void doTask1( params)\n{\n doSubTask1_1(params);\n ...\n}\n"
},
{
"answer_id": 360499,
"author": "thursdaysgeek",
"author_id": 22523,
"author_profile": "https://Stackoverflow.com/users/22523",
"pm_score": 2,
"selected": false,
"text": "procedure GetTextFromValidIndex (input int indexValue, output string textValue)\n// initialize\n// check to see if indexValue is within the acceptable range\n// get min, max from db\n// if indexValuenot between min and max\n// then return with an error\n// find corresponding text in db based on indexValue\n// return textValue\n return \"Not Written\";\nend procedure;\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25664/"
] |
360,466 | <p>This UpdatePanel is contained by an UserControl. When the LinkButton is pressed arow should be added in another GridView. When an user is logged in this control is working well.
The problems appears when an user is not logged in and try to push that button. No event triggers.
Someone suggested me to give a permission for accessing this control in web.config. That didn't work.
Anyone has another idea?</p>
<pre><code><asp:UpdatePanel runat="server" UpdateMode="Conditional" EnableViewState="true" ID="IngredientsUpdatePanel">
<ContentTemplate>
<asp:ObjectDataSource ID="sourceIngredients" runat="server" SelectMethod="GetAll">
</asp:ObjectDataSource>
<asp:GridView ID="Ingredients" AllowPaging="true" runat="server" DataKeyNames="IngredientId"
EnableViewState="true" DataSourceID="sourceIngredients" PageSize="5"
AutoGenerateColumns="false" HorizontalAlign="Center" OnSelectedIndexChanged="Ingredients_SelectedIndexChanged">
<RowStyle HorizontalAlign="Center" />
<HeaderStyle Font-Bold="true" ForeColor="Black" />
<Columns>
<asp:TemplateField HeaderText="Ingrediente" ItemStyle-Font-Size="10">
<ItemTemplate>
<asp:Label ID="lblId" Text='<%# Bind("IngredientId") %>' Visible="false" runat="server"/>
<asp:Label ID="lblPrice" Text='<%# Bind("Price") %>' Visible="false" runat="server"/>
<asp:Label ID="lblDescr" Text='<%# Bind("Description") %>' Visible="false" runat="server"/>
<asp:Label ID="lblName" Text='<%# Bind("Name") %>' Visible="false" runat="server"/>
<asp:Label ID="lblPict" Text='<%# Bind("Picture") %>' Visible="false" runat="server"/>
<div style="text-align:left;">
<img id="img" style="float:right;" src='<%# Eval("Picture") %>'
height="75" runat="server" alt="Picture" />
<b>
<%# Eval("Name") %>
</b>
<br />
<br />
Price: <b><%# Eval("Price") %></b>
<br />
<br />
<br />
</div>
<hr />
<div style="text-align:left;">
<b>Description</b>
</div>
<div style="width:300px;">
<%# Eval("Description") %>
</div>
<br />
<asp:LinkButton Enabled="true" runat="server" Text="Add" CommandName="Select" ID="cmdAdd" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</code></pre>
<p></p>
| [
{
"answer_id": 365009,
"author": "Ionel Bratianu",
"author_id": 45468,
"author_profile": "https://Stackoverflow.com/users/45468",
"pm_score": 2,
"selected": true,
"text": " <Columns>\n <asp:ButtonField Text=\"Add\" CommandName=\"Select\" /> \n <asp:TemplateField>\n ......\n </asp:TemplateField>\n </Columns>\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45468/"
] |
360,467 | <p>I have a table that looks a bit like this actors(forename, surname, stage_name);</p>
<p>I want to update stage_name to have a default value of</p>
<pre><code>forename." ".surname
</code></pre>
<p>So that</p>
<pre><code>insert into actors(forename, surname) values ('Stack', 'Overflow');
</code></pre>
<p>would produce the record</p>
<pre><code>'Stack' 'Overflow' 'Stack Overflow'
</code></pre>
<p>Is this possible?</p>
<p>Thanks :)</p>
| [
{
"answer_id": 360484,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 2,
"selected": false,
"text": "CURRENT_TIMESTAMP"
},
{
"answer_id": 360493,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 5,
"selected": true,
"text": "DEFAULT CREATE TRIGGER format_stage_name \nBEFORE INSERT ON actors\nFOR EACH ROW\nBEGIN\n SET NEW.stage_name = CONCAT(NEW.forename, ' ', NEW.surname);\nEND\n BEFORE UPDATE NULL NULL NULL COALESCE() stage_name NULL stage_name INSERT CREATE TRIGGER format_stage_name \nBEFORE INSERT ON actors\nFOR EACH ROW\nBEGIN\n IF (NEW.stage_name IS NULL) THEN\n SET NEW.stage_name = CONCAT(NEW.forename, ' ', NEW.surname);\n END IF;\nEND\n"
},
{
"answer_id": 360526,
"author": "Chris",
"author_id": 42937,
"author_profile": "https://Stackoverflow.com/users/42937",
"pm_score": 2,
"selected": false,
"text": "actor"
},
{
"answer_id": 74556263,
"author": "deepanshu",
"author_id": 8495763,
"author_profile": "https://Stackoverflow.com/users/8495763",
"pm_score": 0,
"selected": false,
"text": "(concat(forename,\" \",surname))\n ALTER TABLE actors ADD COLUMN stage_name VARCHAR(20) DEFAULT (concat(forename,\" \",surname))\n ALTER TABLE actors alter stage_name set DEFAULT (concat(forename,\" \",surname));\n UPDATE actors SET stage_name=(concat(forename,\" \",surname));\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33604/"
] |
360,473 | <p>What's the most natural way to model a group of objects that form a set? For example, you might have a bunch of user objects who are all subscribers to a mailing list.</p>
<p>Obviously you could model this as an array, but then you have to order the elements and whoever is using your interface might be confused as to why you're encoding arbitrary ordering data.</p>
<p>You can use a hash where the members are keys that map to "1" or "true", but in most languages there are restrictions on what data types a hash key can be.</p>
<p>What's the standard way to do this in modern languages (PHP, Perl, Ruby, Python, etc)?</p>
| [
{
"answer_id": 360485,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": true,
"text": "set set __hash__"
},
{
"answer_id": 360500,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 1,
"selected": false,
"text": "public class EmailAddress // probably needs to override GetHashCode()\n{\n ...\n}\n\nvar addresses = new HashSet<EmailAddress>();\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25068/"
] |
360,476 | <p>How can I write a semi transparent text on an Image (Jpg,Bmp), or a transparent text (color as same background Image) but with a shadow, something I want to do to watermark the images.</p>
<p>I want to accomplish that using Delphi win32.</p>
| [
{
"answer_id": 360495,
"author": "X-Ray",
"author_id": 14031,
"author_profile": "https://Stackoverflow.com/users/14031",
"pm_score": 2,
"selected": false,
"text": "img.Canvas.Brush.Style:=bsClear;\nimg.Canvas.Font.Color:=clBlack;\nimg.Canvas.TextOut(0, 0, 'hi there');\n"
},
{
"answer_id": 360845,
"author": "Jim McKeeth",
"author_id": 255,
"author_profile": "https://Stackoverflow.com/users/255",
"pm_score": 2,
"selected": false,
"text": "// Bold shows up better when over an image\nimage1.Canvas.Font.Style := [fsBold]; \n// Write the shadow first\nimage1.Canvas.Brush.Style:=bsClear;\nimage1.Canvas.Font.Color := clGrayText;\nimage1.Canvas.TextOut(1, 1, 'hi there');\n// Then put the text on top (slightly offset)\nimage1.Canvas.Brush.Style:=bsClear;\nimage1.Canvas.Font.Color :=clBlack;\nimage1.Canvas.TextOut(0, 0, 'hi there');\n"
},
{
"answer_id": 363135,
"author": "Dave Elsberry",
"author_id": 45750,
"author_profile": "https://Stackoverflow.com/users/45750",
"pm_score": 3,
"selected": false,
"text": " \nuses Windows, Graphics;\n.\n.\n.\nvar\n BackgroundImage: Graphics.TBitmap; { need to call out specifically for Graphics.TBitmap\n because the Windows unit also has a TBitmap\n declaration }\n TextImage: Graphics.TBitmap;\n BlendFunc: BLENDFUNCTION;\nbegin\n BlendFunc.BlendOp := AC_SRC_OVER;\n BlendFunc.BlendFlags := 0;\n BlendFunc.SourceConstantAlpha := $C0; { a hex value from $00-$FF (0-255).\n Represents the percent of opaqueness:\n $00 is completely transparent, \n $FF is completely opaque.\n $C0 is 75% opaque }\n BlendFunc.AlphaFormat := AC_SRC_ALPHA;\n\n { BackgroundImage is for holding the image you want to overlay text onto }\n BackgroundImage := Graphics.TBitmap.Create;\n try\n BackgroundImage.LoadFromFile('yourimagehere.bmp');\n\n { Create another TBitmap to hold the text you want to overlay }\n TextImage := Graphics.TBitmap.Create;\n try\n { Set this bitmap to have the same dimensions as the\n background image you want the text to appear on. }\n TextImage.Height := BackgroundImage.Height;\n TextImage.Width := BackgroundImage.Width;\n\n { In my limited experience with AlphaBlend, Black is always 100%\n transparent. So, paint TextImage completely Black. Play around\n with this to see the effect it has on the final outcome. }\n TextImage.Canvas.Brush.Color := clBlack;\n TextImage.Canvas.FloodFill(0, 0, clNone, fsBorder);\n\n TextImage.Canvas.Font.Style := [fsBold];\n\n { Write the shadow first }\n TextImage.Canvas.Brush.Style := bsClear;\n TextImage.Canvas.Font.Color := clDkGray;\n TextImage.Canvas.TextOut(11, 11, 'Test');\n\n { Then put the text on top (slightly offset) }\n TextImage.Canvas.Brush.Style := bsClear;\n TextImage.Canvas.Font.Color := clMaroon;\n TextImage.Canvas.TextOut(10, 10, 'Test');\n\n { Use the AlphaBlend function to overlay the bitmap holding the text\n on top of the bitmap holding the original image. }\n Windows.AlphaBlend(BackgroundImage.Canvas.Handle, 0, 0,\n TextImage.Width, TextImage.Height,\n TextImage.Canvas.Handle, 0, 0, TextImage.Width,\n TextImage.Height, BlendFunc);\n\n { Assign the now updated BackgroundImage to a TImage control for display } \n Image1.Picture.Bitmap.Assign(BackgroundImage);\n finally\n TextImage.Free;\n end;\n finally\n BackgroundImage.Free;\n end;\n end;\n"
},
{
"answer_id": 22894220,
"author": "Server Overflow",
"author_id": 46207,
"author_profile": "https://Stackoverflow.com/users/46207",
"pm_score": 2,
"selected": false,
"text": "{-------------------------------------------------------------------------------------------------------------\n DrawTextShadowBox\n Draws text in a semi-transparent rectangle with shadow text.\n The shadow text is blended to the background and then blurred.\n\n Variant:\n 1: Draws text in a box that is as wide as the BMP and can be aligned to top or bottom\n 2: Draws text in a box that is as wide as text and is placed into the image at coordinates x,y\n\n Parameters:\n Opacity a value from 0-255. 0 => Shadow is completelly transparent\n To set the Font color/size, the caller should do: aCanvas.Font.Size:= x\n\n Issues:\n The blurring function cuts too suddenly. The rectangle that was blurred is too visible. Do a blur that slowly fades at the edges.\n Might be slow becuase of the alpha blending and because of the blur.\n\n Important!\n The input img must be pf24bit.\n When the AlphaFormat member is AC_SRC_ALPHA, the source bitmap must be 32 bpp. If it is not, the AlphaBlend function will fail.\n-------------------------------------------------------------------------------------------------------------}\nprocedure DrawTextShadowBox(BMP: TBitmap; CONST Text: string; AlignTop: Boolean; ShadowColor: TColor= clTextShadow; ShadowOpacity: Byte= 20; Blur: Byte= 2);\nVAR\n Shadow: Vcl.Graphics.TBitmap;\n BlendFunc: BLENDFUNCTION;\n x, y: Integer;\n BmpRect: TRect; { Rectangle in the original bitmap where we want to draw the shadowed text }\n ShadowRect: TRect;\n TextWidth, TextHeight: Integer;\n OriginalColor: TColor;\nbegin\n Assert(BMP.PixelFormat= pf24bit, 'Wrong pixel format!!');\n OriginalColor:= bmp.Canvas.Font.Color;\n TextWidth := BMP.Canvas.TextWidth (Text);\n TextHeight:= BMP.Canvas.TextHeight(Text);\n\n { Write the shadow on a separate bitmap (overlay) }\n Shadow := TBitmap.Create;\n TRY\n { Bitmap setup }\n Shadow.Canvas.Font.Assign(BMP.Canvas.Font);\n Shadow.PixelFormat:= pf24bit;\n Shadow.SetSize(BMP.Width, TextHeight);\n\n { Bitmap rectangle as big as ShadowBMP }\n ShadowRect.Left:= 0;\n ShadowRect.Top := 0;\n ShadowRect.Right := Shadow.Width;\n ShadowRect.Bottom:= Shadow.Height;\n\n { Fill shadow rectangle }\n Shadow.Canvas.Brush.Color := clBlack; { In AlphaBlend, Black is always 100% transparent. So, paint Shadow completely Black. }\n Shadow.Canvas.FillRect(ShadowRect);\n\n BmpRect.Left := 0;\n BmpRect.Right := Shadow.Width;\n if AlignTop\n then BmpRect.Top := 0\n else BmpRect.Top := BMP.Height- TextHeight;\n BmpRect.Bottom:= BmpRect.Top+ TextHeight;\n\n { Blend rectangle with orig image } { Use the AlphaBlend function to overlay the bitmap holding the text on top of the bitmap holding the original image. }\n BlendFunc.BlendOp := AC_SRC_OVER;\n BlendFunc.BlendFlags := 0;\n BlendFunc.SourceConstantAlpha := ShadowOpacity;\n BlendFunc.AlphaFormat := 0; //AC_SRC_ALPHA; // if I put this back, the shadow will be completly invisible when merged with a white source image\n WinApi.Windows.AlphaBlend(BMP.Canvas.Handle, BmpRect.Left, BmpRect.Top, BmpRect.Right, TextHeight, Shadow.Canvas.Handle, 0, 0, Shadow.Width, Shadow.Height, BlendFunc);\n\n { Copy the blended area back to the Shadow bmp }\n Shadow.Canvas.CopyRect(ShadowRect, BMP.Canvas, BmpRect);\n\n { Diagonal shadow }\n x:= (BMP.Width - TextWidth) DIV 2; // Find center\n Shadow.Canvas.Brush.Style:= bsClear;\n Shadow.Canvas.Font.Color := ShadowColor;\n Shadow.Canvas.TextOut(x, 0, Text);\n\n { Blur the shadow }\n janFX.GaussianBlur(Shadow, Blur, 1);\n\n { Paste it back }\n BMP.Canvas.CopyRect(BmpRect, Shadow.Canvas, ShadowRect);\n FINALLY\n FreeAndNil(Shadow);\n END;\n\n { Draw actual text at 100% opacity }\n if AlignTop\n then y := 0\n else y := BMP.Height- TextHeight;\n BMP.Canvas.Brush.Style:= bsClear;\n BMP.Canvas.Font.Color := OriginalColor;\n BMP.Canvas.TextOut(x, y, Text);\nend;\n\n\n\nprocedure DrawTextShadowBox(aCanvas: TCanvas; CONST Text: string; X, Y: Integer; ShadowColor: TColor= clTextShadow; ShadowOpacity: Byte= 20; Blur: Byte= 2);\nVAR\n Shadow: Vcl.Graphics.TBitmap;\n BlendFunc: BLENDFUNCTION;\n H, W: Integer;\n OriginalColor: TColor;\n R, R2: TRect;\nCONST Edge= 5;\nbegin\n OriginalColor:= aCanvas.Font.Color;\n\n { Write the shadow on a separate bitmap (overlay) }\n Shadow := TBitmap.Create;\n TRY\n { Assign font }\n Shadow.Canvas.Font.Assign(aCanvas.Font);\n Shadow.PixelFormat:= pf24bit;\n\n { Compute overlay size }\n W:= Shadow.Canvas.TextWidth (Text);\n H:= Shadow.Canvas.TextHeight(Text);\n Shadow.SetSize(W, H);\n\n { Fill shadow rectangle }\n R:= Rect(0, 0, Shadow.Width, Shadow.Height);\n Shadow.Canvas.Brush.Color := clBlack; { In AlphaBlend, Black is always 100% transparent. So, paint Shadow completely Black. }\n Shadow.Canvas.FillRect(R);\n\n { Blend rectangle with orig image } { Use the AlphaBlend function to overlay the bitmap holding the text on top of the bitmap holding the original image. }\n BlendFunc.BlendOp := AC_SRC_OVER;\n BlendFunc.BlendFlags := 0;\n BlendFunc.SourceConstantAlpha := ShadowOpacity;\n BlendFunc.AlphaFormat := 0; //AC_SRC_ALPHA; // if I put this back, the shadow will be completly invisible when merged with a white source image\n WinApi.Windows.AlphaBlend(aCanvas.Handle, x, y, Shadow.Width, Shadow.Height, Shadow.Canvas.Handle, 0, 0, Shadow.Width, Shadow.Height, BlendFunc);\n\n { Copy the blended area back to the Shadow bmp }\n R2:= rect(x, y, x+Shadow.Width, y+Shadow.Height);\n Shadow.Canvas.CopyRect(R, aCanvas, R2);\n\n { Diagonal shadow }\n Shadow.Canvas.Brush.Style:= bsClear;\n Shadow.Canvas.Font.Color := ShadowColor;\n Shadow.Canvas.TextOut(0, 0, Text);\n\n { Blur the shadow }\n janFX.GaussianBlur(Shadow, blur, 1);\n\n { Paste it back }\n aCanvas.CopyRect(R2, Shadow.Canvas, R);\n FINALLY\n FreeAndNil(Shadow);\n END;\n\n { Draw actual text at 100% opacity }\n aCanvas.Brush.Style:= bsClear;\n aCanvas.Font.Color := OriginalColor;\n aCanvas.TextOut(x, y, Text);\nend;\n\n\nprocedure TfrmTest.UseIt;\nVAR BackgroundImage: tbitmap;\nbegin\n BackgroundImage := Graphics.TBitmap.Create; \n try\n BackgroundImage.LoadFromFile('c:\\test.bmp');\n DrawShadowText (BackgroundImage.Canvas, 'This is some demo text', 20, 40, 140, clRed, clSilver);\n Image1.Picture.Bitmap.Assign(BackgroundImage);\n FINALLY\n BackgroundImage.Free;\n end;\nend;\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24462/"
] |
360,480 | <p>It seems that there're 6 variations to CBC-MAC algorithm. I've been trying to match the MAC algorithm on the PINPad 1000SE [which per manual is ISO 9797-1 Algorithm 1].</p>
<p>I got an excellent start from <a href="http://bytes.com/topic/net/answers/654069-iso-iec-9797-1-cbc-mac-using-vb-net" rel="nofollow noreferrer">here</a>.</p>
<p>And I coded the algorithm as below:</p>
<pre><code>public static byte[] CalculateMAC(this IPinPad pinpad, byte[] message, byte[] key)
{
//Divide the key with Key1[ first 64 bits] and key2 [last 64 bits]
var key1 = new byte[8];
Array.Copy(key, 0, key1, 0, 8);
var key2 = new byte[8];
Array.Copy(key, 8, key2, 0, 8); //64 bits
//divide the message into 8 bytes blocks
//pad the last block with "80" and "00","00","00" until it reaches 8 bytes
//if the message already can be divided by 8, then add
//another block "80 00 00 00 00 00 00 00"
Action<byte[], int> prepArray = (bArr, offset) =>
{
bArr[offset] = 0; //80
for (var i = offset + 1; i < bArr.Length; i++)
bArr[i] = 0;
};
var length = message.Length;
var mod = length > 8? length % 8: length - 8;
var newLength = length + ((mod < 0) ? -mod : (mod > 0) ? 8 - mod : 0);
//var newLength = length + ((mod < 0) ? -mod : (mod > 0) ? 8 - mod : 8);
Debug.Assert(newLength % 8 == 0);
var arr = new byte[newLength];
Array.Copy(message, 0, arr, 0, length);
//Encoding.ASCII.GetBytes(message, 0, length, arr, 0);
prepArray(arr, length);
//use initial vector {0,0,0,0,0,0,0,0}
var vector = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };
//encrypt by DES CBC algorith with the first key KEY 1
var des = new DESCryptoServiceProvider { Mode = CipherMode.CBC };
var cryptor = des.CreateEncryptor(key1, vector);
var outputBuffer = new byte[arr.Length];
cryptor.TransformBlock(arr, 0, arr.Length, outputBuffer, 0);
//Decrypt the result by DES ECB with the second key KEY2 [Original suggestion]
//Now I'm Encrypting
var decOutputBuffer = new byte[outputBuffer.Length];
des.Mode = CipherMode.ECB;
var decryptor = des.CreateEncryptor(key2, vector);
//var decryptor = des.CreateDecryptor(key2, vector);
decryptor.TransformBlock(outputBuffer, 0, outputBuffer.Length, decOutputBuffer, 0);
//Encrypt the result by DES ECB with the first key KEY1
var finalOutputBuffer = new byte[decOutputBuffer.Length];
var cryptor2 = des.CreateEncryptor(key1, vector);
cryptor2.TransformBlock(decOutputBuffer, 0, decOutputBuffer.Length, finalOutputBuffer, 0);
//take the first 4 bytes as the MAC
var rval = new byte[4];
Array.Copy(finalOutputBuffer, 0, rval, 0, 4);
return rval;
}
</code></pre>
<p>Then I discovered there're 3 padding schemes and the one that gave me a start may not necessarily be right. The manual came to my rescue again. It seems the device only pads with 0s. Additional block is also nowhere mentioned so I made the below changes:</p>
<pre><code> Action<byte[], int> prepArray = (bArr, offset) =>
{
bArr[offset] = 0; ... }
</code></pre>
<p>No additional block (if mod 0 [divisible by 8] do not change array length)</p>
<pre><code>var newLength = length + ((mod < 0) ? -mod : (mod > 0) ? 8 - mod : 0);
</code></pre>
<p>The original suggestion wanted me to decrypt at the second step... but Valery <a href="http://www.derkeiler.com/Newsgroups/microsoft.public.dotnet.security/2005-04/0180.html" rel="nofollow noreferrer">here</a> suggests that it's encrypt all the way. So I changed Decrypt to Encrypt. But still I'm unable to get the requisite MAC...</p>
<p>Manual says for key "6AC292FAA1315B4D8234B3A3D7D5933A" [since the key should be 16 bytes, I figured the key here's hex string so I took byte values of 6A, C2, 92, FA...
new byte[] { 106, 194, 146, ...] the MAC should be 7B,40,BA,95 [4 bytes] if the message is [0x1a + byte array of MENTERODOMETER]</p>
<p>Can someone help? Please?</p>
<hr>
<p>Since Pinpad requires that the first character in message is a 0x1a...</p>
<pre><code>public static byte[] CalculateAugmentedMAC(this IPinPad pinpad, string message, byte[] key)
{
var arr = new byte[message.Length + 1];
var source = Encoding.ASCII.GetBytes(message);
arr[0] = 0x1a; //ClearScreenIndicator
Array.Copy(source, 0, arr, 1, source.Length);
return CalculateMAC(pinpad, arr, key);
}
</code></pre>
<p>I'm calling the code above with this input:</p>
<pre><code>var result = pad.CalculateAugmentedMAC("MENTERODOMETER", new byte[] { 106, 194, 146, 250, 161, 49, 91, 77, 130, 52, 179, 163, 215, 213, 147, 58 });
</code></pre>
| [
{
"answer_id": 1459874,
"author": "Aleksander Adamowski",
"author_id": 171960,
"author_profile": "https://Stackoverflow.com/users/171960",
"pm_score": 2,
"selected": false,
"text": "DESEDEISO9797ALG1MACWITHISO7816-4PADDING DESEDEMAC64WITHISO7816-4PADDING"
},
{
"answer_id": 1459901,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 0,
"selected": false,
"text": "TransformFinalBlock"
},
{
"answer_id": 3407321,
"author": "David Chappelle",
"author_id": 7475,
"author_profile": "https://Stackoverflow.com/users/7475",
"pm_score": 0,
"selected": false,
"text": "public static byte[] GenerateMAC(byte[] key, byte[] data)\n{\n using (MACTripleDES mac = new MACTripleDES(key))\n return mac.ComputeHash(data);\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28413/"
] |
360,491 | <p>I'm wanting to use jQuery to wrap a mailto: anchor around an email address, but it's also grabbing the whitepace that the CMS is generating.</p>
<p>Here's the HTML I have to work with, the script as I have it and a copy of the output.</p>
<p>HTML</p>
<pre><code><div class="field field-type-text field-field-email">
<div class="field-item">
name@example.com </div>
</div>
</code></pre>
<p>jQuery JavaScript</p>
<pre><code>$(document).ready(function(){
$('div.field-field-email .field-item').each(function(){
var emailAdd = $(this).text();
$(this).wrapInner('<a href="mailto:' + emailAdd + '"></a>');
});
});
</code></pre>
<p>Generated HTML</p>
<pre><code><div class="field field-type-text field-field-email">
<div class="field-items"><a href="mailto:%0A%20%20%20%20name@example.com%20%20%20%20">
name@example.com </a></div>
</div>
</code></pre>
<p>Though I suspect that others reading this question might want to just strip the leading and tailing whitespace, I'm quite happy to lose all the whitespace considering it's an email address I'm wrapping.</p>
| [
{
"answer_id": 360496,
"author": "Andreas Grech",
"author_id": 44084,
"author_profile": "https://Stackoverflow.com/users/44084",
"pm_score": 9,
"selected": true,
"text": "replace var emailAdd = $(this).text().replace(/ /g,'');\n var emailAdd = $.trim($(this).text());\n"
},
{
"answer_id": 360533,
"author": "Tuxmentat",
"author_id": 15963,
"author_profile": "https://Stackoverflow.com/users/15963",
"pm_score": 6,
"selected": false,
"text": " var emailAdd = jQuery.trim($(this).text());\n"
},
{
"answer_id": 9931128,
"author": "Paul",
"author_id": 1301586,
"author_profile": "https://Stackoverflow.com/users/1301586",
"pm_score": 5,
"selected": false,
"text": "str=str.replace(/^\\s+|\\s+$/g,'');"
},
{
"answer_id": 15791267,
"author": "Jhankar Mahbub",
"author_id": 1535443,
"author_profile": "https://Stackoverflow.com/users/1535443",
"pm_score": 7,
"selected": false,
"text": "str.trim()\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16124/"
] |
360,492 | <p>I'm fooling around with <a href="http://pipes.yahoo.com" rel="nofollow noreferrer">Yahoo! pipes</a> and I'm hitting a wall with some regular expression. Now I'm familiar with regular expressions from Perl but the rules just seem to be different in Yahoo! pipes.</p>
<p><a href="https://i.stack.imgur.com/6I6Ok.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6I6Ok.png" alt="Screenshot of my pipe"></a> </p>
<p>What I'm doing is fetching a page and trying to turn it into a feed, my regex for stripping out the link from the HTML works fine but the title which I want to be what was in <em><i></em> tags just outputs the original text. </p>
<p>Sample text that matches in Perl and on this <a href="http://www.quanetic.com/regex.php" rel="nofollow noreferrer">online regexp tester</a>:</p>
<blockquote>
<p><a rel="nofollow" target="_blank" HREF="http://changed.to/protect/the-guilty.html"><i>"Fee Fi Fo Fun" (English Man)</i></a> (See also this other site <a rel="nofollow" target="_blank" href="http://stackoverflow.com">Nada</a>) Some other text here</p>
</blockquote>
| [
{
"answer_id": 360610,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 4,
"selected": true,
"text": "(?i).*?<i>([^<]*).* [ ] g [x] s [ ] m [ ] i\n (?i).*?href=\"([^\"]*).* [ ] g [x] s [ ] m [ ] i\n (?i)"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3848/"
] |
360,507 | <p>I wonder if there is a less verbose way to do Input Verification in my methods. For example, i commonly write stuff like this:</p>
<pre><code>public string SomeFunction(string param1, int param2)
{
if(string.IsNullOrEmpty(param1)){
throw new ArgumentException("bla", "param1");
}
if(param2 < 0 || param2 > 100 || param2 == 53)
{
throw new ArgumentOutOfRangeException("eek", "param2");
}
}
</code></pre>
<p>Now, I wonder if there is a way to set up constraints on the parameters and have the compiler already handle that for me? I believe that this is called "Contract" and I remember seeing that Spec# is supposed to do that, but that seems to be an experimental research project at the moment.</p>
<p>So I wonder: Is there anything that can give a clean enforcing of Constraints (at least the simple and often recurring ones like string.IsNullOrEmpty) for input parameters for .net 3.5 SP1 and ideally .net 3.0 already?</p>
| [
{
"answer_id": 360548,
"author": "Drejc",
"author_id": 6482,
"author_profile": "https://Stackoverflow.com/users/6482",
"pm_score": 2,
"selected": false,
"text": "public string SomeFunction(string param1, int param2)\n{\n CheckParameterNotNull(param1);\n CheckParameterRange(param2, 0, 100, 53); \n...\n}\n"
},
{
"answer_id": 361449,
"author": "Rob Kennedy",
"author_id": 33732,
"author_profile": "https://Stackoverflow.com/users/33732",
"pm_score": 0,
"selected": false,
"text": "private string InternalSomeFunction(string param1, int param2)\n{\n /* implementation goes here */\n}\n\npublic string SomeFunction(string param1, int param2)\n{\n if (string.IsNullOrEmpty(param1)) {\n throw new ArgumentException(\"bla\", \"param1\");\n }\n if (param2 < 0 || param2 > 100 || param2 == 53) {\n throw new ArgumentOutOfRangeException(\"eek\", \"param2\");\n }\n return InternalSomeFunction(param1, param2);\n}\n InternalSomeMethod param1"
},
{
"answer_id": 361476,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 0,
"selected": false,
"text": "if (IsFormValid)\n{\n // Processing Magic Goes here.\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
] |
360,520 | <p>My company has been evaluating Spring MVC to determine if we should use it in one of our next projects. So far I love what I've seen, and right now I'm taking a look at the Spring Security module to determine if it's something we can/should use. </p>
<p>Our security requirements are pretty basic; a user just needs to be able to provide a username and password to be able to access certain parts of the site (such as to get info about their account); and there are a handful of pages on the site (FAQs, Support, etc) where an anonymous user should be given access.</p>
<p>In the prototype I've been creating, I have been storing a "LoginCredentials" object (which just contains username and password) in Session for an authenticated user; some of the controllers check to see if this object is in session to get a reference to the logged-in username, for example. I'm looking to replace this home-grown logic with Spring Security instead, which would have the nice benefit of removing any sort of "how do we track logged in users?" and "how do we authenticate users?" from my controller/business code. </p>
<p>It seems like Spring Security provides a (per-thread) "context" object to be able to access the username/principal info from anywhere in your app...</p>
<pre><code>Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
</code></pre>
<p>... which seems very un-Spring like as this object is a (global) singleton, in a way.</p>
<p>My question is this: if this is the standard way to access information about the authenticated user in Spring Security, what is the accepted way to inject an Authentication object into the SecurityContext so that it is available for my unit tests when the unit tests require an authenticated user?</p>
<p>Do I need to wire this up in the initialization method of each test case?</p>
<pre><code>protected void setUp() throws Exception {
...
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken(testUser.getLogin(), testUser.getPassword()));
...
}
</code></pre>
<p>This seems overly verbose. Is there an easier way? </p>
<p>The <code>SecurityContextHolder</code> object itself seems very un-Spring-like...</p>
| [
{
"answer_id": 396029,
"author": "Pavel",
"author_id": 48340,
"author_profile": "https://Stackoverflow.com/users/48340",
"pm_score": 5,
"selected": false,
"text": "public class MyUserDetails implements UserDetails {\n // this is your custom UserDetails implementation to serve as a principal\n // implement the Spring methods and add your own methods as appropriate\n}\n\npublic class MyUserHolder {\n public static MyUserDetails getUserDetails() {\n Authentication a = SecurityContextHolder.getContext().getAuthentication();\n if (a == null) {\n return null;\n } else {\n return (MyUserDetails) a.getPrincipal();\n }\n }\n}\n\npublic class MyUserAwareController { \n MyUserDetails currentUser;\n\n public void setCurrentUser(MyUserDetails currentUser) { \n this.currentUser = currentUser;\n }\n\n // controller code\n}\n <bean id=\"userDetails\" class=\"MyUserHolder\" factory-method=\"getUserDetails\" scope=\"request\">\n <aop:scoped-proxy/>\n</bean>\n\n<bean id=\"controller\" class=\"MyUserAwareController\">\n <property name=\"currentUser\" ref=\"userDetails\"/>\n <!-- other props -->\n</bean>\n protected void setUp() {\n // existing init code\n\n MyUserDetails user = new MyUserDetails();\n // set up user as you wish\n controller.setCurrentUser(user);\n}\n"
},
{
"answer_id": 885193,
"author": "Scott Bale",
"author_id": 2495576,
"author_profile": "https://Stackoverflow.com/users/2495576",
"pm_score": 2,
"selected": false,
"text": "SecurityContext SecurityContextHolder SecurityContext"
},
{
"answer_id": 9609015,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "@RunWith(PowerMockRunner.class)\n@PrepareForTest(SecurityContextHolder.class)\npublic class YourTestCase {\n\n @Mock SecurityContext mockSecurityContext;\n\n @Test\n public void testMethodThatCallsStaticMethod() {\n // Set mock behaviour/expectations on the mockSecurityContext\n when(mockSecurityContext.getAuthentication()).thenReturn(...)\n ...\n // Tell mockito to use Powermock to mock the SecurityContextHolder\n PowerMockito.mockStatic(SecurityContextHolder.class);\n\n // use Mockito to set up your expectation on SecurityContextHolder.getSecurityContext()\n Mockito.when(SecurityContextHolder.getSecurityContext()).thenReturn(mockSecurityContext);\n ...\n }\n}\n"
},
{
"answer_id": 17220893,
"author": "Leonardo Eloy",
"author_id": 1464825,
"author_profile": "https://Stackoverflow.com/users/1464825",
"pm_score": 8,
"selected": false,
"text": "SecurityContextHolder.setContext() Authentication a = SecurityContextHolder.getContext().getAuthentication();\n Authentication authentication = Mockito.mock(Authentication.class);\n// Mockito.whens() for your authorization object\nSecurityContext securityContext = Mockito.mock(SecurityContext.class);\nMockito.when(securityContext.getAuthentication()).thenReturn(authentication);\nSecurityContextHolder.setContext(securityContext);\n"
},
{
"answer_id": 17221305,
"author": "Pavel Horal",
"author_id": 865403,
"author_profile": "https://Stackoverflow.com/users/865403",
"pm_score": 1,
"selected": false,
"text": "@Authenticated DirtiesContextTestExecutionListener"
},
{
"answer_id": 24161205,
"author": "borjab",
"author_id": 16206,
"author_profile": "https://Stackoverflow.com/users/16206",
"pm_score": 0,
"selected": false,
"text": "package [myPackage]\n\nimport static org.junit.Assert.*;\n\nimport javax.inject.Inject;\nimport javax.servlet.http.HttpSession;\n\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.experimental.runners.Enclosed;\nimport org.junit.runner.RunWith;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.mock.web.MockHttpServletRequest;\nimport org.springframework.security.core.context.SecurityContext;\nimport org.springframework.security.core.context.SecurityContextHolder;\nimport org.springframework.security.web.FilterChainProxy;\nimport org.springframework.security.web.context.HttpSessionSecurityContextRepository;\nimport org.springframework.test.context.ContextConfiguration;\nimport org.springframework.test.context.junit4.SpringJUnit4ClassRunner;\nimport org.springframework.test.context.web.WebAppConfiguration;\nimport org.springframework.test.web.servlet.MockMvc;\nimport org.springframework.test.web.servlet.setup.MockMvcBuilders;\nimport org.springframework.web.context.WebApplicationContext;\n\nimport static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;\nimport static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;\nimport static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;\n\n@ContextConfiguration(locations={[my config file locations]})\n@WebAppConfiguration\n@RunWith(SpringJUnit4ClassRunner.class)\npublic static class getUserConfigurationTester{\n\n private MockMvc mockMvc;\n\n @Autowired\n private FilterChainProxy springSecurityFilterChain;\n\n @Autowired\n private MockHttpServletRequest request;\n\n @Autowired\n private WebApplicationContext webappContext;\n\n @Before \n public void init() { \n mockMvc = MockMvcBuilders.webAppContextSetup(webappContext)\n .addFilters(springSecurityFilterChain)\n .build();\n } \n\n\n @Test\n public void testTwoReads() throws Exception{ \n\n HttpSession session = mockMvc.perform(post(\"/j_spring_security_check\")\n .param(\"j_username\", \"admin_001\")\n .param(\"j_password\", \"secret007\"))\n .andDo(print())\n .andExpect(status().isMovedTemporarily())\n .andExpect(redirectedUrl(\"/index\"))\n .andReturn()\n .getRequest()\n .getSession();\n\n request.setSession(session);\n\n SecurityContext securityContext = (SecurityContext) session.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);\n\n SecurityContextHolder.setContext(securityContext);\n\n // Your test goes here. User is logged with \n}\n"
},
{
"answer_id": 33734746,
"author": "yankee",
"author_id": 327301,
"author_profile": "https://Stackoverflow.com/users/327301",
"pm_score": 2,
"selected": false,
"text": "@Controller\nclass Controller {\n @RequestMapping(\"/somewhere\")\n public void doStuff(@AuthenticationPrincipal UserDetails myUser) {\n }\n}\n org.springframework.test.web.servlet.MockMvc org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user() mockMvc.perform(get(\"/somewhere\").with(user(myUserDetails)));\n mockMvc.perform(get(\"/somewhere\").with(sessionUser(myUserDetails)));\n/* ... */\nprivate static RequestPostProcessor sessionUser(final UserDetails userDetails) {\n return new RequestPostProcessor() {\n @Override\n public MockHttpServletRequest postProcessRequest(final MockHttpServletRequest request) {\n final SecurityContext securityContext = new SecurityContextImpl();\n securityContext.setAuthentication(\n new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities())\n );\n request.getSession().setAttribute(\n HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, securityContext\n );\n return request;\n }\n };\n}\n"
},
{
"answer_id": 37445761,
"author": "matsev",
"author_id": 303598,
"author_profile": "https://Stackoverflow.com/users/303598",
"pm_score": 6,
"selected": false,
"text": "@WithMockUser @Test\n@WithMockUser(username = \"admin\", authorities = { \"ADMIN\", \"USER\" })\npublic void getMessageWithMockUserCustomAuthorities() {\n String message = messageService.getMessage();\n ...\n}\n @WithUserDetails UserDetails UserDetailsService @Test\n@WithUserDetails(\"customUsername\")\npublic void getMessageWithUserDetailsCustomUsername() {\n String message = messageService.getMessage();\n ...\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4249/"
] |
360,530 | <p>I would like to know how to change the colour of the equality sign and double quotes for html documents in the eclipse PDT IDE. I can change most colours in Preferences -> Web & XML -> HTML Files -> syntax coloring, but can't change the characters <code>=</code> or <code>"</code> e.g. in an anchor tag <code><a href=""></code>.</p>
<p>How to change these colours?</p>
| [
{
"answer_id": 396029,
"author": "Pavel",
"author_id": 48340,
"author_profile": "https://Stackoverflow.com/users/48340",
"pm_score": 5,
"selected": false,
"text": "public class MyUserDetails implements UserDetails {\n // this is your custom UserDetails implementation to serve as a principal\n // implement the Spring methods and add your own methods as appropriate\n}\n\npublic class MyUserHolder {\n public static MyUserDetails getUserDetails() {\n Authentication a = SecurityContextHolder.getContext().getAuthentication();\n if (a == null) {\n return null;\n } else {\n return (MyUserDetails) a.getPrincipal();\n }\n }\n}\n\npublic class MyUserAwareController { \n MyUserDetails currentUser;\n\n public void setCurrentUser(MyUserDetails currentUser) { \n this.currentUser = currentUser;\n }\n\n // controller code\n}\n <bean id=\"userDetails\" class=\"MyUserHolder\" factory-method=\"getUserDetails\" scope=\"request\">\n <aop:scoped-proxy/>\n</bean>\n\n<bean id=\"controller\" class=\"MyUserAwareController\">\n <property name=\"currentUser\" ref=\"userDetails\"/>\n <!-- other props -->\n</bean>\n protected void setUp() {\n // existing init code\n\n MyUserDetails user = new MyUserDetails();\n // set up user as you wish\n controller.setCurrentUser(user);\n}\n"
},
{
"answer_id": 885193,
"author": "Scott Bale",
"author_id": 2495576,
"author_profile": "https://Stackoverflow.com/users/2495576",
"pm_score": 2,
"selected": false,
"text": "SecurityContext SecurityContextHolder SecurityContext"
},
{
"answer_id": 9609015,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "@RunWith(PowerMockRunner.class)\n@PrepareForTest(SecurityContextHolder.class)\npublic class YourTestCase {\n\n @Mock SecurityContext mockSecurityContext;\n\n @Test\n public void testMethodThatCallsStaticMethod() {\n // Set mock behaviour/expectations on the mockSecurityContext\n when(mockSecurityContext.getAuthentication()).thenReturn(...)\n ...\n // Tell mockito to use Powermock to mock the SecurityContextHolder\n PowerMockito.mockStatic(SecurityContextHolder.class);\n\n // use Mockito to set up your expectation on SecurityContextHolder.getSecurityContext()\n Mockito.when(SecurityContextHolder.getSecurityContext()).thenReturn(mockSecurityContext);\n ...\n }\n}\n"
},
{
"answer_id": 17220893,
"author": "Leonardo Eloy",
"author_id": 1464825,
"author_profile": "https://Stackoverflow.com/users/1464825",
"pm_score": 8,
"selected": false,
"text": "SecurityContextHolder.setContext() Authentication a = SecurityContextHolder.getContext().getAuthentication();\n Authentication authentication = Mockito.mock(Authentication.class);\n// Mockito.whens() for your authorization object\nSecurityContext securityContext = Mockito.mock(SecurityContext.class);\nMockito.when(securityContext.getAuthentication()).thenReturn(authentication);\nSecurityContextHolder.setContext(securityContext);\n"
},
{
"answer_id": 17221305,
"author": "Pavel Horal",
"author_id": 865403,
"author_profile": "https://Stackoverflow.com/users/865403",
"pm_score": 1,
"selected": false,
"text": "@Authenticated DirtiesContextTestExecutionListener"
},
{
"answer_id": 24161205,
"author": "borjab",
"author_id": 16206,
"author_profile": "https://Stackoverflow.com/users/16206",
"pm_score": 0,
"selected": false,
"text": "package [myPackage]\n\nimport static org.junit.Assert.*;\n\nimport javax.inject.Inject;\nimport javax.servlet.http.HttpSession;\n\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.experimental.runners.Enclosed;\nimport org.junit.runner.RunWith;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.mock.web.MockHttpServletRequest;\nimport org.springframework.security.core.context.SecurityContext;\nimport org.springframework.security.core.context.SecurityContextHolder;\nimport org.springframework.security.web.FilterChainProxy;\nimport org.springframework.security.web.context.HttpSessionSecurityContextRepository;\nimport org.springframework.test.context.ContextConfiguration;\nimport org.springframework.test.context.junit4.SpringJUnit4ClassRunner;\nimport org.springframework.test.context.web.WebAppConfiguration;\nimport org.springframework.test.web.servlet.MockMvc;\nimport org.springframework.test.web.servlet.setup.MockMvcBuilders;\nimport org.springframework.web.context.WebApplicationContext;\n\nimport static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;\nimport static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;\nimport static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;\n\n@ContextConfiguration(locations={[my config file locations]})\n@WebAppConfiguration\n@RunWith(SpringJUnit4ClassRunner.class)\npublic static class getUserConfigurationTester{\n\n private MockMvc mockMvc;\n\n @Autowired\n private FilterChainProxy springSecurityFilterChain;\n\n @Autowired\n private MockHttpServletRequest request;\n\n @Autowired\n private WebApplicationContext webappContext;\n\n @Before \n public void init() { \n mockMvc = MockMvcBuilders.webAppContextSetup(webappContext)\n .addFilters(springSecurityFilterChain)\n .build();\n } \n\n\n @Test\n public void testTwoReads() throws Exception{ \n\n HttpSession session = mockMvc.perform(post(\"/j_spring_security_check\")\n .param(\"j_username\", \"admin_001\")\n .param(\"j_password\", \"secret007\"))\n .andDo(print())\n .andExpect(status().isMovedTemporarily())\n .andExpect(redirectedUrl(\"/index\"))\n .andReturn()\n .getRequest()\n .getSession();\n\n request.setSession(session);\n\n SecurityContext securityContext = (SecurityContext) session.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);\n\n SecurityContextHolder.setContext(securityContext);\n\n // Your test goes here. User is logged with \n}\n"
},
{
"answer_id": 33734746,
"author": "yankee",
"author_id": 327301,
"author_profile": "https://Stackoverflow.com/users/327301",
"pm_score": 2,
"selected": false,
"text": "@Controller\nclass Controller {\n @RequestMapping(\"/somewhere\")\n public void doStuff(@AuthenticationPrincipal UserDetails myUser) {\n }\n}\n org.springframework.test.web.servlet.MockMvc org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user() mockMvc.perform(get(\"/somewhere\").with(user(myUserDetails)));\n mockMvc.perform(get(\"/somewhere\").with(sessionUser(myUserDetails)));\n/* ... */\nprivate static RequestPostProcessor sessionUser(final UserDetails userDetails) {\n return new RequestPostProcessor() {\n @Override\n public MockHttpServletRequest postProcessRequest(final MockHttpServletRequest request) {\n final SecurityContext securityContext = new SecurityContextImpl();\n securityContext.setAuthentication(\n new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities())\n );\n request.getSession().setAttribute(\n HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, securityContext\n );\n return request;\n }\n };\n}\n"
},
{
"answer_id": 37445761,
"author": "matsev",
"author_id": 303598,
"author_profile": "https://Stackoverflow.com/users/303598",
"pm_score": 6,
"selected": false,
"text": "@WithMockUser @Test\n@WithMockUser(username = \"admin\", authorities = { \"ADMIN\", \"USER\" })\npublic void getMessageWithMockUserCustomAuthorities() {\n String message = messageService.getMessage();\n ...\n}\n @WithUserDetails UserDetails UserDetailsService @Test\n@WithUserDetails(\"customUsername\")\npublic void getMessageWithUserDetailsCustomUsername() {\n String message = messageService.getMessage();\n ...\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/69346/"
] |
360,597 | <p>I have a class hierarchy, this one:</p>
<pre><code>type
TMatrix = class
protected
//...
public
constructor Create(Rows, Cols: Byte);
//...
type
TMinMatrix = class(TMatrix)
private
procedure Allocate;
procedure DeAllocate;
public
constructor Create(Rows, Cols: Byte);
constructor CreateCopy(var that: TMinMatrix);
destructor Destroy;
end;
</code></pre>
<p>So as you see, both derived and base class constructors have the same parameter list.
I explicitly call base class constructor from derived one:</p>
<pre><code>constructor TMinMatrix.Create(Rows, Cols: Byte);
begin
inherited;
//...
end;
</code></pre>
<p>Is it necessary to explicitly call base class constructor in Delphi? May be I need to put overload or override to clear what I intend to do? I know how to do it in C++ - you need explicit call of a base class constructor only if you want to pass some parameters to it - but I haven`t much experience in Delphi programming.</p>
| [
{
"answer_id": 360693,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 2,
"selected": false,
"text": "type\n TMatrix = class\n protected\n //...\n public\n constructor Create(Rows, Cols: Byte);\n //...\ntype\n TMinMatrix = class(TMatrix)\n public\n constructor Create(Rows, Cols: Byte); overload;\n constructor Create(var that: TMinMatrix); overload;\n end;\n constructor TMinMatrix.Create(Rows, Cols: Byte);\nbegin\n inherited Create(Rows, Cols); // Need to call the full name if the parameters are changed.\n //...\nend;\n"
},
{
"answer_id": 360699,
"author": "onnodb",
"author_id": 1037,
"author_profile": "https://Stackoverflow.com/users/1037",
"pm_score": 5,
"selected": true,
"text": "constructor TMinMatrix.Create(Rows, Cols: Byte);\nbegin\n inherited;\n //...\nend;\n override virtual type\nTMatrix = class\n protected\n //...\n public\n constructor Create(Rows, Cols: Byte); virtual; // <-- Added \"virtual\" here\n //...\ntype\n TMinMatrix = class(TMatrix)\n private\n //...\n public\n constructor Create(Rows, Cols: Byte); override; // <-- Added \"override\" here\n constructor CreateCopy(var that: TMinMatrix);\n destructor Destroy; override; // <-- Also make the destructor \"override\"!\n end;\n override type\nTMyMatrix = class(TMatrix)\n//...\npublic\n constructor Create(Rows, Cols, InitialValue: Byte); reintroduce; virtual;\n//...\nend\n\nimplementation\n\nconstructor TMyMatrix.Create(Rows, Cols, InitialValue: Byte);\nbegin\n inherited Create(Rows, Cols); // <-- Explicitly give parameters here\n //...\nend;\n"
},
{
"answer_id": 360712,
"author": "CheGueVerra",
"author_id": 17787,
"author_profile": "https://Stackoverflow.com/users/17787",
"pm_score": 2,
"selected": false,
"text": "type\n TFirst = class\n private\n FValue: string;\n FNumber: Integer;\n public\n constructor Create(AValue: string; ANumber: integer);\n\n property MyValue: string read FValue write FValue;\n property MyNumber: Integer read Fnumber write FNumber; \n end;\n\n TSecond = class(TFirst)\n public\n constructor Create(AValue: string; ANumber: Integer);\n end;\n\nconstructor TFirst.Create(AValue: string; ANumber: integer);\nbegin\n MyValue := AValue;\n MyNumber := ANumber;\nend;\n\n{ TSecond }\n\nconstructor TSecond.Create(AValue: string; ANumber: Integer);\nbegin\n inherited;\nend;\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28298/"
] |
360,612 | <p>I'm working on a toolkit (sort of a live-CD Lisp-in-a-Box) for people new to Common Lisp, and I want to make sure it is broadly satisfying. What is attractive to you about Lisp? What do/did/would you need to get you started and keep you interested?</p>
<p>What I have so far: SBCL 10.22, Emacs 22.3, SLIME, and LTK bundled together and configured on a Linux live-CD that boots entirely to RAM.</p>
<hr>
<p>I've now released the result of this; it is available at the <a href="http://www.jasonfruit.com/thnake" rel="nofollow noreferrer">Thnake website</a>.</p>
| [
{
"answer_id": 361351,
"author": "Brian Carper",
"author_id": 23070,
"author_profile": "https://Stackoverflow.com/users/23070",
"pm_score": 3,
"selected": false,
"text": "hello-world"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21778/"
] |
360,615 | <p>In postgres I am fairly sure you can do something like this</p>
<pre><code>SELECT
authors.stage_name,
count(select id from books where books.author_id = authors.id)
FROM
authors,
books;
</code></pre>
<p>Essentially, in this example I would like to return a list of authors and how many books each has written.... in the same query.</p>
<p>Is this possible? I suspect this approach is rather naive..</p>
<p>Thanks :)</p>
| [
{
"answer_id": 360647,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 0,
"selected": false,
"text": "SELECT authors.stage_name, count(*) \nFROM authors INNER JOIN books on books.author_id = authors.id\nGROUP BY authors.stage_name\n"
},
{
"answer_id": 360648,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 2,
"selected": true,
"text": "SELECT a.stage_name, COUNT(b.id)\nFROM authors a\n LEFT OUTER JOIN books b ON (a.id = b.author_id)\nGROUP BY a.id;\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33604/"
] |
360,628 | <p>I'm trying to embed an xsl into a XML file. The reason for doing this is to create a single file that could be moved to different computers, this would prevent the need to move the xsl file. </p>
<p>The xsl file is creating a table and grabbing a test step from the xml and whether it passed or failed, pretty simple.<br>
The issue I'm having, I think, is that the xsl has javascript and its being displayed when the xml is loaded in IE. </p>
<p>When I load the xml file with IE, the javascript is displayed above the table and below the table the xml is displayed.</p>
<p>Here is how my document is laid-out :</p>
<pre><code><!DOCTYPE doc [
<!ATTLIST xsl:stylesheet
id ID #REQUIRED>
]>
<doc>
<xsl:stylesheet id="4.1.0"
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:user="http://www.ni.com/TestStand"
xmlns:vb_user="http://www.ni.com/TestStand/" >
<xsl:template match="xsl:stylesheet" />
<xsl:text disable-output-escaping="yes">
<msxsl:script language="vbscript" implements-prefix="vb_user">
option explicit
'This function will return the localized decimal point for a decimal number
Function GetLocalizedDecimalPoint ()
dim lDecPoint
lDecPoint = Mid(CStr(1.1),2,1)
GetLocalizedDecimalPoint = lDecPoint
End Function
</msxsl:script>
<msxsl:script language="javascript" implements-prefix="user"><![CDATA[
// This style sheet will not show tables instead of graphs for arrays of values if
// 1. TSGraph control is not installed on the machine
// 2. Using the stylesheet in windows XP SP2. Security settings prevent stylesheets from creatign the GraphControl using scripting.
// Refer to the TestStand Readme for more information.
//more javascript functions
//code to build table and insert data from the xml
</xsl:stylesheet>
<Reports>
<Report Type='UUT' Title='UUT Report' Link='-1-2008-12-3-10-46-52-713' UUTResult='Failed' StepCount='51'>
// rest of xml
</Report>
</Reports>
</doc>
</code></pre>
| [
{
"answer_id": 361237,
"author": "Dimitre Novatchev",
"author_id": 36305,
"author_profile": "https://Stackoverflow.com/users/36305",
"pm_score": 4,
"selected": false,
"text": "<xsl:template>"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7617/"
] |
360,643 | <p>I used to have one class for one file. For example <em>car.cs</em> has the class <em>car</em>. But as I program more classes, I would like to add them to the same file. For example <em>car.cs</em> has the class <em>car</em> and the <em>door</em> class, etc.</p>
<p>My question is good for Java, C#, PHP or any other programming language. Should I try not having multiple classes in the same file or is it ok?</p>
| [
{
"answer_id": 360735,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 5,
"selected": false,
"text": "public class Customer { /* whatever */ }\n\npublic class CustomerCollection : List<Customer> { /* whatever */ }\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21386/"
] |
360,649 | <p>Is there a way to vertically stack selected td elments? I would like to have the same table, though display it differently using only css. Would this be possible, or do I have to have separate html markups? I would like to try to have the same html markup, though use different css for different sites/looks.</p>
<pre><code><table>
<tr>
<td class="vertical" id="one" >i'm</td>
<td class="vertical" id="two" >above</td>
<td class="vertical" id="three" >this</td>
<td class="horizontal" id="four" >i'm horizontal</td>
</tr>
</table>
</code></pre>
| [
{
"answer_id": 360674,
"author": "Eduardo Molteni",
"author_id": 2385,
"author_profile": "https://Stackoverflow.com/users/2385",
"pm_score": 3,
"selected": true,
"text": "<table>\n <tr>\n <td class=\"vertical\">i'm</td>\n <td class=\"horizontal\" rowspan=\"3\">i'm horizontal</td>\n </tr>\n <tr>\n <td class=\"vertical\">above</td>\n </tr>\n <tr>\n <td class=\"vertical\">this</td>\n </tr>\n</table>\n"
},
{
"answer_id": 60413247,
"author": "Axelle",
"author_id": 1780110,
"author_profile": "https://Stackoverflow.com/users/1780110",
"pm_score": 3,
"selected": false,
"text": ".vertical{\n display:flex;\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20641/"
] |
360,673 | <p>Is there a way to do gradients in css/html/javascript only that will work across all the major browsers? (MS IE 5+, Firefox, Opera, Safari)?</p>
<p>Edit: I would like to do this for backgrounds (header, main panel, side panels). Also, would like to have vertical line gradients as well.</p>
<p>Edit: after reading the responses, let's open this up to Javascript solutions as well, since HTML/CSS by itself makes it tougher to achieve.</p>
| [
{
"answer_id": 360811,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 2,
"selected": false,
"text": "var parent = document.getElementByID('foo');\nfor(var i=0; i< count; i++) {\n var div = document.createElement('div');\n div.style.position = 'absolute';\n div.style.width='100%';\n div.style.height = 1/count+\"%\";\n div.style.top = i/count+\"%\";\n div.style.zIndex = -1;\n parent.appendChild(div);\n}\n"
},
{
"answer_id": 18691055,
"author": "Avdhut",
"author_id": 1460732,
"author_profile": "https://Stackoverflow.com/users/1460732",
"pm_score": 0,
"selected": false,
"text": "linear-gradient: ([angle | to ] ,[ [color-stop], [color-stop]+); \n linear-gradient: ([angle | to ] ,[ [color-stop], [color-stop]+); \n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20641/"
] |
360,694 | <p>If you have a web application that will run inside a network, it makes sense for it to support windows authentication (active directory?).</p>
<p>Would it make sense to use AD security model as well, or would I make my own roles/security module that some admin would have to configure for each user?</p>
<p>I've never dealt with windows security before, so I am very confused as to how I should be handling security for a web application that runs within a windows network.</p>
<p>I guess there are 2 major points I have to tackle:</p>
<pre><code>1. authentication
2. authorization
</code></pre>
<p>I have a feeling that best-practice would say to handle authorization myself, but use AD authentication right?</p>
| [
{
"answer_id": 360717,
"author": "Ian G",
"author_id": 31765,
"author_profile": "https://Stackoverflow.com/users/31765",
"pm_score": 4,
"selected": true,
"text": "web.config <system.web>\n ...\n <authentication mode=\"Windows\"/>\n ...\n </system.web>\n web.config <authorization>\n <deny users=\"DomainName\\UserName\" />\n <allow roles=\"DomainName\\WindowsGroup\" />\n</authorization>\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39677/"
] |
360,725 | <p>I am fetching an array of floats from my database but the array I get has converted the values to strings.</p>
<p>How can I convert them into floats again without looping through the array?<br />
Alternatively, how can I fetch the values from the database without converting them to strings?</p>
<hr />
<h3>EDIT:</h3>
<ul>
<li><p>I am using the Zend Framework and I am using PDO_mysql. The values are stored one per column and that is a requirement so I can't serialize them.</p>
</li>
<li><p><code>array_map('floatval', $array)</code> only works on single dimensional arrays.</p>
</li>
<li><p>I can't <code>floatval</code> the single elements when I use them because I have to pass an array to my flash chart.</p>
</li>
<li><p>The momentary, non-generic solution is to extract the rows and do <code>array_map('floatval',$array)</code> with each row.</p>
</li>
</ul>
| [
{
"answer_id": 360736,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 6,
"selected": true,
"text": "$floats = array_map('floatval', $nonFloats);\n PDO::ATTR_STRINGIFY_FETCHES true function toFloats($array)\n{\n return array_map('floatval', $array);\n}\n\n$data = array_map('toFloats', $my2DArray);\n"
},
{
"answer_id": 360744,
"author": "Kris",
"author_id": 18565,
"author_profile": "https://Stackoverflow.com/users/18565",
"pm_score": 1,
"selected": false,
"text": "array_map floatval $data = array_map('floatval', $data);"
},
{
"answer_id": 360824,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": -1,
"selected": false,
"text": "(float) $string"
},
{
"answer_id": 361030,
"author": "rg88",
"author_id": 11252,
"author_profile": "https://Stackoverflow.com/users/11252",
"pm_score": 0,
"selected": false,
"text": "protected function _c2f($input)\n {\n $input = (float)$input;\n $output = round(($input * 1.8) + 32, 2);\n\n return $output;\n }\n"
},
{
"answer_id": 64620357,
"author": "Parteek Kumar Kherpa",
"author_id": 3843888,
"author_profile": "https://Stackoverflow.com/users/3843888",
"pm_score": 0,
"selected": false,
"text": "\n \n\n $example= array(\"12.20\", \"15.05\", \"55.70\");\n foreach($example as $float) \n{\n $update_value = number_format($float,2);\n echo $update_value.\"<br>\";\n}\n\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11995/"
] |
360,748 | <p>I understand Big-O notation, but I don't know how to calculate it for many functions. In particular, I've been trying to figure out the computational complexity of the naive version of the Fibonacci sequence:</p>
<pre><code>int Fibonacci(int n)
{
if (n <= 1)
return n;
else
return Fibonacci(n - 1) + Fibonacci(n - 2);
}
</code></pre>
<p>What is the computational complexity of the Fibonacci sequence and how is it calculated?</p>
| [
{
"answer_id": 360768,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 7,
"selected": false,
"text": "F(n) F(1) 1 F(n) F(n-1) + F(n-2) a (1+sqrt(5))/2 = 1.6180339887"
},
{
"answer_id": 360773,
"author": "mmx",
"author_id": 33708,
"author_profile": "https://Stackoverflow.com/users/33708",
"pm_score": 10,
"selected": true,
"text": "Fib(n) Fib(n-1) Fib(n-2) O(1) Fib(n) T(n<=1) = O(1) T(n) = T(n-1) + T(n-2) + O(1) n O(2 n ) n = 1 T(n-1) = O(2 n-1 ) T(n) = T(n-1) + T(n-2) + O(1) T(n) = O(2 n-1 ) + O(2 n-2 ) + O(1) = O(2 n ) Fib(n) f(n) = f(n-1) + f(n-2) Fib(n) T(n) Fib(n) x O(1) θ(1.6 n )"
},
{
"answer_id": 360896,
"author": "Dave L.",
"author_id": 3093,
"author_profile": "https://Stackoverflow.com/users/3093",
"pm_score": 4,
"selected": false,
"text": "2^(n/2) T(n) = Ω(2^(n/2)) (lower bound)\nT(n) = O(2^n) (upper bound)\nT(n) = Θ(Fib(n)) (tight bound)\n"
},
{
"answer_id": 360938,
"author": "Bob Cross",
"author_id": 5812,
"author_profile": "https://Stackoverflow.com/users/5812",
"pm_score": 5,
"selected": false,
"text": "Fib(N) = (1/sqrt(5)) * 1.618^(N+1) (approximately)\n O((1/sqrt(5)) * 1.618^(N+1)) = O(1.618^(N+1))\n"
},
{
"answer_id": 13436378,
"author": "pgaur",
"author_id": 1832811,
"author_profile": "https://Stackoverflow.com/users/1832811",
"pm_score": 1,
"selected": false,
"text": "O(2^n) F(n-(n-1)) F(1) 1+2+4+.......(n-1)\n= 1((2^n)-1)/(2-1)\n=2^n -1\n 2^n [ O(2^n) ]"
},
{
"answer_id": 22084314,
"author": "benkc",
"author_id": 642160,
"author_profile": "https://Stackoverflow.com/users/642160",
"pm_score": 4,
"selected": false,
"text": "IN | OUT | TOT | LEAF | INT\n 1 | 1 | 1 | 1 | 0\n 2 | 1 | 1 | 1 | 0\n 3 | 2 | 3 | 2 | 1\n 4 | 3 | 5 | 3 | 2\n 5 | 5 | 9 | 5 | 4\n 6 | 8 | 15 | 8 | 7\n 7 | 13 | 25 | 13 | 12\n 8 | 21 | 41 | 21 | 20\n 9 | 34 | 67 | 34 | 33\n10 | 55 | 109 | 55 | 54\n fib(n) fib(n) - 1 2 * fib(n) - 1 θ(fib(n))"
},
{
"answer_id": 23095023,
"author": "J.P.",
"author_id": 1504065,
"author_profile": "https://Stackoverflow.com/users/1504065",
"pm_score": 5,
"selected": false,
"text": "n *\nn-1 **\nn-2 **** \n...\n2 ***********\n1 ******************\n0 ***************************\n F(6) * <-- only once\nF(5) * <-- only once too\nF(4) ** \nF(3) ****\nF(2) ********\nF(1) **************** <-- 16\nF(0) ******************************** <-- 32\n O( F(6) ) = O(2^6)\nO( F(n) ) = O(2^n)\n"
},
{
"answer_id": 45618079,
"author": "Tony Tannous",
"author_id": 6530695,
"author_profile": "https://Stackoverflow.com/users/6530695",
"pm_score": 5,
"selected": false,
"text": " T(n) = T(n-1) + T(n-2) <\n T(n-1) + T(n-1) \n\n = 2*T(n-1) \n = 2*2*T(n-2)\n = 2*2*2*T(n-3)\n ....\n = 2^i*T(n-i)\n ...\n ==> O(2^n)\n"
},
{
"answer_id": 46507560,
"author": "Miguel",
"author_id": 1624104,
"author_profile": "https://Stackoverflow.com/users/1624104",
"pm_score": 2,
"selected": false,
"text": "static int fib(int n)\n{\n /* memory */\n int f[] = new int[n+1];\n int i;\n\n /* Init */\n f[0] = 0;\n f[1] = 1;\n\n /* Fill */\n for (i = 2; i <= n; i++)\n {\n f[i] = f[i-1] + f[i-2];\n }\n\n return f[n];\n}\n m = log2(n) // your real input size\n m = log2(n)\n2^m = 2^log2(n) = n\n T(m) = n steps = 2^m steps\n"
},
{
"answer_id": 53533067,
"author": "nikhil kekan",
"author_id": 2520170,
"author_profile": "https://Stackoverflow.com/users/2520170",
"pm_score": 4,
"selected": false,
"text": " n\n (n-1) (n-2)\n(n-2)(n-3) (n-3)(n-4) ...so on\n i\n0 n\n1 (n-1) (n-2)\n2 (n-2) (n-3) (n-3) (n-4)\n3 (n-3)(n-4) (n-4)(n-5) (n-4)(n-5) (n-5)(n-6)\n 2^0=1 n\n2^1=2 (n-1) (n-2)\n2^2=4 (n-2) (n-3) (n-3) (n-4)\n2^3=8 (n-3)(n-4) (n-4)(n-5) (n-4)(n-5) (n-5)(n-6) ..so on\n2^i for ith level\n i work\n1 2^1\n2 2^2\n3 2^3..so on\n"
},
{
"answer_id": 59432036,
"author": "bob",
"author_id": 12532017,
"author_profile": "https://Stackoverflow.com/users/12532017",
"pm_score": 2,
"selected": false,
"text": "2 (2 -> 1, 0)\n\n4 (3 -> 2, 1) (2 -> 1, 0)\n\n8 (4 -> 3, 2) (3 -> 2, 1) (2 -> 1, 0)\n (2 -> 1, 0)\n\n\n14 (5 -> 4, 3) (4 -> 3, 2) (3 -> 2, 1) (2 -> 1, 0)\n (2 -> 1, 0)\n\n (3 -> 2, 1) (2 -> 1, 0)\n\n22 (6 -> 5, 4)\n (5 -> 4, 3) (4 -> 3, 2) (3 -> 2, 1) (2 -> 1, 0)\n (2 -> 1, 0)\n\n (3 -> 2, 1) (2 -> 1, 0)\n\n (4 -> 3, 2) (3 -> 2, 1) (2 -> 1, 0)\n (2 -> 1, 0)\n"
},
{
"answer_id": 70659822,
"author": "Fırat Kıyak",
"author_id": 6087087,
"author_profile": "https://Stackoverflow.com/users/6087087",
"pm_score": 1,
"selected": false,
"text": "f_1,f_2, ... f_1 = f_2 = 1 f_1 , f_2 , f_3 , ...\nf_2 , f_3 , f_4 , ...\n v_{n+1} M.v_{n} M = [0 1]\n [1 1]\n f_{n+1} = f_{n+1} and f_{n+2} = f_{n} + f_{n+1} 1 1\nx_1 x_2\n x*x-x-1 = 0 D = [x_1 0]\n [0 x_2]\n f_n = 1/sqrt(5)*(x_1^n-x_2^n)\n O(log_2(n))"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40516/"
] |
360,751 | <p>I would like to have an app include a custom font for rendering text, load it, and then use it with standard <code>UIKit</code> elements like <code>UILabel</code>. Is this possible?</p>
| [
{
"answer_id": 361613,
"author": "August",
"author_id": 30966,
"author_profile": "https://Stackoverflow.com/users/30966",
"pm_score": 4,
"selected": false,
"text": "fontWithName:size:"
},
{
"answer_id": 370257,
"author": "Genericrich",
"author_id": 39932,
"author_profile": "https://Stackoverflow.com/users/39932",
"pm_score": 5,
"selected": false,
"text": "- (void)loadFont{\n // Get the path to our custom font and create a data provider.\n NSString *fontPath = [[NSBundle mainBundle] pathForResource:@\"mycustomfont\" ofType:@\"ttf\"]; \n CGDataProviderRef fontDataProvider = CGDataProviderCreateWithFilename([fontPath UTF8String]);\n\n // Create the font with the data provider, then release the data provider.\n customFont = CGFontCreateWithDataProvider(fontDataProvider);\n CGDataProviderRelease(fontDataProvider); \n}\n drawRect: -(void)drawRect:(CGRect)rect{\n [super drawRect:rect];\n // Get the context.\n CGContextRef context = UIGraphicsGetCurrentContext();\n CGContextClearRect(context, rect);\n // Set the customFont to be the font used to draw.\n CGContextSetFont(context, customFont);\n\n // Set how the context draws the font, what color, how big.\n CGContextSetTextDrawingMode(context, kCGTextFillStroke);\n CGContextSetFillColorWithColor(context, self.fontColor.CGColor);\n UIColor * strokeColor = [UIColor blackColor];\n CGContextSetStrokeColorWithColor(context, strokeColor.CGColor);\n CGContextSetFontSize(context, 48.0f);\n\n // Create an array of Glyph's the size of text that will be drawn.\n CGGlyph textToPrint[[self.theText length]];\n\n // Loop through the entire length of the text.\n for (int i = 0; i < [self.theText length]; ++i) {\n // Store each letter in a Glyph and subtract the MagicNumber to get appropriate value.\n textToPrint[i] = [[self.theText uppercaseString] characterAtIndex:i] + 3 - 32;\n }\n CGAffineTransform textTransform = CGAffineTransformMake(1.0, 0.0, 0.0, -1.0, 0.0, 0.0);\n CGContextSetTextMatrix(context, textTransform);\n CGContextShowGlyphsAtPoint(context, 20, 50, textToPrint, [self.theText length]);\n}\n"
},
{
"answer_id": 733907,
"author": "Matt Sephton",
"author_id": 28290,
"author_profile": "https://Stackoverflow.com/users/28290",
"pm_score": 3,
"selected": false,
"text": "ATSApplicationFontsPath"
},
{
"answer_id": 809307,
"author": "commanda",
"author_id": 21447,
"author_profile": "https://Stackoverflow.com/users/21447",
"pm_score": 8,
"selected": false,
"text": "UILabel FontLabel.h FontLabel.m Info.plist Info.plist [UIFont fontWithName:@\"CustomFontName\" size:15] UILabels UITextViews"
},
{
"answer_id": 809568,
"author": "rpetrich",
"author_id": 4007,
"author_profile": "https://Stackoverflow.com/users/4007",
"pm_score": 5,
"selected": false,
"text": "UIFont .ttf BOOL GSFontAddFromFile(const char * path);\nNSUInteger loadFonts()\n{\n NSUInteger newFontCount = 0;\n for (NSString *fontFile in [[NSBundle mainBundle] pathsForResourcesOfType:@\"ttf\" inDirectory:nil])\n newFontCount += GSFontAddFromFile([fontFile UTF8String]);\n return newFontCount;\n}\n NSLog(@\"Available Font Families: %@\", [UIFont familyNames]);\n[label setFont:[UIFont fontWithName:@\"Consolas\" size:20.0f]];\n #import <dlfcn.h>\nNSUInteger loadFonts()\n{\n NSUInteger newFontCount = 0;\n NSBundle *frameworkBundle = [NSBundle bundleWithIdentifier:@\"com.apple.GraphicsServices\"];\n const char *frameworkPath = [[frameworkBundle executablePath] UTF8String];\n if (frameworkPath) {\n void *graphicsServices = dlopen(frameworkPath, RTLD_NOLOAD | RTLD_LAZY);\n if (graphicsServices) {\n BOOL (*GSFontAddFromFile)(const char *) = dlsym(graphicsServices, \"GSFontAddFromFile\");\n if (GSFontAddFromFile)\n for (NSString *fontFile in [[NSBundle mainBundle] pathsForResourcesOfType:@\"ttf\" inDirectory:nil])\n newFontCount += GSFontAddFromFile([fontFile UTF8String]);\n }\n }\n return newFontCount;\n}\n"
},
{
"answer_id": 1637559,
"author": "Jacob Wallström",
"author_id": 173157,
"author_profile": "https://Stackoverflow.com/users/173157",
"pm_score": 3,
"selected": false,
"text": "[UIFont fontWithName:size:] [UIFont fontWithName:size:] GSFontAddFromFile"
},
{
"answer_id": 2616101,
"author": "samvermette",
"author_id": 87158,
"author_profile": "https://Stackoverflow.com/users/87158",
"pm_score": 10,
"selected": true,
"text": "Info.plist Info.plist UIAppFonts UIAppFonts Info.plist [UIFont fontWithName:@\"CustomFontName\" size:12]"
},
{
"answer_id": 3198821,
"author": "alexey",
"author_id": 92238,
"author_profile": "https://Stackoverflow.com/users/92238",
"pm_score": 7,
"selected": false,
"text": "Chalkduster.ttf info.plist UIAppFonts Chalkduster.ttf [UIFont fontWithName:@\"Chalkduster\" size:16] UILabel @implementation CustomFontLabel\n\n- (id)initWithCoder:(NSCoder *)decoder\n{\n if (self = [super initWithCoder: decoder])\n {\n [self setFont: [UIFont fontWithName: @\"Chalkduster\" size: self.font.pointSize]];\n }\n return self;\n}\n\n@end\n"
},
{
"answer_id": 4372551,
"author": "Nano",
"author_id": 350506,
"author_profile": "https://Stackoverflow.com/users/350506",
"pm_score": 3,
"selected": false,
"text": "fontWithName"
},
{
"answer_id": 5323191,
"author": "RichX",
"author_id": 473505,
"author_profile": "https://Stackoverflow.com/users/473505",
"pm_score": 3,
"selected": false,
"text": "Fonts provided by application info.plist UIFont"
},
{
"answer_id": 8672403,
"author": "Jarson",
"author_id": 652627,
"author_profile": "https://Stackoverflow.com/users/652627",
"pm_score": 3,
"selected": false,
"text": "[UIFont fontWithName:@\"Real Font Name\" size:16] UIFont fontWithName:"
},
{
"answer_id": 9896585,
"author": "SKris",
"author_id": 1296461,
"author_profile": "https://Stackoverflow.com/users/1296461",
"pm_score": 4,
"selected": false,
"text": "xcode 4.3 font Build Phase Copy Bundle Resources OTF TTF copying the files over to the project folder UIAppFonts names GothamBold GothamBold-Italic project name Project Navigator Build Phases Copy Bundle Resources \"+\" \"+\" add to the project"
},
{
"answer_id": 9941019,
"author": "kumar123",
"author_id": 579511,
"author_profile": "https://Stackoverflow.com/users/579511",
"pm_score": 4,
"selected": false,
"text": "info.plist setFont:\"corresponding Font Name\" NSArray *check = [UIFont familyNames];"
},
{
"answer_id": 12251216,
"author": "AaronBaker",
"author_id": 473699,
"author_profile": "https://Stackoverflow.com/users/473699",
"pm_score": 3,
"selected": false,
"text": "UIFont *yourCustomFont = [UIFont fontWithName:@\"YOUR-CUSTOM-FONT-POSTSCRIPT-NAME\" size:14.0];\n[yourUILabel setFont:yourCustomFont];\n"
},
{
"answer_id": 12599180,
"author": "Alejandro Luengo",
"author_id": 728728,
"author_profile": "https://Stackoverflow.com/users/728728",
"pm_score": 3,
"selected": false,
"text": "[theUILabel setFont:[UIFont fontWithName:@\"DINEngschriftStd\" size:21]];\n NSLog(@\"Available Font Families: %@\", [UIFont familyNames]);\n"
},
{
"answer_id": 12935465,
"author": "bdev",
"author_id": 890395,
"author_profile": "https://Stackoverflow.com/users/890395",
"pm_score": 6,
"selected": false,
"text": "Fonts provided by application\n Item 0 myfontname.ttf\n Item 1 myfontname-bold.ttf\n ...\n for (NSString *familyName in [UIFont familyNames]) {\n for (NSString *fontName in [UIFont fontNamesForFamilyName:familyName]) {\n NSLog(@\"%@\", fontName);\n }\n}\n [label setFont:[UIFont fontWithName:@\"MyFontName-Regular\" size:18]];\n"
},
{
"answer_id": 13024994,
"author": "Nishan29",
"author_id": 970605,
"author_profile": "https://Stackoverflow.com/users/970605",
"pm_score": 2,
"selected": false,
"text": "Info.plist [UIFont fontwithName:@\"FONT NAME\" size:12];"
},
{
"answer_id": 15307180,
"author": "Kirtikumar A.",
"author_id": 1376496,
"author_profile": "https://Stackoverflow.com/users/1376496",
"pm_score": 3,
"selected": false,
"text": ".plist info.plist install install <key>UIAppFonts</key>\n<array>\n <string>MyriadPro.otf</string>\n</array>\n class .m [lblPoints setFont:[UIFont fontWithName:@\"Myriad Pro\" size:15.0]];\n UILabel"
},
{
"answer_id": 15512592,
"author": "David M.",
"author_id": 382938,
"author_profile": "https://Stackoverflow.com/users/382938",
"pm_score": 2,
"selected": false,
"text": "CTFontManagerRegisterGraphicsFont UIFont NSData *inData = /* your font-file data */;\nCFErrorRef error;\nCGDataProviderRef provider = CGDataProviderCreateWithCFData((CFDataRef)inData);\nCGFontRef font = CGFontCreateWithDataProvider(provider);\nif (! CTFontManagerRegisterGraphicsFont(font, &error)) {\n CFStringRef errorDescription = CFErrorCopyDescription(error)\n NSLog(@\"Failed to load font: %@\", errorDescription);\n CFRelease(errorDescription);\n}\nCFRelease(font);\nCFRelease(provider);\n"
},
{
"answer_id": 16491090,
"author": "Bharat Gulati",
"author_id": 781067,
"author_profile": "https://Stackoverflow.com/users/781067",
"pm_score": 1,
"selected": false,
"text": "[self.labelOutlet setFont:[UIFont fontWithName:@\"Sathu\" size:10]];\n"
},
{
"answer_id": 18182996,
"author": "Raptor",
"author_id": 188331,
"author_profile": "https://Stackoverflow.com/users/188331",
"pm_score": 0,
"selected": false,
"text": "-(void)viewDidLoad [super viewDidLoad] NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,\n NSUserDomainMask, YES);\nNSMutableArray *system_fonts = [NSMutableArray array];\nfor (NSString *familyName in [UIFont familyNames]) {\n for (NSString *fontName in [UIFont fontNamesForFamilyName:familyName]) {\n [system_fonts addObject:fontName];\n }\n}\nif([paths count] > 0) {\n [system_fonts writeToFile:[[paths objectAtIndex:0]\n stringByAppendingPathComponent:@\"array.out\"] atomically:YES];\n}\n .plist Add To Target NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,\n NSUserDomainMask, YES);\nNSMutableArray *system_fonts = [NSMutableArray arrayWithContentsOfFile:[[paths objectAtIndex:0]\n stringByAppendingPathComponent:@\"array.out\"]];\n\nfor (NSString *familyName in [UIFont familyNames]) {\n for (NSString *fontName in [UIFont fontNamesForFamilyName:familyName]) {\n if (![system_fonts containsObject:fontName]) {\n NSLog(@\"%@\", fontName);\n }\n }\n}\n .ttc .ttf"
},
{
"answer_id": 20514948,
"author": "user2691469",
"author_id": 2691469,
"author_profile": "https://Stackoverflow.com/users/2691469",
"pm_score": 1,
"selected": false,
"text": "Info.plist Info.plist [UIFont fontWithName:@\"your Custom font Name\" size:20] UILabels [UIFont fontWithName:@\" here past your Custom font Name\" size:20]"
},
{
"answer_id": 25618714,
"author": "Dima Deplov",
"author_id": 1207902,
"author_profile": "https://Stackoverflow.com/users/1207902",
"pm_score": 5,
"selected": false,
"text": "iOS 8 Xcode 6 Xcode IB info.plist Fonts provided by application func allFonts(){\n\n for family in UIFont.familyNames(){\n\n println(family)\n\n\n for name in UIFont.fontNamesForFamilyName(family.description)\n {\n println(\" \\(name)\")\n }\n\n }\n\n}\n bug UITextField viewcontroller textfield viewDidLoad"
},
{
"answer_id": 32849653,
"author": "Chris Klingler",
"author_id": 1982051,
"author_profile": "https://Stackoverflow.com/users/1982051",
"pm_score": 4,
"selected": false,
"text": "Fonts provided by application for family: String in UIFont.familyNames(){\n print(\"\\(family)\")\n for names: String in UIFont.fontNamesForFamilyName(family){\n print(\"== \\(names)\")\n }\n}\n for (NSString* family in [UIFont familyNames]){\n NSLog(@\"%@\", family);\n for (NSString* name in [UIFont fontNamesForFamilyName: family]){\n NSLog(@\" %@\", name);\n }\n}\n label.font = UIFont(name: \"SourceSansPro-Regular\", size: 18)\n label.font = [UIFont fontWithName:@\"SourceSansPro-Regular\" size:18];\n"
},
{
"answer_id": 33412266,
"author": "Daniel Krom",
"author_id": 4126633,
"author_profile": "https://Stackoverflow.com/users/4126633",
"pm_score": 2,
"selected": false,
"text": "appDelegate didFinishLaunchingWithOptions func loadFont(filePath: String) {\n\n let fontData = NSData(contentsOfFile: filePath)!\n\n let dataProvider = CGDataProviderCreateWithCFData(fontData)\n let cgFont = CGFontCreateWithDataProvider(dataProvider)!\n\n var error: Unmanaged<CFError>?\n if !CTFontManagerRegisterGraphicsFont(cgFont, &error) {\n let errorDescription: CFStringRef = CFErrorCopyDescription(error!.takeUnretainedValue())\n print(\"Unable to load font: %@\", errorDescription, terminator: \"\")\n }\n\n}\n if let fontPath = NSBundle.mainBundle().pathForResource(\"My-Font\", ofType: \"ttf\"){\n loadFont(fontPath)\n}\n UIFont(name: \"My-Font\", size: 16.5)\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18017/"
] |
360,753 | <p>So I'm a newbie to TDD, and I successfully created a nice little sample app using the MVP pattern. The major problem to my current solution is that its blocking the UI thread, So I was trying to setup the Presenter to use the SynchronizationContext.Current, but when I run my tests the SynchronizationContext.Current is null.</p>
<p>Presenter Before Threading</p>
<pre><code>public class FtpPresenter : IFtpPresenter
{
...
void _view_GetFilesClicked(object sender, EventArgs e)
{
_view.StatusMessage = Messages.Loading;
try
{
var settings = new FtpAuthenticationSettings()
{
Site = _view.FtpSite,
Username = _view.FtpUsername,
Password = _view.FtpPassword
};
var files = _ftpService.GetFiles(settings);
_view.FilesDataSource = files;
_view.StatusMessage = Messages.Done;
}
catch (Exception ex)
{
_view.StatusMessage = ex.Message;
}
}
...
}
</code></pre>
<p>Test Before Threading</p>
<pre><code>[TestMethod]
public void Can_Get_Files()
{
var view = new FakeFtpView();
var presenter = new FtpPresenter(view, new FakeFtpService(), new FakeFileValidator());
view.GetFiles();
Assert.AreEqual(Messages.Done, view.StatusMessage);
}
</code></pre>
<p>Now after I added a SynchronizationContext Threading to the Presenter I tried to set a AutoResetEvent on my Fake View for the StatusMessage, but when I run the test the SynchronizationContext.Current is null. I realize that the threading model I'm using in my new Presenter isn't perfect, but is this the right technique for Testing Multithreading? Why is my SynchronizationContext.Current null? What should I do instead?</p>
<p>Presenter After Threading</p>
<pre><code>public class FtpPresenter : IFtpPresenter
{
...
void _view_GetFilesClicked(object sender, EventArgs e)
{
_view.StatusMessage = Messages.Loading;
try
{
var settings = new FtpAuthenticationSettings()
{
Site = _view.FtpSite,
Username = _view.FtpUsername,
Password = _view.FtpPassword
};
// Wrap the GetFiles in a ThreadStart
var syncContext = SynchronizationContext.Current;
new Thread(new ThreadStart(delegate
{
var files = _ftpService.GetFiles(settings);
syncContext.Send(delegate
{
_view.FilesDataSource = files;
_view.StatusMessage = Messages.Done;
}, null);
})).Start();
}
catch (Exception ex)
{
_view.StatusMessage = ex.Message;
}
}
...
}
</code></pre>
<p>Test after threading</p>
<pre><code>[TestMethod]
public void Can_Get_Files()
{
var view = new FakeFtpView();
var presenter = new FtpPresenter(view, new FakeFtpService(), new FakeFileValidator());
view.GetFiles();
view.GetFilesWait.WaitOne();
Assert.AreEqual(Messages.Done, view.StatusMessage);
}
</code></pre>
<p>Fake View</p>
<pre><code>public class FakeFtpView : IFtpView
{
...
public AutoResetEvent GetFilesWait = new AutoResetEvent(false);
public event EventHandler GetFilesClicked = delegate { };
public void GetFiles()
{
GetFilesClicked(this, EventArgs.Empty);
}
...
private List<string> _statusHistory = new List<string>();
public List<string> StatusMessageHistory
{
get { return _statusHistory; }
}
public string StatusMessage
{
get
{
return _statusHistory.LastOrDefault();
}
set
{
_statusHistory.Add(value);
if (value != Messages.Loading)
GetFilesWait.Set();
}
}
...
}
</code></pre>
| [
{
"answer_id": 360780,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 3,
"selected": true,
"text": " public FtpPresenter() : this(null) { }\n\n public FtpPresenter( SynchronizationContext context )\n {\n this.CurrentContext = context ?? SynchronizationContext.Current;\n }\n\n void _view_GetFilesClicked(object sender, EventArgs e)\n {\n ....\n new Thread(new ThreadStart(delegate\n {\n var files = _ftpService.GetFiles(settings);\n this.CurrentContext.Send(delegate\n {\n _view.FilesDataSource = files;\n _view.StatusMessage = Messages.Done;\n }, null);\n })).Start();\n\n ...\n }\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37881/"
] |
360,758 | <p>I have a server that hosts my Subversion code base. That server is currently a <a href="http://en.wikipedia.org/wiki/Windows_Server_2003" rel="noreferrer">Windows Server 2003</a> box, and my IT administrator wants to update it to <a href="http://en.wikipedia.org/wiki/Windows_Server_2008" rel="noreferrer">Windows Server 2008</a>.</p>
<p>This means that I'm going to need to move my Subversion repository while the server gets built up and was wondering what the best practices are for moving the repository to a new server.</p>
<p>It seems like, looking online, the recommended way is to use:</p>
<pre><code>svnadmin dump /path/to/repository > repository-name.dmp
</code></pre>
<p>And then use:</p>
<pre><code>svnadmin create repository-name
svnadmin load repository-name< repository-name.dmp
</code></pre>
<p>To import the repository.</p>
<p>Does the method above seem like the best approach?</p>
| [
{
"answer_id": 360919,
"author": "alexandrul",
"author_id": 19756,
"author_profile": "https://Stackoverflow.com/users/19756",
"pm_score": 5,
"selected": false,
"text": "svnadmin create repository-name --fs-type fsfs\nsvnadmin load repository-name --force-uuid < repository-name.dmp\n FSFS --force-uuid"
},
{
"answer_id": 23101804,
"author": "orezvani",
"author_id": 585874,
"author_profile": "https://Stackoverflow.com/users/585874",
"pm_score": 2,
"selected": false,
"text": "svnadmin hotcopy path/to/your_current_directory /path/to/your_destination_directory\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10420/"
] |
360,766 | <p>I'd like to define a generic type, whose actual type parameter can only be</p>
<ol>
<li>One of the numeric primitive wrapper classes (<code>Long</code>, <code>Integer</code>, <code>Float</code>, <code>Double</code>)</li>
<li><code>String</code></li>
</ol>
<p>I can meet the first requirement with a definition like this</p>
<pre><code>public final class MyClass<T extends Number> {
// Implementation omitted
}
</code></pre>
<p>But I can't figure out how to meet both of them. I suspect this is not actually possible, because AFAIK there's no way to specify "or" semantics when defining a formal type parameter, though you can specify "and" semantics using a definition such as</p>
<pre><code>public final class MyClass<T extends Runnable & Serializable > {
// Implementation omitted
}
</code></pre>
<p>Cheers,
Don</p>
| [
{
"answer_id": 360796,
"author": "Dave L.",
"author_id": 3093,
"author_profile": "https://Stackoverflow.com/users/3093",
"pm_score": 4,
"selected": false,
"text": "public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll)\n"
},
{
"answer_id": 361109,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 2,
"selected": false,
"text": "Number String Object Number BigInteger"
},
{
"answer_id": 362308,
"author": "Markus",
"author_id": 45064,
"author_profile": "https://Stackoverflow.com/users/45064",
"pm_score": 2,
"selected": false,
"text": "public final class MyClass<T> {\n public static MyClass<Integer> newInstance(int i) {\n return new MyClass<Integer>(i);\n }\n public static MyClass<String> newInstance(String s) {\n return new MyClass<String>(s);\n }\n //More factory methods...\n\n protected MyClass(T obj) {\n //...\n }\n}\n"
},
{
"answer_id": 20544353,
"author": "Bartosz Klimek",
"author_id": 79920,
"author_profile": "https://Stackoverflow.com/users/79920",
"pm_score": 0,
"selected": false,
"text": "MyClass<T> MyClass<T> MyNumericClass<T extends Number> extends MyClass<T>\nMyStringClass extends MyClass<String>\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
] |
360,777 | <p>I have an animation and I want it to play it just only once. From where can I set so when I export to SWF the default will be AUTO LOOPING disabled.</p>
<p>Thanks</p>
| [
{
"answer_id": 24054393,
"author": "Khadka Pushpendra",
"author_id": 2318637,
"author_profile": "https://Stackoverflow.com/users/2318637",
"pm_score": 0,
"selected": false,
"text": "<param name='loop' value='false' />\n\n<object type='application/x-shockwave-flash' data='sourcefile' width='300' height='120' loop='false'>\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44973/"
] |
360,782 | <p>Given either the binary or string representation of an IPv6 address and its prefix length, what's the best way to extract the prefix in Python?</p>
<p>Is there a library that would do this for me, or would I have to:</p>
<ol>
<li>convert the address from string to an int (inet_ntop)</li>
<li>Mask out the prefix</li>
<li>Convert prefix back to binary </li>
<li>Convert binary to string (inet_ntop)</li>
</ol>
| [
{
"answer_id": 360989,
"author": "Martin v. Löwis",
"author_id": 33006,
"author_profile": "https://Stackoverflow.com/users/33006",
"pm_score": 3,
"selected": true,
"text": "py> p=ipaddr.IPv6(\"2001:888:2000:d::a2\")\npy> p.SetPrefix(64)\npy> p\nIPv6('2001:888:2000:d::a2/64')\npy> p.network_ext\n'2001:888:2000:d::'\n"
},
{
"answer_id": 7661089,
"author": "Gary van der Merwe",
"author_id": 72911,
"author_profile": "https://Stackoverflow.com/users/72911",
"pm_score": 0,
"selected": false,
"text": ">>> from netaddr.ip import IPNetwork, IPAddress\n>>> IPNetwork('2001:888:2000:d::a2/64').network\n2001:888:2000:d::\n"
},
{
"answer_id": 62116450,
"author": "Steffen",
"author_id": 1465758,
"author_profile": "https://Stackoverflow.com/users/1465758",
"pm_score": 0,
"selected": false,
"text": "# Returns the IPv6 prefix\ndef getIPv6Prefix(ipv6Addr, prefixLen):\n prefix = \"\"\n curPrefixLen = 0\n ipv6Parts = ipv6Addr.split(\":\")\n for part in ipv6Parts:\n if not prefix == \"\": # if it's not empty\n prefix = prefix + \":\"\n prefix = prefix + part\n curPrefixLen += 32\n if int(curPrefixLen) >= int(prefixLen):\n return prefix\n return prefix\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] |
360,789 | <p>I want to otherwise block code execution on the main thread while still allowing UI changes to be displayed.</p>
<p>I tried to come up with a simplified example version of what I'm trying to do; and this is the best I could come up with. Obviously it doesn't demonstrate the behavior I'm wanting or I wouldn't be posting the question. I just hope it gives some code context to back my poor explanation of the problem I'm hoping to solve.</p>
<p>Within a button click handler on a form I have this:</p>
<pre><code> private void button2_Click(object sender, EventArgs e)
{
AutoResetEvent autoResetEvent = new AutoResetEvent(false);
new Thread(delegate()
{
// do something that takes a while.
Thread.Sleep(1000);
// Update UI w/BeginInvoke
this.BeginInvoke(new ThreadStart(
delegate() {
this.Text = "Working... 1";
this.Refresh();
Thread.Sleep(1000); // gimme a chance to see the new text
}));
// do something else that takes a while.
Thread.Sleep(1000);
// Update UI w/Invoke
this.Invoke(new ThreadStart(
delegate() {
this.Text = "Working... 2";
this.Refresh();
Thread.Sleep(1000); // gimme a chance to see the new text
}));
// do something else that takes a while.
Thread.Sleep(1000);
autoResetEvent.Set();
}).Start();
// I want the UI to update during this 4 seconds, even though I'm
// blocking the mainthread
if (autoResetEvent.WaitOne(4000, false))
{
this.Text = "Event Signalled";
}
else
{
this.Text = "Event Wait Timeout";
}
Thread.Sleep(1000); // gimme a chance to see the new text
this.Refresh();
}
</code></pre>
<p>If I didn't set a timout on the WaitOne() the app would deadlock on the Invoke() call.</p>
<hr>
<p>As to why I'd want to do this, I've been tasked with moving one subsystem of an app to do work in a background thread, but still have it block user's workflow (the main thread) only sometimes and for certain types of work related to that subsystem only.</p>
| [
{
"answer_id": 360944,
"author": "Maghis",
"author_id": 45355,
"author_profile": "https://Stackoverflow.com/users/45355",
"pm_score": 2,
"selected": false,
"text": "private void button1_Click(object sender, EventArgs e)\n{\n // this is the UI thread\n\n ThreadPool.QueueUserWorkItem(delegate(object state)\n {\n // this is the background thread\n // get the job done\n Thread.Sleep(5000);\n int result = 2 + 2;\n\n // next call is to the Invoke method of the form\n this.Invoke(new Action<int>(delegate(int res)\n {\n // this is the UI thread\n // update it!\n label1.Text = res.ToString();\n }), result);\n });\n}\n"
},
{
"answer_id": 362250,
"author": "Stormenet",
"author_id": 2090,
"author_profile": "https://Stackoverflow.com/users/2090",
"pm_score": 0,
"selected": false,
"text": " private void StartMyDoSomethingThread() {\n Thread d = new Thread(new ThreadStart(DoSomething));\n d.Start();\n }\n\n private void DoSomething() {\n Thread.Sleep(1000);\n ReportBack(\"I'm still working\");\n Thread.Sleep(1000);\n ReportBack(\"I'm done\");\n }\n\n private void ReportBack(string p) {\n if (this.InvokeRequired) {\n this.Invoke(new Action<string>(ReportBack), new object[] { p });\n return;\n }\n this.Text = p;\n }\n"
},
{
"answer_id": 447957,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "private static TimeSpan InfiniteTimeout = TimeSpan.FromMilliseconds(-1); \nprivate const Int32 MAX_WAIT = 100; \n\npublic static bool Wait(WaitHandle handle, TimeSpan timeout) \n{ \n Int32 expireTicks; \n bool signaled; \n Int32 waitTime; \n bool exitLoop; \n\n // guard the inputs \n if (handle == null) { \n throw new ArgumentNullException(\"handle\"); \n } \n else if ((handle.SafeWaitHandle.IsClosed)) { \n throw new ArgumentException(\"closed wait handle\", \"handle\"); \n } \n else if ((handle.SafeWaitHandle.IsInvalid)) { \n throw new ArgumentException(\"invalid wait handle\", \"handle\"); \n } \n else if ((timeout < InfiniteTimeout)) { \n throw new ArgumentException(\"invalid timeout <-1\", \"timeout\"); \n } \n\n // wait for the signal \n expireTicks = (int)Environment.TickCount + timeout.TotalMilliseconds; \n do { \n if (timeout.Equals(InfiniteTimeout)) { \n waitTime = MAX_WAIT; \n } \n else { \n waitTime = (expireTicks - Environment.TickCount); \n if (waitTime <= 0) { \n exitLoop = true; \n waitTime = 0; \n } \n else if (waitTime > MAX_WAIT) { \n waitTime = MAX_WAIT; \n } \n } \n\n if ((handle.SafeWaitHandle.IsClosed)) { \n exitLoop = true; \n } \n else if (handle.WaitOne(waitTime, false)) { \n exitLoop = true; \n signaled = true; \n } \n else { \n if (Application.MessageLoop) { \n Application.DoEvents(); \n } \n else { \n Thread.Sleep(1); \n } \n } \n } \n while (!exitLoop); \n\n return signaled;\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16260/"
] |
360,816 | <p>For some reason I can't use <code>runat="server"</code> as an attribute for the input tag in order for the jQuery to display the image button and work. Is something wrong without <code>runat="server"</code>? It works fine. And I want the format to be "yyyy/mm/dd" and also I need it for the server because this is where I check to see if the date manually entered is a valid date and that it matches the accepted format. I really want to use an <code>asp:button</code> but since I can't use <code>runat="server"</code> attribute I don't know what to do since that is required for asp controls</p>
<pre><code><script language="javascript" type="text/javascript">
$(document).ready(function(){
$("#datepicker").datepicker({ showOn: "both",
buttonImage: "/Content/img/calendar.gif",
buttonImageOnly: true });
});
</script>
</code></pre>
| [
{
"answer_id": 360832,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 4,
"selected": true,
"text": "<input id='datepicker' runat='server' class='datepicker' />\n\n$(document).ready(function(){\n$(\".datepicker\").datepicker({ showOn: \"both\", \n buttonImage: \"/Content/img/calendar.gif\", \n buttonImageOnly: true });\n}); \n"
},
{
"answer_id": 11461589,
"author": "brichins",
"author_id": 957950,
"author_profile": "https://Stackoverflow.com/users/957950",
"pm_score": 0,
"selected": false,
"text": "runat='server' clientidmode='static'"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39809/"
] |
360,830 | <p>I'm trying to retrieve data from an SQL Server 2000 server, and place into Excel. Which sounds simple I know.
I'm currently Copying, and Pasting into Excel, from Management Studio</p>
<p>The problem is one of the columns is an address, and it’s not retaining the newlines.
These new lines have to stay in the same cell in excel, I.E cannot take up 3 rows, for 3 lines of an address.</p>
<p>In the SQL Data CHAR(10) and CHAR(13) are included, and other software pick up on these correctly.</p>
<p>EDIT: Sorry I forgot to metion, I want the lines to be present in the cell, but not span multiple cells.</p>
| [
{
"answer_id": 360886,
"author": "Tmdean",
"author_id": 45084,
"author_profile": "https://Stackoverflow.com/users/45084",
"pm_score": 2,
"selected": true,
"text": "Sub FixNewlines()\n For Each Cell In UsedRange\n Cell.FormulaR1C1 = Replace(Cell.FormulaR1C1, Chr(13), \"\")\n Next Cell\nEnd Sub\n"
},
{
"answer_id": 360933,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 0,
"selected": false,
"text": "\"a\" & Chr(13) + Chr(10) & \"b\"\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18405/"
] |
360,831 | <p>I have a scenario in which I'm going to need an arbitrary number of servers to provide the same SOAP web service. I would like to generate one set of proxy classes and be able to supply them with a location to point them at the different servers at runtime. Unfortunately, it looks as though the <code>wsdl:port</code> node (child of <code>wsdl:service</code>) requires the address of a specific server to be hardcoded. It appears that due to this the URL will be baked into my proxy classes. I know that I could potentially modify this by hand-editing the generated proxy classes, or modifying the code generation, but I'd really prefer not to resort to that. I feel like there's got to be a better way to solve this problem. I just want to decouple the interface definition from the location that the service will be residing at. I'm using VS2008 and C#.NET if that's of any help though best would be a language-agnostic (SOAP or WSDL specific) general solution to this problem.</p>
| [
{
"answer_id": 360967,
"author": "rbrayb",
"author_id": 9922,
"author_profile": "https://Stackoverflow.com/users/9922",
"pm_score": 2,
"selected": false,
"text": "Service svc = new Service ();\nsvc.url = \"Value read from config. file or some such\"\noutput = svc.method (input);\n"
},
{
"answer_id": 361145,
"author": "DreamSonic",
"author_id": 6531,
"author_profile": "https://Stackoverflow.com/users/6531",
"pm_score": 0,
"selected": false,
"text": "/appsettingurlkey"
},
{
"answer_id": 362070,
"author": "david valentine",
"author_id": 36627,
"author_profile": "https://Stackoverflow.com/users/36627",
"pm_score": 0,
"selected": false,
"text": "nslookup www.google.com"
},
{
"answer_id": 654059,
"author": "Glenn",
"author_id": 78936,
"author_profile": "https://Stackoverflow.com/users/78936",
"pm_score": 0,
"selected": false,
"text": "public class PortChangeReflector : SoapExtensionReflector\n{ \n public override void ReflectDescription()\n {\n ServiceDescription description = ReflectionContext.ServiceDescription;\n foreach (Service service in description.Services)\n {\n foreach (Port port in service.Ports)\n {\n foreach (ServiceDescriptionFormatExtension extension in port.Extensions)\n {\n SoapAddressBinding binding = extension as SoapAddressBinding;\n if (binding != null && !binding.Location.Contains(\"8092\"))\n {\n binding.Location = binding.Location.Replace(\"92\", \"8092\");\n }\n }\n }\n }\n }\n}\n Add_Code <webServices>\n <soapExtensionReflectorTypes>\n <add type=\"Dev.PortChangeReflector,App_Code\"/>\n </soapExtensionReflectorTypes>\n</webServices>\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2327/"
] |
360,836 | <p>Now this is all way simplified, but here goes:</p>
<p>I have a User Control that consists only of a single *.ascx file. The control has no code-behind: it's just a script with a few functions, like this:</p>
<pre><code><%@ Control Language="VB" EnableViewState="False" ClassName="MyControlType" %>
<script runat="server">
Public Function MyFunction() As String
return "CalledMyFunction!"
End Function
</script>
</code></pre>
<p>That's the entire file. I can successfully add this control to an aspx page using markup like so:</p>
<pre><code><%@ Register Src="~/path/to/Control.ascx" TagPrefix="aaa" TagName="MyControl" %>
...
<aaa:MyControl runat="server" id="MyControl1" />
</code></pre>
<p>Now what I want to do is call MyFunction from the page's code-behind, like this:</p>
<pre><code>Dim someString As String = MyControl1.MyFunction()
</code></pre>
<p>Unfortunately, I can't do that. Instead, I get a compile error to the effect of "<code>'MyFunction' is not a member of 'System.Web.UI.UserControl'.</code>"</p>
<p>I've also tried this:</p>
<pre><code>Dim someString As String = DirectCast(MyControl1, MyControlType).MyFunction()
</code></pre>
<p>and then the compiler tells me, "<code>Type 'MyControlType' is not defined.</code>"</p>
<p>I've played with this a lot, and I just can't make it work. All efforts to cast MyControl1 to a more exact type have failed, as have other work-arounds. I suspect the problem is that the ascx file without a code-behind is unable to be compiled to an assembly but the code-behind wants to be compiled to an assembly and therefore the compiler gets confused about what type the control is.</p>
<p>What do I need to do to be able to call that function?</p>
<p>[edit]<br>
So I'm just gonna have to add code-behind for the user control. It's what I wanted to do anyway. I'd still like to know how to do this without needing one, though.</p>
| [
{
"answer_id": 361052,
"author": "BigJump",
"author_id": 8542,
"author_profile": "https://Stackoverflow.com/users/8542",
"pm_score": 0,
"selected": false,
"text": "<script ruant=\"server\"> \n"
},
{
"answer_id": 361078,
"author": "BigJump",
"author_id": 8542,
"author_profile": "https://Stackoverflow.com/users/8542",
"pm_score": 2,
"selected": false,
"text": "Imports Microsoft.VisualBasic\n\nPublic Class MyControlType\n Inherits UserControl\nEnd Class\n <%@ Page Language=\"VB\" AutoEventWireup=\"false\" CodeFile=\"Default.aspx.vb\" Inherits=\"_Default\" %>\n<%@ Register Src=\"~/WebUserControl.ascx\" TagPrefix=\"aaa\" TagName=\"MyControl\" %>\n...\n<aaa:MyControl runat=\"server\" id=\"MyControl1\" />\n Partial Class _Default\n Inherits System.Web.UI.Page\n\n Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)\n Dim someString As String = MyControl1.MyFunction()\n End Sub\n\nEnd Class\n <%@ Control Language=\"VB\" EnableViewState=\"False\" %>\n<script runat=\"server\">\n Public Function MyFunction() As String\n return \"CalledMyFunction!\"\n End Function\n</script>\n"
},
{
"answer_id": 361664,
"author": "user21826",
"author_id": 21826,
"author_profile": "https://Stackoverflow.com/users/21826",
"pm_score": 0,
"selected": false,
"text": "\n\n<%@ Control Language=\"VB\" ClassName=\"WebUserControl\" %>\n\n<script runat=\"server\">\n Public Function MyFunction() As String\n Return \"CalledMyFunction!\"\n End Function\n</script>\n\n \n<%@ Page Language=\"VB\" AutoEventWireup=\"false\" CodeFile=\"Default.aspx.vb\" Inherits=\"_Default\" %>\n<%@ Register Src=\"WebUserControl.ascx\" TagPrefix=\"aaa\" TagName=\"MyControl\" %>\n\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\" >\n<head runat=\"server\">\n <title>Untitled Page</title>\n</head>\n<body>\n <form id=\"form1\" runat=\"server\">\n <div>\n <aaa:MyControl runat=\"server\" ID=\"mycontrolid\" />\n <%\n Dim i As String = mycontrolid.MyFunction()\n Response.Write(i)\n %>\n </div>\n </form>\n</body>\n</html>\n"
},
{
"answer_id": 2426302,
"author": "Mani",
"author_id": 236725,
"author_profile": "https://Stackoverflow.com/users/236725",
"pm_score": -1,
"selected": false,
"text": "protected <solutionName>.<controlName> myControl1; /*C#*/\n"
},
{
"answer_id": 21572754,
"author": "Mukund Thakkar",
"author_id": 874524,
"author_profile": "https://Stackoverflow.com/users/874524",
"pm_score": -1,
"selected": false,
"text": "Public Function MyFunction() As String\n Return \"CalledMyFunction!\"\n End Function\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043/"
] |
360,844 | <p>I'd like to implement a <a href="http://en.wikipedia.org/wiki/Bloom_filter" rel="noreferrer">bloom filter</a> using MySQL (other a suggested alternative).</p>
<p>The problem is as follows:</p>
<p>Suppose I have a table that stores 8 bit integers, with these following values:</p>
<pre><code>1: 10011010
2: 00110101
3: 10010100
4: 00100110
5: 00111011
6: 01101010
</code></pre>
<p>I'd like to find all results that are bitwise AND to this:</p>
<pre><code>00011000
</code></pre>
<p>The results should be rows 1 and 5.</p>
<p>However, in my problem, they aren't 8 bit integers, but rather n-bit integers. How do I store this, and how do I query? Speed is key.</p>
| [
{
"answer_id": 361093,
"author": "Alexei Tenitski",
"author_id": 45508,
"author_profile": "https://Stackoverflow.com/users/45508",
"pm_score": 4,
"selected": false,
"text": "number\n\n154\n53\n148\n38\n59\n106\n SELECT * FROM test WHERE number & 24 = 24\n INSERT INTO test SET number = b'00110101';\n SELECT bin(number) FROM test WHERE number & b'00011000' = b'00011000'\n"
},
{
"answer_id": 28498755,
"author": "cWarren",
"author_id": 895732,
"author_profile": "https://Stackoverflow.com/users/895732",
"pm_score": 2,
"selected": false,
"text": "SELECT * FROM test WHERE cast(filter, UNSIGNED) & cast(?, UNSIGNED) = cast(?, UNSIGNED) filter char* char* unsigned char* target & candidate = target my_bool bloommatch(UDF_INIT *initid, UDF_ARGS *args, char* result, unsigned long* length, char *is_null, char *error)\n{\n if (args->lengths[0] > args->lengths[1])\n {\n return 0;\n }\n char* b1=args->args[0];\n char* b2=args->args[1];\n int limit = args->lengths[0];\n unsigned char a;\n unsigned char b;\n int i;\n for (i=0;i<limit;i++)\n {\n a = (unsigned char) b1[i];\n b = (unsigned char) b2[i];\n if ((a & b) != a)\n {\n return 0;\n }\n }\n return 1;\n}\n"
},
{
"answer_id": 58397819,
"author": "Barry Kelly",
"author_id": 3712,
"author_profile": "https://Stackoverflow.com/users/3712",
"pm_score": 1,
"selected": false,
"text": "bigint"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43005/"
] |
360,849 | <p>From what I understand, in TDD you have to write a failing test first, then write the code to make it pass, then refactor. But what if your code already accounts for the situation you want to test?</p>
<p>For example, lets say I'm TDD'ing a sorting algorithm (this is just hypothetical). I might write unit tests for a couple of cases: <br></p>
<p>input = 1, 2, 3<br>
output = 1, 2, 3
<br>
<br>
input = 4, 1, 3, 2<br>
output = 1, 2, 3, 4
<br>
etc...
<p>
To make the tests pass, I wind up using a quick 'n dirty bubble-sort. Then I refactor and replace it with the more efficient merge-sort algorithm. Later, I realize that we need it to be a stable sort, so I write a test for that too. Of course, the test will never fail because merge-sort is a stable sorting algorithm! Regardless, I still need this test incase someone refactors it again to use a different, possibly unstable sorting algorithm.
<p>
Does this break the TDD mantra of always writing failing tests? I doubt anyone would recommend I waste the time to implement an unstable sorting algorithm just to test the test case, then reimplement the merge-sort. How often do you come across a similar situation and what do you do?</p>
| [
{
"answer_id": 360875,
"author": "David Norman",
"author_id": 34502,
"author_profile": "https://Stackoverflow.com/users/34502",
"pm_score": 2,
"selected": false,
"text": "assertTrue(x = 1);\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32998/"
] |
360,851 | <p>What is the syntax to concatenate text into a binding expression for an asp.net webpage (aspx).</p>
<p>For example if I had a hyperlink that was being bound like this:</p>
<pre><code><asp:HyperLink id="lnkID" NavigateUrl='<%# Bind("Link") %>' Target="_blank"
Text="View" runat="server"/>
</code></pre>
<p>How do you change, say, the Text to concatenate a bound value with a string? Variations like this aren't quite right.</p>
<pre><code>Text='<%# Bind("ID") + " View" %>'
</code></pre>
<p>neither does</p>
<pre><code>Text='<%# String.Concat(Bind("ID"), " View") %>'
</code></pre>
| [
{
"answer_id": 360865,
"author": "Andrew Rollings",
"author_id": 40410,
"author_profile": "https://Stackoverflow.com/users/40410",
"pm_score": 2,
"selected": false,
"text": "String.Format(\"{0}{1}\""
},
{
"answer_id": 360936,
"author": "TheEmirOfGroofunkistan",
"author_id": 1874,
"author_profile": "https://Stackoverflow.com/users/1874",
"pm_score": 5,
"selected": false,
"text": "Text='<%# Eval(\"ID\", \"{0} View\") %>'\n"
},
{
"answer_id": 364328,
"author": "TheEmirOfGroofunkistan",
"author_id": 1874,
"author_profile": "https://Stackoverflow.com/users/1874",
"pm_score": 4,
"selected": true,
"text": "<asp:TemplateField HeaderText=\"Name\" SortExpression=\"sortName\">\n<ItemTemplate>\n <asp:LinkButton ID=\"lbName\" runat=\"server\" OnClick=\"lbName_Click\" CommandArgument='<%# Eval(\"ID\") %>'>\n <%--Enter any text / eval bindind you want between the tags--%>\n <%# Eval(\"Name\") %> (<%# Eval(\"ID\") %>)\n </asp:LinkButton>\n</ItemTemplate>\n"
},
{
"answer_id": 58834112,
"author": "Lea",
"author_id": 12365909,
"author_profile": "https://Stackoverflow.com/users/12365909",
"pm_score": 1,
"selected": false,
"text": "CommandArgument='<%#String.Format(\"{0}|{1}\", Eval(\"ArgZero\"), Eval(\"ArgOn\"))%>'\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1874/"
] |
360,877 | <pre><code>private static final GridLayout layout = new GridLayout( 3, 1, 1, 0 );
</code></pre>
<p>in this line of code what do the numbers represent and how do you use them to arrange the checkboxes and buttons in the window?</p>
| [
{
"answer_id": 361593,
"author": "Joe Liversedge",
"author_id": 4552,
"author_profile": "https://Stackoverflow.com/users/4552",
"pm_score": 3,
"selected": false,
"text": "public GridLayout(int rows,\n int cols,\n int hgap,\n int vgap)\n\nCreates a grid layout with the specified number of rows and columns. All components in the layout are given equal size.\nIn addition, the horizontal and vertical gaps are set to the specified values. Horizontal gaps are placed between each of the columns. Vertical gaps are placed between each of the rows.\n\nOne, but not both, of rows and cols can be zero, which means that any number of objects can be placed in a row or in a column.\n\nAll GridLayout constructors defer to this one.\n\nParameters:\nrows - the rows, with the value zero meaning any number of rows\ncols - the columns, with the value zero meaning any number of columns\nhgap - the horizontal gap\nvgap - the vertical gap\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
360,889 | <p>I'm looking for a tool (or a set of tools) for Windows that will perform the following:</p>
<ol>
<li>Capture UDP packets from a specific network interface to a file.</li>
<li>Play a stream of packets from a file through a network interface.</li>
<li>In addition to 2: replay the original packets to a different host than the original one.</li>
</ol>
<p>I've already got 1 and 2, but I can't find a tool to do 3.</p>
<p>For capturing I can use <a href="http://www.wireshark.org" rel="noreferrer">Wireshark</a>, for playback <a href="http://www.colasoft.com/packet_player/index.php?click=text" rel="noreferrer">Colasoft Packet Player</a>, but I couldn't find a way to change the host the packets are sent to.</p>
<p>The tool should work on Windows XP SP2/3.</p>
| [
{
"answer_id": 13054921,
"author": "spxl",
"author_id": 1207973,
"author_profile": "https://Stackoverflow.com/users/1207973",
"pm_score": 3,
"selected": true,
"text": "bittwiste"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33982/"
] |
360,899 | <p>I have been working on this for the greater part of the day and I cant seem to make this part of my code work. The intent of the code is to allow the user to input a set of values in order to calculate the missing value. As an additional feature I placed a CheckBox on the form to allow the user to do further calculation. That is where my problem lies. I know the code works because if I change the formula the value that appears in tb3_aic.Text changes per the formula. However, when I use the below the answer does not change like it should. Please reference the attached code. If a jpg image is needed of the formula I can e-mail it. </p>
<pre><code> void Calc3Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(tb3_skv.Text) | String.IsNullOrEmpty(tb3_kva.Text) | String.IsNullOrEmpty(tb3_z.Text))
{
MessageBox.Show("Enter all required values", "Missing Data", MessageBoxButtons.OK);
} //If user does not enter all the values required for the calculation show error message box
else
{
if (!String.IsNullOrEmpty(tb3_skv.Text) & !String.IsNullOrEmpty(tb3_kva.Text) & !String.IsNullOrEmpty(tb3_z.Text))
{ //If motor load check box is not checked and required values are entered calculate AIC based on formula.
int y;
decimal x, z, a;
x = decimal.Parse(tb3_skv.Text);
y = int.Parse(tb3_kva.Text);
a = decimal.Parse(tb3_z.Text);
z = (y * 1000) / (x * 1.732050808m) / (a / 100); //the m at the end of the decimal allows for the multiplication of decimals
tb3_aic.Text = z.ToString();
tb3_aic.Text = Math.Round(z,0).ToString();
}
if (cb3_ml.Checked==true)
{//If Motor Load CB is checked calculate the following
int y, b;
decimal x, z, a;
x = decimal.Parse(tb3_skv.Text);
y = int.Parse(tb3_kva.Text);
a = decimal.Parse(tb3_z.Text);
b = int.Parse(tb3_ml.Text);
z = ((y * 1000) / (x * 1.732050808m) / (a / 100))+((b / 100)*(6*y)/(x*1.732050808m)*1000);
tb3_aic.Text = z.ToString();
tb3_aic.Text = Math.Round(z,5).ToString();
}
}
</code></pre>
<p>I am grateful for any help that can be provided. </p>
<p>Thank you,
Greg Rutledge</p>
| [
{
"answer_id": 360946,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 2,
"selected": false,
"text": "int y, b;\n int y;\ndecimal b;\n public void Test2()\n {\n int y;\n decimal b;\n decimal x, z, a;\n decimal z1, z2;\n x = 480m;\n y = 2500;\n a = 5.75m;\n b = 10;\n z1 = ((y * 1000) / (x * 1.732050808m) / (a / 100));\n z2 = ((b / 100) * (6 * y) / (x * 1.732050808m) * 1000);\n z = z1 + z2;\n Console.WriteLine(\"{0}, {1}\", z1, z2);\n Console.WriteLine(Math.Round(z, 0).ToString());\n }\n"
},
{
"answer_id": 360952,
"author": "Programmin Tool",
"author_id": 21691,
"author_profile": "https://Stackoverflow.com/users/21691",
"pm_score": 0,
"selected": false,
"text": "tb3_aic.Text = z.ToString();\ntb3_aic.Text = Math.Round(z,0).ToString();\n"
},
{
"answer_id": 360974,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 0,
"selected": false,
"text": "if (!String.IsNullOrEmpty(tb3_skv.Text) & !String.IsNullOrEmpty(tb3_kva.Text) & !String.IsNullOrEmpty(tb3_z.Text)) {\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45151/"
] |
360,912 | <p>If an application† crashes,</p>
<p><a href="https://i.stack.imgur.com/o8DiZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/o8DiZ.png" alt="enter image description here"></a></p>
<p>I hit "Debug" and Visual Studio is my currently registered Just-In-Time (JIT) debugger:</p>
<p><a href="https://i.stack.imgur.com/SKRAS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SKRAS.png" alt="enter image description here"></a></p>
<p>Visual Studio appears, but there's no way to debug anything:</p>
<p><a href="https://i.stack.imgur.com/Yc8tK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Yc8tK.png" alt="enter image description here"></a></p>
<ul>
<li>I do not see any disassembly</li>
<li>I do not see any registers (assuming it runs on a CPU with registers)</li>
<li>The call stack is empty (assuming the CPU has a stack pointer)</li>
<li>I do not see any symbols (assuming it had any)</li>
<li>I do not see reconstructed source code from reflection (assuming it was managed)</li>
</ul>
<p>Other JIT debugger products are able to show disassembly, but they are either command-line based (<a href="http://www.microsoft.com/whdc/devtools/debugging/default.mspx" rel="nofollow noreferrer">Debugging Tools for Windows</a>), or do not support symbols (<a href="http://www.ollydbg.de/" rel="nofollow noreferrer">OllyDbg</a>, <a href="http://en.wikipedia.org/wiki/Borland_Delphi" rel="nofollow noreferrer">Delphi</a>). Additionally, my question is about debugging using Visual Studio, since I already have it installed, and it is already my registered JIT.</p>
<p>How do you debug a program using Visual Studio?</p>
<p><strong>Alternatively</strong>: has anyone written a graphical debugger that supports the Microsoft symbol server?</p>
<p>† Not, necessarily, written in Visual Studio.</p>
<p><strong>Edit:</strong> Changes title to <strong>process</strong> rather than <strong>application</strong>, since the latter somehow implies "<em>my</em> application."</p>
<p><strong>Edit:</strong> Assume the original application was written in assembly language by Steve Gibson. That is, there is no source code or debug information. Visual Studio should still be able to show me an assembly dump.</p>
| [
{
"answer_id": 2464489,
"author": "i_am_jorf",
"author_id": 74815,
"author_profile": "https://Stackoverflow.com/users/74815",
"pm_score": 1,
"selected": false,
"text": "http://msdl.microsoft.com/download/symbols"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12597/"
] |
360,913 | <p>How do I update my subversion repository so it can accept updates to the log message field? I've got a Windows installation and I changed the pre-revprop-change.tmpl file name to a batch file, but now when I try to update a the log message property my tortoise svn just hangs and the property isn't updated. Am I doing something wrong? </p>
<p>Since its so small, my pre-revprop-change.bat file is below</p>
<pre><code>REPOS="$1"
REV="$2"
USER="$3"
PROPNAME="$4"
ACTION="$5"
if [ "$ACTION" = "M" -a "$PROPNAME" = "svn:log" ]; then exit 0; fi
echo "Changing revision properties other than svn:log is prohibited" >&2
exit 1
</code></pre>
| [
{
"answer_id": 2464489,
"author": "i_am_jorf",
"author_id": 74815,
"author_profile": "https://Stackoverflow.com/users/74815",
"pm_score": 1,
"selected": false,
"text": "http://msdl.microsoft.com/download/symbols"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18927/"
] |
360,928 | <p>I have a table (SQL 2000) with over 10,000,000 records. Records get added at a rate of approximately 80,000-100,000 per week. Once a week a few reports get generated from the data. The reports are typically fairly slow to run because there are few indexes (presumably to speed up the INSERTs). One new report could really benefit from an additional index on a particular "char(3)" column.</p>
<p>I've added the index using Enterprise Manager (Manage Indexes -> New -> select column, OK), and even rebuilt the indexes on the table, but the SELECT query has not sped up at all. Any ideas?</p>
<p><strong>Update</strong>:</p>
<p>Table definition:</p>
<pre><code>ID, int, PK
Source, char(3) <--- column I want indexed
...
About 20 different varchar fields
...
CreatedDate, datetime
Status, tinyint
ExternalID, uniqueidentifier
</code></pre>
<p>My test query is just:</p>
<pre><code>select top 10000 [field list] where Source = 'abc'
</code></pre>
| [
{
"answer_id": 361403,
"author": "jmucchiello",
"author_id": 44065,
"author_profile": "https://Stackoverflow.com/users/44065",
"pm_score": 0,
"selected": false,
"text": " select top 10000 \n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1664/"
] |
360,935 | <p>I have a menu of report links in my master page. I need to append an ID to the end of each whenever the user changes a value on the child page. What's a good way to accomplish this?</p>
<p>UPDATE: I should have mentioned that the child update is happening inside an UpdatePanel, meaning the master page is not reloaded when the change happens.</p>
| [
{
"answer_id": 361010,
"author": "jrcs3",
"author_id": 3819,
"author_profile": "https://Stackoverflow.com/users/3819",
"pm_score": 2,
"selected": false,
"text": "public partial class _default : System.Web.UI.MasterPage\n{\n protected string m_myString = string.Empty;\n public string myString\n {\n get { return m_myString; }\n set { m_myString = value; }\n }\n protected void Page_Load(object sender, EventArgs e)\n {\n\n }\n}\n public partial class index : System.Web.UI.Page\n{\n protected void Page_Load(object sender, EventArgs e)\n {\n // Cast here to get access to your MasterPage\n _default x = (_default)this.Master;\n x.myString = \"foo\";\n }\n}\n"
},
{
"answer_id": 362094,
"author": "jrcs3",
"author_id": 3819,
"author_profile": "https://Stackoverflow.com/users/3819",
"pm_score": 1,
"selected": true,
"text": "Request.Form[\"fieldName\"] fieldName.Text"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23935/"
] |
360,943 | <p>I have a problem on how to read text from file and perform operations on it for example</p>
<p>i have this text file that include</p>
<p>//name-//sex---------//birth //m1//m2//m3</p>
<pre><code>fofo, male, 1986, 67, 68, 69
momo, male, 1986, 99, 98, 100
Habs, female, 1988, 99, 100, 87
toto, male, 1989, 67, 68, 69
lolo, female, 1990, 89, 80, 87
soso, female, 1988, 99, 100, 83
</code></pre>
<p>now i know how to read line by line till i reach null .</p>
<p>but this time I want later to perform and average function to get the average of the first colume of numbers m1</p>
<p>and then get the average of m1 for females only and for males only</p>
<p>and some other operations that i can do no problem</p>
<hr>
<p>I need help i don't know how to get it
what i have in mind is to read each line in the text file and put it in a string then split the string (str.Split(','); ) but how to get the m1 record on each string
I'm really confused should i use regex to get the integers ? should i use an array 2d? I'm totally lost, any ideas? </p>
<p>please if u can improve any ideas by a code sample that will be great and a kindness initiation from u.</p>
<p>and after i done it i will post it for you guys to check.</p>
<p>{ as a girl I Think I made the wrong decision to join the IT community :-( }</p>
| [
{
"answer_id": 360996,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 1,
"selected": false,
"text": "List<T> using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing MiscUtil.Linq;\nusing MiscUtil.Linq.Extensions;\nstatic class Program\n{\n\n static void Main()\n {\n // prepare a query that is capable of parsing\n // the input file into the expected format\n string path = \"foo.txt\";\n var qry = from line in ReadLines(path)\n let arr = line.Split(',')\n select new\n {\n Name = arr[0].Trim(),\n Male = arr[1].Trim() == \"male\",\n Birth = int.Parse(arr[2].Trim()),\n M1 = int.Parse(arr[3].Trim())\n // etc\n };\n\n // get a \"data producer\" to start the query process\n var producer = CreateProducer(qry);\n\n // prepare the overall average\n var avg = producer.Average(row => row.M1);\n\n // prepare the gender averages\n var avgMale = producer.Where(row => row.Male)\n .Average(row => row.M1); \n var avgFemale = producer.Where(row => !row.Male)\n .Average(row => row.M1);\n\n // run the query; until now *nothing has happened* - we haven't\n // even opened the file \n producer.ProduceAndEnd(qry);\n\n // show the results\n Console.WriteLine(avg.Value);\n Console.WriteLine(avgMale.Value);\n Console.WriteLine(avgFemale.Value);\n }\n // helper method to get a DataProducer<T> from an IEnumerable<T>, for\n // use with the anonymous type\n static DataProducer<T> CreateProducer<T>(IEnumerable<T> data)\n {\n return new DataProducer<T>();\n }\n // this is just a lazy line-by-line file reader (iterator block) \n static IEnumerable<string> ReadLines(string path)\n {\n using (var reader = File.OpenText(path))\n {\n string line;\n while ((line = reader.ReadLine()) != null)\n {\n yield return line;\n }\n }\n }\n\n}\n"
},
{
"answer_id": 361033,
"author": "Tim Jarvis",
"author_id": 10387,
"author_profile": "https://Stackoverflow.com/users/10387",
"pm_score": 3,
"selected": false,
"text": " var qry = from line in File.ReadAllLines(@\"C:\\Temp\\Text.txt\")\n let vals = line.Split(new char[] { ',' })\n select new\n {\n Name = vals[0].Trim(),\n Sex = vals[1].Trim(),\n Birth = vals[2].Trim(),\n m1 = Int32.Parse(vals[3]),\n m2 = Int32.Parse(vals[4]),\n m3 = Int32.Parse(vals[5])\n };\n\n double avg = qry.Average(a => a.m1);\n double GirlsAvg = qry.Where(a => a.Sex == \"female\").Average(a => a.m1);\n double BoysAvg = qry.Where(a => a.Sex == \"male\").Average(a => a.m1);\n"
},
{
"answer_id": 361946,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 0,
"selected": false,
"text": "// rows is the jagged array of string1, string2 etc\nint totalCounter = 0, totalSum = 0; // etc\nforeach(string[] row in rows)\n{\n int m1 = int.Parse(row[3]);\n totalCounter++;\n totalSum += m1;\n switch(row[2]) {\n case \"male\":\n maleCount++;\n maleSum += m1;\n break;\n case \"female\":\n femaleCount++;\n femaleSum += m1;\n break;\n }\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
360,961 | <p>I've got a table, called faq_questions with the following structure:</p>
<pre><code>id int not_null auto_increment,
question varchar(255),
sort_order int
</code></pre>
<p>I'm attempting to build a query that given a sort order, selects the row with the next highest sort order. </p>
<p>Example:</p>
<pre><code>id question sort_order
1 'This is question 1' 10
2 'This is question 2' 9
3 'This is another' 8
4 'This is another one' 5
5 'This is yet another' 4
</code></pre>
<p>Ok, so imagine I pass in 5 for my known sort order (id 4), I need it to return the row with id 3. Since there's no guarantee that sort_order will be contiguous I can't just select known_sort_order + 1. </p>
<p>Thanks! </p>
| [
{
"answer_id": 360975,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": 6,
"selected": true,
"text": "SELECT id,question FROM `questions` \nWHERE `sort_order` > sort_order_variable\nORDER BY sort_order ASC \nLIMIT 1\n"
},
{
"answer_id": 360976,
"author": "dkretz",
"author_id": 31641,
"author_profile": "https://Stackoverflow.com/users/31641",
"pm_score": 2,
"selected": false,
"text": "TOP LIMIT SELECT TOP 1 * FROM faq_questions\nWHERE sort_order > 5\nORDER BY sort_order ASC\n SELECT * \nFROM faq_questions AS f1 \nLEFT JOIN faq_questions AS f2 \n ON f1.sort_order > f2.sort_order \n AND f2.sort_order = 5 \nLEFT JOIN faq_questions AS f3 \n ON f3.sort_order BETWEEN f1.sort_order AND f2.sort_order \nWHERE f3.id IS NULL\n"
},
{
"answer_id": 360983,
"author": "Electronic Zebra",
"author_id": 1742702,
"author_profile": "https://Stackoverflow.com/users/1742702",
"pm_score": 0,
"selected": false,
"text": "SELECT \n id, question, sort_order\nFROM faq_questions \nWHERE sort_order in \n(SELECT \n MIN(sort_order) \n FROM faq_questions \n WHERE sort_order > ?);\n"
},
{
"answer_id": 360993,
"author": "Alexei Tenitski",
"author_id": 45508,
"author_profile": "https://Stackoverflow.com/users/45508",
"pm_score": 2,
"selected": false,
"text": "SELECT * FROM table_name WHERE sort_order > 5 ORDER BY sort_order ASC LIMIT 1\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1742702/"
] |
360,968 | <p>I'm seeing some code I've inherited that looks like the following:</p>
<pre><code>@interface SomeClass (private)
</code></pre>
<p>This is within <code>SomeClass.m</code>, the implementation file. There is an accompanying header file which doesn't suggest that the class is using a category. Is <code>(private)</code> in this case just a poor name given to a category for <code>SomeClass</code>? And I'm assuming it's perfectly legitimate to specify categories such as these in an implementation?</p>
| [
{
"answer_id": 361140,
"author": "Abizern",
"author_id": 41116,
"author_profile": "https://Stackoverflow.com/users/41116",
"pm_score": 6,
"selected": true,
"text": "@interface NSString (Capitals)\n\n-(NSString *)alternateCaps:(NSString *)aString;\n\n@end\n @implementation NSString (Capitals)\n-(NSString *)alternateCaps:(NSString *)aString\n{\n // Implementation\n}\n // someClass.m\n@interface someClass (extension)\n-(void)extend;\n@end\n\n@implementation someClass\n // all the methods declared in the .h file and any superclass\n // overrides in this block\n@end\n\n@implementation someClass (extension)\n-(void)extend {\n // implement private method here;\n}\n // someClass.m\n@interface someClass ()\n-(void)extend;\n@end\n\n@implementation someClass\n // all the methods declared in the .h file and any superclass\n // overrides in this block\n // Implement private methods in this block as well.\n-(void)extend {\n // implement private method here;\n}\n\n@end\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40882/"
] |
360,982 | <p>I was searching here about converting a string like "16:20" to a DateTime type without losing the format, I said I dont want to add dd/MM/yyy or seconds or AM/PM, because db just accept this format.</p>
<p>I tried with Cultures yet</p>
<p>Thanks in Advance</p>
| [
{
"answer_id": 360998,
"author": "MartinHN",
"author_id": 2972,
"author_profile": "https://Stackoverflow.com/users/2972",
"pm_score": 2,
"selected": false,
"text": "DateTime dt = new DateTime(2008, 12, 11, Convert.ToInt32(\"16\"), Convert.ToInt32(\"32\"), 0);\n"
},
{
"answer_id": 361000,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "HH:mm"
},
{
"answer_id": 361032,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 1,
"selected": false,
"text": "DateTime.Parse(\"16:20\")\n"
},
{
"answer_id": 361095,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 5,
"selected": true,
"text": "TimeSpan span = TimeSpan.Parse(\"16:20\");\n TimeSpan span = TimeSpan.Parse(\"16.20\");\nDateTime dt = DateTime.MinValue.Add(span);\n// will get you 1/1/1900 4:20 PM which can be formatted with .ToString(\"HH:mm\") for 24 hour formatting\n"
},
{
"answer_id": 12089805,
"author": "Arno",
"author_id": 565194,
"author_profile": "https://Stackoverflow.com/users/565194",
"pm_score": 5,
"selected": false,
"text": "string DateFormat = \"yyyy MM d \" string DateFormat = \"yyyy MM d HH:mm:ss \" 24 hours time format \"h\" will give you the 12 hours time string DateFormat = \"yyyyMMdHHmmss\";\nstring date = DateTime.Now.ToStrign(DateFormat);\n Console.writeline(DateTime.Now.ToStrign(DateFormat));\n 20120823132544\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1388553/"
] |
360,990 | <p>I am looking to get a list of the column names returned from a Model. Anyone know how this would be done, any help would be greatly appreciated.</p>
<p>Example Code:</p>
<pre><code>var project = db.Projects.Single(p => p.ProjectID.Equals(Id));
</code></pre>
<p>This code would return the Projects object, how would I get a list of all the column names in this Model.</p>
<p>Thanks</p>
| [
{
"answer_id": 361201,
"author": "shahkalpesh",
"author_id": 23574,
"author_profile": "https://Stackoverflow.com/users/23574",
"pm_score": 2,
"selected": true,
"text": "DataContext Mapping MetaModel MetaModel GetMetaType Type typeof(Project) GetMetaType MetaType GetDataMember MemberInfo Projects MemberInfo MetaDataMember GetDataMember"
},
{
"answer_id": 362745,
"author": "tsquillario",
"author_id": 45509,
"author_profile": "https://Stackoverflow.com/users/45509",
"pm_score": 3,
"selected": false,
"text": "var db = new GMPDataContext();\nvar columnNames = db.Mapping.MappingSource\n .GetModel(typeof(GMPDataContext))\n .GetMetaType(typeof(Project))\n .DataMembers;\n"
},
{
"answer_id": 363746,
"author": "Todd Smith",
"author_id": 31624,
"author_profile": "https://Stackoverflow.com/users/31624",
"pm_score": 4,
"selected": false,
"text": "public static class LinqExtensions\n{\n public static ReadOnlyCollection<MetaDataMember> ColumnNames<TEntity> (this DataContext source)\n {\n return source.Mapping.MappingSource.GetModel (typeof (DataContext)).GetMetaType (typeof (TEntity)).DataMembers;\n }\n}\n var columnNames = myDataContext.ColumnNames<Orders> ();\n"
},
{
"answer_id": 5501103,
"author": "Contra",
"author_id": 112508,
"author_profile": "https://Stackoverflow.com/users/112508",
"pm_score": 2,
"selected": false,
"text": "var columnNames = db.ColumnNames<Orders>().Where(n => n.Member.GetCustomAttributes(typeof(System.Data.Linq.Mapping.ColumnAttribute), false).FirstOrDefault() != null).Select(n => n.Name);\n"
},
{
"answer_id": 20968853,
"author": "Nalan Madheswaran",
"author_id": 1217713,
"author_profile": "https://Stackoverflow.com/users/1217713",
"pm_score": 0,
"selected": false,
"text": " public string[] GetColumnNames()\n {\n var propnames = GetPropertyNames(_context.Users);\n return propnames.ToArray();\n }\n\n static IEnumerable<string> GetPropertyNames<T>(IEnumerable<T> lst)\n {\n foreach (var pi in typeof(T).GetProperties())\n {\n yield return pi.Name;\n }\n }\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45509/"
] |
360,992 | <p>Can anyone explain the differences between <strong>Protocols</strong> and <strong>Categories</strong> in Objective-C? When do you use one over the other?</p>
| [
{
"answer_id": 361067,
"author": "mipadi",
"author_id": 28804,
"author_profile": "https://Stackoverflow.com/users/28804",
"pm_score": 8,
"selected": true,
"text": "NSObject NSObject NSObject"
},
{
"answer_id": 361072,
"author": "e.James",
"author_id": 33686,
"author_profile": "https://Stackoverflow.com/users/33686",
"pm_score": 4,
"selected": false,
"text": "NSView NSView NSView NSView NSView #import NSView"
},
{
"answer_id": 361133,
"author": "Alex",
"author_id": 35999,
"author_profile": "https://Stackoverflow.com/users/35999",
"pm_score": 5,
"selected": false,
"text": "@protocol @protocol @optional @required @protocol"
},
{
"answer_id": 661647,
"author": "dreamlax",
"author_id": 10320,
"author_profile": "https://Stackoverflow.com/users/10320",
"pm_score": 1,
"selected": false,
"text": "NSString *test = @\"Leet speak\";\nNSString *leet = [test stringByConvertingToLeet];\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/360992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40882/"
] |
361,002 | <p>For fun, I'm trying to write one of my son's favorite board games as a piece of software. Eventually I expect to build a WPF UI on top of it, but right now I'm building the machine that models the games and its rules.</p>
<p>As I do this, I keep seeing problems that I think are common to many board games, and perhaps others have already solved them better than I will. </p>
<p>(Note that AI to play the game, and patterns around high performance are not interesting to me.)</p>
<p>So far my patterns are:</p>
<ul>
<li><p>Several immutable types representing entities in the game box, e.g. dice, checkers, cards, a board, spaces on the board, money, etc.</p></li>
<li><p>An object for each player, which contains the players resources (e.g. money, score), their name, etc.</p></li>
<li><p>An object that represents the state of the game: the players, who's turn it is, the layout of the peices on the board, etc.</p></li>
<li><p>A state machine that manages the turn sequence. For example, many games have a small pre-game where each player rolls to see who goes first; that's the start state. When a player's turn starts, first they roll, then they move, then they have to dance in place, then other players guess what breed of chicken they are, then they receive points.</p></li>
</ul>
<p>Is there some prior art I can take advantage of?</p>
<p><strong>EDIT:</strong> One thing I realized recently is that game state can be split in to two categories:</p>
<ul>
<li><p><strong>Game artifact state</strong>. "I have $10" or "my left hand is on blue".</p></li>
<li><p><strong>Game sequence state</strong>. "I have rolled doubles twice; the next one puts me in jail". A state machine may make sense here.</p></li>
</ul>
<p><strong>EDIT:</strong> What I'm really looking for here is the <em>best</em> way to implement multiplayer turn-based games like Chess or Scrabble or Monopoly. I'm sure I could create such a game by just working through it start to finish, but, like other Design Patterns, there are probably some ways to make things go much more smoothly that aren't obvious without careful study. That's what I'm hoping for. </p>
| [
{
"answer_id": 361254,
"author": "Stefan",
"author_id": 19307,
"author_profile": "https://Stackoverflow.com/users/19307",
"pm_score": 3,
"selected": false,
"text": "1 2 3 \n4 (5) 6 BoardArray 5 = row 2, col 2\n7 8 9 \n"
},
{
"answer_id": 558437,
"author": "Andrew Top",
"author_id": 30036,
"author_profile": "https://Stackoverflow.com/users/30036",
"pm_score": 8,
"selected": true,
"text": "class RollDice : public Action\n{\n public:\n RollDice(int player);\n\n virtual void Apply(GameState& gameState) const; // Apply the action to the gamestate, modifying the gamestate\n virtual bool IsLegal(const GameState& gameState) const; // Returns true if this is a legal action\n};\n"
},
{
"answer_id": 572678,
"author": "Pyrolistical",
"author_id": 21838,
"author_profile": "https://Stackoverflow.com/users/21838",
"pm_score": 4,
"selected": false,
"text": "GamePhase abstract public GamePhase turn();\n GamePhase turn() GamePhase GamePhase turn() turn() GamePhase turn() GamePhase state = ...initial phase\nwhile(true) {\n // read the state, do some ui work\n state = state.turn();\n}\n GamePhase turn() Player Strategy Strategy Player Strategy GamePhase GamePhase GamePhase GamePhase CommunityChestAdvanceToGo PlayerLandsOnGo PlayerLandsOnGo"
},
{
"answer_id": 24321562,
"author": "Reasurria",
"author_id": 2790482,
"author_profile": "https://Stackoverflow.com/users/2790482",
"pm_score": 2,
"selected": false,
"text": "StartPhase();\nEndPhase();\nAction();\n phase = new MovePhase();\nphase.StartPhase();\n GameState state; //Set in constructor.\nDie die; // Only relevant to the roll phase.\nint doublesRemainingBeforeJail;\nStartPhase()\n{\n die = new Die();\n doublesRemainingBeforeJail = 3;\n}\n\nAction()\n{\n if(doublesRemainingBeforeJail<=0)\n {\n state.phase = new JailPhase(); // JailPhase::StartPhase(){set moves to 0}; \n state.phase.StartPhase();\n return;\n }\n\n int die1 = die.Roll();\n int die2 = die.Roll();\n\n if(die1 == die2)\n {\n --doublesRemainingBeforeJail;\n state.activePlayer.AddMovesRemaining(die1 + die2);\n Action(); //Roll again.\n }\n\n state.activePlayer.AddMovesRemaining(die1 + die2);\n this.EndPhase(); // Continue to moving phase. Player has X moves remaining.\n}\n While(movesRemaining>0)\n AdvanceTo(currentTile.nextTile);\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5314/"
] |
361,049 | <p>I have a web application deployed in an internet hosting provider. This web application consumes a WCF Service deployed at an IIS server located at my company’s application server, in order to have data access to the company’s database, the network guys allowed me to expose this WCF service through a firewall for security reasons. A diagram would look like this. </p>
<blockquote>
<p>[Hosted page] ---> (Internet) ---> |Firewall <code><Public IP>:<Port-X ></code>|
---> [IIS with WCF Service <code><Comp. Network Ip>:<Port-Y></code>]</p>
</blockquote>
<p>I also wanted to use wsHttpBinding to take advantage of its security features, and encrypt sensible information.</p>
<p>After trying it out I get the following error:</p>
<blockquote>
<p>Exception Details: System.ServiceModel.EndpointNotFoundException: The
message with To 'http://:/service/WCFService.svc' cannot be
processed at the receiver, due to an AddressFilter mismatch at the
EndpointDispatcher. Check that the sender and receiver's
EndpointAddresses agree.</p>
</blockquote>
<p>Doing some research I found out that wsHttpBinding uses WS-Addressing standards, and reading about this standard I learned that the SOAP header is enhanced to include tags like ‘MessageID’, ‘ReplyTo’, ‘Action’ and ‘To’.</p>
<p>So I’m guessing that, because the client application endpoint specifies the Firewall IP address and Port, and the service replies with its internal network address which is different from the Firewall’s IP, then WS-Addressing fires the above message. Which I think it’s a very good security measure, but it’s not quite useful in my scenario.</p>
<p>Quoting the WS-Addressing standard submission (<a href="http://www.w3.org/Submission/ws-addressing/" rel="nofollow noreferrer">http://www.w3.org/Submission/ws-addressing/</a>) </p>
<blockquote>
<p>"Due to the range of network technologies currently in wide-spread use
(e.g., NAT, DHCP, firewalls), many deployments cannot assign a
meaningful global URI to a given endpoint. To allow these ‘anonymous’
endpoints to initiate message exchange patterns and receive replies,
WS-Addressing defines the following well-known URI for use by
endpoints that cannot have a stable, resolvable URI.
<a href="http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous" rel="nofollow noreferrer">http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a>"</p>
</blockquote>
<p><strong>HOW can I configure my wsHttpBinding Endpoint to address my Firewall’s IP and to ignore or bypass the address specified in the ‘To’ WS-Addressing tag in the SOAP message header? Or do I have to change something in my service endpoint configuration?</strong></p>
<p>Help and guidance will be much appreciated.</p>
<p>Marko.</p>
<p>P.S.: While I find any solution to this, I’m using basicHttpBinding with absolutely no problem of course.</p>
| [
{
"answer_id": 362108,
"author": "Mitch Baker",
"author_id": 37896,
"author_profile": "https://Stackoverflow.com/users/37896",
"pm_score": 4,
"selected": true,
"text": "[ServiceBehavior(AddressFilterMode = AddressFilterMode.Any)]\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45516/"
] |
361,066 | <p>I recently <a href="https://stackoverflow.com/questions/353912/functional-programming-state-vs-reassignment">asked a question</a> about functional programming, and received (good!) answers that prompted more questions (as seems to be the case with learning, sometimes). Here are a couple examples:</p>
<ol>
<li><p>One answer made reference to an advantage of immutable data structures: each thread can have its own copy. Now, to me, this sounds rather like a version control system (to use an analogy), where instead of locking code that someone has checked out so that it can't be modified by anyone else, everyone can check out their own copies. Sounds good. However, in VCS you have the concept of "merging" changes, in the case that two people changed the same stuff. It seems like this issue could certainly come up in a multithreaded scenario... so how is "merging" done when it's important that threads see the most recent data?</p></li>
<li><p><a href="https://stackoverflow.com/questions/353912/functional-programming-state-vs-reassignment#355040">This answer</a> talked about the case where operations were being performed in a loop on an object, and how you can use a new object each time through instead of updating an old one. However, let's say the <code>bankAccount</code> is being updated in a non-loop scenario--for example a GUI banking system. The operator clicks the "Change Interest Rate" button, which fires an event that would (in C# for example) do something like <code>bankAccount.InterestRate = newRateFromUser</code>. I feel like I'm being dense here, but hopefully my example makes sense: there has to be some way that the object is updated, right? Several other things may depend on the the new data.</p></li>
</ol>
<p>Anyway, if you can help me get my head around the paradigm shift, I'd be appreciative. I remember my brain going through similar "stupid phases" when learning OOP after a background of the simple procedural imperative approach to coding.</p>
| [
{
"answer_id": 361379,
"author": "tsimon",
"author_id": 1685,
"author_profile": "https://Stackoverflow.com/users/1685",
"pm_score": 3,
"selected": false,
"text": "String s1 = \"there\";\nString s2 = s1.Insert(0, \"hello \");\n\nConsole.Writeline(\"string 1: \" + s1);\nConsole.Writeline(\"string 2: \" + s2);\n StringBuilder sb = new StringBuilder(\"there\");\nStringBuilder sb2 = sb.Insert(0, \"hi \");\n\nConsole.WriteLine(\"sb 1: \" + sb.ToString());\nConsole.WriteLine(\"sb 2: \" + sb2.ToString());\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38803/"
] |
361,069 | <p>An answer and subsequent <a href="https://stackoverflow.com/questions/360899/c-math-problem#360931">debate in the comments</a> in another thread prompted me to ask:</p>
<p>In C# || and && are the short-circuited versions of the logical operators | and & respectively.<br /></p>
<p>Example usage:</p>
<pre><code>if (String.IsNullOrEmpty(text1) | String.IsNullOrEmpty(text2) | String.IsNullOrEmpty(text3))
{
//...
}
</code></pre>
<p>versus:</p>
<pre><code>if (String.IsNullOrEmpty(text1) || String.IsNullOrEmpty(text2) || String.IsNullOrEmpty(text3))
{
//...
}
</code></pre>
<p>In terms of coding practice which is the better to use and why?</p>
<p>Note: I do realize this question is similar to <a href="https://stackoverflow.com/questions/89154/benefits-of-using-short-circuit-evaluation">this question</a> but I believe it warrants a language specific discussion.</p>
| [
{
"answer_id": 361085,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 7,
"selected": true,
"text": "bool nullorempty = str == null || str.Length == 0;\n string.IsNullOrEmpty str null NullReferenceException bool hasBuzzed = checkMakeBuzz();\nbool isFrobbed = checkMakeFrob();\nbool result = hasBuzzed || isFrobbed;\n"
},
{
"answer_id": 361106,
"author": "Grant Wagner",
"author_id": 9254,
"author_profile": "https://Stackoverflow.com/users/9254",
"pm_score": 2,
"selected": false,
"text": "&& || & | & | if (false & somethingThatUpdatesTheDatabase()) { /* ... */ }\n"
},
{
"answer_id": 361262,
"author": "tsimon",
"author_id": 1685,
"author_profile": "https://Stackoverflow.com/users/1685",
"pm_score": 3,
"selected": false,
"text": "bool isPasswordValid = true;\n\nisPasswordValid &= isEightCharacters(password);\nisPasswordValid &= containsNumeric(password);\nisPasswordValid &= containsBothUppercaseAndLowercase(password);\n\nreturn isPasswordValid;\n return (isEightCharacters(password) &&\n containsNumberic(password) &&\n containsBothUppercaseAndLowercase(password));\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33226/"
] |
361,077 | <p>Today I ran into a problem were I needed to remote-debug a program. The program was launched from another system, so I really don't have an opportunity to interact with it on the command line. I could change its source easily though.</p>
<p>What I needed to happen was for the program to start normally, and then wait for me to attach to it with a debugger. I couldn't come up with a way to do it that made me happy. I did find the bug, but without the help of the debugger.</p>
<pre><code>while(true) { }
</code></pre>
<p>Kept the process alive, and then I could "set next statement" with the debugger, but it seemed awkward and rude.</p>
<pre><code>Console.ReadLine();
</code></pre>
<p>Seemed odd to type since there wasn't actually a Console for me to press <strong>enter</strong> at. (It didn't work, either. Set next statement and then run takes you back into the ReadLine() wait.)</p>
<p>So what kind of code can I insert into a .NET/CLR/C# program that says "wait here until I can attach with a debugger"?</p>
| [
{
"answer_id": 361124,
"author": "Steven Behnke",
"author_id": 42588,
"author_profile": "https://Stackoverflow.com/users/42588",
"pm_score": 3,
"selected": false,
"text": "System.Diagnostics.Debugger.Break()"
},
{
"answer_id": 361125,
"author": "Arron S",
"author_id": 16628,
"author_profile": "https://Stackoverflow.com/users/16628",
"pm_score": -1,
"selected": false,
"text": "Thread.Sleep(30000);\n"
},
{
"answer_id": 552748,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "Debug.Assert(true);\n MessageBox.Show() \n"
},
{
"answer_id": 552788,
"author": "Daniel Richardson",
"author_id": 52049,
"author_profile": "https://Stackoverflow.com/users/52049",
"pm_score": 8,
"selected": true,
"text": "using System;\nusing System.Diagnostics;\nusing System.Threading;\n\nnamespace DebugApp\n{\n class Program\n {\n static void Main(string[] args)\n {\n Console.WriteLine(\"Waiting for debugger to attach\");\n while (!Debugger.IsAttached)\n {\n Thread.Sleep(100);\n }\n Console.WriteLine(\"Debugger attached\");\n }\n }\n}"
},
{
"answer_id": 3711497,
"author": "Martin Sherburn",
"author_id": 144306,
"author_profile": "https://Stackoverflow.com/users/144306",
"pm_score": 5,
"selected": false,
"text": "Debugger.Launch();\n"
},
{
"answer_id": 14318001,
"author": "ya23",
"author_id": 29430,
"author_profile": "https://Stackoverflow.com/users/29430",
"pm_score": 3,
"selected": false,
"text": "System.Diagnostics.Debugger.Launch();\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8173/"
] |
361,097 | <p>I have a service that sometimes calls a batch file. The batch file takes 5-10 seconds to execute:</p>
<pre><code>System.Diagnostics.Process proc = new System.Diagnostics.Process(); // Declare New Process
proc.StartInfo.FileName = fileName;
proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
proc.WaitForExit();
</code></pre>
<p>The file does exist and the code works when I run the same code in-console. However when it runs inside the service, it hangs up at <code>WaitForExit()</code>. I have to kill the batch file from the Process in order to continue. (I am certain the file exists, as I can see it in the processes list.)</p>
<p>How can I fix this hang-up?</p>
<h1>Update #1:</h1>
<p>Kevin's code allows me to get output. One of my batch files is still hanging. </p>
<blockquote>
<p>"C:\EnterpriseDB\Postgres\8.3\bin\pg_dump.exe" -i -h localhost -p 5432 -U postgres -F p -a -D -v -f "c:\backupcasecocher\backupdateevent2008.sql" -t "\"public\".\"dateevent\"" "DbTest" </p>
</blockquote>
<p>The other batch file is:</p>
<blockquote>
<p>"C:\EnterpriseDB\Postgres\8.3\bin\vacuumdb.exe" -U postgres -d DbTest</p>
</blockquote>
<p>I have checked the path and the <code>postgresql</code> path is fine. The output directory does exist and still works outside the service. Any ideas?</p>
<h1>Update #2:</h1>
<p>Instead of the path of the batch file, I wrote the "C:\EnterpriseDB\Postgres\8.3\bin\pg_dump.exe" for the <code>proc.StartInfo.FileName</code> and added all parameters to <code>proc.StartInfo.Arguments</code>. The results are unchanged, but I see the <code>pg_dump.exe</code> in the process window. Again this only happens inside the service.</p>
<h1>Update #3:</h1>
<p>I have run the service with a user in the administrator group, to no avail. I restored <code>null</code> for the service's username and password</p>
<h1>Update #4:</h1>
<p>I created a simple service to write a trace in the event log and execute a batch file that contains "dir" in it. It will now hang at <code>proc.Start();</code> - I tried changing the Account from LocalSystem to <strong>User</strong> and I set the admnistrator user and password, still nothing.</p>
| [
{
"answer_id": 361121,
"author": "kemiller2002",
"author_id": 1942,
"author_profile": "https://Stackoverflow.com/users/1942",
"pm_score": 6,
"selected": true,
"text": "proc.StartInfo.FileName = target;\nproc.StartInfo.RedirectStandardError = true;\nproc.StartInfo.RedirectStandardOutput = true;\nproc.StartInfo.UseShellExecute = false;\n\nproc.Start();\n\nproc.WaitForExit\n (\n (timeout <= 0)\n ? int.MaxValue : timeout * NO_MILLISECONDS_IN_A_SECOND *\n NO_SECONDS_IN_A_MINUTE\n );\n\nerrorMessage = proc.StandardError.ReadToEnd();\nproc.WaitForExit();\n\noutputMessage = proc.StandardOutput.ReadToEnd();\nproc.WaitForExit();\n"
},
{
"answer_id": 361139,
"author": "LarryF",
"author_id": 18518,
"author_profile": "https://Stackoverflow.com/users/18518",
"pm_score": 2,
"selected": false,
"text": "echo Y | copy foo.log c:\\backup\\\n"
},
{
"answer_id": 365606,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 1,
"selected": false,
"text": " System.Diagnostics.Process proc = new System.Diagnostics.Process();\n proc.StartInfo.FileName = fileName;\n proc.StartInfo.RedirectStandardError = true;\n proc.StartInfo.RedirectStandardOutput = true;\n proc.StartInfo.UseShellExecute = false;\n\n\n proc.Start();\n proc.WaitForExit();\n output1 = proc.StandardError.ReadToEnd();\n proc.WaitForExit();\n output2 = proc.StandardOutput.ReadToEnd();\n proc.WaitForExit();\n"
},
{
"answer_id": 2019383,
"author": "samir",
"author_id": 245406,
"author_profile": "https://Stackoverflow.com/users/245406",
"pm_score": 4,
"selected": false,
"text": "using System;\n using System.Collections.Generic;\n using System.Linq;\n using System.Text;\n using System.Diagnostics;\n namespace VG\n {\n class VGe\n {\n [STAThread]\n static void Main(string[] args)\n {\n Process proc = null;\n try\n { \n string targetDir = string.Format(@\"D:\\adapters\\setup\");//this is where mybatch.bat lies\n proc = new Process();\n proc.StartInfo.WorkingDirectory = targetDir;\n proc.StartInfo.FileName = \"mybatch.bat\";\n proc.StartInfo.Arguments = string.Format(\"10\");//this is argument\n proc.StartInfo.CreateNoWindow = false;\n proc.Start();\n proc.WaitForExit();\n }\n catch (Exception ex)\n {\n Console.WriteLine(\"Exception Occurred :{0},{1}\", ex.Message,ex.StackTrace.ToString());\n }\n }\n }\n }\n"
},
{
"answer_id": 16454824,
"author": "suresh",
"author_id": 1651046,
"author_profile": "https://Stackoverflow.com/users/1651046",
"pm_score": 2,
"selected": false,
"text": " string targetDir = string.Format(@\"D:\\\");//PATH\n proc = new Process();\n proc.StartInfo.WorkingDirectory = targetDir;\n proc.StartInfo.FileName = \"GetFiles.bat\";\n proc.StartInfo.Arguments = string.Format(\"10\");//argument\n proc.StartInfo.CreateNoWindow = false;\n proc.Start();\n proc.WaitForExit();\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13913/"
] |
361,115 | <p>I tried to make a dynamic 2D array of <code>char</code> as follow:</p>
<pre><code>char** ppMapData = (char**)malloc(sizeof(char*)*iMapHeight);
for (int i=0; i< iMapHeight; i++)
{
ppMapData[i] = (char*)malloc(sizeof(char)*iMapWidth);
//do something
}
// do something
for (int i=0; i<iMapHeight; i++)
free(ppMapData[i]);
free(ppMapData);
</code></pre>
<p>It looks fine to me; however, when it comes to run time, my program crash at the line which calls <code>free(ppMapData[i])</code>. Any ideas what is the problem here.
Thank you very much.</p>
| [
{
"answer_id": 361131,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "vector<vector<char> > vector<string> vector<string>"
},
{
"answer_id": 361246,
"author": "jmucchiello",
"author_id": 44065,
"author_profile": "https://Stackoverflow.com/users/44065",
"pm_score": 2,
"selected": false,
"text": "char* array = (char*)malloc(iMapHeight*iMapWidth);\n char val = array[height*iMapWidth + width];\n #define GET_VAL(h, w) array[h*iMapWidth + w]\n"
},
{
"answer_id": 376227,
"author": "hhafez",
"author_id": 42303,
"author_profile": "https://Stackoverflow.com/users/42303",
"pm_score": 0,
"selected": false,
"text": "//do something\n i"
},
{
"answer_id": 376268,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 0,
"selected": false,
"text": "char **ppMapData = malloc(iMapHeight * sizeof(char*) +\n iMapHeight * iMapWidth * sizeof(char)));\n\nfor (int i = 0; i < iMapHeight; i++) {\n ppMapData[i] = (char *)(ppMapData + iMapHeight) + i * iMapWidth;\n /* do something */\n}\n\n/* do something */\n\nfree(ppMapData);\n // do something ppMapData[i] ppMapData[i] = NULL free(ppMapData[i]) free(NULL)"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
361,130 | <p>When selecting a block of text (possibly spanning across many DOM nodes), is it possible to extract the selected text and nodes using Javascript?</p>
<p>Imagine this HTML code:</p>
<pre><code><h1>Hello World</h1><p>Hi <b>there!</b></p>
</code></pre>
<p>If the user initiated a mouseDown event starting at "World..." and then a mouseUp even right after "there!", I'm hoping it would return:</p>
<pre><code>Text : { selectedText: "WorldHi there!" },
Nodes: [
{ node: "h1", offset: 6, length: 5 },
{ node: "p", offset: 0, length: 16 },
{ node: "p > b", offset: 0, length: 6 }
]
</code></pre>
<p>I've tried putting the HTML into a textarea but that will only get me the selectedText. I haven't tried the <code><canvas></code> element but that may be another option.</p>
<p>If not JavaScript, is there a way this is possible using a Firefox extension? </p>
| [
{
"answer_id": 364476,
"author": "Borgar",
"author_id": 27388,
"author_profile": "https://Stackoverflow.com/users/27388",
"pm_score": 5,
"selected": true,
"text": "// selection objects will differ between browsers\nfunction getSelection () {\n return ( msie ) \n ? document.selection\n : ( window.getSelection || document.getSelection )();\n}\n\n// range objects will differ between browsers\nfunction getRange () {\n return ( msie ) \n ? getSelection().createRange()\n : getSelection().getRangeAt( 0 )\n}\n\n// abstract getting a parent container from a range\nfunction parentContainer ( range ) {\n return ( msie )\n ? range.parentElement()\n : range.commonAncestorContainer;\n}\n"
},
{
"answer_id": 9004949,
"author": "JamesBond",
"author_id": 1150992,
"author_profile": "https://Stackoverflow.com/users/1150992",
"pm_score": 0,
"selected": false,
"text": "function getRange(){\n return (navigator.appName==\"Microsoft Internet Explorer\")\n ? document.selection.createRange().parentElement()\n : (getSelection||document.getSelection)().getRangeAt(0).commonAncestorContainer\n}\n"
},
{
"answer_id": 10075894,
"author": "Tim Down",
"author_id": 96100,
"author_profile": "https://Stackoverflow.com/users/96100",
"pm_score": 3,
"selected": false,
"text": "getNodes() function getSelectedNodes() {\n var selectedNodes = [];\n var sel = rangy.getSelection();\n for (var i = 0; i < sel.rangeCount; ++i) {\n selectedNodes = selectedNodes.concat( sel.getRangeAt(i).getNodes() );\n }\n return selectedNodes;\n}\n var selectedText = rangy.getSelection().toString();\n function getSelectedText() {\n var sel, text = \"\";\n if (window.getSelection) {\n text = \"\" + window.getSelection();\n } else if ( (sel = document.selection) && sel.type == \"Text\") {\n text = sel.createRange().text;\n }\n return text;\n}\n node <br> var sel = rangy.getSelection();\nvar selRange = sel.getRangeAt(0);\nvar rangePrecedingNode = rangy.createRange();\nrangePrecedingNode.setStart(selRange.startContainer, selRange.startOffset);\nrangePrecedingNode.setEndBefore(node);\nvar startIndex = rangePrecedingNode.toString().length;\nrangePrecedingNode.setEndAfter(node);\nvar endIndex = rangePrecedingNode.toString().length;\nalert(startIndex + \", \" + endIndex);\n"
},
{
"answer_id": 20336116,
"author": "User",
"author_id": 1320237,
"author_profile": "https://Stackoverflow.com/users/1320237",
"pm_score": 2,
"selected": false,
"text": "<p> ... </p><p> ... </p><p> ... </p><p> ... </p><p> ... </p>...\n<p> ... </p><p> ... </p><p> ... </p><p> ... </p><p> ... </p>\n function getSelectedNodes() {\n // from https://developer.mozilla.org/en-US/docs/Web/API/Selection\n var selection = window.getSelection();\n if (selection.isCollapsed) {\n return [];\n };\n var node1 = selection.anchorNode;\n var node2 = selection.focusNode;\n var selectionAncestor = get_common_ancestor(node1, node2);\n if (selectionAncestor == null) {\n return [];\n }\n return getNodesBetween(selectionAncestor, node1, node2);\n}\n\nfunction get_common_ancestor(a, b)\n{\n // from http://stackoverflow.com/questions/3960843/how-to-find-the-nearest-common-ancestors-of-two-or-more-nodes\n $parentsa = $(a).parents();\n $parentsb = $(b).parents();\n\n var found = null;\n\n $parentsa.each(function() {\n var thisa = this;\n\n $parentsb.each(function() {\n if (thisa == this)\n {\n found = this;\n return false;\n }\n });\n\n if (found) return false;\n });\n\n return found;\n}\n\nfunction isDescendant(parent, child) {\n // from http://stackoverflow.com/questions/2234979/how-to-check-in-javascript-if-one-element-is-a-child-of-another\n var node = child;\n while (node != null) {\n if (node == parent) {\n return true;\n }\n node = node.parentNode;\n }\n return false;\n}\n\nfunction getNodesBetween(rootNode, node1, node2) {\n var resultNodes = [];\n var isBetweenNodes = false;\n for (var i = 0; i < rootNode.childNodes.length; i+= 1) {\n if (isDescendant(rootNode.childNodes[i], node1) || isDescendant(rootNode.childNodes[i], node2)) {\n if (resultNodes.length == 0) {\n isBetweenNodes = true;\n } else {\n isBetweenNodes = false;\n }\n resultNodes.push(rootNode.childNodes[i]);\n } else if (resultNodes.length == 0) {\n } else if (isBetweenNodes) {\n resultNodes.push(rootNode.childNodes[i]);\n } else {\n return resultNodes;\n }\n };\n if (resultNodes.length == 0) {\n return [rootNode];\n } else if (isDescendant(resultNodes[resultNodes.length - 1], node1) || isDescendant(resultNodes[resultNodes.length - 1], node2)) {\n return resultNodes;\n } else {\n // same child node for both should never happen\n return [resultNodes[0]];\n }\n}\n"
},
{
"answer_id": 48788879,
"author": "John",
"author_id": 606371,
"author_profile": "https://Stackoverflow.com/users/606371",
"pm_score": 0,
"selected": false,
"text": "window.getSelection().getRangeAt(0).toString()\n window.getSelection().anchorNode\n window.getSelection().focusNode\n console.log(window.getSelection());\nconsole.log(window.getSelection().getRangeAt(0));\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45435/"
] |
361,135 | <p>I have a table where I store customer sales (on periodicals, like newspaper) data. The product is stored by issue. Example</p>
<pre>
custid prodid issue qty datesold
1 123 2 12 01052008
2 234 1 5 01022008
1 123 1 5 01012008
2 444 2 3 02052008
</pre>
<p>How can I retrieve (whats a faster way) the get last issue for all products, for a specific customer? Can I have samples for both SQL Server 2000 and 2005? Please note, the table is over 500k rows.</p>
<p>Thanks</p>
| [
{
"answer_id": 361146,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "SELECT prodid, max(issue) FROM sales WHERE custid = ? GROUP BY prodid;\n"
},
{
"answer_id": 361183,
"author": "Patrick Harrington",
"author_id": 41165,
"author_profile": "https://Stackoverflow.com/users/41165",
"pm_score": 1,
"selected": false,
"text": "CustID LastName FirstName\n------ -------- ---------\n1 Woman Test\n2 Man Test\n\nProdID ProdName\n------ --------\n123 NY Times\n234 Boston Globe\n\nProdID IssueID PublishDate\n------ ------- -----------\n123 1 12/05/2008\n123 2 12/06/2008\n\nCustID OrderID OrderDate\n------ ------- ---------\n1 1 12/04/2008\n\nOrderID ProdID IssueID Quantity\n------- ------ ------- --------\n1 123 1 5\n2 123 2 12\n"
},
{
"answer_id": 361214,
"author": "Rockcoder",
"author_id": 5290,
"author_profile": "https://Stackoverflow.com/users/5290",
"pm_score": 1,
"selected": false,
"text": "SELECT prodid, issue\n FROM Sales \nWHERE custid = @custid \n AND datesold = SELECT MAX(datesold) \n FROM Sales s \n WHERE s.prodid = Sales.prodid\n AND s.issue = Sales.issue\n AND s.custid = @custid \n"
},
{
"answer_id": 361732,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 3,
"selected": true,
"text": "SELECT\n T1.prodid,\n T1.issue\nFROM\n Sales T1\nLEFT OUTER JOIN dbo.Sales T2 ON\n T2.custid = T1.custid AND\n T2.prodid = T1.prodid AND\n T2.datesold > T1.datesold\nWHERE\n T1.custid = @custid AND\n T2.custid IS NULL\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23667/"
] |
361,137 | <p>Is it possible to bypass the Freemarker cache when certain templates are requested? I realise that I'll probably have to implement my own TemplateLoader in order to do this, but even so, I can't see a way to check the cache when say template A is requested, but bypass it when template B is requested?</p>
<p>If this is not possible, I'll just have to disable caching completely.</p>
| [
{
"answer_id": 361242,
"author": "Dan Vinton",
"author_id": 21849,
"author_profile": "https://Stackoverflow.com/users/21849",
"pm_score": 2,
"selected": false,
"text": "configuration.setTemplateUpdateDelay(0);\n getLastModified"
},
{
"answer_id": 972122,
"author": "toluju",
"author_id": 12457,
"author_profile": "https://Stackoverflow.com/users/12457",
"pm_score": 1,
"selected": false,
"text": "cfg.setSetting(Configuration.CACHE_STORAGE_KEY, \"strong:0, soft:0\");\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
] |
361,151 | <p>I made an html file called test.html then I navigated to it as "<a href="http://site.com/test.html?test1=a" rel="nofollow noreferrer">http://site.com/test.html?test1=a</a>" but the textbox stayed blank. Why is this? </p>
<p>Super simple code</p>
<pre><code><html>
<head>
<title>Test</title>
</head>
<body >
<input type=text name="test1">
</body>
</html>
</code></pre>
| [
{
"answer_id": 361158,
"author": "Sydius",
"author_id": 43496,
"author_profile": "https://Stackoverflow.com/users/43496",
"pm_score": 3,
"selected": true,
"text": "<html>\n<head>\n <title>Test</title>\n</head>\n<body>\n <input type=\"text\" name=\"test1\" value=\"<?php echo htmlspecialchars($_GET['test1'], ENT_QUOTES); ?>\">\n</body>\n</html>\n"
},
{
"answer_id": 361203,
"author": "jmucchiello",
"author_id": 44065,
"author_profile": "https://Stackoverflow.com/users/44065",
"pm_score": 0,
"selected": false,
"text": "<html>\n<head>\n<title>Test</title>\n</head>\n<body >\n <input type=text name=\"test1\" value=\"<?php echo htmlspecialchars($_GET['test1']);?>\">\n</body>\n</html>\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39143/"
] |
361,161 | <p>I have a Rails app that lets a user construct a database query by filling out an extensive form. I wondered the best practice for checking form parameters in Rails. Previously, I have had my <code>results</code> method (the one to which the form submits) do the following:</p>
<pre><code>if params[:name] && !params[:name].blank?
@name = params[:name]
else
flash[:error] = 'You must give a name'
redirect_to :action => 'index'
return
end
</code></pre>
<p>But for several form fields, seeing this repeated for each one got tiresome. I couldn't just stick them all in some loop to check for each field, because the fields are set up differently:</p>
<ul>
<li>a single key: <code>params[:name]</code></li>
<li>a key and a sub-key: <code>params[:image][:font_size]</code></li>
<li>only expect some form fields to be filled out if another field was set</li>
</ul>
<p>Etc. This was also repetitive, because I was setting <code>flash[:error]</code> for each missing/invalid parameter, and redirecting to the same URL for each one. I switched to using a <code>before_filter</code> that checks for all necessary form parameters and only returns true if everything's okay. Then the my <code>results</code> method continues, and variables are just assigned flat-out, with no checking involved:</p>
<pre><code>@name = params[:name]
</code></pre>
<p>In my <code>validate_form</code> method, I have sections of code like the following:</p>
<pre><code>if (
params[:analysis_type][:to_s] == 'development' ||
params[:results_to_generate].include?('graph')
)
{:graph_type => :to_s, :graph_width => :to_s,
:theme => :to_s}.each do |key, sub_key|
unless params[key] && params[key][sub_key]
flash[:error] = "Cannot leave '#{Inflector.humanize(key)}' blank"
redirect_to(url)
return false
end
end
end
</code></pre>
<p>I was just wondering if I'm going about this in the best way, or if I'm missing something obvious when it comes to parameter validation. I worry this is still not the most efficient technique, because I have several blocks where I assign a value to <code>flash[:error]</code>, then redirect to the same URL, then return false.</p>
<p><em>Edit to clarify:</em> The reason I don't have this validation in model(s) currently is for two reasons:</p>
<ul>
<li>I'm not trying to gather data from the user in order to create or update a row in the database. None of the data the user submits is saved after they log out. It's all used right when they submit it to search the database and generate some stuff.</li>
<li>The query form takes in data pertaining to several models, and it takes in other data that doesn't pertain to a model at all. E.g. graph type and theme as shown above do not connect to any model, they just convey information about how the user wants to display his results.</li>
</ul>
<p><em>Edit to show improved technique:</em> I make use of application-specific exceptions now, thanks to Jamis Buck's <a href="http://weblog.jamisbuck.org/2007/3/7/raising-the-right-exception" rel="noreferrer">Raising the Right Exception article</a>. For example:</p>
<pre><code>def results
if params[:name] && !params[:name].blank?
@name = params[:name]
else
raise MyApp::MissingFieldError
end
if params[:age] && !params[:age].blank? && params[:age].numeric?
@age = params[:age].to_i
else
raise MyApp::MissingFieldError
end
rescue MyApp::MissingFieldError => err
flash[:error] = "Invalid form submission: #{err.clean_message}"
redirect_to :action => 'index'
end
</code></pre>
| [
{
"answer_id": 361699,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": true,
"text": "class MyForm < ActiveForm\n validates_presence_of :name\n validates_presence_of :graph_size, :if => # ...blah blah \nend\n\nform = MyForm.new(params[:form])\nform.validate\nform.errors\n"
},
{
"answer_id": 51116700,
"author": "zawhtut",
"author_id": 379779,
"author_profile": "https://Stackoverflow.com/users/379779",
"pm_score": 0,
"selected": false,
"text": "class Person \n include ActiveModel::Validations\n include ActiveModel::Conversion\n extend ActiveModel::Naming\n\n attr_accessor :name\n attr_accessor :email\n\n\n validates_presence_of :name,:message => \"Please Provide User Name\"\n validates_presence_of :email,:message => \"Please Provide Email\"\nend\n @person.name= params[\"name\"]\n@person.email= params[\"email\"]\n@person.valid?\n <%if @person.errors.any? %>\n <%@person.errors.messages.each do|msg| %>\n <div class=\"alert alert-danger\">\n <%=msg[0][1]%>\n </div>\n <%end%>\n<%end%>\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38743/"
] |
361,163 | <p>I want to use pretty 3d button images on my website. However, currently the way this works is the text is part of the image.</p>
<p>So, when I want to change the text (or make a new button) it's a 10 minute editing chore instead of a 20 second text change.</p>
<p>I've seen a few websites that have a blank button with text on it.</p>
<p>The real trick is making the <em>entire</em> image clickable. I've been able to make the link inside an image visible but that's a poor UI. Users will expect to click the button anywhere and failure to behave that way will frustrate them.</p>
<p>It seems like they're wrapping a .DIV tag with an image background around a Hyperlink.</p>
<pre>
<Div (class w/ image>
<a> text
</a>
</pre>
<p>EXAMPLE:
<a href="https://www.box.net/signup/g" rel="nofollow noreferrer">https://www.box.net/signup/g</a></p>
<p>Anyone have any insight or explanation of how this works?'</p>
<p>CODE SAMPLE</p>
<pre><code><a href="#" class="button" style="position: relative;left:-5px;"
onmousedown="return false;"
onclick="document.forms['register_form'].submit(); return false;">
<span>
My text
</span>
</a>
</code></pre>
| [
{
"answer_id": 361171,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 0,
"selected": false,
"text": "a { \n width: something ; \n height: something; \n display: block; \n background: url('hi.png'); \n }\n input { background: url('hi.png'); } \n"
},
{
"answer_id": 361173,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<style>\ndiv.button a {\n display: block;\n width: /* image width */;\n line-height: /* image height */;\n text-align: center;\n background: url(/* image uri */) no-repeat;\n}\n</style>\n"
},
{
"answer_id": 361180,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "<a onclick=\"document.forms['register_form'].submit(); return false;\"\n onmousedown=\"return false;\" style=\"position: relative; left: -5px;\"\n class=\"button\" href=\"#\">\n <span>Continue</span>\n</a>\n a.button \n{\n background:transparent url(../img/greenbutton2.gif) no-repeat scroll left top;\n font-size:16px;\n height:42px;\n line-height:42px;\n width:155px;\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4906/"
] |
361,175 | <p>Been using the code below to return a single record from the database. I have read that ExecuteScalar is the right way to return a single record. I have never been able to get ExecuteScalar to work though. How would I change this to return a single value in VB.Net using ExecuteScalar?</p>
<pre><code> Dim oracleConnection As New OracleConnection
oracleConnection.ConnectionString = LocalConnectionString()
Dim cmd As New OracleCommand()
Dim o racleDataAdapter As New OracleClient.OracleDataAdapter
cmd.Connection = oracleConnection
cmd.CommandText = "FALCON.CMS_DATA.GET_MAX_CMS_TH"
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add(New OracleParameter("i_FACID_C", OracleType.Char)).Value = facilityShortName
cmd.Parameters.Add(New OracleParameter("RS_MAX", OracleType.Cursor)).Direction = ParameterDirection.Output
Try
Using oracleConnection
oracleConnection.Open()
Using oracleDataAdapter
oracleDataAdapter = New OracleClient.OracleDataAdapter(cmd)
Dim workingDataSet As DataSet
oracleDataAdapter.TableMappings.Add("OutputSH", "RS_MAX")
workingDataSet = New DataSet
oracleDataAdapter.Fill(workingDataSet)
For Each row As DataRow In workingDataSet.Tables(0).Rows
Return CDate(row("MAXDATE"))
Next
End Using
End Using
</code></pre>
| [
{
"answer_id": 372242,
"author": "Brian Schmitt",
"author_id": 30492,
"author_profile": "https://Stackoverflow.com/users/30492",
"pm_score": 0,
"selected": false,
"text": "oracleConnection.Open\nDim obj as object 'Object to hold our return value\nobj = cmd.ExecuteScalar()\noracleConnection.Close\n\nIf obj IsNot Nothing then\n Return CDate(obj)\nend if\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38349/"
] |
361,193 | <p>I'm the developer of twittertrend.net, I was wondering if there was a faster way to get headers of a URL, besides doing curl_multi? I process over 250 URLs a minute, and I need a really fast way to do this from a PHP standpoint. Either a bash script could be used and then output the headers or C appliation, anything that could be faster? I have primarily only programmed in PHP, but I can learn. Currently, CURL_MULTI (with 6 URLs provided at once, does an ok job, but I would prefer something faster?
Ultimately I would like to stick with PHP for any MySQL storing and processing.</p>
<p>Thanks,
James Hartig</p>
| [
{
"answer_id": 361263,
"author": "Pras",
"author_id": 45435,
"author_profile": "https://Stackoverflow.com/users/45435",
"pm_score": 1,
"selected": false,
"text": "curl_setopt ($ch, CURLOPT_HEADER, 1);\ncurl_setopt ($ch, CURLOPT_NOBODY, 1);\ncurl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);\n --server-response\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45530/"
] |
361,204 | <p>I am trying to use ASP to create a connection to my database and i have the following connection code:</p>
<pre><code>Set objConn = ConnectDB()
Set objRS = objConn.Execute(query)
</code></pre>
<p>I have an include file that I have at the top of my page:</p>
<pre><code><!--#include FILE=dbcano.inc-->
</code></pre>
<p>And I get this error when I call my page:</p>
<blockquote>
<p>Microsoft VBScript runtime error
'800a01f4' Variable is undefined:
'ConnectDB' patti_trinkets.asp, line 9</p>
</blockquote>
<p>The <code>ConnectDB()</code> is a function I created that is stored within the <code>dbcano.inc</code> file.</p>
<p>Any suggestions as to why I am getting this error when I call my page?</p>
<p>My full code can be found here: <a href="http://pastie.org/337183" rel="nofollow noreferrer">http://pastie.org/337183</a></p>
| [
{
"answer_id": 361263,
"author": "Pras",
"author_id": 45435,
"author_profile": "https://Stackoverflow.com/users/45435",
"pm_score": 1,
"selected": false,
"text": "curl_setopt ($ch, CURLOPT_HEADER, 1);\ncurl_setopt ($ch, CURLOPT_NOBODY, 1);\ncurl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);\n --server-response\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
361,209 | <p>I've got two controls, a TextBlock and a PopUp. When the user clicks (MouseDown) on the textblock, I want to display the popup. I would think that I could do this with an EventTrigger on the Popup, but I can't use setters in an EventTrigger, I can only start storyboards. I want to do this strictly in XAML, because the two controls are in a template and I don't know how I'd find the popup in code.</p>
<p>This is what conceptually I want to do, but can't because you can't put a setter in an EventTrigger (like you can with a DataTrigger):</p>
<pre><code><TextBlock x:Name="CCD">Some text</TextBlock>
<Popup>
<Popup.Style>
<Style>
<Style.Triggers>
<EventTrigger SourceName="CCD" RoutedEvent="MouseDown">
<Setter Property="Popup.IsOpen" Value="True" />
</EventTrigger>
</Style.Triggers>
</Style>
</Popup.Style>
...
</code></pre>
<p>What is the best way to show a popup strictly in XAML when an event happens on a different control?</p>
| [
{
"answer_id": 361302,
"author": "bendewey",
"author_id": 37881,
"author_profile": "https://Stackoverflow.com/users/37881",
"pm_score": 3,
"selected": false,
"text": "<Window x:Class=\"WpfApplication1.Window1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n Title=\"Window1\" Height=\"300\" Width=\"300\">\n <Grid>\n <Control VerticalAlignment=\"Top\">\n <Control.Template>\n <ControlTemplate>\n <StackPanel>\n <TextBox x:Name=\"MyText\"></TextBox>\n <Popup x:Name=\"Popup\" PopupAnimation=\"Fade\" VerticalAlignment=\"Top\">\n <Border Background=\"Red\">\n <TextBlock>Test Popup Content</TextBlock>\n </Border>\n </Popup>\n </StackPanel>\n <ControlTemplate.Triggers>\n <EventTrigger RoutedEvent=\"UIElement.MouseEnter\" SourceName=\"MyText\">\n <BeginStoryboard>\n <Storyboard>\n <BooleanAnimationUsingKeyFrames Storyboard.TargetName=\"Popup\" Storyboard.TargetProperty=\"(Popup.IsOpen)\">\n <DiscreteBooleanKeyFrame KeyTime=\"00:00:00\" Value=\"True\"/>\n </BooleanAnimationUsingKeyFrames>\n </Storyboard>\n </BeginStoryboard>\n </EventTrigger>\n <EventTrigger RoutedEvent=\"UIElement.MouseLeave\" SourceName=\"MyText\">\n <BeginStoryboard>\n <Storyboard>\n <BooleanAnimationUsingKeyFrames Storyboard.TargetName=\"Popup\" Storyboard.TargetProperty=\"(Popup.IsOpen)\">\n <DiscreteBooleanKeyFrame KeyTime=\"00:00:00\" Value=\"False\"/>\n </BooleanAnimationUsingKeyFrames>\n </Storyboard>\n </BeginStoryboard>\n </EventTrigger>\n </ControlTemplate.Triggers>\n </ControlTemplate>\n </Control.Template>\n </Control>\n </Grid>\n</Window>\n"
},
{
"answer_id": 399824,
"author": "John Melville",
"author_id": 50088,
"author_profile": "https://Stackoverflow.com/users/50088",
"pm_score": 8,
"selected": true,
"text": " <StackPanel>\n <ToggleButton Name=\"button\"> \n <ToggleButton.Template>\n <ControlTemplate TargetType=\"ToggleButton\">\n <TextBlock>Click Me Here!!</TextBlock>\n </ControlTemplate> \n </ToggleButton.Template>\n </ToggleButton>\n <Popup IsOpen=\"{Binding IsChecked, ElementName=button}\" StaysOpen=\"False\">\n <Border Background=\"LightYellow\">\n <TextBlock>I'm the popup</TextBlock>\n </Border>\n </Popup> \n </StackPanel>\n"
},
{
"answer_id": 8946055,
"author": "Qwertie",
"author_id": 22820,
"author_profile": "https://Stackoverflow.com/users/22820",
"pm_score": 6,
"selected": false,
"text": "<ToggleButton x:Name=\"Btn\" IsHitTestVisible=\"{Binding ElementName=Popup, Path=IsOpen, Mode=OneWay, Converter={local:BoolInverter}}\">\n <TextBlock Text=\"Click here for popup!\"/>\n</ToggleButton>\n\n<Popup IsOpen=\"{Binding IsChecked, ElementName=Btn}\" x:Name=\"Popup\" StaysOpen=\"False\">\n <Border BorderBrush=\"Black\" BorderThickness=\"1\" Background=\"LightYellow\">\n <CheckBox Content=\"This is a popup\"/>\n </Border>\n</Popup>\n public class BoolInverter : MarkupExtension, IValueConverter\n{\n public override object ProvideValue(IServiceProvider serviceProvider)\n {\n return this;\n }\n\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value is bool)\n return !(bool)value;\n return value;\n }\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n return Convert(value, targetType, parameter, culture);\n }\n}\n PreviewMouseDown += (s, e) =>\n{\n // Workaround for popup not closing automatically when \n // two popups are on-screen at once.\n if (Popup.IsOpen)\n {\n Point p = e.GetPosition(Popup.Child);\n if (!IsInRange(p.X, 0, ((FrameworkElement)Popup.Child).ActualWidth) ||\n !IsInRange(p.Y, 0, ((FrameworkElement)Popup.Child).ActualHeight))\n Popup.IsOpen = false;\n }\n};\n// Elsewhere...\npublic static bool IsInRange(int num, int lo, int hi) => \n num >= lo && num <= hi;\n"
},
{
"answer_id": 23404882,
"author": "Mike",
"author_id": 3592197,
"author_profile": "https://Stackoverflow.com/users/3592197",
"pm_score": 0,
"selected": false,
"text": "<Border x:Name=\"Bd\" BorderBrush=\"{TemplateBinding BorderBrush}\" BorderThickness=\"{TemplateBinding BorderThickness}\" Background=\"{TemplateBinding Background}\" Padding=\"{TemplateBinding Padding}\" SnapsToDevicePixels=\"true\">\n <StackPanel>\n <Image Source=\"{Binding ProductImage,RelativeSource={RelativeSource TemplatedParent}}\" Stretch=\"Fill\" Width=\"65\" Height=\"85\"/>\n <ContentPresenter HorizontalAlignment=\"{TemplateBinding HorizontalContentAlignment}\" SnapsToDevicePixels=\"{TemplateBinding SnapsToDevicePixels}\" VerticalAlignment=\"{TemplateBinding VerticalContentAlignment}\"/>\n <Button x:Name=\"myButton\" Width=\"40\" Height=\"10\">\n <Popup Width=\"100\" Height=\"70\" IsOpen=\"{Binding ElementName=myButton,Path=IsMouseOver, Mode=OneWay}\">\n <StackPanel Background=\"Yellow\">\n <ItemsControl ItemsSource=\"{Binding Produkt.SubProducts}\"/>\n </StackPanel>\n </Popup>\n </Button>\n </StackPanel>\n </Border>\n"
},
{
"answer_id": 29298573,
"author": "BatteryBackupUnit",
"author_id": 684096,
"author_profile": "https://Stackoverflow.com/users/684096",
"pm_score": 4,
"selected": false,
"text": "EventTrigger Popup ToggleButton Click Button <Button x:Name=\"OpenPopup\">Popup\n <Button.Triggers>\n <EventTrigger RoutedEvent=\"Button.Click\">\n <EventTrigger.Actions>\n <BeginStoryboard>\n <Storyboard>\n <BooleanAnimationUsingKeyFrames \n Storyboard.TargetName=\"ContextPopup\" \n Storyboard.TargetProperty=\"IsOpen\">\n <DiscreteBooleanKeyFrame KeyTime=\"0:0:0\" Value=\"True\" />\n </BooleanAnimationUsingKeyFrames>\n </Storyboard>\n </BeginStoryboard>\n </EventTrigger.Actions>\n </EventTrigger>\n </Button.Triggers>\n</Button>\n<Popup x:Name=\"ContextPopup\"\n PlacementTarget=\"{Binding ElementName=OpenPopup}\"\n StaysOpen=\"False\">\n <Label>Popupcontent...</Label>\n</Popup>\n Popup Button x:Name=\"...\" Popup Button Storyboard SetProperty"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4572/"
] |
361,225 | <p>I'd like to create a custom loading screen for a JavaFX application. Don't want the user to see the Java coffee cup icon, I want to put my own graphic there!</p>
<p>I've found out how to provide a static image, or even an animated GIF, but I'm more interested in a Flash-like screen where I can specify what the state of the image looks like at certain percentages.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 23728365,
"author": "ufukomer",
"author_id": 3650955,
"author_profile": "https://Stackoverflow.com/users/3650955",
"pm_score": -1,
"selected": false,
"text": "stage.getIcons().add(new Image(\"images/myimage.png\"));\n"
},
{
"answer_id": 24479931,
"author": "drojokef",
"author_id": 2899047,
"author_profile": "https://Stackoverflow.com/users/2899047",
"pm_score": 1,
"selected": false,
"text": "Timer tm= new Timer(); \nStage ilk;\nint count;\n\npublic void check() { \n\n ilk=new Stage();\n TimerTask mission;\n\n gorev = new TimerTask() {\n @Override\n public void run() {\n\n Group root = new Group(); \n\n Scene scene;\n scene = new Scene(root, 960, 540);\n scene.setFill(Color.BLACK);\n ilk.setScene(scene);\n ilk.setTitle(\"Splash Screen\"); \n\n sayac++;\n if(count==5){\n tm.cancel();\n ilk.show(); \n }\n }\n };\n tm.schedule(mission, 0, 2000);\n}\n"
},
{
"answer_id": 74279131,
"author": "Remzi Cavdar",
"author_id": 10686802,
"author_profile": "https://Stackoverflow.com/users/10686802",
"pm_score": 2,
"selected": true,
"text": "package YOUR_PACKAGE_NAME;\n\nimport javafx.application.Application;\n\n/**\n * Minimal reproducible example (MRE) - Example of a simple JavaFX preloader.\n * Java Main class for starting up the JavaFX application with a call to launch MainApplication.\n * @author Remzi Cavdar - ict@remzi.info - <a href=\"https://github.com/Remzi1993\">@Remzi1993</a>\n */\npublic class Main {\n public static void main(String[] args) {\n /*\n * The following Java system property is important for JavaFX to recognize your custom preloader class.\n * Which should extend javafx.application.Preloader.\n */\n System.setProperty(\"javafx.preloader\", Preloader.class.getName());\n // Launch the main JavaFX application class.\n Application.launch(MainApplication.class, args);\n }\n}\n package YOUR_PACKAGE_NAME;\n\nimport javafx.scene.Scene;\nimport javafx.scene.control.ProgressBar;\nimport javafx.scene.layout.BorderPane;\nimport javafx.stage.Stage;\n\n/**\n * Minimal reproducible example (MRE) - Example of a simple JavaFX preloader class.\n * @author Remzi Cavdar - ict@remzi.info - <a href=\"https://github.com/Remzi1993\">@Remzi1993</a>\n */\npublic class Preloader extends javafx.application.Preloader {\n private ProgressBar progressBar;\n private Stage stage;\n\n private Scene createPreloaderScene() {\n progressBar = new ProgressBar();\n BorderPane borderPane = new BorderPane();\n borderPane.setCenter(progressBar);\n return new Scene(borderPane, 800, 600);\n }\n\n @Override\n public void start(Stage stage) throws Exception {\n this.stage = stage;\n // I also recommend to set app icon: stage.getIcons().add();\n stage.setTitle(\"YOUR TILE HERE\");\n stage.setScene(createPreloaderScene());\n stage.show();\n }\n\n @Override\n public void handleProgressNotification(ProgressNotification pn) {\n progressBar.setProgress(pn.getProgress());\n }\n\n @Override\n public void handleStateChangeNotification(StateChangeNotification evt) {\n if (evt.getType() == StateChangeNotification.Type.BEFORE_START) {\n stage.hide();\n }\n }\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2197/"
] |
361,231 | <p>I have a cookie which is generated from a servlet and that I would like to be persistent - that is, set the cookie, close down IE, start it back up, and still be able to read the cookie. The code that I'm using is the following:</p>
<pre><code>HttpServletResponse response =
(HttpServletResponse) FacesContext.getCurrentInstance()
.getExternalContext().getResponse();
Cookie cookie = new Cookie("someKey", "someValue");
cookie.setMaxAge(7 * 24 * 60 * 60);
response.addCookie(cookie);
</code></pre>
<p>This works great in firefox, but in IE 6/7, the cookie is not saved between browser restarts. I've checked everything that I can think of in my settings, but can't figure out what would be causing the cookie to be deleted. As far as I know, calling setMaxAge with a positive number makes the cookie persistent. Any ideas why this would be going wrong?</p>
<p><b>Edit</b></p>
<p>I have verified, using the more info trick suggested by Olaf, that the cookie is attempting to be set as a session cookie, not a persistent cookie; the max age is set to "end of session". So it doesn't seem like the max age is being set for IE - I have verified that in Firefox, the max age is set correctly. I still have no idea what's going on.</p>
| [
{
"answer_id": 4187173,
"author": "Briguy37",
"author_id": 508537,
"author_profile": "https://Stackoverflow.com/users/508537",
"pm_score": 0,
"selected": false,
"text": "public static String encodeString(String s) {\n String encodedString = s;\n\n try{\n encodedString = URLEncoder.encode(s, \"UTF-8\");\n } catch (UnsupportedEncodingException e) {}\n\n return encodedString;\n}\npublic static String decodeString(String s) {\n String decodedString = s;\n\n try{\n decodedString = URLDecoder.decode(s, \"UTF-8\");\n } catch (UnsupportedEncodingException e) {}\n\n return decodedString;\n}\n"
},
{
"answer_id": 22933122,
"author": "sdfasdf",
"author_id": 3510298,
"author_profile": "https://Stackoverflow.com/users/3510298",
"pm_score": 0,
"selected": false,
"text": " try{\n encodedString = URLEncoder.encode(s, \"UTF-8\");\n } catch (UnsupportedEncodingException e) {}\n\n return encodedString;`a`\n}\npublic static String decodeString(String s) {\n String decodedString = s;\n\n try{\n decodedString = URLDecoder.decode(s, \"UTF-8\");\n } catch (UnsupportedEncodingException e) {}\n\n return decodedString;\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1322/"
] |
361,247 | <p>I have some data that I want to store somewhere in my Rails app because I use it for generating form fields, checking a submitted form to ensure its values are valid, etc. Basically, I want the data in one location because I make use of it in several places.</p>
<p>Previously, I was defining an <code>initialize</code> method in my controller and initializing instance variables within that method, e.g. <code>@graph_types = ['bar', 'line']</code>. This seemed a bad idea because that's really all <code>initialize</code> was being used for (initializing those values) and the instance variables could be changed later, which I don't want.</p>
<p>Now, I define constants outside of any method in my controller, right up at the top after my filters, and I freeze them, e.g. <code>GraphTypes = ['bar', 'line'].freeze</code>.</p>
<p>I didn't want to store such data in a config file because then I would have to keep track of an extra file, read in the file and parse it, etc. I didn't want to store this data in the database because that seems like overkill; I don't need to do any crazy LEFT OUTER JOIN-type queries combining available graph types with another of my constants, say <code>Themes = ['Keynote', 'Odeo', '37 Signals', 'Rails Keynote'].freeze</code>. I didn't want to store the data in environment.rb because this data only pertains to a particular controller.</p>
<p>Considering all this, am I going about this 'the Ruby way'?</p>
| [
{
"answer_id": 362247,
"author": "Daniel Lucraft",
"author_id": 11951,
"author_profile": "https://Stackoverflow.com/users/11951",
"pm_score": 2,
"selected": false,
"text": "GRAPH_TYPES initialize"
},
{
"answer_id": 364712,
"author": "user37011",
"author_id": 37011,
"author_profile": "https://Stackoverflow.com/users/37011",
"pm_score": 5,
"selected": false,
"text": " class StaticData\n\n GRAPH_TYPES = ['bar', 'line']\n\n SOMETHING_ELSE = ['A', 'B']\n\n end\n StaticData::GRAPH_TYPES\n"
},
{
"answer_id": 8072707,
"author": "Sasha",
"author_id": 201377,
"author_profile": "https://Stackoverflow.com/users/201377",
"pm_score": 4,
"selected": false,
"text": "Rails.root/config/initializers/constants.rb # Application configuration should go into files in config/initializers\n# -- all .rb files in that directory are automatically loaded\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38743/"
] |
361,248 | <p>Does VbScript have a native implementation for Regex? I need to validate e-mail addresses on an old ASP application.</p>
<p>Any pointers would be great.</p>
| [
{
"answer_id": 361273,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 4,
"selected": true,
"text": "Function ValidEmail(ByVal emailAddress) \n\n'this function will use regular expressions to check an '\n'email address for validity '\n\n'instantiate regex object container, output boolean '\nDim objRegEx, retVal \n\n'using late binding, vbscript reference is not required '\nSet objRegEx = CreateObject(\"VBScript.RegExp\") \n\n'.pattern -looks for a valid email address '\nWith objRegEx \n .Pattern = \"^\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}\\b$\" \n .IgnoreCase = True \nEnd With \n\nretVal = objRegEx.Test(emailAddress) \n\n'get rid of RegEx object '\nSet objRegEx = Nothing \n\nValidEmail = retVal \n\nEnd Function\n"
},
{
"answer_id": 378009,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 4,
"selected": false,
"text": "Option Explicit\n\nFunction GetEmailValidator()\n\n Set GetEmailValidator = New RegExp\n\n GetEmailValidator.Pattern = \"^((?:[A-Z0-9_%+-]+\\.?)+)@((?:[A-Z0-9-]+\\.)+[A-Z]{2,4})$\"\n\n GetEmailValidator.IgnoreCase = True\n\nEnd Function\n\nDim EmailValidator : Set EmailValidator = GetEmailValidator()\n Response.Write EmailValidator.Test(\"\") = False\nResponse.Write EmailValidator.Test(\" \") = False\nResponse.Write EmailValidator.Test(\"somebody@domain.co.uk\") = True\nResponse.Write EmailValidator.Test(\"someone@domain.com\") = True\nResponse.Write EmailValidator.Test(\"some.body@domain.co.uk\") = True\nResponse.Write EmailValidator.Test(\"broken@domain..co.uk\") = False\nResponse.Write EmailValidator.Test(\"@oops.co.uk\") = False\nResponse.Write EmailValidator.Test(\"name\") = False\nResponse.Write EmailValidator.Test(\"name@uk\") = False\nResponse.Write EmailValidator.Test(\"name@uk\") = False\nResponse.Write EmailValidator.Test(\"name@domain.abcde\") = False\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] |
361,258 | <p>I was going through some code and came across a scenario where my combobox has not been initialized yet. This is in .NET 2.0 and in the following code, this.cbRegion.SelectedValue is null.</p>
<pre><code>int id = (int)this.cbRegion.SelectedValue;
</code></pre>
<p>This code threw a null reference exception instead of an invalid cast exception. I was wondering if anyone knew why it would throw a null reference exception instead of a invalid cast?</p>
| [
{
"answer_id": 361303,
"author": "liggett78",
"author_id": 19762,
"author_profile": "https://Stackoverflow.com/users/19762",
"pm_score": 3,
"selected": false,
"text": "object o = null;\nint a = (int)o;\n ldnull\n...\nunbox.any int32\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23502/"
] |
361,266 | <p>If I have a base class such that</p>
<pre><code>public abstract class XMLSubscription <T extends XMLMessage>
</code></pre>
<p>Is it possible to write a method in XMLSubscription that returns a class object of T?</p>
<p>The only possible solution that I came up with is to have each descendant of XMLSubscription have a method like:</p>
<pre><code>public class XMLStatusSubscription extends XMLSubscription<XMLStatusMessage>
{
public Class <XMLStatusMessage> getExpectedMessageType()
{
return XMLStatusMessage.class;
}
}
</code></pre>
| [
{
"answer_id": 361288,
"author": "Greg Case",
"author_id": 462,
"author_profile": "https://Stackoverflow.com/users/462",
"pm_score": 3,
"selected": true,
"text": "Class public abstract class XMLSubscription <T extends XMLMessage> {\n private Class<T> messageType;\n\n protected XMLSubscription(Class<T> messageType) {\n this.messageType = messageType;\n }\n\n public Class<T> getExpectedMessageType() {\n return this.messageType;\n }\n}\n\npublic class XMLStatusSubscription extends XMLSubscription<XMLStatusMessage> {\n\n public XMLStatusSubscription() {\n super(XMLStatusMessage.class);\n }\n}\n"
},
{
"answer_id": 361308,
"author": "kdgregory",
"author_id": 42126,
"author_profile": "https://Stackoverflow.com/users/42126",
"pm_score": 0,
"selected": false,
"text": "public Class<T> getExpectedMessageType()\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7949/"
] |
361,285 | <p>I'm writing a basic crawler that simply caches pages with PHP.</p>
<p>All it does is use <code>get_file_contents</code> to get contents of a webpage and regex to get all the links out <code><a href="URL">DESCRIPTION</a></code> - at the moment it returns:</p>
<pre><code>Array {
[url] => URL
[desc] => DESCRIPTION
}
</code></pre>
<p>The problem I'm having is figuring out the logic behind determining whether the page link is local or sussing out whether it may be in a completely different local directory.</p>
<p>It could be any number of combinations: i.e. <code>href="../folder/folder2/blah/page.html"</code> or <code>href="google.com"</code> or <code>href="page.html"</code> - the possibilities are endless.</p>
<p>What would be the correct algorithm to approach this? I don't want to lose any data that could be important.</p>
| [
{
"answer_id": 361320,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 3,
"selected": true,
"text": "foreach(DOMDocument::loadHTML($source)->getElementsByTagName('a') as $a)\n{\n $a->getAttribute('href');\n}\n // http://example.com\n//example.com/\n href=\"google.com\" wget"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24416/"
] |
361,301 | <p>Is there any way I can vary caching by a controller action parameter using the <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.outputcacheattribute(v=vs.108).aspx" rel="nofollow noreferrer">outputcache</a> attribute? We have <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.outputcacheattribute.varybyparam(v=vs.108).aspx" rel="nofollow noreferrer">varybyparam</a> which will not work if my parameters are embedded within the URL in a REST manner.</p>
| [
{
"answer_id": 865003,
"author": "Simon_Weaver",
"author_id": 16940,
"author_profile": "https://Stackoverflow.com/users/16940",
"pm_score": 3,
"selected": false,
"text": "[OutputCache(CacheProfile = \"ContentPage\", VaryByParam = \"mode\")]\npublic ActionResult Index(string key, string mode)\n{\n\n}\n routes.MapRoute(\n \"video-route-short\",\n \"video/{key}\",\n new { controller = \"Video\", action = \"Index\", key = (string)null }\n );\n ?mode=1"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33764/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.