text stringlengths 8 267k | meta dict |
|---|---|
Q: PHP / Mime Types - List of mime types publically available? I'm looking for an array, preferably php or json, that maps file extensions to mime types. This is intended to be a fallback for servers without Fileinfo, mime_content_type, or PEAR support.
Here is my pathetic list atm...
// Fallback for servers without Fileinfo, mime_content_type, or PEAR support.
$mime_types_map = array(
'3dm' => 'x-world/x-3dmf', '3dmf' => 'x-world/x-3dmf', 'a' => 'application/octet-stream', 'aab' => 'application/x-authorware-bin',
'aam' => 'application/x-authorware-map', 'aas' => 'application/x-authorware-seg', 'abc' => 'text/vnd.abc', 'acgi' => 'text/html',
'afl' => 'video/animaflex', 'ai' => 'application/postscript', 'aif' => 'audio/aiff', 'aif' => 'audio/x-aiff',
'aifc' => 'audio/aiff', 'aifc' => 'audio/x-aiff', 'aiff' => 'audio/aiff', 'aiff' => 'audio/x-aiff',
'aim' => 'application/x-aim', 'aip' => 'text/x-audiosoft-intra', 'ani' => 'application/x-navi-animation', 'aos' => 'application/x-nokia-9000-communicator-add-on-software',
'aps' => 'application/mime', 'arc' => 'application/octet-stream', 'arj' => 'application/arj', 'arj' => 'application/octet-stream',
'art' => 'image/x-jg', 'asf' => 'video/x-ms-asf', 'asm' => 'text/x-asm', 'asp' => 'text/asp',
'asx' => 'application/x-mplayer2', 'asx' => 'video/x-ms-asf', 'asx' => 'video/x-ms-asf-plugin', 'au' => 'audio/basic',
'au' => 'audio/x-au', 'avi' => 'application/x-troff-msvideo', 'avi' => 'video/avi', 'avi' => 'video/msvideo',
'avi' => 'video/x-msvideo', 'avs' => 'video/avs-video', 'bcpio' => 'application/x-bcpio', 'bin' => 'application/mac-binary',
'bin' => 'application/macbinary', 'bin' => 'application/octet-stream', 'bin' => 'application/x-binary', 'bin' => 'application/x-macbinary',
'bm' => 'image/bmp', 'bmp' => 'image/bmp', 'bmp' => 'image/x-windows-bmp', 'boo' => 'application/book',
'book' => 'application/book', 'boz' => 'application/x-bzip2', 'bsh' => 'application/x-bsh', 'bz' => 'application/x-bzip',
'bz2' => 'application/x-bzip2', 'c' => 'text/plain', 'c' => 'text/x-c', 'c++' => 'text/plain',
'cat' => 'application/vnd.ms-pki.seccat', 'cc' => 'text/plain', 'cc' => 'text/x-c', 'ccad' => 'application/clariscad',
'cco' => 'application/x-cocoa', 'cdf' => 'application/cdf', 'cdf' => 'application/x-cdf', 'cdf' => 'application/x-netcdf',
'cer' => 'application/pkix-cert', 'cer' => 'application/x-x509-ca-cert', 'cha' => 'application/x-chat', 'chat' => 'application/x-chat',
'class' => 'application/java', 'class' => 'application/java-byte-code', 'class' => 'application/x-java-class', 'com' => 'application/octet-stream',
'com' => 'text/plain', 'conf' => 'text/plain', 'cpio' => 'application/x-cpio', 'cpp' => 'text/x-c',
'cpt' => 'application/mac-compactpro', 'cpt' => 'application/x-compactpro', 'cpt' => 'application/x-cpt', 'crl' => 'application/pkcs-crl',
'crl' => 'application/pkix-crl', 'crt' => 'application/pkix-cert', 'crt' => 'application/x-x509-ca-cert', 'crt' => 'application/x-x509-user-cert',
'csh' => 'application/x-csh', 'csh' => 'text/x-script.csh', 'css' => 'application/x-pointplus', 'css' => 'text/css',
'cxx' => 'text/plain', 'dcr' => 'application/x-director', 'deepv' => 'application/x-deepv', 'def' => 'text/plain',
'der' => 'application/x-x509-ca-cert', 'dif' => 'video/x-dv', 'dir' => 'application/x-director', 'dl' => 'video/dl',
'dl' => 'video/x-dl', 'doc' => 'application/msword', 'dot' => 'application/msword', 'dp' => 'application/commonground',
'drw' => 'application/drafting', 'dump' => 'application/octet-stream', 'dv' => 'video/x-dv', 'dvi' => 'application/x-dvi',
'dwf' => 'drawing/x-dwf', 'dwf' => 'model/vnd.dwf', 'dwg' => 'application/acad', 'dwg' => 'image/vnd.dwg',
'dwg' => 'image/x-dwg', 'dxf' => 'application/dxf', 'dxf' => 'image/vnd.dwg', 'dxf' => 'image/x-dwg',
'dxr' => 'application/x-director', 'el' => 'text/x-script.elisp', 'elc' => 'application/x-bytecode.elisp', 'elc' => 'application/x-elc',
'env' => 'application/x-envoy', 'eps' => 'application/postscript', 'es' => 'application/x-esrehber', 'etx' => 'text/x-setext',
'evy' => 'application/envoy', 'evy' => 'application/x-envoy', 'exe' => 'application/octet-stream', 'f' => 'text/plain',
'f' => 'text/x-fortran', 'f77' => 'text/x-fortran', 'f90' => 'text/plain', 'f90' => 'text/x-fortran',
'fdf' => 'application/vnd.fdf', 'fif' => 'application/fractals', 'fif' => 'image/fif', 'fli' => 'video/fli',
'fli' => 'video/x-fli', 'flo' => 'image/florian', 'flx' => 'text/vnd.fmi.flexstor', 'fmf' => 'video/x-atomic3d-feature',
'for' => 'text/plain', 'for' => 'text/x-fortran', 'fpx' => 'image/vnd.fpx', 'fpx' => 'image/vnd.net-fpx',
'frl' => 'application/freeloader', 'funk' => 'audio/make', 'g' => 'text/plain', 'g3' => 'image/g3fax',
'gif' => 'image/gif', 'gl' => 'video/gl', 'gl' => 'video/x-gl', 'gsd' => 'audio/x-gsm',
'gsm' => 'audio/x-gsm', 'gsp' => 'application/x-gsp', 'gss' => 'application/x-gss', 'gtar' => 'application/x-gtar',
'gz' => 'application/x-compressed', 'gz' => 'application/x-gzip', 'gzip' => 'application/x-gzip', 'gzip' => 'multipart/x-gzip',
'h' => 'text/plain', 'h' => 'text/x-h', 'hdf' => 'application/x-hdf', 'help' => 'application/x-helpfile',
'hgl' => 'application/vnd.hp-hpgl', 'hh' => 'text/plain', 'hh' => 'text/x-h', 'hlb' => 'text/x-script',
'hlp' => 'application/hlp', 'hlp' => 'application/x-helpfile', 'hlp' => 'application/x-winhelp', 'hpg' => 'application/vnd.hp-hpgl',
'hpgl' => 'application/vnd.hp-hpgl', 'hqx' => 'application/binhex', 'hqx' => 'application/binhex4', 'hqx' => 'application/mac-binhex',
'hqx' => 'application/mac-binhex40', 'hqx' => 'application/x-binhex40', 'hqx' => 'application/x-mac-binhex40', 'hta' => 'application/hta',
'htc' => 'text/x-component', 'htm' => 'text/html', 'html' => 'text/html', 'htmls' => 'text/html',
'htt' => 'text/webviewhtml', 'htx' => 'text/html', 'ice' => 'x-conference/x-cooltalk', 'ico' => 'image/x-icon',
'idc' => 'text/plain', 'ief' => 'image/ief', 'iefs' => 'image/ief', 'iges' => 'application/iges',
'iges' => 'model/iges', 'igs' => 'application/iges', 'igs' => 'model/iges', 'ima' => 'application/x-ima',
'imap' => 'application/x-httpd-imap', 'inf' => 'application/inf', 'ins' => 'application/x-internett-signup', 'ip' => 'application/x-ip2',
'isu' => 'video/x-isvideo', 'it' => 'audio/it', 'iv' => 'application/x-inventor', 'ivr' => 'i-world/i-vrml',
'ivy' => 'application/x-livescreen', 'jam' => 'audio/x-jam', 'jav' => 'text/plain', 'jav' => 'text/x-java-source',
'java' => 'text/plain', 'java' => 'text/x-java-source', 'jcm' => 'application/x-java-commerce', 'jfif' => 'image/jpeg',
'jfif' => 'image/pjpeg', 'jfif-tbnl' => 'image/jpeg', 'jpe' => 'image/jpeg', 'jpe' => 'image/pjpeg',
'jpeg' => 'image/jpeg', 'jpeg' => 'image/pjpeg', 'jpg' => 'image/jpeg', 'jpg' => 'image/pjpeg',
'jps' => 'image/x-jps', 'js' => 'application/x-javascript', 'jut' => 'image/jutvision', 'kar' => 'audio/midi',
'kar' => 'music/x-karaoke', 'ksh' => 'application/x-ksh', 'ksh' => 'text/x-script.ksh', 'la' => 'audio/nspaudio',
'la' => 'audio/x-nspaudio', 'lam' => 'audio/x-liveaudio', 'latex' => 'application/x-latex', 'lha' => 'application/lha',
'lha' => 'application/octet-stream', 'lha' => 'application/x-lha', 'lhx' => 'application/octet-stream', 'list' => 'text/plain',
'lma' => 'audio/nspaudio', 'lma' => 'audio/x-nspaudio', 'log' => 'text/plain', 'lsp' => 'application/x-lisp',
'lsp' => 'text/x-script.lisp', 'lst' => 'text/plain', 'lsx' => 'text/x-la-asf', 'ltx' => 'application/x-latex',
'lzh' => 'application/octet-stream', 'lzh' => 'application/x-lzh', 'lzx' => 'application/lzx', 'lzx' => 'application/octet-stream',
'lzx' => 'application/x-lzx', 'm' => 'text/plain', 'm' => 'text/x-m', 'm1v' => 'video/mpeg',
'm2a' => 'audio/mpeg', 'm2v' => 'video/mpeg', 'm3u' => 'audio/x-mpequrl', 'man' => 'application/x-troff-man',
'map' => 'application/x-navimap', 'mar' => 'text/plain', 'mbd' => 'application/mbedlet', 'mc$' => 'application/x-magic-cap-package-1.0',
'mcd' => 'application/mcad', 'mcd' => 'application/x-mathcad', 'mcf' => 'image/vasa', 'mcf' => 'text/mcf',
'mcp' => 'application/netmc', 'me' => 'application/x-troff-me', 'mht' => 'message/rfc822', 'mhtml' => 'message/rfc822',
'mid' => 'application/x-midi', 'mid' => 'audio/midi', 'mid' => 'audio/x-mid', 'mid' => 'audio/x-midi',
'mid' => 'music/crescendo', 'mid' => 'x-music/x-midi', 'midi' => 'application/x-midi', 'midi' => 'audio/midi',
'midi' => 'audio/x-mid', 'midi' => 'audio/x-midi', 'midi' => 'music/crescendo', 'midi' => 'x-music/x-midi',
'mif' => 'application/x-frame', 'mif' => 'application/x-mif', 'mime' => 'message/rfc822', 'mime' => 'www/mime',
'mjf' => 'audio/x-vnd.audioexplosion.mjuicemediafile', 'mjpg' => 'video/x-motion-jpeg', 'mm' => 'application/base64', 'mm' => 'application/x-meme',
'mme' => 'application/base64', 'mod' => 'audio/mod', 'mod' => 'audio/x-mod', 'moov' => 'video/quicktime',
'mov' => 'video/quicktime', 'movie' => 'video/x-sgi-movie', 'mp2' => 'audio/mpeg', 'mp2' => 'audio/x-mpeg',
'mp2' => 'video/mpeg', 'mp2' => 'video/x-mpeg', 'mp2' => 'video/x-mpeq2a', 'mp3' => 'audio/mpeg3',
'mp3' => 'audio/x-mpeg-3', 'mp3' => 'video/mpeg', 'mp3' => 'video/x-mpeg', 'mpa' => 'audio/mpeg',
'mpa' => 'video/mpeg', 'mpc' => 'application/x-project', 'mpe' => 'video/mpeg', 'mpeg' => 'video/mpeg',
'mpg' => 'audio/mpeg', 'mpg' => 'video/mpeg', 'mpga' => 'audio/mpeg', 'mpp' => 'application/vnd.ms-project',
'mpt' => 'application/x-project', 'mpv' => 'application/x-project', 'mpx' => 'application/x-project', 'mrc' => 'application/marc',
'ms' => 'application/x-troff-ms', 'mv' => 'video/x-sgi-movie', 'my' => 'audio/make', 'mzz' => 'application/x-vnd.audioexplosion.mzz',
'nap' => 'image/naplps', 'naplps' => 'image/naplps', 'nc' => 'application/x-netcdf', 'ncm' => 'application/vnd.nokia.configuration-message',
'nif' => 'image/x-niff', 'niff' => 'image/x-niff', 'nix' => 'application/x-mix-transfer', 'nsc' => 'application/x-conference',
'nvd' => 'application/x-navidoc', 'o' => 'application/octet-stream', 'oda' => 'application/oda', 'omc' => 'application/x-omc',
'omcd' => 'application/x-omcdatamaker', 'omcr' => 'application/x-omcregerator', 'p' => 'text/x-pascal', 'p10' => 'application/pkcs10',
'p10' => 'application/x-pkcs10', 'p12' => 'application/pkcs-12', 'p12' => 'application/x-pkcs12', 'p7a' => 'application/x-pkcs7-signature',
'p7c' => 'application/pkcs7-mime', 'p7c' => 'application/x-pkcs7-mime', 'p7m' => 'application/pkcs7-mime', 'p7m' => 'application/x-pkcs7-mime',
'p7r' => 'application/x-pkcs7-certreqresp', 'p7s' => 'application/pkcs7-signature', 'part' => 'application/pro_eng', 'pas' => 'text/pascal',
'pbm' => 'image/x-portable-bitmap', 'pcl' => 'application/vnd.hp-pcl', 'pcl' => 'application/x-pcl', 'pct' => 'image/x-pict',
'pcx' => 'image/x-pcx', 'pdb' => 'chemical/x-pdb', 'pdf' => 'application/pdf', 'pfunk' => 'audio/make',
'pfunk' => 'audio/make.my.funk', 'pgm' => 'image/x-portable-graymap', 'pgm' => 'image/x-portable-greymap', 'pic' => 'image/pict',
'pict' => 'image/pict', 'pkg' => 'application/x-newton-compatible-pkg', 'pko' => 'application/vnd.ms-pki.pko', 'pl' => 'text/plain',
'pl' => 'text/x-script.perl', 'plx' => 'application/x-pixclscript', 'pm' => 'image/x-xpixmap', 'pm' => 'text/x-script.perl-module',
'pm4' => 'application/x-pagemaker', 'pm5' => 'application/x-pagemaker', 'png' => 'image/png', 'pnm' => 'application/x-portable-anymap',
'pnm' => 'image/x-portable-anymap', 'pot' => 'application/mspowerpoint', 'pot' => 'application/vnd.ms-powerpoint', 'pov' => 'model/x-pov',
'ppa' => 'application/vnd.ms-powerpoint', 'ppm' => 'image/x-portable-pixmap', 'pps' => 'application/mspowerpoint', 'pps' => 'application/vnd.ms-powerpoint',
'ppt' => 'application/mspowerpoint', 'ppt' => 'application/powerpoint', 'ppt' => 'application/vnd.ms-powerpoint', 'ppt' => 'application/x-mspowerpoint',
'ppz' => 'application/mspowerpoint', 'pre' => 'application/x-freelance', 'prt' => 'application/pro_eng', 'ps' => 'application/postscript',
'psd' => 'application/octet-stream', 'pvu' => 'paleovu/x-pv', 'pwz' => 'application/vnd.ms-powerpoint', 'py' => 'text/x-script.phyton',
'pyc' => 'applicaiton/x-bytecode.python', 'qcp' => 'audio/vnd.qcelp', 'qd3' => 'x-world/x-3dmf', 'qd3d' => 'x-world/x-3dmf',
'qif' => 'image/x-quicktime', 'qt' => 'video/quicktime', 'qtc' => 'video/x-qtc', 'qti' => 'image/x-quicktime',
'qtif' => 'image/x-quicktime', 'ra' => 'audio/x-pn-realaudio', 'ra' => 'audio/x-pn-realaudio-plugin', 'ra' => 'audio/x-realaudio',
'ram' => 'audio/x-pn-realaudio', 'ras' => 'application/x-cmu-raster', 'ras' => 'image/cmu-raster', 'ras' => 'image/x-cmu-raster',
'rast' => 'image/cmu-raster', 'rexx' => 'text/x-script.rexx', 'rf' => 'image/vnd.rn-realflash', 'rgb' => 'image/x-rgb',
'rm' => 'application/vnd.rn-realmedia', 'rm' => 'audio/x-pn-realaudio', 'rmi' => 'audio/mid', 'rmm' => 'audio/x-pn-realaudio',
'rmp' => 'audio/x-pn-realaudio', 'rmp' => 'audio/x-pn-realaudio-plugin', 'rng' => 'application/ringing-tones', 'rng' => 'application/vnd.nokia.ringing-tone',
'rnx' => 'application/vnd.rn-realplayer', 'roff' => 'application/x-troff', 'rp' => 'image/vnd.rn-realpix', 'rpm' => 'audio/x-pn-realaudio-plugin',
'rt' => 'text/richtext', 'rt' => 'text/vnd.rn-realtext', 'rtf' => 'application/rtf', 'rtf' => 'application/x-rtf',
'rtf' => 'text/richtext', 'rtx' => 'application/rtf', 'rtx' => 'text/richtext', 'rv' => 'video/vnd.rn-realvideo',
's' => 'text/x-asm', 's3m' => 'audio/s3m', 'saveme' => 'application/octet-stream', 'sbk' => 'application/x-tbook',
'scm' => 'application/x-lotusscreencam', 'scm' => 'text/x-script.guile', 'scm' => 'text/x-script.scheme', 'scm' => 'video/x-scm',
'sdml' => 'text/plain', 'sdp' => 'application/sdp', 'sdp' => 'application/x-sdp', 'sdr' => 'application/sounder',
'sea' => 'application/sea', 'sea' => 'application/x-sea', 'set' => 'application/set', 'sgm' => 'text/sgml',
'sgm' => 'text/x-sgml', 'sgml' => 'text/sgml', 'sgml' => 'text/x-sgml', 'sh' => 'application/x-bsh',
'sh' => 'application/x-sh', 'sh' => 'application/x-shar', 'sh' => 'text/x-script.sh', 'shar' => 'application/x-bsh',
'shar' => 'application/x-shar', 'shtml' => 'text/html', 'shtml' => 'text/x-server-parsed-html', 'sid' => 'audio/x-psid',
'sit' => 'application/x-sit', 'sit' => 'application/x-stuffit', 'skd' => 'application/x-koan', 'skm' => 'application/x-koan',
'skp' => 'application/x-koan', 'skt' => 'application/x-koan', 'sl' => 'application/x-seelogo', 'smi' => 'application/smil',
'smil' => 'application/smil', 'snd' => 'audio/basic', 'snd' => 'audio/x-adpcm', 'sol' => 'application/solids',
'spc' => 'application/x-pkcs7-certificates', 'spc' => 'text/x-speech', 'spl' => 'application/futuresplash', 'spr' => 'application/x-sprite',
'sprite' => 'application/x-sprite', 'src' => 'application/x-wais-source', 'ssi' => 'text/x-server-parsed-html', 'ssm' => 'application/streamingmedia',
'sst' => 'application/vnd.ms-pki.certstore', 'step' => 'application/step', 'stl' => 'application/sla', 'stl' => 'application/vnd.ms-pki.stl',
'stl' => 'application/x-navistyle', 'stp' => 'application/step', 'sv4cpio' => 'application/x-sv4cpio', 'sv4crc' => 'application/x-sv4crc',
'svf' => 'image/vnd.dwg', 'svf' => 'image/x-dwg', 'svr' => 'application/x-world', 'svr' => 'x-world/x-svr',
'swf' => 'application/x-shockwave-flash', 't' => 'application/x-troff', 'talk' => 'text/x-speech', 'tar' => 'application/x-tar',
'tbk' => 'application/toolbook', 'tbk' => 'application/x-tbook', 'tcl' => 'application/x-tcl', 'tcl' => 'text/x-script.tcl',
'tcsh' => 'text/x-script.tcsh', 'tex' => 'application/x-tex', 'texi' => 'application/x-texinfo', 'texinfo' => 'application/x-texinfo',
'text' => 'application/plain', 'text' => 'text/plain', 'tgz' => 'application/gnutar', 'tgz' => 'application/x-compressed',
'tif' => 'image/tiff', 'tif' => 'image/x-tiff', 'tiff' => 'image/tiff', 'tiff' => 'image/x-tiff',
'tr' => 'application/x-troff', 'tsi' => 'audio/tsp-audio', 'tsp' => 'application/dsptype', 'tsp' => 'audio/tsplayer',
'tsv' => 'text/tab-separated-values', 'turbot' => 'image/florian', 'txt' => 'text/plain', 'uil' => 'text/x-uil',
'uni' => 'text/uri-list', 'unis' => 'text/uri-list', 'unv' => 'application/i-deas', 'uri' => 'text/uri-list',
'uris' => 'text/uri-list', 'ustar' => 'application/x-ustar', 'ustar' => 'multipart/x-ustar', 'uu' => 'application/octet-stream',
'uu' => 'text/x-uuencode', 'uue' => 'text/x-uuencode', 'vcd' => 'application/x-cdlink', 'vcs' => 'text/x-vcalendar',
'vda' => 'application/vda', 'vdo' => 'video/vdo', 'vew' => 'application/groupwise', 'viv' => 'video/vivo',
'viv' => 'video/vnd.vivo', 'vivo' => 'video/vivo', 'vivo' => 'video/vnd.vivo', 'vmd' => 'application/vocaltec-media-desc',
'vmf' => 'application/vocaltec-media-file', 'voc' => 'audio/voc', 'voc' => 'audio/x-voc', 'vos' => 'video/vosaic',
'vox' => 'audio/voxware', 'vqe' => 'audio/x-twinvq-plugin', 'vqf' => 'audio/x-twinvq', 'vql' => 'audio/x-twinvq-plugin',
'vrml' => 'application/x-vrml', 'vrml' => 'model/vrml', 'vrml' => 'x-world/x-vrml', 'vrt' => 'x-world/x-vrt',
'vsd' => 'application/x-visio', 'vst' => 'application/x-visio', 'vsw' => 'application/x-visio', 'w60' => 'application/wordperfect6.0',
'w61' => 'application/wordperfect6.1', 'w6w' => 'application/msword', 'wav' => 'audio/wav', 'wav' => 'audio/x-wav',
'wb1' => 'application/x-qpro', 'wbmp' => 'image/vnd.wap.wbmp', 'web' => 'application/vnd.xara', 'wiz' => 'application/msword',
'wk1' => 'application/x-123', 'wmf' => 'windows/metafile', 'wml' => 'text/vnd.wap.wml', 'wmlc' => 'application/vnd.wap.wmlc',
'wmls' => 'text/vnd.wap.wmlscript', 'wmlsc' => 'application/vnd.wap.wmlscriptc', 'word' => 'application/msword', 'wp' => 'application/wordperfect',
'wp5' => 'application/wordperfect', 'wp5' => 'application/wordperfect6.0', 'wp6' => 'application/wordperfect', 'wpd' => 'application/wordperfect',
'wpd' => 'application/x-wpwin', 'wq1' => 'application/x-lotus', 'wri' => 'application/mswrite', 'wri' => 'application/x-wri',
'wrl' => 'application/x-world', 'wrl' => 'model/vrml', 'wrl' => 'x-world/x-vrml', 'wrz' => 'model/vrml',
'wrz' => 'x-world/x-vrml', 'wsc' => 'text/scriplet', 'wsrc' => 'application/x-wais-source', 'wtk' => 'application/x-wintalk',
'xbm' => 'image/x-xbitmap', 'xbm' => 'image/x-xbm', 'xbm' => 'image/xbm', 'xdr' => 'video/x-amt-demorun',
'xgz' => 'xgl/drawing', 'xif' => 'image/vnd.xiff', 'xl' => 'application/excel', 'xla' => 'application/excel',
'xla' => 'application/x-excel', 'xla' => 'application/x-msexcel', 'xlb' => 'application/excel', 'xlb' => 'application/vnd.ms-excel',
'xlb' => 'application/x-excel', 'xlc' => 'application/excel', 'xlc' => 'application/vnd.ms-excel', 'xlc' => 'application/x-excel',
'xld' => 'application/excel', 'xld' => 'application/x-excel', 'xlk' => 'application/excel', 'xlk' => 'application/x-excel',
'xll' => 'application/excel', 'xll' => 'application/vnd.ms-excel', 'xll' => 'application/x-excel', 'xlm' => 'application/excel',
'xlm' => 'application/vnd.ms-excel', 'xlm' => 'application/x-excel', 'xls' => 'application/excel', 'xls' => 'application/vnd.ms-excel',
'xls' => 'application/x-excel', 'xls' => 'application/x-msexcel', 'xlt' => 'application/excel', 'xlt' => 'application/x-excel',
'xlv' => 'application/excel', 'xlv' => 'application/x-excel', 'xlw' => 'application/excel', 'xlw' => 'application/vnd.ms-excel',
'xlw' => 'application/x-excel', 'xlw' => 'application/x-msexcel', 'xm' => 'audio/xm', 'xml' => 'application/xml',
'xml' => 'text/xml', 'xmz' => 'xgl/movie', 'xpix' => 'application/x-vnd.ls-xpix', 'xpm' => 'image/x-xpixmap',
'xpm' => 'image/xpm', 'x-png' => 'image/png', 'xsr' => 'video/x-amt-showrun', 'xwd' => 'image/x-xwd',
'xwd' => 'image/x-xwindowdump', 'xyz' => 'chemical/x-pdb', 'z' => 'application/x-compress', 'z' => 'application/x-compressed',
'zip' => 'application/x-compressed', 'zip' => 'application/x-zip-compressed', 'zip' => 'application/zip', 'zip' => 'multipart/x-zip',
'zoo' => 'application/octet-stream', 'zsh' => 'text/x-script.zsh',
);
Edit: This script is for a buddy who isn't php/apache savvy. I don't know where it will be deployed - so I can't install PEAR or anything.
Edit2: Updated array from list in rfausak's comment - http://www.webmaster-toolkit.com/mime-types.shtml
A: If your using Apache .htaccess can be used to map mime types.
moreinfo
Here is IANA's List of MIME TYPES
A: June, 2022 update: The mime-db project is the best source of mime DB type mappings that I'm aware of. It aggregates MIME information from IANA, Apache, and NGINX, and is updated regularly, and publishes this information as a single JSON file.
A: I think you won't find the whole list in one page, but you can take a look around google. Good one is this list
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519393",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: drupal_map_assoc($array) function _ahah_example_get_first_dropdown_options() {
$stid = oci_parse($conn, "SELECt code,descr1 FROM dbtest.regions");
oci_execute($stid);
$region= array();
while (($row = oci_fetch_array($stid, OCI_ASSOC))) {
$region[$row['CODE']]= $row['DESCR1'];
}
$region['']='Select';
oci_free_statement($stid);
oci_close($conn);
return drupal_map_assoc($region);
}
but it returns the key and the value equal I need the original key to be returne cause im using it's value in a javascript function?anyone would know how to return the original Key?
A: From your code, you should be able to skip drupal_map_assoc and just return $region. Give that a try and see if you like the results.
Reference http://api.drupal.org/api/drupal/includes--common.inc/function/drupal_map_assoc/6
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519397",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to convert Java Map to a basic Javascript object? I'm starting to use the dynamic rhinoscript feature in Java 6 for use by customers who are more likely to know Javascript than Java.
What is the best way to pass a Map (associative array, javascript obj, whatever) into Javascript so the script-writers can use the standard Javascript dot notation for accessing values?
I'm currently passing a java.util.Map of values into the script, however then the script writer has to write "map.get('mykey')" instead of "map.mykey".
Basically, I want to do the opposite of this question.
A: I am using an utility class that convert Map into javascript hash object:
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import org.mozilla.javascript.Scriptable;
public class MapScriptable implements Scriptable, Map {
public final Map map;
public MapScriptable(Map map) {
this.map = map;
}
public void clear() {
map.clear();
}
public boolean containsKey(Object key) {
return map.containsKey(key);
}
public boolean containsValue(Object value) {
return map.containsValue(value);
}
public Set entrySet() {
return map.entrySet();
}
public boolean equals(Object o) {
return map.equals(o);
}
public Object get(Object key) {
return map.get(key);
}
public int hashCode() {
return map.hashCode();
}
public boolean isEmpty() {
return map.isEmpty();
}
public Set keySet() {
return map.keySet();
}
public Object put(Object key, Object value) {
return map.put(key, value);
}
public void putAll(Map m) {
map.putAll(m);
}
public Object remove(Object key) {
return map.remove(key);
}
public int size() {
return map.size();
}
public Collection values() {
return map.values();
}
@Override
public void delete(String name) {
map.remove(name);
}
@Override
public void delete(int index) {
map.remove(index);
}
@Override
public Object get(String name, Scriptable start) {
return map.get(name);
}
@Override
public Object get(int index, Scriptable start) {
return map.get(index);
}
@Override
public String getClassName() {
return map.getClass().getName();
}
@Override
public Object getDefaultValue(Class<?> hint) {
return toString();
}
@Override
public Object[] getIds() {
Object[] res=new Object[map.size()];
int i=0;
for (Object k:map.keySet()) {
res[i]=k;
i++;
}
return res;
}
@Override
public Scriptable getParentScope() {
return null;
}
@Override
public Scriptable getPrototype() {
return null;
}
@Override
public boolean has(String name, Scriptable start) {
return map.containsKey(name);
}
@Override
public boolean has(int index, Scriptable start) {
return map.containsKey(index);
}
@Override
public boolean hasInstance(Scriptable instance) {
return false;
}
@Override
public void put(String name, Scriptable start, Object value) {
map.put(name, value);
}
@Override
public void put(int index, Scriptable start, Object value) {
map.put(index, value);
}
@Override
public void setParentScope(Scriptable parent) {}
@Override
public void setPrototype(Scriptable prototype) {}
}
Sample:
import java.util.HashMap;
import java.util.Map;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ScriptableObject;
public class MapScriptableMain {
public static void main(String[] args) {
Map src=new HashMap();
src.put("foo", 2);
src.put("bar", 3);
MapScriptable m=new MapScriptable(src);
Context c=Context.enter();
ScriptableObject scope = c.initStandardObjects();
ScriptableObject.putProperty(scope, "m", m);
String source = "m.baz=m.foo+m.bar;";
Object a=c.evaluateString(scope, source, "TEST", 1, null);
System.out.println(a); // 5.0
System.out.println(src.get("baz")); // 5.0;
}
}
A: After figuring out that the SimpleScriptContext will only take the Map object and thus force you to use the Java methods in your JavaScript, here's what I did.
Map<String, String> myMap = new HashMap<String, String>();
myMap.put("test", "hello world!");
ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
Object eval = engine.eval("var map = " + new Gson().toJson(myMap) + ";\n"
+ "println(map.test);");
Which printed out
hello world!
A: You just need to encode your object as JSON, either manually, or using a library like Jackson or gson. As you said, it's the exact oposite of that question and the author of that question is not happy with the JSON notation :)
What you need to send to the browser is basically something like this:
var someObject = { "key1": "value1", "key2": "value2", ... }
And then the javascript developer can simply access: someObject.key2.
A: I took the Java NativeObject approach and here is what I did...
// build a Map
Map<String, String> map = new HashMap<String, String>();
map.put("bye", "now");
// Convert it to a NativeObject (yes, this could have been done directly)
NativeObject nobj = new NativeObject();
for (Map.Entry<String, String> entry : map.entrySet()) {
nobj.defineProperty(entry.getKey(), entry.getValue(), NativeObject.READONLY);
}
// Get Engine and place native object into the context
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("javascript");
engine.put("map", nobj);
// Standard Javascript dot notation prints 'now' (as it should!)
engine.eval("println(map.bye);");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: android: Unable to access struct static data members I'm having the next kind of error when linking the application:
undefined reference to 'MyStructure::K_VARIABLE_A
undefined reference to 'MyStructure::K_VARIABLE_B
...
The structure is defined inside "MyStructure.h" as:
struct MyStructure
{
const static int K_VARIABLE_A=1;
const static int K_VARIABLE_B=2;
...
}
How can i get rid of this error?
My source code compiles successfully for Windows platform but I get the error mentioned above when compiling for the android platform.
The header of this structure is properly included in the .cpp file.
Thanks in advance.
A: The preferred way to define constant values in the scope of a class/struct is this:
struct MyStructure
{
enum
{
K_VARIABLE_A=1,
K_VARIABLE_B=2, // Note that you CAN keep the trailing comma
...
};
};
A: The construct which you are using is called as In-Class Initialization. It is a valid syntax for integral constant types but it maynot work with some compilers.
Solution is to do:
const int MyStructure::K_VARIABLE_A=1;
const int MyStructure::K_VARIABLE_B=2;
in one of your cpp(Implementation) files.
A: For each of your static variables you will need to declare them in an compilation unit (traditionally .cpp file) so that they have storage space as such
#include "Mystructure.h"
const int MyStructure::K_VARIABLE_A = 1;
const int MyStructure::K_VARIABLE_B = 2;
// other stuff here...
This is because static members do not belong to any instance of the structure/class, but need storage space declared somewhere. The compilers leave it up to the programmer to specify which compilation unit contains the storage for the static members, but traditionally they will be placed in the .cpp file corresponding to the .h file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519404",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Multiple Frontends - Java Backend I just started working on a project which will about making a big website.
With big i mean:
*
*Webshop
*Forum
*Normal Website (Information pages etc..)
At first i just wanted to pick a decent open-source webshop and just built my site around it.
But then i started thinking about how to expand etc.
I started to think how i would like this website to be acces from a mobile phone. Not just with a browser but with an App. (I have decent experience in making apps for Android & Iphone). So the real question is:
Would it be smart to make the "Core" of my whole website in Java and use services to acces it and thus allowing different frontends to use the same "Core". Like:
- PHP for browser frontend
- Java (android) for the android App
- Objective C for the IPhone App.
And let them all just communication to the "Core" through REST (Json).
What will be the advantages / disadvantages with this approach and will there be a significant delay in rendering eg. a webpage (http request to php, then php making calls to java server (different physical server) then accessing the database and then returning it all, so php can format it to HTML).
Hope hearing some answers or suggestions!
A: I would skip the Java layer and make the "core" PHP. There is a wealth of tools and frameworks (like Zend FW) for building thoses components in PHP. Design your application around a REST interface and allow your mobile apps to use REST.
Better yet, use Rails. It's so easy to design and set up a REST interface.
A: I think your solution is “smart”. The only changes I suggest are:
Use the same platform to build both the "core" and the "browser frontend." This way you will have more productivity.
Keep the "core" and "browser" frontend on the same server, if possible in the same process. Unless you have a reason do it differently. This will reduce problems with performance, latency and so on.
A: If you're already familiar with Java I would suggest you look at something like GWT (or GWT + third-party libraries like Ext GWT or Smart GWT) for your front-end. I don't see the point in picking another language for the front-end unless you really want to learn something else (e.g. PHP as you suggest in your question).
I think the rest of your approach is sound (i.e. Java on the backend, providing RESTful services, etc.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519411",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Merge multiple *.csv, *.txt, or *.ascii files based on a common field using python I want to merge about 8 *.csv files into one.
An example file:
ID, Average
34, 4.5
35, 5.6
36, 3.4
Another file could be:
ID, Max
34, 6
35, 7
36, 4
And I need the output to be:
ID, Average, Max
34, 4.5, 6
35, 5.6, 7
36, 3.4, 4
This only half works.... it appends all the data into the same two columns.
import glob, string
outfile = open('<directory>/<fileName>.csv','a')
files = glob.glob(r"<directory>/*.csv")
for y in files:
newfile = open(y,'r+')
data = newfile.read()
newfile.close()
outfile.writerow(y)
How can I append the data to new columns, and not repeat the "ID" field?
A: You have three problems here.
*
*Read in each of the csv files
*Merge on a common field
*Write the merged data to a new csv file
Code
#!/usr/bin/env python
import argparse, csv
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='merge csv files on field', version='%(prog)s 1.0')
parser.add_argument('infile', nargs='+', type=str, help='list of input files')
parser.add_argument('--out', type=str, default='temp.csv', help='name of output file')
args = parser.parse_args()
data = {}
fields = []
for fname in args.infile:
with open(fname, 'rb') as df:
reader = csv.DictReader(df)
for line in reader:
# assuming the field is called ID
if line['ID'] not in data:
data[line['ID']] = line
else:
for k,v in line.iteritems():
if k not in data[line['ID']]:
data[line['ID']][k] = v
for k in line.iterkeys():
if k not in fields:
fields.append(k)
del reader
writer = csv.DictWriter(open(args.out, "wb"), fields, dialect='excel')
# write the header at the top of the file
writer.writeheader()
writer.writerows(data)
del writer
Note that this will ignore data with an identical field name.
An alternative to the parser section is this:
#!/usr/bin/env python
import glob, csv
if __name__ == '__main__':
infiles = glob.glob('./*.csv')
out = 'temp.csv'
data = {}
fields = []
for fname in infiles:
df = open(fname, 'rb')
reader = csv.DictReader(df)
for line in reader:
# assuming the field is called ID
if line['ID'] not in data:
data[line['ID']] = line
else:
for k,v in line.iteritems():
if k not in data[line['ID']]:
data[line['ID']][k] = v
for k in line.iterkeys():
if k not in fields:
fields.append(k)
del reader
df.close()
writer = csv.DictWriter(open(out, "wb"), fields, dialect='excel')
# write the header at the top of the file
writer.writeheader()
writer.writerows(data)
del writer
A: data1 = ['1,blue,red',
'2,purple,yellow',
'3,white,brown']
data2 = ['1,fee',
'2,fie',
'3,foe',
'4,fum']
data_table = dict(s.split(',',1) for s in data1)
for line in data2:
key, _ = line.split(',',1)
print ','.join((line, data_table.get(key,',')))
gives:
1,fee,blue,red
2,fie,purple,yellow
3,foe,white,brown
4,fum,,
And here is a csv version:
import csv
data1 = ['1,blue,red',
'2,purple,yellow',
'3,white,brown']
data2 = ['1,fee',
'2,fie',
'3,foe',
'4,fum']
with open('out.txt','w') as f:
combined = csv.writer(f)
data1 = ['1,blue,red',
'2,purple,yellow',
'3,white,brown']
data2 = ['1,fee',
'2,fie',
'3,foe',
'4,fum']
data_table = dict((row[0], row[1:]) for row in csv.reader(data1))
for row in csv.reader(data2):
key = row[0]
combined.writerow(row + data_table.get(key, ['','']))
A: Could txtselect work, perhaps? I haven't used it, but the author is going to do a talk on it at pyArkansas next month.
A: I'm a big fan of atpy to read in tables - it's rather versatile and what I've used mostly. Also if you look at these tables as arrays, rather than just large tables you want to slice together, then it might be easier to work with. Assuming that the list of IDs are in the same order for every file, you read in one file first and then append to each row:
data = open('bigtable.txt','w')
table1 = atpy.Table("path/Table1.csv", type="ascii", delimiter=",")
table2 = atpy.Table("path/Table1.txt", type="ascii", delimiter="|")
c = 9 #number of columns
a = []
for ii in range(len(table1)):
a[0].append(table1[ii][0])
a[1].append(table1[ii][1])
a[2].append(table2[ii][1]) #...etc. it was hard to tell from your example what
# columns you wanted where
data.write("%s\n" % a)
data.close
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519412",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Android Map Cross Marks Why is this coming? i use eclipse and in that use the "export signed application" option. I use the existing keystore i.e. debug.keystore. I've got my own api key dev key, and have used it at all the proper places. The cross marks dont come all the time, but they do come often enough to look for a solution!
A: remove the setSatellite() and setStreetView() methods from ur activity class if hv included them. that seems to be a bug in the mapView.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519414",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to you change the value of android:summary on-the-fly using coding? I have the following in a settings.xml file:
<PreferenceCategory android:title="@string/chiming_activity_time_category_title">
<Preference android:title="@string/chiming_start_time_title"
android:summary="@string/chiming_start_time_summary" android:key="preferences_start_time" />
</PreferenceCategory>
And this is from the strings.xml file:
<string name="chiming_start_time_summary">Allow chiming to be active STARTING from
Can you tell me how you change the value of android:summary on-the-fly using coding?
I need to have it display different values based on what the user selects in the preferences screen.
Thanks.
Truly,
Emad
A: Took a look at the documentation? setSummary
You can find your Preference in the PreferenceActivity with findPreference
Documetation of PreferenceActivity shows you how setup your activity (which you probably did).
Do something like that on end of onCreate:
findPreference("keyOfPreferenceWhichChanges").setOnPreferenceChangeListener(
new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (somethingChanged) {
findPreference("keyOfPreferenceWithNewSummary").setSummary("here's the change!");
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519415",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I make a query where it filters everything that starts with a number in Django? I have a model called Book with a Title Field.
class Book(models.Model):
title = models.CharField(null = False,blank=False)
Now I need a filter to get all books with titles starting with a number.
This works but how will I extend the queryset?
b = Book.objects.filter(title__startswith = 1).order_by('title')
This doesn't work
b = b + Book.objects.filter(title__startswith = 2).order_by('title')
or this
b.extend(Book.objects.filter(title__startswith = 2).order_by('title'))
A: You can use a regular expression as a query parameter to check that the a value starts with a number:
Book.objects.filter(title__regex=r'^\d')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519419",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: graph of linked tags Hi I have a list of lists of linked tag, like this:
some_tags = [[u'art', u'interactive', u'media', u'berlin', u'gallery'], [u'event', u'art', u'Istanbul', u'experimental', u'newmedia', u'bioart'], [u'seriousgames', u'installation', u'interaction', u'design', u'art', u'london', u'people'], [u'event', u'art', u'newmedia', u'Istanbul'], [u'art', u'artist', u'interactive', u'installation', u'berlin', u'german', u'people', u'video']]
In each sub list there are linked tags. I want to have a dictionary of occurences of links so I can draw the graph. Now I have this code:
def remove_all_occurences(l, item):
return filter(lambda x: x != item, l)
_d = dict()
# occurences dictionary of tags
for taglist in some_tags:
for tag in taglist:
if _d.get(tag):
_d[tag].extend(taglist)
else:
_d[tag] = taglist
_d[tag] = remove_all_occurences(_d[tag], tag)
# add counts
for k, taglist in _d.items():
l = set(taglist)
_d[k] = [(e,taglist.count(e)) for e in taglist]
from pprint import pprint
pprint(_d)
This code works but there are repetitions:
For example, the link art-video is present two times, first in _d[u'art'] and second in _d[u'video'].
Is there a smart way to make sure there are no repetitions?
A: Take a "Map Reduce" approach:
from itertools import product, groupby
from operator import itemgetter
def generate_pairs(some_tags):
for linked_tags in some_tags:
for left,right in product(linked_tags, linked_tags):
if left != right:
yield (left, right)
_d=dict()
for key,g in groupby(sorted(generate_pairs(some_tags)), key=itemgetter(0,1)):
if key[1] in _d and key[0] in [tag for tag, count in _d[key[1]]]:
continue
if key[0] not in _d:
_d[key[0]]=[]
_d[key[0]] += [(key[1], len([j for j in g]))]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519420",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jQuery - How to get attribute of an element when using the 'click' event I'm using jQuery to get a click on an 'a' element. I have a list of those links where each one has a class which by him I'm capturing the click.
I would like to know which of the links has been clicked (I have an attribute 'setid' for each link) and also get the point where the mouse has been clicked.
How could this be accomplished?
example of the code:
<a href="#" class="newItem" setid="28">click me</a>
$('.newItem').click(function (e) {
alert(e.attr('setid'));
});
EDIT:
OK, so to get the position I would use e.pageX
A: To use jQuery methods you have to wrap this with a call to jQuery.
$('.newItem').click(function () {
alert($(this).attr('setid'));
});
A: refer to the code given below:
document.getElementById("element_id").addEventListener("click",function(e)
{
console.log(e.srcElement.getAttribute("data-name"));
},false);
A: Like Skylar said in the comment to your question, you can use "data-" in front of your new attribute (which is HTML5 valid).
<a href="#" class="newItem" data-setid="28">click me</a>
Then in jQuery (v1.4.3+) you can get it like:
var setid = $(this).data("foo");
It's even a little nicer than attr() that other people have mentioned. See this for more examples - http://www.broken-links.com/2010/11/18/data-attributes-in-html-and-jquery/
A: You're on the correct path.
$(function(){
$('.newItem').click(function () {
alert( $(this).attr('setid') );
})
});
A: Your code is almost right to get the attribute. The only thing missing is wrapping this (a DOM element) in the jQuery wrapper so you can use jQuery functions. $(this).attr('setid') should work.
To get the page coordinates, use the pageX and pageY properties of the event object. So:
$('.newItem').click(function (e) { // e is the event object
alert($(this).attr('setid'));
alert(e.pageX);
alert(e.pageY);
});
See the documentation on the Event object.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519423",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
} |
Q: Child view focus in MVVM application to see Command I am developing an MVVM application. I have a main Window, which looks more or less like this:
<Window>
<ContentControl Content={Binding ContentViewModel} />
</Window>
Then I have this ViewModel, which exposes a certain number of Commands, and I want these commands to be available to the user both from the UI (with buttons, etc), AND from the keyboard, using KeyBindings.
The commands work properly from the UI buttons. But the Keybindings don't always work, it'd seem to me that the problem is that the loaded view is not always in focus.
This is the code for the view.
<UserControl>
<UserControl.InputBindings>
<KeyBinding Key="Delete" Command="{Binding RemoveEntityCommand, ElementName=Designer}" />
</UserControl.InputBindings>
<Grid>
<namespace:Designer x:Name="Designer" />
</Grid>
</UserControl>
How to solve this permanently for an MVVM application? I've encountered this problem multiple times.
Note: all namespace declarations removed for simplicity.
Thanks.
A: I would probably attach a Command to the KeyDown or KeyUp event of the Window instead of the UserControl, and route it from there.
It can either be routed to the ShellViewModel, which will in turn pass it to the current ContentViewModel if needed, or perhaps use some kind of Messaging system that broadcasts special key combinations, and ViewModel's can subscribe to them.
A: What I would do is implement a PreviewKeyUp event and use that to call a method on my view model, something like this:
protected void PreviewKeyUp(object sender, KeyEventArgs args)
{
args.Handled = myViewModel.HandleKeyUp(args.Key);
}
public bool HandleKeyUp(Key key)
{
// Determine if you should execute a command
if(myCommands.ShouldExecuteOnKey(key))
{
// Execute the commad
return true;
}
return false;
}
A lot of people seem to think that MVVM means no code-behind, but that's not always true, or even possible.
A: Yeah, key bindings are a pain. And I agree with Rachel that you likely want something available at the window level in this specific case.
You can avoid code behind and get the goodness of mvvm by doing the following:
*
*make your commands aware of key gestures
*give a KeyBinding an additional property that takes advantage of (1)
This is obviously a bit of infrastructure work tho it is testable and reusable once you have it in place. In this case, since you want the bindings available at the window level, your ShellVm holds the commands and delegates to child view models as needed. I've left just enough code below to give you a feel for the idea
HTH,
Berryl
sample bindings
<Window.InputBindings>
<cmdRef:KeyBindingEx CommandReference="{Binding AddCommand}"/>
</Window.InputBindings>
extended KeyBinding
public class KeyBindingEx : KeyBinding
{
public static readonly DependencyProperty CommandReferenceProperty = DependencyProperty
.Register("CommandReference", typeof(CommandReference), typeof(KeyBindingEx),
new PropertyMetadata(OnCommandReferenceChanged));
private static void OnCommandReferenceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
var kb = (KeyBinding) d;
var cmdRef = e.NewValue as VmCommand;
if(cmdRef==null) return;
kb.Key = cmdRef.GestureKey;
kb.Modifiers = cmdRef.GestureModifier;
kb.Command = cmdRef;
}
public CommandReference CommandReference
{
get { return (CommandReference)GetValue(CommandReferenceProperty); }
set { SetValue(CommandReferenceProperty, value); }
}
}
Command Reference base class extract
public class CommandReference : PropertyChangedBase
{
...
public Key GestureKey
{
get { return _gestureKey; }
set
{
if (_gestureKey == value) return;
_gestureKey = value;
NotifyOfPropertyChange(() => GestureKey);
}
}
private Key _gestureKey;
}
/// <summary>A command whose primary purpose is to relay its functionality to other objects by invoking delegates.</summary>
public class VmCommand : CommandReference, ICommand
{
...
/// <summary>Action to be called when the Execute method of the command gets called</summary>
public Action ExecuteDelegate { get; protected set; }
/// <summary>Predicate to execute when the CanExecute of the command gets called (default is <c>true</c>)</summary>
public Func<bool> CanExecuteDelegate { get; protected set; }
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519425",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Codeigniter URI function url_title() how to use I am using the CodeIgniter framework and I am confused on how to remove %20 from my urls. Below is an example of my code.
Controller - blog
method - show
attribute - this is my blog
public function show($blog= null)
{
// my attempt to set the uri segment
$blogName = $this->uri->segment(3, url_title($blog));
... //other code
}
this doesnt work, I am confused where I implement the url_title('this is my blog') function so that on page load it shows:
/blog/show/this-is-my-blog
do I need to do something in the config/routes.php file?
thank you!
EDIT:
Alright so I found out that url_title() output this20is20my20blog so I now have this:
$blogUrl = str_replace("%20", "-", $blog);
$this->uri->segment(3, $blogUrl);
but it still returns the URL with %20
A: You just need to use the native php function urldecode to remove any characters that get encoded in a url. Spaces in a URL get encoded to %20 so instead of doing a str_replace just try
public function show($blog= null)
{
// i'm not sure what url_title does so you might have to tweak this a little
$blogName = $this->uri->segment(3, urldecode(url_title($blog)));
}
http://php.net/manual/en/function.urldecode.php
A: Try echoing the url_title() just before you do the $this->uri->segment(); to ensure it's returning correctly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519427",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Deploying a custom build of Dojo I'm trying to build Dojo 1.6.1.
I ran C:\somepath\dojo-release-1.6.1-src\dojo-release-1.6.1-src\util\buildscripts>build.bat action=release htmlFiles="C:\path\test.jsp"
Test.jsp contained a few js files. One of which contained all the require statements.
Now I have a release\dojo folder, but if I put these contents into my original source location, it will break my test.jsp's <script> tags.
I found some documentation of the build process: http://dojotoolkit.org/documentation/tutorials/1.6/build/
I could not find documentation on how to DEPLOY the build. Is the deploy simply a copy paste but the problem was that my build didn't work properly?
A: A Dojo custom build is intended to serve as a drop-in replacement for a standard full Dojo distribution as you would include via:
<script type='text/javascript' src='/path/to/dojo/dojo/dojo.js'></script>
Typically deployment is simply changing that to:
<script type='text/javascript' src='/path/to/your-custom-dojo/dojo/dojo.js'></script>
If your test.jsp file does things like dojo.require() with inline <script> tags, they should continue working correctly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519428",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to get the dropbox-php library with pear HTTP_OAUTH to work? I've been struggelig to get the dropbox-php library to work, but the page where I try to use the classes outputs an error:
Warning: include(HTTP/OAuth/Consumer.php) [function.include]: failed to open stream: No such file or directory in /home/sensured/public_html/sensured.net/Dropbox/OAuth/PEAR.php on line 47
Warning: include(HTTP/OAuth/Consumer.php) [function.include]: failed to open stream: No such file or directory in /home/sensured/public_html/sensured.net/Dropbox/OAuth/PEAR.php on line 47
Warning: include() [function.include]: Failed opening 'HTTP/OAuth/Consumer.php' for inclusion (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/sensured/public_html/sensured.net/Dropbox/OAuth/PEAR.php on line 47
Fatal error: Uncaught exception 'Dropbox_Exception' with message 'The HTTP_OAuth_Consumer class could not be found! Did you install the pear HTTP_OAUTH class?' in /home/sensured/public_html/sensured.net/Dropbox/OAuth/PEAR.php:51 Stack trace: #0 /home/sensured/public_html/sensured.net/Dropbox/getmetadata.php(11): Dropbox_OAuth_PEAR->__construct('', '') #1 {main} thrown in /home/sensured/public_html/sensured.net/Dropbox/OAuth/PEAR.php on line 51
The pear HTTP_OAUTH class is installed (v 0.2.3), but its done though cpanel so I'm unsure where and don't even know if that has anything to say.
A: You need to make sure that PEAR's PHP directory is in your include_path.
Find the path with
$ pear config-get php_dir
then add it to your php.ini's include_path directive. Restart your web server software afterwards to activate the new settings .
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519429",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: dynamically set height of browser action popup based on window size When a user clicks my browser action I'd like it's corresponding popup window to (almost) fill the screen. I need the:
*
*height/width of the current window
WHEN
*
*the user clicks my popup
I know I can get the height/width of the current window with chrome.windows.getCurrent(function(currentWindow) { console.log(currentWindow.height); });, however I don't know how to tell that my popup was opened (event), or how to dynamically set it's size (setting document.body.width or window.inner/outerWidth in the popup's inspector doesn't seem to do it). Thanks!
Edit: found http://code.google.com/chrome/extensions/browserAction.html#event-onClicked , however it says it will not fire it a browser action has a popup, is binding to onload in the popup page what I'm trying to achieve?
A: window.resizeTo resizes the browser window.
You can pass this information between your parent window and the child popup in any of many creative ways. The simplest I can think of that's pretty much assured to work would be to tack on the dimensions in a query string or hash for the child window URL and then to parse it with JS.
The usual disclaimer applies that there is almost always a better "way" to do things than resizing the browser window.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519436",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: websphere 7.0 JAXWS webservice deployed in tomcat 7.0 not working Friends:
I have a JAXWS webservice developed in WebSphere 7.0. It is working there. The stack in Websphere is Axis2.0
I wrote a POJO Java class, annotated with the @WebService annotation and then I did a wsgen to generate the necessary artifacts and created the war file.
The imp thing is that web.xml does NOT have any servlets in it or listeners defined.
view plaincopy to clipboardprint?
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>CMSExternalWebServices</display-name>
<servlet>
<servlet-name>Log4JControl</servlet-name>
<servlet-class>it.openutils.log4j.Log4jConfigurationServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Log4JControl</servlet-name>
<url-pattern>/Log4JControl/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
However when I deploy that war file to Tomcat 7.0 and then copy the axis2 jars to the WEB-INF\lib folder.
When I restart Tomcat, the WebService does not work.
What I am curious is, how come Websphere7, deploys the WebService on startup without any entires in web.xml but Tomcat refuses to do so ?
What am I missing ?
-Narahari
A: WebSphere searches the classpath for @WebService annotations during startup, it is not necessary to have any entries in web.xml, this is according to Java EE 6 specification.
As Tomcat does not fully support Java EE 6 (it's a servlet engine 'only'), you must define a trigger to get Axis2 to load your web services. As far as I know you must define each Web Service in web.xml to be able to run on Tomcat (I may have missed some enhancements).
A: Depends on how you're trying to deploy it, but I think you're assuming Tomcat works like a full Java EE server, which it isn't.
If you take the axis jar and put it as its own web app, it should work (see here.
I don't know that Tomcat would do anything at all with a @WebService annotation, since it isn't a full Java EE server. See here, although that's with Tomcat 6, not Tomcat 7.
See also this which leads me to believe it might support it, but it looks like it's still using Metro.
A: I think I've seen a similar thing before (i.e. the web services not being listed in the web.xml file). Are there any other XML files in the WEB-INF or META-INF called ibm-something-something.xml or similar? From memory, that's where the info was when I was developing in Rational Application Developer and deploying to WAS 7.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519438",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Paypal integration on website My need: I want users to click on button and goes to paypal, where they can login or add the credit card details and payment should be get done. In short, I don't want to store credit card info on my website.
I found 'Express Checkout' is a suitable paypal method for the same. Am I right?
Does this method requires return urls on https only or can work with simple urls?
Can anyone help me with tutorial or something for the same?
Thanks for all of your support.
A: Here is an excellent PHP Class for PayPal IPN I've used countless times, which doesn't require user registration: http://www.micahcarrick.com/php-paypal-ipn-integration-class.html
Incidentally, IPN lets you set a return URL via PayPal, though with that class you can send a return URL to IPN before the user pays.
If you want a tutorial or more help though you'll need to tell us which language you're using.
A: The easiest and most flexible solution that comes without a monthly fee, and is available globally, is PayPal Express Checkout. Express Checkout does not require a https return/cancel URL.
Here is how it works:
Express Checkout is based on three API calls; SetExpressCheckout, GetExpressCheckoutDetails and DoExpressCheckoutPayment.
*
*SetExpressCheckout sets up the payment and returns a token.
*You redirect the buyer to https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=TOKEN-HERE, where TOKEN-HERE is the token you received earlier
*After the buyer has agreed to the payment, he is returned back to your site.
*You can call GetExpressCheckoutDetails and supply the token as a parameter to get the PAYERID of the buyer.
*Call DoExpressCheckoutPayment with the token and PAYERID supplied to finalize the payment
Note: If you want to force the 'card details' screen to be displayed initially, and allow buyers to pay without having a PayPal account, ensure you're setting SOLUTIONTYPE to 'Sole' and LANDINGPAGE to 'Billing' in your SetExpressCheckout API request.
In addition, the 'PayPal Account Optional' setting must be switched to 'On' inside the Payment Receiving Preferences of your PayPal Profile.
You can find additional documentation for Express Checkout at https://www.x.com/community/ppx/documentation#ec as well as the SDK's and sample code at https://www.x.com/community/ppx/sdks#NVP
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519441",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Safely and properly pulling value from Nullable?
Possible Duplicate:
Which is preferred: Nullable<>.HasValue or Nullable<> == null?
I'm working in a codebase which uses both of the following forms for "safely" getting values out of Nullable types. For example, if foo is a Nullable (int?):
if (foo != null) {
value = (int)foo;
}
if (foo.HasValue) {
value = foo.Value;
}
I prefer the second form, but is there any particular context which might make the first (or the second, for that matter) certainly preferred over the other?
A: The first and second are exactly equivalent, and compile down to the same IL.
EDIT: They do indeed generate the same IL, like this:
IL_000b: ldloca.s V_1
IL_000d: call instance bool valuetype
[mscorlib]System.Nullable`1<int32>::get_HasValue()
IL_0012: ldc.i4.0
IL_0013: ceq
IL_0015: stloc.2
IL_0016: ldloc.2
IL_0017: brtrue.s IL_0023
IL_0019: nop
IL_001a: ldloca.s V_1
IL_001c: call instance !0 valuetype
[mscorlib]System.Nullable`1<int32>::get_Value()
IL_0021: stloc.0
This is guaranteed by section 7.10.9 of the C# 4 spec (or the equivalent in other versions).
Basically - use whichever form you and your team find more readable.
Anton highlighted the null-coalescing operator - while Anton's code isn't equivalent to yours, it's an operator that you definitely should be familiar with, as it can really make for nice code.
A: I tend to use the second form because it represents what a Nullable actually is -- a struct with two members.
A: I personally prefer
var value = foo ?? 0;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519442",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: SQL Question checking nulls I'm very new to sql. I am on this project where I have to check if something is null and if it is I have to change it to zero but there are many tables that I would have to do this and many columns. I was wondering if there was a way that I can check the whole table for nulls instead of checking every column of every table.
A: Michelle, no you need to check every column for NULLS. The bigger question is why are NULLS being allowed? While I'm not an advocate for never having NULLS in a database (I believe that they have their purpose), an excessive number of NULL values in a table is a good indicator that the database is not normalized properly or has other architectural issues.
A: You say you have to change any NULL values to 0, so perhaps the easiest way would be to use COALESCE(value, 0).
COALESCE(value, value2, value3) is a shortcut to a CASE statement like
CASE
WHEN value1 IS NOT NULL THEN value1
WHEN value2 IS NOT NULL THEN value2
...
END
Edit:
If you actually want to update all NULLS to 0 on the table, you could do the following SQL statement:
SELECT 'UPDATE '
+ OBJECT_NAME(OBJECT_ID)
+ ' SET '
+ sc.name
+ ' = 0 WHERE '
+ sc.name
+ ' IS NULL'
FROM sys.columns sc
INNER JOIN sys.types st ON st.system_type_id = sc.system_type_id
WHERE st.name IN ('bigint', 'int', 'smallint')
AND OBJECT_NAME(OBJECT_ID) = 'YourTable'
Which will product a text string that you should be able to copy and paste and run, or run programatically in a loop. It depends on your columns having a number data type, and could be dangerous if you have any such columns whose NULLs you actually want to stay as null. You could take out that last part of the WHERE clause to run it for all tables, but you may want to test and validate beforehand.
I don't have a SQL Server instance at the ready to test on, so this comes with the generic "use at your own risk" disclaimer. :-)
A: It does depend on the platform, but in some cases you can use the system table information to get a list of all of the columns, and utilise this to generate queries to verify every column in every table.
However, that would be quite a hack. The real questions are a) why are there so many nulls ( there might be good reasons, but it does suggest that the structure is wrong, as per Wil ) and b) why is there a sudden need to change then all to zeros? Does this only apply to numeric fields? There are so many other questions that you need to ask before a clear solution becomes clear.
A: Select nvl(col,'0') from table ;
NVL will work fine in oracle.
NVL will check if col is null, if it is null it will change it to zero.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519443",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Visual Studio 2010 Database Builds Drop If Exists Is there any way i can change the "Alter" statements for tables and procs to "Drop if exists" when the build spits out the scripts??
Using Visual Studio 2010 Ultimate. TFS 2010.
A: I believe the code you are referring to is generated from a template.
Look here...
C:\Program Files\Microsoft Visual Studio 10.0\Common7\Tools\Templates\Database Project Items
and the modify these two files.
*
*New Table Script.sql
*New Stored Procedure Script.sql
A: After the procedure has been created for the first time what you will see is the code the tool gets/reads from the database, no longer an script that you could edit; of course you could copy/paste whatever it shows you into a text editor and save it as an SQL file (.sql extension).
If you try this sample code
IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'usp_test_proc')
BEGIN
DROP Procedure usp_test_proc
END
ALTER PROCEDURE dbo.usp_test_proc
/*
(
@parameter1 int = 5,
@parameter2 datatype OUTPUT
)
*/
AS
/* SET NOCOUNT ON */
select name, comment from test_table
RETURN
you will get this message:
"Unable to save object because the statement type is not supported. It must begin with CREATE or ALTER."
I suggest you create your own SQL procedure files and add the exists statment at the top, for example:
IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'usp_test_proc')
BEGIN
DROP Procedure usp_test_proc
END
CREATE PROCEDURE usp_test_proc
/*
(
@parameter1 int = 5,
@parameter2 datatype OUTPUT
)
*/
AS
/* SET NOCOUNT ON */
select name, comment from test_table
RETURN
That way you can edit/change your SQL code file at your convenience then just recreate the procedure connecting to your database by opening a new query connection through the Visual Studio menu 'Data/Transact-SQL Editor/New Query Connection', opening the SQL file and clicking on the Execute SQL toolbar button (green arrow).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519445",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: What excectly is Cirrus server role in flash P2P connection According to the article quoted below, if we want to use Cirrus for RTMFP connection it should stay connected for the whole communication period.
Cirrus service
Flash Player instances must connect to the Cirrus service (using rtmfp://p2p.rtmfp.net) in order to communicate with one another. Cirrus is a hosted rendezvous service that helps Flash Player instances contact one another even if they are located behind NATs. Although connecting to Cirrus service is very similar to connecting to Flash Media Server, Cirrus does not provide any of the typical Flash Media Server features (media relay, shared objects, remoting, etc.). Flash Player endpoints must stay connected to Cirrus during the entire time of communication . In order to access Cirrus, you will need a developer key that is generated when you create your Adobe Developer ID.
http://www.adobe.com/devnet/flashplayer/articles/rtmfp_cirrus_app.html
And I wonder why do we need to keep the server communication after the first NAT traversing hand shake?
What part does it take when a P2P connection between the clients is done?
A: Imagine you have various clients in a NetGroup and then one client suddenly disconnects. Due to the stateless nature of UDP, the other clients don't recognize the disconnect. This event is being handled and dispatched to the other clients by Cirrus.
Furthermore, Cirrus handles the translation of peer IDs to network addresses. This must be done in the period in which clients are connected.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519451",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Custom asp.net mvc 3 jquery.validate.unobtrusive I am converting a site from asp.net mvc 2 to asp.net mvc 3. I am wanting to use the built in validation in mvc 3 which uses the jquery.validate and the jquery.validate.unobtrusive. However on my old site I was already using jquery.validate and added custom method for validation that I would then call when a drop down was changed.
I need to be able to:
*
*Register this method.
*Call only when the dropdown is changed.
Here is my code for this on my asp.net 2 site.
//add class to the html element
$("#ClientId-input").addClass("validClient");
//create the method "validClient"
$.validator.addMethod("validClient", function(value, element) {
//get the actual value in the input box
var _value = $("#ClientId").data('tComboBox').value();
//get all the items in the list
var _items = $("#ClientId").data('tComboBox').data;
//set the value to return
var _retVal = false;
//loop through the items if the selected value equals a value we are valid
$.each(_items, function(index, value)
{
if(value.Value == _value){
_retVal = true;
//return false in the loop to break.
return false;
}
});
return _retVal;
}, "Please choose a Client from the list.");
//Assign the rule to the validator
$.validator.addClassRules({
validClient:{validClient:true}
});
//this is called when dropdownchanges
function ClientsChanged(e)
{
if($("#ClientId-input").valid())
{
//do work here
}
}
A: In my answer here, at the bottom, you will see code showing how to add and register a custom validation method, so that MVC 3 unobtrusive validation will handle your custom validator.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519452",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can I change in app purchase price that is ready for sale ? without entering review again? Just to be sure.
I have application with in app purchase, ready for sale state.
If I change the price, this will be effective immediatly(or 24 hours..the same) or this will need disable the in app purchase item, and need to go for apple review ?
Thanks
A: No, if you change the price it will be immediate although the change is not REALLY immediate. The change has to populate to all iTunes servers, so for a short period of time, some stores may have it at different prices. But the time is usually less than an hour or two.
The point of the review is to review functionality, the price is in your hands.
A: "ready for sale" app's price modification does not put app in review again. review is ment for testing the app functionality not pricing!!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: NSNumber to NSString (without trailing zeros if it has decimals) I'm struggling with this issue, and I couldn't find any resource for it :
I have an NSNumber that I want to display in an UITextField, so the user can edit it.
So I need to convert this NSNumber to an NSString, like this :
float value -> desired string value
1.0000000... -> 1
10.000000... -> 10
1.1230000... -> 1.123 or 1,123 depending on the locale
1000000.0... -> 1000000
I've tried to use NSNumberFormatter, but then I get spaces or comas for big numbers :
1000000.0... -> 1,000,000 or 1 000 000 depending on the locale
I also tried
[NSString stringWithFormat:@"%g", val]
But then for big numbers I have a scientific expression :
1000000.0 -> 1e+06
Did somebody have a successful experience with this ?
A: NSNumberFormatter has such method as :
- (void)setGroupingSeparator:(NSString *)string
I think, you can return to variant where you has:
1000000.0... -> 1,000,000 or 1 000 000 depending on the locale
and set additional parameter using that function:
[formatter setGroupingSeparator:@""];
Or moreover try this method:
[formatter setUsesGroupingSeparator:NO];
A: NSNumberFormatter is the solution, you were on the right path.
But:
*
*the formatting it uses depends on the locale (either it uses the default locale if you don't override it, or you can set the locale used by the NSFormatter), because the NSLocale information also carries the Region Formatting info (formatting numbers using the US locale or the FR locale leads to different formats and different representations)
*You can customize the formatting by tuning the options of NSNumberFormatter, like changing the grouping separators used, changing the decimal separator, etc.
This way you can really customize the way the NSNumberFormatter represents the numeric value into a string.
A: try converting nsnumber value to NSInteger or CGFloat and store it in the new variables. Then set the converted variables to uitextfield.
CGFloat floatNumber = [numberInNSNumber floatValue];
textfield.text = [NSString stringWithFormat:@"%0.2f",floatNumber];
I think it should work for you..!!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519458",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: .NET Mutext.ReleaseMutex and Mutex.Close What's the difference between the two? If I do Mutex.Close() instead of Mutex.Release() when shutting down my app, what would be the side effect?
A: ReleaseMutex is used to allow another thread to obtain the mutex. It should only be called if you have acquired the mutex (called WaitOne and acquired it or acquired through the constructor). Important Note ReleaseMutex will throw an exception if you have not acquired the mutex.
Close is used to clean up the resources that have been allocated by declaring the mutex object, whether you ever blocked on it or not, if you have acquired the mutex it will release it (equivalent to calling ReleaseMutex. If you plan to lock on the mutex for the whole application (i.e. using this to ensure a single instance of your app), then I would wrap it in a using statement like the example in Joseph Albahari's threading guide (a must read).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519465",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Line plot with arrows in matplotlib I have a line graph that I want to plot using arrows instead of lines. That is, the line between successive pairs of points should be an arrow going from the first point to the second point.
I know of the arrow function, but that only seems to do individual arrows. Before I work out a way to try and use this to do a whole plot, is there a nicer way to do it?
A: You can do this with quiver, but it's a little tricky to get the keyword arguments right.
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2*np.pi, 10)
y = np.sin(x)
plt.figure()
plt.quiver(x[:-1], y[:-1], x[1:]-x[:-1], y[1:]-y[:-1], scale_units='xy', angles='xy', scale=1)
plt.show()
A: You could superpose a quiver plot on your line plot.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519467",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "35"
} |
Q: httppost.execute goes to exception i have searched each and every thing at this site but still i don't understand what is matter with my code i have debugged it also it goes to exception when it tries to execute the this line "HttpResponse response=httpclient.execute(httppost)" i have also added permission of internet in android manifest file but still don't understand whats the matter.
please help me i shall be very thankful to all of you.....
here is my code
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// set a click listener on the alert button
Button alert = (Button) findViewById(R.id.alertbtn);
alert.setOnClickListener(this);
}
public void onClick(View view)
{
if (view == findViewById(R.id.alertbtn))
{
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(2);
postParameters.add(new BasicNameValuePair("email","awais"));
postParameters.add(new BasicNameValuePair("password","123"));
try
{
HttpClient httpclient=new DefaultHttpClient();
HttpPost httppost=new HttpPost("http://localhost/doctroidlogin.php");
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpResponse response=httpclient.execute(httppost);
HttpEntity entity=response.getEntity();
if(entity.toString().length()>0)
alertbox.setMessage("Welcome to DangerZone!");
else
alertbox.setMessage("Invalid Email or Password");
alertbox.show();
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
Log Cat
09-23 00:53:51.251: WARN/System.err(327): java.net.UnknownHostException: pannl.com
09-23 00:53:51.266: WARN/System.err(327): at java.net.InetAddress.lookupHostByName(InetAddress.java:506)
09-23 00:53:51.285: WARN/System.err(327): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:294)
09-23 00:53:51.285: WARN/System.err(327): at java.net.InetAddress.getAllByName(InetAddress.java:256)
09-23 00:53:51.306: WARN/System.err(327): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:136)
09-23 00:53:51.316: WARN/System.err(327): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
09-23 00:53:51.336: WARN/System.err(327): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
09-23 00:53:51.356: WARN/System.err(327): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:359)
09-23 00:53:51.366: WARN/System.err(327): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
09-23 00:53:51.375: WARN/System.err(327): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
09-23 00:53:51.386: WARN/System.err(327): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
09-23 00:53:51.406: WARN/System.err(327): at huuah.dialogboxes.LastActivity.onClick(LastActivity.java:57)
09-23 00:53:51.415: WARN/System.err(327): at android.view.View.performClick(View.java:2485)
09-23 00:53:51.436: WARN/System.err(327): at android.view.View$PerformClick.run(View.java:9080)
09-23 00:53:51.466: WARN/System.err(327): at android.os.Handler.handleCallback(Handler.java:587)
09-23 00:53:51.476: WARN/System.err(327): at android.os.Handler.dispatchMessage(Handler.java:92)
09-23 00:53:51.486: WARN/System.err(327): at android.os.Looper.loop(Looper.java:123)
09-23 00:53:51.506: WARN/System.err(327): at android.app.ActivityThread.main(ActivityThread.java:3683)
09-23 00:53:51.516: WARN/System.err(327): at java.lang.reflect.Method.invokeNative(Native Method)
09-23 00:53:51.526: WARN/System.err(327): at java.lang.reflect.Method.invoke(Method.java:507)
09-23 00:53:51.546: WARN/System.err(327): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
09-23 00:53:51.566: WARN/System.err(327): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
09-23 00:53:51.566: WARN/System.err(327): at dalvik.system.NativeStart.main(Native Method)
A: http://localhost implies that you are running server on your device (or emulator). Are you? I guess not since it's php.
You have to use a real IP or domain name of the server.
OTOH if you are trying this on emulator and server is on your host machne then you need to set a few parameters: http://juristr.com/blog/2009/10/accessing-host-machine-from-your/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How does one Animate Layout properties of ViewGroups? I have the following layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent">
<FrameLayout android:id="@+id/viewgroup_left"
android:layout_height="match_parent"
android:layout_weight="2"
android:layout_width="0dp">
... children ...
</FrameLayout>
<LinearLayout android:id="@+id/viewgroup_right"
android:layout_height="match_parent"
android:layout_weight="1"
android:layout_width="0dp"
android:orientation="vertical">
... children ...
</LinearLayout>
</LinearLayout>
I end up with something like this:
+------------------------+------------+
| | |
| | |
| Left | Right |
| | |
| | |
+------------------------+------------+
When a certain toggle is toggled, I want to animate Left so that its width expands to fill the entire screen. At the same time, I would like to animate the width of Right so that it shrinks to zero. Later, when the toggle is toggled again, I need to restore things to the above state.
I've tried writing my own Animation that calls View.getWidth() but when I animate back to that value (by setting View.getLayoutParams().width) it is wider than when it began. I suspect I'm just doing it wrong. I have also read all the documentation on the Honeycomb animation stuff, but I don't want to translate or scale... I want to animate the layout width property. I can't find an example of this.
What is the correct way to do this?
A: Just adding my 2 cents here to Knickedi's excellent answer - just in case someone needs it:
If you animate using weights you will end up with issues with clipping/non-clipping on contained views and viewgroups. This is especially true if you use viewgroups with weight as fragment containers. To overcome it, you might as well need to animate margins of the problematic child views and viewgroups / fragment containers.
And, to do all these things together, its always better to go for ObjectAnimator and AnimatorSet (if you can use them), along with some utility classes like MarginProxy
A: Since noone helped you yet and my first answer was such a mess I'll try to give you the right answer this time ;-)
Actually I like the idea and I think this is a great visual effect which might be useful for a bunch of people. I would implement an overflow of the right view (I think the shrink looks strange since the text is expanding to the bottom).
But anyway, here's the code which works perfectly fine (you can even toggle while it's animating).
Quick explanation:
You call toggle with a boolean for your direction and this will start a handler animation call loop. This will increase or decrease the weights of both views based on the direction and the past time (for a smooth calculation and animation). The animation call loop will invoke itself as long it hasn't reached the start or end position.
The layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="10"
android:id="@+id/slide_layout">
<TextView
android:layout_weight="7"
android:padding="10dip"
android:id="@+id/left"
android:layout_width="0dip"
android:layout_height="fill_parent"></TextView>
<TextView
android:layout_weight="3"
android:padding="10dip"
android:id="@+id/right"
android:layout_width="0dip"
android:layout_height="fill_parent"></TextView>
</LinearLayout>
The activity:
public class TestActivity extends Activity {
private static final int ANIMATION_DURATION = 1000;
private View mSlidingLayout;
private View mLeftView;
private View mRightView;
private boolean mAnimating = false;
private boolean mLeftExpand = true;
private float mLeftStartWeight;
private float mLayoutWeightSum;
private Handler mAnimationHandler = new Handler();
private long mAnimationTime;
private Runnable mAnimationStep = new Runnable() {
@Override
public void run() {
long currentTime = System.currentTimeMillis();
float animationStep = (currentTime - mAnimationTime) * 1f / ANIMATION_DURATION;
float weightOffset = animationStep * (mLayoutWeightSum - mLeftStartWeight);
LinearLayout.LayoutParams leftParams = (LinearLayout.LayoutParams)
mLeftView.getLayoutParams();
LinearLayout.LayoutParams rightParams = (LinearLayout.LayoutParams)
mRightView.getLayoutParams();
leftParams.weight += mLeftExpand ? weightOffset : -weightOffset;
rightParams.weight += mLeftExpand ? -weightOffset : weightOffset;
if (leftParams.weight >= mLayoutWeightSum) {
mAnimating = false;
leftParams.weight = mLayoutWeightSum;
rightParams.weight = 0;
} else if (leftParams.weight <= mLeftStartWeight) {
mAnimating = false;
leftParams.weight = mLeftStartWeight;
rightParams.weight = mLayoutWeightSum - mLeftStartWeight;
}
mSlidingLayout.requestLayout();
mAnimationTime = currentTime;
if (mAnimating) {
mAnimationHandler.postDelayed(mAnimationStep, 30);
}
}
};
private void toggleExpand(boolean expand) {
mLeftExpand = expand;
if (!mAnimating) {
mAnimating = true;
mAnimationTime = System.currentTimeMillis();
mAnimationHandler.postDelayed(mAnimationStep, 30);
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.slide_test);
mLeftView = findViewById(R.id.left);
mRightView = findViewById(R.id.right);
mSlidingLayout = findViewById(R.id.slide_layout);
mLeftStartWeight = ((LinearLayout.LayoutParams)
mLeftView.getLayoutParams()).weight;
mLayoutWeightSum = ((LinearLayout) mSlidingLayout).getWeightSum();
}
}
A: A different way to the solution posted by @knickedi is to use ObjectAnimator instead of Runnable. The idea is to use ObjectAnimator to adjust the weight of both left and right views. The views, however, need to be customised so that the weight can be exposed as a property for the ObjectAnimator to animate.
So first, define a customised view (using a LinearLayout as an example):
public class CustomLinearLayout extends LinearLayout {
public CustomLinearLayout(Context context) {
super(context);
}
public CustomLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomLinearLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setMyWeight(float value) {
LinearLayout.LayoutParams p = (LinearLayout.LayoutParams)getLayoutParams();
p.weight = value;
requestLayout();
}
}
Then, update the layout XML to use this custom linear layout.
Then, when you need to toggle the animation, use ObjectAnimator:
ObjectAnimator rightView = ObjectAnimator.ofFloat(viewgroup_right, "MyWeight", 0.5f, 1.0f);
ObjectAnimator leftView = ObjectAnimator.ofFloat(viewgroup_left, "MyWeight", 0.5f, 0.0f);
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.setDuration(1000); // 1 second of animation
animatorSet.playTogether(rightView, leftView);
animatorSet.start();
The above code assumes both views are linear layout and are half in weight to start with. The animation will expand the right view to full weight (so the left one is hidden). Note that ObjectAnimator is animated using the "MyWeight" property of the customised linear layout. The AnimatorSet is used to tie both left and right ObjectAnimators together, so the animation looks smooth.
This approach reduces the need to write runnable code and the weight calculation inside it, but it needs a customised class to be defined.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519479",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: FFTW: Trouble with real to complex and complex to real 2D tranfsorms As the title states I'm using FFTW (version 3.2.2) with Fortran 90/95 to perform a 2D FFT of real data (actually a field of random numbers). I think the forward step is working (at least I am getting some ouput). However I wanted to check everything by doing the IFFT to see if I can re-construct the original input. Unfortunately when I call the complex to real routine, nothing happens and I obtain no error output, so I'm a bit confused. Here are some code snippets:
implicit none
include "fftw3.f"
! - im=501, jm=401, and lm=60
real*8 :: u(im,jm,lm),recov(im,jm,lm)
complex*8 :: cu(1+im/2,jm)
integer*8 :: planf,planb
real*8 :: dv
! - Generate array of random numbers
dv=4.0
call random_number(u)
u=u*dv
recov=0.0
k=30
! - Forward step (FFT)
call dfftw_plan_dft_r2c_2d(planf,im,jm,u(:,:,k),cu,FFTW_ESTIMATE)
call dfftw_execute_dft_r2c(planf,u(:,:,k),cu)
call dfftw_destroy_plan(planf)
! - Backward step (IFFT)
call dfftw_plan_dft_c2r_2d(planb,im,jm,cu,recov(:,:,k),FFTW_ESTIMATE)
call dfftw_execute_dft_c2r(planb,cu,recov(:,:,k))
call dfftw_destroy_plan(planb)
The above forward step seems to work (r2c) but the backward step does not seem to work. I checked this by differencing the u and recov arrays - which ended up not being zero. Additionally the max and min values of the recov array were both zero, which seems to indicate that nothing was changed.
I've looked around the FFTW documentation and based my implementation on the following page http://www.fftw.org/fftw3_doc/Fortran-Examples.html#Fortran-Examples . I am wondering if the problem is related to indexing, at least that's the direction I am leaning. Anyway, if any one could offer some help, that would be wonderful!
Thanks!
A: Not sure if this is the root of all troubles here, but the way you declare variables may be the culprit.
For most compilers (this is apparently not even a standard), Complex*8 is an old syntax for single precision: the complex variable occupies a total of 8 bytes, shared between the real and the imaginary part (4+4 bytes).
[Edit 1 following Vladimir F comment to my answer, see his link for details:] In my experience (i.e. the systems/compiler I ever used), Complex(Kind=8) corresponds to the declaration of a double precision complex number (a real and an imaginary part, both of which occupy 8 bytes).
On any system/compiler, Complex(Kind=Kind(0.d0)) should declare a double precision complex.
In short, your complex array does not have the right size. Replace occurences of Real*8 and Complex*8 by Real(kind=8) and Complex(Kind=8) (or Complex(Kind=kind(0.d0)) for a better portability), respectively.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Toolbar button similar to Back/Forward buttons of firefox - xul I am developing a Firefox addon. I need to create two buttons which exactly looks and operates like back and forward buttons. But the difference is I need to put my own icon inside them. I am completely blank. Any directions will be really helpful.
[Edit]
I am asking for creating two buttons with the look and feel of back/forward button(Although there are two buttons, it seems like one) in the latest Firefox on windows environment.
Thanks.
A: It's really easy to add your own Image to toolbar buttons. Read these links you'll have your answer & don't forget to link your images for the buttons in CSS file.
https://developer.mozilla.org/en/XUL_School/Adding_Toolbars_and_Toolbar_Buttons
https://developer.mozilla.org/en/XUL_Tutorial/Toolbars
https://developer.mozilla.org/en/CSS/-moz-border-image
https://developer.mozilla.org/en/custom_toolbar_button
https://developer.mozilla.org/en/XUL/Toolbars/Creating_toolbar_buttons
For example:
<window id="main-window">
<toolbox id="navigator-toolbox">
<toolbar id="xulschoolhello-toolbar" toolbarname="&xulschoolhello.toolbarName.label;"
accesskey="&xulschoolhello.toolbar.accesskey;"
customizable="true" mode="icons" context="toolbar-context-menu"
defaultset="xulschoolhello-hello-world-button"
insertbefore="PersonalToolbar" />
</toolbox>
</window>
CSS File:
//LInk you image here//
toolbarbutton.xulschoolhello-toolbarbutton,
window:not([active="true"]) toolbarbutton.xulschoolhello-toolbarbutton,
toolbar[iconsize="small"] toolbarbutton.xulschoolhello-toolbarbutton {
list-style-image: url("chrome://xulschoolhello-os/skin/toolbar.png");
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519484",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Return value copying issue (to improve debug timing) -- What's the solution here? The most interesting C++ question I've encountered recently goes as follows:
We determined (through profiling) that our algorithm spends a lot of time in debug mode in MS Visual Studio 2005 with functions of the following type:
MyClass f(void)
{
MyClass retval;
// some computation to populate retval
return retval;
}
As most of you probably know, the return here calls a copy constructor to pass out a copy of retval and then the destructor on retval. (Note: the reason release mode is very fast for this is because of the return value optimization. However, we want to turn this off when we debug so that we can step in and nicely see things in the debugger IDE.)
So, one of our guys came up with a cool (if slightly flawed) solution to this, which is, create a conversion operator:
MyClass::MyClass(MyClass *t)
{
// construct "*this" by transferring the contents of *t to *this
// the code goes something like this
this->m_dataPtr = t->m_dataPtr;
// then clear the pointer in *t so that its destruction still works
// but becomes 'trivial'
t->m_dataPtr = 0;
}
and also changing the function above to:
MyClass f(void)
{
MyClass retval;
// some computation to populate retval
// note the ampersand here which calls the conversion operator just defined
return &retval;
}
Now, before you cringe (which I am doing as I write this), let me explain the rationale. The idea is to create a conversion operator that basically does a "transfer of contents" to the newly constructed variable. The savings happens because we're no longer doing a deep copy, but simply transferring the memory by its pointer. The code goes from a 10 minute debug time to a 30 second debug time, which, as you can imagine, has a huge positive impact on productivity. Granted, the return value optimization does a better job in release mode, but at the cost of not being able to step in and watch our variables.
Of course, most of you will say "but this is abuse of a conversion operator, you shouldn't be doing this kind of stuff" and I completely agree. Here's an example why you shouldn't be doing it too (this actually happened:)
void BigFunction(void)
{
MyClass *SomeInstance = new MyClass;
// populate SomeInstance somehow
g(SomeInstance);
// some code that uses SomeInstance later
...
}
where g is defined as:
void g(MyClass &m)
{
// irrelevant what happens here.
}
Now this happened accidentally, i.e., the person who called g() should not have passed in a pointer when a reference was expected. However, there was no compiler warning (of course). The compiler knew exactly how to convert, and it did so. The problem is that the call to g() will (because we've passed it a MyClass * when it was expecting a MyClass &) called the conversion operator, which is bad, because it set the internal pointer in SomeInstance to 0, and rendered SomeInstance useless for the code that occured after the call to g(). ... and time consuming debugging ensued.
So, my question is, how do we gain this speedup in debug mode (which has as direct debugging time benefit) with clean code that doesn't open the possibility to make such other terrible errors slip through the cracks?
I'm also going to sweeten the pot on this one and offer my first bounty on this one once it becomes eligible. (50 pts)
A: You need to use something called "swaptimization".
MyClass f(void)
{
MyClass retval;
// some computation to populate retval
return retval;
}
int main() {
MyClass ret;
f().swap(ret);
}
This will prevent a copy and keep the code clean in all modes.
You can also try the same trick as auto_ptr, but that's more than a little iffy.
A: If your definition of g is written the same as in your code base I'm not sure how it compiled since the compiler isn't allowed to bind unnamed temporaries to non-const references. This may be a bug in VS2005.
If you make the converting constructor explicit then you can use it in your function(s) (you would have to say return MyClass(&retval);) but it won't be allowed to be called in your example unless the conversion was explicitly called out.
Alternately move to a C++11 compiler and use full move semantics.
(Do note that the actual optimization used is Named Return Value Optimization or NRVO).
A: The problem is occuring because you're using MyClass* as a magic device, sometimes but not always. Solution: use a different magic device.
class MyClass;
class TempClass { //all private except destructor, no accidental copies by callees
friend MyClass;
stuff* m_dataPtr; //unfortunately requires duplicate data
//can't really be tricked due to circular dependancies.
TempClass() : m_dataPtr(NULL) {}
TempClass(stuff* p) : m_dataPtr(p) {}
TempClass(const TempClass& p) : m_dataPtr(p) {}
public:
~TempClass() {delete m_dataPtr;}
};
class MyClass {
stuff* m_dataPtr;
MyClass(const MyClass& b) {
m_dataPtr = new stuff();
}
MyClass(TempClass& b) {
m_dataPtr = b.m_dataPtr ;
b.m_dataPtr = NULL;
}
~MyClass() {delete m_dataPtr;}
//be sure to overload operator= too.
TempClass f(void) //note: returns hack. But it's safe
{
MyClass retval;
// some computation to populate retval
return retval;
}
operator TempClass() {
TempClass r(m_dataPtr);
m_dataPtr = nullptr;
return r;
}
Since TempClass is almost all private (friending MyClass), other objects cannot create, or copy TempClass. This means the hack can only be created by your special functions when clearly told to, preventing accidental usage. Also, since this doesn't use pointers, memory can't be accidentally leaked.
A: Move semantics have been mentioned, you've agreed to look them up for education, so that's good. Here's a trick they use.
There's a function template std::move which turns an lvalue into an rvalue reference, that is to say it gives "permission" to move from an object[*]. I believe you can imitate this for your class, although I won't make it a free function:
struct MyClass;
struct MovableMyClass {
MyClass *ptr;
MovableMyClass(MyClass *ptr) : ptr(ptr) {}
};
struct MyClass {
MyClass(const MovableMyClass &tc) {
// unfortunate, we need const reference to bind to temporary
MovableMyClass &t = const_cast<MovableMyClass &>(tc);
this->m_dataPtr = t.ptr->m_dataPtr;
t.ptr->m_dataPtr = 0;
}
MovableMyClass move() {
return MovableMyClass(this);
}
};
MyClass f(void)
{
MyClass retval;
return retval.move();
}
I haven't tested this, but something along those lines. Note the possibility of doing something const-unsafe with a MovableMyClass object that actually is const, but it should be easier to avoid ever creating one of those than it is to avoid creating a MyClass* (which you've found out is quite difficult!)
[*] Actually I'm pretty sure I've over-simplified that to the point of being wrong, it's actually about affecting what overload gets chosen rather than "turning" anything into anything else as such. But causing a move instead of a copy is what std::move is for.
A: A different approach, given your special scenario:
Change MyClass f(void) (or operator+) to something like the following:
MyClass f(void)
{
MyClass c;
inner_f(c);
return c;
}
And let inner_f(c) hold the actual logic:
#ifdef TESTING
# pragma optimize("", off)
#endif
inline void inner_f(MyClass& c)
{
// actual logic here, setting c to whatever needed
}
#ifdef TESTING
# pragma optimize("", on)
#endif
Then, create an additional build configurations for this kind of testing, in which TESTING is included in the preprocessor definitions.
This way, you can still take advantage of RVO in f(), but the actual logic will not be optimized on your testing build. Note that the testing build can either be a release build or a debug build with optimizations turned on. Either way, the sensitive parts of the code will not be optimized (you can use the #pragma optimize in other places too, of course - in the code above it only affects inner_f itself, and not code called from it).
A: Possible solutions
*
*Set higher optimization options for the compiler so it optimizes out the copy construction
*Use heap allocation and return pointers or pointer wrappers, preferably with garbage collection
*Use the move semantics introduced in C++11; rvalue references, std::move, move constructors
*Use some swap trickery, either in the copy constructor or the way DeadMG did, but I don't recommend them with a good conscience. An inappropriate copy constructor like that could cause problems, and the latter is a bit ugly and needs easily destructible default objects which might not be true for all cases.
*+1: Check and optimize your copy constructors, if they take so long then something isn't right about them.
A: I would prefer to simply pass the object by reference to the calling function when MyClass is too big to copy:
void f(MyClass &retval) // <--- no worries !
{
// some computation to populate retval
}
Just simple KISS principle.
A: Okay I think I have a solution to bypass the Return Value Optimization in release mode, but it depends on the compiler and not guaranteed to work. It is based on this.
MyClass f (void)
{
MyClass retval;
MyClass dummy;
// ...
volatile bool b = true;
if b ? retval : dummy;
}
As for why the copy construction takes so long in DEBUG mode, I have no idea. The only possible way to speed it up while remaining in DEBUG mode is to use rvalue references and move semantics. You already discovered move semantics with your "move" constructor that accepts pointer. C++11 gives a proper syntax for this kind of move semantics. Example:
// Suppose MyClass has a pointer to something that would be expensive to clone.
// With move construction we simply move this pointer to the new object.
MyClass (MyClass&& obj) :
ptr (obj.ptr)
{
// We set the source object to some trivial state so it is easy to delete.
obj.ptr = NULL;
}
MyClass& operator = (MyClass&& obj) :
{
// Here we simply swap the pointer so the old object will be destroyed instead of the temporary.
std::swap(ptr, obj.ptr);
return *this;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519486",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: jQueryUI modal add function to defaults I always find myself fixing this chrome scrollbar issue on every jQueryUI modal I add. So, I was thinking that I could add that code to the jqueryUI dialog defaults. I found this question but can't quite bridge the gap and apply it to my code.
$.extend($.ui.dialog.prototype.options, {
open: function(event, ui){
window.setTimeout(function(){jQuery(document).unbind('mousedown.dialog-overlay').unbind('mouseup.dialog-overlay');}, 100);
}
});
The problem is, if I have code in a dialog open event, it will override the default.
$("#modalContent").dialog({
open:function(){
alert('Hey buddy!');
}
});
So my question is two parts; How do I stack the functions instead of overriding them and should I even do this in the first place? Thanks!
Here is a jsfiddle:
http://jsfiddle.net/McWatt/HSA8M/
A: The solution is alot simpler then that. You can just remove those events by overriding $.ui.dialog.overlay.events, which will prevent them from being bound to begin with:
$.ui.dialog.overlay.events = $.map('focus,keydown,keypress'.split(','),
function(event) { return event + '.dialog-overlay'; }).join(' ');
Note: If you remove keydown you won't be able to close the dialog with the escape key. You might want to look at overriding the create-method as well. Check the source for more info.
See test case on jsFiddle
A: In my opinion you have one problem in your jsfiddle:
*
*the dialog is not destroyed and therefore the open callback remains the same
Here is an updated fiddle: http://jsfiddle.net/thomas_peklak/HSA8M/3/
Still, I would not really recommend modifying the defaults of a library object. In my opinion it is a lot safer to create your own ui.widget based on ui.dialog and override the defaults in your object.
Your case seems to be rather simple but where should we draw the line between clean and entangled code?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519489",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Python regex gotcha Could you explain me why the first regex doesn't match?
Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
>>> import re
>>> re.match(r'\d','.0')
>>> re.match(r'.\d','.0')
<_sre.SRE_Match object at 0x109adbd30>
A: re.match() tries to match from the beginning of the string.
Use re.search() instead if you want to locate a match anywhere in the string.
PS: You might want to escape the ., because it's a metacharacter that matches any1 character (so x0 would match your second example).
>>> re.match(r'\.\d', 'x0')
>>> re.match(r'.\d', 'x0')
<_sre.SRE_Match object at 0x01F67138>
1 except newlines, unless re.DOTALL is used.
A: Because you're using match and that matches a string from beginning (like if you used ^)
Try re.search
A: For reference to search vs match: http://docs.python.org/library/re.html#search-vs-match
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519493",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: C# - Windows 2000 BalloonTip Events workaround Ive been looking all over for a workaround for this but have found nothing besides "Just have them click the NotifyIcon".
Windows 2000 obviously does not support BalloonTip events but I need a way to detect when either the balloon tip is clicked or closed. So I was thinking if there was a way for my program to know if the balloonTip is currently displayed, then I can create a timer that checks if the balloonTip is no longer displayed. Maybe something like this:
timer_tick(object sender, EventArgs e)
{
if (!balloonTipDisplayed())
{
//balloon is closed, do somthing...
}
}
Does anyone know of a way to do this? Or maybe have a better workaround?
Thanks for any help.
A: There is nothing out there to resolve that AFAIK. There is no event in the Windows 2000 UI which can be fired. It's something I battled with for a while and ended up writing something to do it instead for just Windows 2000. I used another Windows Form which was shown "always on top" in the bottom right hand corner of the screen to emulate it. Not pretty but it worked :)
A: I took what Chris said and ended up finding this great project:
TaskbarNotifier
It works in 2000 and XP which is just what i need, and it even looks nicer than a balloonTip.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519495",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Subclipse - Repository Exploring Fetching Children Takes Forever I recently got the latest version of Eclipse Indigo for Java Developers - then installed Subclipse using the update site: http://subclipse.tigris.org/update_1.6.x
Now when I go to SVN Repository Exporing perspective - my repository location having been added - when I expand the repository it says "Pending..." and tasks show it is "Fetching children of xxxx..."
Note that I tried using both JavaHL and SVNKit SVN interface. Sometimes it actually does finally show me the directory (after a few minutes), but other times it just sits there forever (one time I let it sit overnight).
But it never seems to show anything even if it let it sit for a really long time. I know this has worked in the past though.
I even created a different installation which had subversive plugin installed instead of subclipse. In this case it seems to be much faster. However, I find that synchronizing with subversive is painful because it tries to refresh the synchronization any time I do anything. Subclipse seemed to work a lot better with synchronizing, so I would really like to get this to work.
Here is a copy of my installation:
*
*Apache Ivy 2.2.0.final_20100923230623
*Apache IvyDE 2.1.0.201008101807-RELEASE
*Eclipse IDE for Java Developers
*Eclipse Java Web Developer Tools 3.3.0.v201103310009-7F7AFO-C25TohFunnht_0yz0s92kZCb4ufuz0TLG
*Eclipse Web Developer Tools 3.3.0.v201102200555-7O7IFhJEMiB5vNMYta56_GonLeahqrwnYjv2mBz-
*JavaScript Development Tools 1.3.0.v201103031824-7F78FXPFBBoPbXRIcIgs0z0
*JNA Library 3.2.7
*PHP Development Tools (PDT) SDK Feature 3.0.0.v20110516-1100-77--84_23JBVgSVXO7XGJz0VLa9O
*Subclipse (Required) 1.6.18
*Subversion Client Adapter (Required) 1.6.12
*Subversion JavaHL Native Library Adapter (Required) 1.6.17
*Subversion Revision Graph 1.0.9
*SVNKit Client Adapter (Not required) 1.6.15
*SVNKit Library 1.3.5.7406
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519496",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Why can't I place this object into an array? In PHP, you can normally place an object in an array, like so:
class Car{}
$car = new Car();
// This runs without error
$array['vehicle'] = $car;
I have a custom MVC framework I've built, and I need the controller to get an ORM object from the model, so it can pass that to the view. So, I initialize my user object:
$user = new User(2);
Now, I want to put that user object into a $data array so it can be passed to the view:
($user->data returns an ORM object)
$array['user'] = $user->data;
The problem is, after doing this, I receive the following error:
Object of class ORM could not be converted to string
What am I doing wrong? Is there something I'm missing?
Thanks for any help in advance.
Edit: Here's what $user->data refers to, this is from the constructor of class User:
$this->data = ORM::for_table("users")->find_one($this->user_id);
(I'm using Idiorm as an ORM)
A: If you get an error message like:
Object of class ORM could not be converted to string
The first question you should ask is, "why does it have to be converted to a string"? An array can take a string just fine, so you can guess that $data is actually a string and PHP thinks you want to modify $data[0].
As you've seen, dynamically typed languages can leave befuddled if you aren't careful.
When your variables show suspect behavior, try to see what's actually in them using var_dump().
It's also a good idea to explicitly initialize arrays (eg: $my_array = array();) before using them.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519497",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Set allowing quick insert/deletion and random selection in C# What data structure could I use in C# to allow quick insertion/deletion as well as uniform random selection? A List has slow deletion by element (since it needs to find the index of the element each time), while a HashSet does not seem to allow random selection of an element (without copying to a list.)
The data structure will be updated continuously, so insertion and deletion need to be online procedures. It seems as if there should be a way to make insertion, deletion, and random selection all O(log n).
A binary search tree with arbitrary integer keys assigned to the objects would solve all of these problems, but I can't find the appropriate class in the C# standard library. Is there a canonical way to solve this without writing a custom binary search tree?
A: There is already a BST in the C# BCL, it's called a SortedDictionary<TKey, TValue>, if you don't want Key Value Pairs, but instead want single items, you can use the SortedSet<T> (SortedSet is in .NET 4.0).
It sounds like from your example you'd want a SortedDictionary<int, WhateverValueType>. Though I'm not sure exactly what you are after when you say "uniform random selection".
Of course, the Dictionary<TKey, TValue> is O(1) which is much faster. So unless you have a need for sorted order of the keys, I'd use that.
UPDATE: From the sounds of your needs, you're going to have a catch-22 on efficiency. To be able to jump into a random contiguous index in the data structure, how often will you be inserting/deleting? If not often, you could use an array and just Sort() after (O(n log n)), or always insert/delete in order (O(n)).
Or, you could wrap a Dictionary<int, YourType> and keep a parallel List<int> and update it after every Add/Delete:
_dictionary.Add(newIndex, newValue);
_indexes.Add(newIndex);
And then just access a random index from the list on lookups. The nice thing is that in this method really the Add() will be ~ O(1) (unless List resizes, but you can set an initial capacity to avoid some of that) but you would incurr a O(n) cost on removes.
I'm afraid the problem is you'll either sacrifice times on the lookups, or on the deletes/inserts. The problem is all the best access-time containers are non-contiguous. With the dual List<int>/Dictionary<int, YourValue> combo, though, you'd have a pretty good mix.
UPDATE 2: It sounds like from our continued discussion that if that absolute performance is your requirement you may have better luck rolling your own. Was fun to think about though, I'll update if I think of anything else.
A: Binary search trees and derived structures, like SortedDictionary or SortedSet, operate by comparing keys.
Your objects are not comparable by itself, but they offer object identity and a hash value. Therefore, a HashSet is the right data structure. Note: A Dictionary<int,YourType> is not appropriate because removal becomes a linear search (O(n)), and doesn't solve the random problem after removals.
*
*Insert is O(1)
*Remove is O(1)
*RandomElement is O(n). It can easily be implemented, e.g.
set.ElementAt(random.Next(set.Count))
No copying to an intermediate list is necessary.
A: I realize that this question is over 3 years old, but just for people who come across this page:
If you don't need to keep the items in the data set sorted, you can just use a List<ItemType>.
Insertion and random selection are O(1). You can do deletion in O(1) by just moving the last item to the position of the item you want to delete and removing it from the end.
Code:
using System; // For the Random
using System.Collections.Generic; // The List
// List:
List<ItemType> list = new List<ItemType>();
// Add x:
ItemType x = ...; // The item to insert into the list
list.Add( x );
// Random selection
Random r = ...; // Probably get this from somewhere else
int index = r.Next( list.Count );
ItemType y = list[index];
// Remove item at index
list[index] = list[list.Count - 1]; // Copy last item to index
list.RemoveAt( list.Count - 1 ); // Remove from end of list
EDIT: Of course, to remove an element from the List<ItemType> you'll need to know its index. If you want to remove a random element, you can use a random index (as done in the example above). If you want to remove a given item, you can keep a Dictionary<ItemType,int> which maps the items to their indices. Adding, removing and updating these indices can all be done in O(1) (amortized).
Together this results in a complexity of O(1) (amortized) for all operations.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: MySQL - complicated LEFT JOIN I have that one-to-many relationship going here. Plus, not all "primary" records will have a joined record in the second database table.
Here are my tables:
tbl_customers
tbl_addresses
A customer record in tbl_customers can obviously have many addresses, in the tbl_addresses table.
Here's my dilemma. There are many customer records with several addresses, and I assign one of those address records as the "main" address for a customer record. This is simply a single column called: primaryAddress. The value will be a number 1, if that address record is the main address.
So here is my query:
SELECT c.customername, a.state
FROM `tbl_customers` c
LEFT JOIN `tbl_addresses` a ON c.customerid = a.customerid
That query will result in duplicate records for any customer with more than 1 address.
If I add a little more to the LEFT JOIN:
SELECT c.customername, a.state
FROM `tbl_customers` c
LEFT JOIN `tbl_addresses` a ON c.customerid = a.customerid AND a.primaryAddress = 1
This produces no results, even when I see in the database there are plenty of address records with primaryAddress = 1.
So I'm thinking my query is wrong.
Can someone see what I'm missing?
A: To anyone who happens to land on this page looking for a solution:
THIS DOES NOT PROPERLY ANSWER THE QUESTION
The user was able to find the cause after discussing the problem here. Turns out he had a typo on his original code. The second block of SQL code posted on the question is correct, and should give the expected results. +1 for user JoeStefanelli for pointing this out.
Please read the comments for details. My original answer is below. Now I see I should have deleted it, instead of trying to amend it, as soon I realized it was flawed. At least the discussion helped the user find a solution...
My original answer:
You are almost there. Add a.primaryAddress = 1 to the WHERE clause instead.
EDIT
Not sure if this will exclude costumers with zero addresses from the results...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519501",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: In Ruby how can the last method on a chain access the initial object - EDIT, SOLVED -
Ended up creating a method Object#rec to accomplish what I needed, this is the result:
#$l stores the last object on which Object#rec was called
$l=nil;class Object;def rec;$l=self;end;end
class String
attr_accessor :ref
alias_method :old_reverse, :reverse
def reverse
self.rec.old_reverse
end
def my_method
$l.ref + ' ' + self
end
end
a = "Hello"
b = "dlroW" ; b.ref = a
p b.reverse.my_method #=> Hello World
If anyone has a better way the question is still open.
- EDIT, SOLVED -
The problem:
I have a situation similar to this:
obj.method1.method2
where method1 returns something other than obj and I need method2 to access obj again as it holds a reference I need.
For example:
class String
attr_accessor :ref
def my_method(b)
b.ref + ' ' + self
end
end
a = "Hello"
b = "dlroW" ; b.ref = a
#I want my_method to access 'b.ref' without having to pass 'b'
p b.reverse.my_method(b) #=> Hello World
Alternative:
I know I could avoid having to pass b again if I used obj.my_method and my_method did both reversing(for the example) and accessing the reference, or like commented by the Tin Man have method1 change obj but return the original obj, but what I want is to know if it's possible or not to accomplish the above.
Thanks in advance.
A: Sounds kind of like you're looking for Object.tap:
Yields x to the block, and then returns x. The primary purpose of this method is to “tap into” a method chain, in order to perform operations on intermediate results within the chain.
For your example, you might be able to use String's reverse! inside the tap to manipulate the object. For your application, manipulate the object as you desire inside tap, then the object will be passed on to your following method.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519502",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Override TD:first-child with TR:hover? I have a table where the first cells have a different background. When the TR:hover is applied those cells do not change.
Is there a way to override them when the row is hovered?
#spreadsheet TABLE, #spreadsheet TH, #spreadsheet TD {
border:1px solid #CCC;
}
#spreadsheet TABLE TR:hover {
background:#BAFECB !important;
}
#spreadsheet TD:first-child {
background:#fff;
white-space:nowrap;
}
A: try
#spreadsheet TABLE TR:hover TD { background:#BAFECB !important; }
Yep, it works.
Code: http://jsfiddle.net/b9ndZ/1/
A: The problem is that the td elements are nested in the tr element, which means that td's background will be "above" the tr's background.
To let the tds "loose" their background you have at least two options:
One: http://jsfiddle.net/mqchen/WXvkk/
Using the :not() pseudo selector you can set the td's background only when the user isn't hovering over the tr. Downside with this is that :not() only works in some browsers (IE) if you use e.g. http://selectivizr.com/
table tr:not(:hover) td:first-child {
background-color: #eee;
}
table tr:hover {
background-color: yellow;
}
Two: http://jsfiddle.net/mqchen/zPGW9/
Set the td's background color to be transparent when it's parent tr is hovered over.
table td:first-child {
background-color: #eee;
}
table tr:hover td:first-child {
background-color: transparent;
}
table tr:hover {
background-color: yellow;
}
The advantage of these solutions vs. that by Samich is that this will also work where the parent element's background not a solid color, eg. a graphic, gradient, etc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519506",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: textFieldShouldReturn is not working anymore On iPad, textFieldShouldReturn is not working anymore. I had it working until like five minutes ago, suddenly the method is not called anymore … Any Ideas? Below is the code, the only thing changed was a notification for an UITextView… Thanks!
- (BOOL)textFieldShouldReturn:(UITextField *)tf
{
NSString* newName = textField.text;
textLabel.text = textField.text;
NSLog(@"Called!");
newName = [newName stringByAppendingPathExtension:@"txt"];
NSString* newPath = [[currentFilePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:newName];
NSLog(@"%@",newPath);
[[NSFileManager defaultManager] moveItemAtPath:currentFilePath toPath:newPath error:nil];
[[NSNotificationCenter defaultCenter] postNotificationName:@"DataSaved" object:nil];
[currentFilePath retain];
currentFilePath = newPath;
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
[currentFilePath retain];
// Write out the contents of home directory to console
NSLog(@"Documents directory: %@", [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil]);
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5];
textLabel.alpha = 1.0;
textField.alpha = 0.0;
[UIView commitAnimations];
[tf resignFirstResponder];
return YES;
}
A: best possibility - you might have accidentally removed the delegate for the textfield.
A: Check for (BOOL)textFieldShouldReturn:(UITextField *)textField method in IOS 6. You have to set the textField delegate in XIB and write down the following code:
(BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Table column width unexpectedly shortened I have an HTML table (populated from a datatable on server side), with no styling except background color, and for some reason it breaks some of the lines.
Is there any CSS behavior that dictates this? I tried to replicate it with a table populated with a random string of "M "s, and it also broke the line after every space...
EDIT:
What's happening:
|M|M|
|M|M|
|M|M|
What's supposed to happen:
|M M M |M M M |
Thanks!
A: I think you mean the NOWRAP option.
<table><tr><td NOWRAP>Text</td></tr></table>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519508",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Enterprise Library 5 Logging Block: How to write to event viewer? I'm using Logging Application Block from Enterprise Library 5 trying to log into flat file and event log. My configuration looks like this:
I'm using this code to write to logs:
Logger.Write("message", "General1");
Logger.Write("message", "General2");
The problem is, I get the flat file logging ok, but event log never shows the log entries. I've made there a custom view to filter for "Enterprise Library Logging".
How can one produce entries in the event viewer log with Ent lib 5?
Thanks.
Pom.
A: I think there are two things that could be happening here:
*
*Logging is working but your custom filter is not correct
*Logging is not working
Let's be optimistic and assume that logging is working.
Logging is Working
You've configured the EventLogTraceListener to log to an Event Log called MyLog with a source of "Enterprise Library Logging". Perhaps the custom filter is configured to filter by log and is not searching MyLog? Double check your filter and also check that there actually is a log under Applications and Services Logs called MyLog.
If I were to guess, though, that's probably not the issue.
Logging Is Not Working
Let's assume that logging is not working. The most likely reason that it is not working is that you don't have permission to create an event log.
I also notice that the Logging Errors & Warnings section is not configured with a listener. It's always a good idea to setup the Logging Errors & Warnings to use a trace listener (I prefer the flat file trace listener since it's one of the simplest so less can go wrong).
So, in your case, I would set it to use the "Flat File Trace Listener" that you have already set up:
<specialSources>
<allEvents switchValue="All" name="All Events" />
<notProcessed switchValue="All" name="Unprocessed Category" />
<errors switchValue="All" name="Logging Errors & Warnings">
<listeners>
<add name="Flat File Trace Listener" />
</listeners>
</errors>
</specialSources>
Now if you re-run your program you should probably see an error message in the consoletrace.log.
If permissions are the problem the usual solution is to create the event logs and their sources during installation with an account that has the proper permissions. E.g. logging a message as administrator to setup your log and category.
A: I know this is an older question now, but in order to use the event log, the event source must be created first (by a user having Administrative Privileges). In addition, if you are trying to use this within a web site, the NETWORK SERVICE account must be granted access to write to the event log. This site will help: http://msdn.microsoft.com/en-us/library/ms998320.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519520",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: VB6 to COM-callable wrapped .NET - problems finding .NET libraries Premise:
*
*Wrote a COM-callable wrapper (CCW) written in C# to be called by VB6 code.
*The C# code has .NET libraries (third party) that it must utilize.
*The wrapped C# class instantiates fine, raises events properly, takes method calls properly.
Problem:
*
*The VB6 code, when running the C# code, gets an error when the C# code attempts to access the additional .NET libraries mentioned above.
Process tested:
*
*C# wrapped code completed.
*VB6 code written, references the COM dll created.
*"File not found..." error received when the C# code tries to access the .NET libraries from inside itself.
*Copied the third party .NET libraries into the main folder of the VB6 code (also into system32 folder).
*
*Still "File not found..." error.
*Wrote a C# Windows Form test project. Referenced the C# wrapped code.
*
*Received the same error as the VB6 code.
*In C# Windows Form test project, referenced the .NET libraries used by the C# wrapped code.
*
*The program ran just fine.
Conclusion/Question:
*
*Can VB6 call/use a com-callable wrapped C# program that references other third party .NET libraries?
A: I've done this with tons of third party libraries and as long as the third party library DLL's are in the same directory as your C# DLL's there shouldn't be a problem.
*
*Copying them into the same directory as your VB6 code will do nothing, the effective directory of VB6 code when running the in VB6 debugger is %ProgramFiles%\Microsoft Visual Studio\VB98, so the code running will have no visibility of that.
*The system32 directory has nothing to do with DotNet dll's (the only DLL's they would affect is PInvoke'd dll's and you say you add a reference so that isn't the case).
Adding the third party library to the GAC should fix things, however that is not necessarily possible/easy due to the need to sign the DLL. So just make sure the Libraries you are referencing are in the directory of YOUR library and that VB6 is actually referencing that version of your library (Debug/Release whatever what last compiled). You may want to hand RegAsm the library to make sure the correct library is Com Registered.
So to sumerize, suppose your source code looks like this:
c:\projects\vb6project
c:\projects\c#project
And your project is set to Debug, the third party libraries should be in:
c:\projects\c#project\bin\Debug
When you actually want to distribute the application, make sure that ALL the libraries are in the same directory as your VB6 exe.
A: This will mirror somewhat the answer by Kris Erickson.
First, for my usage which solves these problems, I did not use the GAC. Assuming that my VB6 application is in c:\program files\mycompany\vb6app.exe, I placed the COM-friendly .NET dll (lets call it net4vb.dll) in the folder with the executable. I then regsiter that dll there with RegAsm using the /codebase option. Finally, I place the .NET assembly that I'm wrapping or using (lets call it purenet.dll) in that folder as well.
At this point, vb6app.exe should run with no errors.
It is important to note that if you select the "Register for COM Interop" in Visual Studio then it will overwrite the registration you did above. So do not use this option. Stick with the command-line tools only for this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519523",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I use the same variable in one function with another function, without making that variable Global? How can I take one variable from one function and use it in another function without having to make that variable global?
A: You have basically two choices.
One is to pass it to the second function as a parameter. (If you want the first function to see changes to the value, it needs to be a reference type (e.g. a dict/list) and you have to not overwrite the object, only modify it (e.g. a.append(b) rather than a = a + [b]).
The second is to define a class that can be used as a singleton. Technically, this is still defining something 'globally', but it lets you keep things grouped:
class FooSingleton(object):
class_var = "foo"
def func1():
FooSingleton.class_var = "bar"
def func2():
print(FooSingleton.class_var)
(You could also do this with a dict instead of a class; matter of preference.)
A: have the function take a parameter, and pass that parameter in.
def one_function():
one_variable = ''
return one_variable
def another_function(a_param):
# do something to a_param
return
A: Technically possible and may be used, e.g. for memoisation (but then it is usually hidden behind a decorator and only implemented by people who are sure they do the right thing even though they might still feel a bit bad about it):
def g():
if not hasattr(g, "x"):
g.x = 0
return g.x
g()
# 0
g.x = 100
g()
# 100
A: You can use closure to handle this, or more natural is to define both functions as methods of a class and the "global" variable as member of the class.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519527",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Sort AS3 XMLList in document order In Actionscript 3, is there a way to sort the nodes (instances of type XML) in an XMLList in document order (as defined in the XDM spec; "Informally, document order is the order in which nodes appear in the XML serialization of a document")? Alternately, is there a way to compare the document position of two nodes?
Here's a little example of what I mean. In the real case, the list is constructed by a much more complicated process and might have hundreds of nodes.
var x:XML = <a><b/><b/></a>;
var b0:XML = x.b[0];
var b1:XML = x.b[1];
var l:XMLList = new XMLList();
l += b1;
l += b0;
var sl:XMLList = documentSortFunction(l);
assertTrue(sl[0] === b0);
I'm not sure I have a lot of hope here, since it seems that ECMA-357 (E4X) doesn't really have a concept of document, much less document order.
A: Well, here's a sketch of the answer I came up with. This hasn't been tested much yet, but I thought I'd record it before I forget to.
The idea is to implement a function to generate a string for a node, such that the order of the strings is the same as the order of the nodes.
protected function generateSortID(n:XML):String
{
var ret:String = '';
while (n != null && n.childIndex() > -1)
{
var s:String = '' + n.childIndex();
ret = '0000000'.substring(s.length) + s + '!' + ret;
n = n.parent();
}
return ret;
}
protected function compareNodePair(a:Array, b:Array):int
{
var ai:String = a[0];
var bi:String = b[0];
if (ai < bi)
return -1;
else if (ai > bi)
return 1;
else
return 0;
}
// all nodes in input list must be part of the same document.
protected function documentSortFunction(l:XMLList):XMLList
{
var augArr:Array = [];
for (var il:String in l)
augArr.push([generateSortID(l[il]), l[il]]);
augArr.sort(compareNodePair);
var ret:XMLList = new XMLList();
for (var ia:String in augArr)
ret += augArr[ia][1];
return ret;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519534",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C# Process, unable to run exe that creates an Image and read it back I am trying to run an exe from C#
ProcessStartInfo si = new ProcessStartInfo
(
ExePath, InputImageFilePath +" "+
numericUpDownResize.Value +" "+
numericUpDownPad.Value+" "+
numericUpDownWindow.Value
);
si.UseShellExecute = true;
si.CreateNoWindow = true;
si.WindowStyle = ProcessWindowStyle.Normal;
si.Verb = "runas";
Process process = Process.Start(si);
process.WaitForExit();
int indexOfLastSlash = ExePath.LastIndexOf(@"\");
string outputFilePath = ExePath.Substring(0, indexOfLastSlash);
OutputImage = new Bitmap(outputFilePath + @"\output.jpg");
When I run the exe from command line prompt, it works fine as expected and the JPEG is created. But when I try the C# program, after allowing the program run once through UAC, I see the command line prompt open and display the status. But the output image is not produced.
Is there something that I miss?
Update
After adding the Manifest as suggested by Moxplod, I was going through the security settings. Does the highlighted box I have shown need to be checked green like the other few?
A: You can add a manifest entry so you dont get permission errors. If this is what you want.
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
A: Does program produce output image in the current directory? Because you are checking for image in the directory that contains executable which may be different from current directory.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519537",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I tell if a file is currently being written to? I'm saving a fairly large bitmap in a background thread. It takes about a second. The main thread will try to load the same file into a canvas. How can I tell the main thread to wait until it has finished saving?
Edit:
I wanted to know how to check on the file, not how to wait; sorry for the misunderstanding.
The bitmap object was removed from the main thread's memory for various reasons.
Is there a standard way to do check if the file is being used, or should I just use a workaround?
A: The FileObserver class suits your needs perfectly. Here is the documentation. It's easy to use. When a observed file is closed after writing, the onEvent callback is called with CLOSE_WRITE as the parameter.
A: Use AsyncTaskto run a background thread and update UI when finished. It was designed for specifically this task.
Also note that you should never hog the UI thread (like waiting for background thread to finish) because this blocks UI interaction and your UI will be unresponsive or worse you might get an ANR.
A: Android's AsyncTask will be suitable for this problem:
http://developer.android.com/reference/android/os/AsyncTask.html
You can update the bitmap in doInBackground, and then onPostExecute you can notify the main thread do draw it to canvas.
edit/what he said
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: command execution with nohup in background when executing a command with nohup , is that necessary to execute it in background.
If the only thing required is that the command should not hang when closed the terminal, then what is the differnce in
( nohup command & )
and
( nohup command )
?
Both of the above statements achive this.
A: Yes, it's necessary that you execute it in the background, if you wish for the shell to be able to exit.
A: The & at the end indicates that the command should be running in the background. That means, you can continue to enter commands into the shell.
For your particular question, it does not make any difference as it seems you want to close the terminal window right afterwards anyway.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519539",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Popup Message instead of lblMessage I want show this "lblMessage.Text = "Message sent successfully.";" message in a popup upon Clicking on the submit button. How do i do that in asp.net?
A: Change the text after hiding all the form. Choose an update panel where it will update asynchronously and after the completion of the event replace it with a label and set the text to message sent succesfully. Thats what i can understand from the description. If you can provide your scenario it would be more helpful. or if you want to show a popup message then this would be helpful
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519542",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Read exe file as binary file in C# I want to read an exe file in my C# code then decode as base64.
I am doing it like this
FileStream fr = new FileStream(@"c:\1.exe", FileMode.Open, FileAccess.Read, FileShare.Read);
StreamReader sr = new StreamReader(fr);
fr.Read(data, 0, count);
But the problem is that when I write this file the written file gets corrupted.
When analyzing in hex workshop code value 20 in hex is being replaced by 0.
A: A StreamReader should be used only with text files. With binary files you need to use directly a FileStream or:
byte[] buffer = File.ReadAllBytes(@"c:\1.exe");
string base64Encoded = Convert.ToBase64String(buffer);
// TODO: do something with the bas64 encoded string
buffer = Convert.FromBase64String(base64Encoded);
File.WriteAllBytes(@"c:\2.exe", buffer);
A: StreamReader official docs:
"Implements a TextReader that reads characters from a byte stream in a particular encoding."
It's for text, not binary files. Try just Stream or BinaryReader.. (Why did you try a StreamReader?)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519544",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: COM Applications not working Our Test web server recently went down and we lost COM+ Applications installations. I am trying to reinstall the COM Applications. I have the installed the COM Applications and have the Identity set to run as Local Service. I have Security set to Perform access checks at the process and component level. The activation type is Server Application.
Environment:
Windows Server 2003
Classic ASP
I have verified that ASP is installed and works. I get a 500 Internal Server error when the page gets to a point to call CreateObject.
There must be a security setting somewhere that I am missing. I have tried giving Local Service Account and Network Service account full permissions on the root folder housing the .dll's.
A: Can't pinpoint it because the possible causes are legion.
There should be a setting in ASP that will report the HRESULT of the failed CreateObject call, instead of a useless 500 - Internal Error. From there, it should be easier to go on.
Aren't you unsure about LocalService, too? Shouldn't it be NetworkService instead?
Sorry that this is rather meager.
A: Found the problem. We had to go into IIS, view the website properties, go to the Home Directory, Click on Configuration and then the Options tab and finally check the "Enable Parent Path" checkbox.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519548",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Printing result of mysql query from variable So I wrote this earlier (in php), but everytime I try echo $test", I just get back resource id 5. Does anyone know how to actually print out the mysql query from the variable?
$dave= mysql_query("SELECT order_date, no_of_items, shipping_charge, SUM(total_order_amount) as test FROM `orders` WHERE DATE(`order_date`) = DATE(NOW()) GROUP BY DATE(`order_date`)") or die(mysql_error());
print $dave;
A: well you are returning an array of items from the database. so you need something like this.
$dave= mysql_query("SELECT order_date, no_of_items, shipping_charge,
SUM(total_order_amount) as test FROM `orders`
WHERE DATE(`order_date`) = DATE(NOW()) GROUP BY DATE(`order_date`)")
or die(mysql_error());
while ($row = mysql_fetch_assoc($dave)) {
echo $row['order_date'];
echo $row['no_of_items'];
echo $row['shipping_charge'];
echo $row['test '];
}
A: This will print out the query:
$query = "SELECT order_date, no_of_items, shipping_charge, SUM(total_order_amount) as test FROM `orders` WHERE DATE(`order_date`) = DATE(NOW()) GROUP BY DATE(`order_date`)";
$dave= mysql_query($query) or die(mysql_error());
print $query;
This will print out the results:
$query = "SELECT order_date, no_of_items, shipping_charge, SUM(total_order_amount) as test FROM `orders` WHERE DATE(`order_date`) = DATE(NOW()) GROUP BY DATE(`order_date`)";
$dave= mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($dave)){
foreach($row as $cname => $cvalue){
print "$cname: $cvalue\t";
}
print "\r\n";
}
A: From php docs:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning
resultset, mysql_query() returns a resource on success, or FALSE on
error.
For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc,
mysql_query() returns TRUE on success or FALSE on error.
The returned result resource should be passed to mysql_fetch_array(),
and other functions for dealing with result tables, to access the
returned data.
http://php.net/manual/en/function.mysql-query.php
A: $sql = "SELECT * FROM table_name ORDER BY ID DESC LIMIT 1";
$records = mysql_query($sql);
you can change
LIMIT 1
to
LIMIT any number you want
This will show you the last INSERTED row first.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519549",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: How to make button-looking buttons that are not images in form-submit buttons? I had a designer help me make links that look like buttons that look something like this: http://www.comehike.com/hikes/scheduled_hike.php?hike_id=233 (the yellow buttons are the RSVP, Ride, Drive, etc.)
Those are not images. They are just styled links.
My question is - can I make a similar type of non-image button for the buttons that are submit buttons in forms?
Thanks!
A: Yes, you can style the default buttons anyway you like, here is some CSS to get you started:
HTML
<a href="#" class="button">Gray Button</a>
<a href="#" class="button red">Red Button</a>
<a href="#" class="button green">Green Button</a>
<button>Normal Button</button>
<button class="btn green">Green Button</button>
<button class="btn red">Red Button</button>
<button class="btn gray">Gray Button</button>
CSS
a, button {
display:list-item;
margin:10px 0;
}
a.button, button.btn {
color: #6e6e6e;
font: bold 12px Helvetica, Arial, sans-serif;
text-decoration: none;
padding: 7px 12px;
position: relative;
display: inline-block;
background: #f3f3f3;
background: -webkit-gradient(linear,0% 40%,0% 70%,from(#F5F5F5),to(#F1F1F1));
background: -moz-linear-gradient(linear,0% 40%,0% 70%,from(#F5F5F5),to(#F1F1F1));
border: solid 1px #dcdcdc;
border-radius: 2px;
-webkit-border-radius: 2px;
-moz-border-radius: 2px;
margin-right: 10px;
}
a.red, button.red {
color:#fff;
background: red;
background: -webkit-gradient(linear,0% 40%,0% 70%,from(#FF0000),to(#F1F1F1));
background: -moz-linear-gradient(linear,0% 40%,0% 70%,from(#FF0000),to(#F1F1F1));
}
a.green, button.green {
background: #7FFF24;
background: -webkit-gradient(linear,0% 40%,0% 70%,from(#7FFF24),to(#F1F1F1));
background: -moz-linear-gradient(linear,0% 40%,0% 70%,from(#7FFF24),to(#F1F1F1));
}
Demo link: http://jsfiddle.net/andresilich/cXv8A/1/
A: Submit button with hover effect.
<!doctype html>
<head>
<style>
.button{
-moz-border-radius:6px;
-webkit-border-radius:6px;
border-radius: 6x;
border: 1px solid #ABABAB;
background-image: -webkit-gradient(linear, left top, left bottom, from(#E1E1E1), to(#F7F7F7));
background-image: -webkit-linear-gradient(top, #E1E1E1, #F7F7F7);
background-image: -moz-linear-gradient(top, #E1E1E1, #F7F7F7);
background-image: -ms-linear-gradient(top, #E1E1E1, #F7F7F7);
background-image: -o-linear-gradient(top, #E1E1E1, #F7F7F7);
background-image: linear-gradient(top, #E1E1E1, #F7F7F7);
filter: progid:DXImageTransform.Microsoft.gradient(startColorStr='#E1E1E1', EndColorStr='#F7F7F7');
padding: 15px 0px;
margin: 0 auto;
width: 224px;
display: block;
color: #434953;
text-transform: uppercase;
font: 182% "League Gothic", Helvetica, Arial, sans-serif;
text-decoration:none;
text-align:center;
}
.button:hover{
border: 1px solid #ABABAB;
color: #303030;
background-image: -webkit-gradient(linear, left top, left bottom, from(#F7F7F7), to(#E1E1E1));
background-image: -webkit-linear-gradient(top, #F7F7F7, #E1E1E1);
background-image: -moz-linear-gradient(top, #F7F7F7, #E1E1E1);
background-image: -ms-linear-gradient(top, #F7F7F7, #E1E1E1);
background-image: -o-linear-gradient(top, #F7F7F7, #E1E1E1);
background-image: linear-gradient(top, #F7F7F7, #E1E1E1);
filter: progid:DXImageTransform.Microsoft.gradient(startColorStr='#F7F7F7', EndColorStr='#E1E1E1');
-webkit-box-shadow: 0px 0px 5px rgba(0,0,0,0.10) inset;
-moz-box-shadow: 0px 0px 5px rgba(0,0,0,0.10) inset;
box-shadow: 0px 0px 5px rgba(0,0,0,0.10) inset;
}
</style>
</head>
<body>
<input type="submit" class="button" value="submit" />
</body>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519554",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to setup custom api for Magento with SOAP V2? I am on Magento 1.4.1.1 and I am trying to setup a custom function in the API using SOAP v2. I have it working for SOAP v1 but I need v2 so that C# can use it. For v2 the function shows up in the WSDL but alwasy returns this error: Procedure 'testFoo' not present.
Here are my files:
/app/etc/modules/ABT_Test.xml
<?xml version="1.0"?>
<config>
<modules>
<ABT_Test>
<active>true</active>
<codePool>local</codePool>
</ABT_Test>
</modules>
</config>
/app/code/local/ABT/Test/etc/config.xml
<?xml version="1.0"?>
<config>
<modules>
<ABT_Test>
<active>true</active>
<codePool>local</codePool>
<version>1.0</version>
</ABT_Test>
</modules>
<global>
<models>
<test>
<class>ABT_Test_Model</class>
</test>
</models>
</global>
</config>
/app/code/local/ABT/Test/etc/api.xml
<?xml version="1.0"?>
<config>
<api>
<resources>
<test>
<model>test/api</model>
<title>ABT Test Api</title>
<methods>
<foo translate="title" module="test">
<title>Foo Test</title>
<method>foo</method>
<acl>test/foo</acl>
</foo>
</methods>
</test>
</resources>
<v2>
<resources_function_prefix>
<test>test</test>
</resources_function_prefix>
</v2>
</api>
</config>
/app/code/local/ABT/Test/etc/wsdl.xml
<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns:typens="urn:{{var wsdl.name}}" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns="http://schemas.xmlsoap.org/wsdl/"
name="{{var wsdl.name}}" targetNamespace="urn:{{var wsdl.name}}">
<types>
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="urn:Magento">
<import namespace="http://schemas.xmlsoap.org/soap/encoding/" schemaLocation="http://schemas.xmlsoap.org/soap/encoding/" />
</schema>
</types>
<message name="testFooRequest">
<part name="sessionId" type="xsd:string" />
</message>
<message name="testFooResponse">
<part name="result" type="typens:boolean" />
</message>
<portType name="{{var wsdl.handler}}PortType">
<operation name="testFoo">
<documentation>Test Foo</documentation>
<input message="typens:testFooRequest" />
<output message="typens:testFooResponse" />
</operation>
</portType>
<binding name="{{var wsdl.handler}}Binding" type="typens:{{var wsdl.handler}}PortType">
<soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http" />
<operation name="testFoo">
<soap:operation soapAction="urn:{{var wsdl.handler}}Action" />
<input>
<soap:body namespace="urn:{{var wsdl.name}}" use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
</input>
<output>
<soap:body namespace="urn:{{var wsdl.name}}" use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
</output>
</operation>
</binding>
</definitions>
/app/code/local/ABT/Test/Model/API.php
<?php
class ABT_Test_Model_Api extends Mage_Api_Model_Resource_Abstract
{
public function foo()
{
return true;
}
}
?>
/app/code/local/ABT/Test/Model/API/V2.php
<?php
class ABT_Test_Model_Api_V2 extends ABT_Test_Model_Api
{
}
?>
And here is the code I use to test the API:
<?php
$mageUser = '########';
$mageApiKey = '########';
//SOAP V1
echo "SOAP V1 <br />";
$mageUrl = 'http://www.########.com/api/soap/?wsdl';
$soap = new SoapClient($mageUrl, array('cache_wsdl' => 0));
try {
$sessionID = $soap->login($mageUser, $mageApiKey);
var_dump($soap->call($sessionID, 'test.foo', array()));
} catch (Exception $e) {
echo 'Exception: ' . $e->getMessage() . '<br />';
}
//SOAP V2
echo "SOAP V2 <br />";
$mageUrl2 = 'http://www.########.com/api/v2_soap/?wsdl';
$soap2 = new SoapClient($mageUrl2, array('cache_wsdl' => 0));
try {
$sessionID2 = $soap2->login($mageUser, $mageApiKey);
var_dump($soap2->testFoo($sessionID2));
} catch (Exception $e) {
echo 'Exception: ' . $e->getMessage() . '<br />';
}
?>
I obscured the username, password and url. The function shows up in the v2 WSDL and the php code recognizes that it is in the WSDL but I still get the error: Procedure 'testFoo' not present.
So what am I missing?
EDIT:
I did what Zyava suggested and it got my example working. I then copied the folder and did an exact (case sensitive) find and replace to use a meaningful Module name and function name. I was careful to pick names that I didn't think would be reserve words. On the new module the call on the v1 WSDL works fine but the v2 gives the same "Procedure 'xxx' not present" message. I then went and renamed the method on the test from 'Foo' to 'Fooz' and I got this message: "Resource path is not callable." I find it interesting that I get a different message. This leads me to believe there is some cache/configuration/something that is causing the problem. Any ideas?
A: At first I should warn you that Magento doesn't support SOAP v2 format for now, api/v2_soap/?wsdl is just second version of soap api.
1.
<models>
<test>
<class>ABT_Test_Model</class>
</test>
</models>
Because you are writing module which isn't core, you should write <abt_test>
2.<model>test/api</model>. Should be <model>abt_test/api</model> in your case.
3.<acl>test/foo</acl>.
Does this acl section exist in your adminhtml.xml?
A: bygrace,
your code is so perfect!
add
....
<resources_alias>
<test>test</test>
</resources_alias>
.....
same level with
<resources> and <v2>
on Api.xml
and it'll be working good.
A: I has having the same issue and i tried clearing the tmp file as i had hosted it using xampp it didnt work i was getting Procedure ххх not present exception, I had to disable the cache management in the admin page of the server.
How to disable Cache in Admin page
In the admin page under the system there is a section called cache management disable everything during the development phase or else any change you do wont be reflected in the wsdl.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519556",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: TFS 2010 gated check-in using TortoiseSvn over SvnBridge I have the configuration in the above title. I am using the TFS gated check-in feature which works fine if i use the TFS tools to check in my changes.
A review of my understanding of the way it works:
my changes are intercepted by the gated check in and put in a shelveset. The shelveset is pulled down by the build server, built, unit tests run, and gets checked in with NO CI appended to the end of the check in comment. When all that is done, a prompt to reconcile the workspace occurs.
Using TortoiseSvn:
i can commit code and update code just fine as long as I do not have gated check-ins set up.
With gated check-ins set up, the TFS server sends back a 500 error (see exception below) and the tortoiseSvn client shows the error labeled below, though the check in process continues. The build server builds, runs tests, and commits the code with no problem but this is pretty annoying and would be hard to convince other developers to use because you get the error on commit and then have to perform an update on the code to get the changes actually committed by the build server.
Thanks for any ideas or help.
TortoiseSvn Error
Error: Commit failed (details follow):
Error: Server sent unexpected return value (500 Internal Server Error) in response to
Error: MERGE request for '/mil-tfsprd-01/Inst%20Trading%20Support/Source/Main/ODS/Eliminator/Eliminator
Stack trace from SoapException
System.Web.Services.Protocols.SoapException: Your check-in has been placed into shelveset Gated_2011-09-22_10.26.49.8403;US\RPieper and submitted for validation by build definition \Inst Trading Support\Eliminator.
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at CodePlex.TfsLibrary.RepositoryWebSvc.Repository.CheckIn(String workspaceName, String ownerName, String[] serverItems, Changeset info, CheckinNotificationInfo checkinNotificationInfo, CheckinOptions checkinOptions, Failure[]& failures)
at CodePlex.TfsLibrary.ObjectModel.SourceControlService.<>c__DisplayClass4.<Commit>b__3()
at CodePlex.TfsLibrary.ObjectModel.SourceControlService.WrapWebException[T](WrapWebExceptionDelegate`1 function)
at CodePlex.TfsLibrary.ObjectModel.SourceControlService.Commit(String tfsUrl, ICredentials credentials, String workspaceName, String comment, IEnumerable`1 serverItems)
at SvnBridge.SourceControl.TFSSourceControlProvider.<>c__DisplayClass18.<MergeActivity>b__17(Activity activity)
at SvnBridge.SourceControl.ActivityRepository.Use(String activityId, Action`1 action)
at SvnBridge.SourceControl.TFSSourceControlProvider.MergeActivity(String activityId)
at SvnBridge.Proxies.RemotingInvocation.Proceed()
at SvnBridge.Proxies.TracingInterceptor.Invoke(IInvocation invocation)
at SvnBridge.Proxies.RemotingInvocation.Proceed()
at SvnBridge.Proxies.RetryOnExceptionsInterceptor`1.Invoke(IInvocation invocation)
at SvnBridge.Proxies.RemotingInvocation.Proceed()
at SvnBridge.Proxies.ProxyFactory.RemotingProxy.Invoke(IMessage msg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at SvnBridge.SourceControl.TFSSourceControlProvider.MergeActivity(String activityId)
at SvnBridge.Handlers.MergeHandler.Handle(IHttpContext context, TFSSourceControlProvider sourceControlProvider)
at SvnBridge.Handlers.RequestHandlerBase.Handle(IHttpContext context, IPathParser pathParser, NetworkCredential credentials)
at SvnBridge.Net.HttpContextDispatcher.Dispatch(IHttpContext connection)
at SvnBridge.Net.Listener.Process(TcpClient tcpClient)
at SvnBridge.Net.Listener.Accept(IAsyncResult asyncResult)
A: SvnBridge doesn't support gated checkin - as you note, you'll fall back to this behavior.
If you're only using SvnBridge for Tortoise, you might want to check out the TFS integration into Windows Explorer instead which provides native access to TFS instead of through a bridge. It's available in the Team Foundation Server Power Tools.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519558",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: VB .net : How can a Server handle multiple clients simultaneosly at an instance I am facing a problem in VB .net Client/Server application where I am successfully able to talk between them using TCPListener and TCPClient class usage. However, when I try to connect another Client to the same server on the same welcome port, it errors out throwing an exception or behaves very unexpectedly.
*
*Isn't it true that the Server connection is on a WELCOME PORT for all the clients, and that each client connected gets a new port to carry on its communication with the server AUTOMATICALLY (according to the Tomcat webserver working)?
*OR, is the above statement untrue and that the APP program handle the connections manually?
Pls clarify with an example in VB .net, if possible?
A: The answer to your question is 'Yes it is true'. I do not have VB.NET code ready but you can have a look at C# code here C# sockets handling multiple clients.
A: Okay.. pasting my server code here for your comments... Pls pardon my ignorance in coding and teach me if I were wrong. Thanks.
The Client is more obvious... so dint paste it here.
Server:
Public Class ServerSide2
...other stuff...
Public Class Packet
Public packetType As String = "Data"
Public packetOwnerIPAddress As String
Public packetOwnerPort As String
Public content As String
Public Sub New(ByVal type As String, ByVal ip As String, ByVal port As String, ByVal data As String)
packetType = type
packetOwnerIPAddress = ip
packetOwnerPort = port
content = data
End Sub
End Class
Public Class Worker
Dim myLogger As Logger
Dim name As String
Dim ipClientAddress As IPAddress 'Client's IP address
Dim ipClientPort As Integer = 22222 'Client listening on this port
Dim tcpServer As TcpListener
Dim tcpClient As TcpClient
Dim networkStream As NetworkStream
Dim readSize As Integer = 100
Public Sub New(ByRef logger As Logger, ByVal id As String)
myLogger = logger
name = id
myLogger.Trace("A new Worker object has been created for client: {0}", ipClientAddress)
End Sub
'Listener code
Public Sub runClientHandler(ByVal ar As IAsyncResult)
'code to listen to independent client
Dim clientdata As String
Dim numBytesRead As Integer = 0
Thread.CurrentThread.Priority = ThreadPriority.Highest
' Get the listener that handles the client request.
Dim listener As TcpListener = CType(ar.AsyncState, TcpListener)
' End the operation and display the received data on
' the console.
tcpClient = listener.EndAcceptTcpClient(ar)
' Process the connection here. (Add the client to a
' server table, read data, etc.)
myLogger.Info("Client connected completed")
' Signal the calling thread to continue.
tcpClientConnected.Set()
networkStream = tcpClient.GetStream()
Dim ipEndPoint As IPEndPoint = tcpClient.Client.RemoteEndPoint
ipClientAddress = ipEndPoint.Address
myLogger.Info("A new Worker thread has been started.")
While Not stopping
myLogger.Trace("Start looping.")
Dim bytes(readSize) As Byte
numBytesRead = networkStream.Read(bytes, 0, bytes.Length)
clientdata = Encoding.ASCII.GetString(bytes, 0, numBytesRead)
'check for validity of the data
If numBytesRead = 0 Then
'connection lost
myLogger.Trace("No data read.")
Exit While
End If
If clientdata.Contains("SampleTest : {") Then
'Message box the client data
MsgBox("Test data from Client = " + clientdata)
myLogger.Trace("Test data from Client = " + clientdata)
ElseIf clientdata.Contains("Recieve Port : ") Then
'Heed to Client's request on the port number server should reply
Dim dest(5) As Char
Dim destString As String = ""
clientdata.CopyTo(15, dest, 0, clientdata.Length - 15)
ipClientPort = CInt(CStr(dest))
myLogger.Trace("Client Waiting on Port# : " + CStr(dest) + "for sorted packets.")
'MsgBox("Client Waiting on Port# : " + CStr(dest))
ElseIf clientdata.Contains("Packet Size : ") Then
Dim dest(5) As Char
Dim destString As String = ""
clientdata.CopyTo(14, dest, 0, clientdata.Length - 14)
readSize = CInt(CStr(dest))
myLogger.Trace("Client's communicated Packet Size : " + CStr(dest))
Else
myLogger.Info("Begin to queue Data Packets.")
While True
myLogger.Info("Data Packet.")
SyncLock Stats.locker
myLogger.Info("Got the lock.")
Stats.queueLength = Stats.requestQueue.Count
If Stats.queueLength < Stats.MAX_QUEUE_LENGTH Then
'Queue has some space to fit more packets
myLogger.Info("Queue has some space for this packet.")
Stats.packetNum = Stats.packetNum + 1
Dim newPacket As Packet = New Packet("Data", ipClientAddress.ToString, ipClientPort, clientdata)
Stats.requestQueue.Enqueue(newPacket)
Stats.sumQueueLength = Stats.sumQueueLength + Stats.requestQueue.Count
Stats.meanQueueLength = Stats.sumQueueLength / Stats.packetNum
myLogger.Info("Stats :: Packet #: {0}, QueueLength: {1}, MeanQueueLength: {2}.", Stats.packetNum, Stats.requestQueue.Count, Stats.meanQueueLength)
Else
'Queue is FULL, Ignore the packet
Stats.numDropPackets = Stats.numDropPackets + 1
myLogger.Info("Stats :: Dropped Packets: {0}.", Stats.numDropPackets)
End If
End SyncLock
numBytesRead = networkStream.Read(bytes, 0, bytes.Length)
clientdata = Encoding.ASCII.GetString(bytes, 0, numBytesRead)
'check for validity of the data
If numBytesRead = 0 Then
'connection lost
myLogger.Trace("No data read.")
Exit Sub
End If
End While
End If
End While
myLogger.Trace("End looping.")
End Sub
End Class
Sub ListeningThread()
Dim count As Integer = 0
tcpServer = New TcpListener(ipAddress, iPort)
tcpServer.Start()
Try
While Not stopping And count < Stats.MAX_CLIENTS
count = count + 1
Dim workerName = "worker:" + CStr(count)
Dim worker As Worker = New Worker(logger, workerName)
logger.Info("Waiting for a client to connect")
DoBeginAcceptTcpClient(worker, tcpServer)
logger.Info("Connected to {0}.", workerName)
'Add the client to the hashTable
'ADITYA later clients.Add(workerName, client)
If SortAndSendThrd Is Nothing Then
'Start a new thread
SortAndSendThrd = New Thread(SortAndSendThrdStart)
SortAndSendThrd.Priority = ThreadPriority.Highest
End If
If Not SortAndSendThrd.IsAlive Then
SortAndSendThrd.Start()
logger.Debug("Started off a Sort thread")
End If
'Dim i As Integer = 0
'Dim objValue As Object
'For Each objKey In clients.Keys
' objValue = clients.Item(objKey)
' 'MsgBox("[" & objKey.ToString & ", " & objValue.ToString & "]")
'Next objKey
End While
Catch ex As IOException
ToolStripStatusLabel1.Text = "ERROR : SocketException: {0}" + ex.Message
'MsgBox(ex.Message + ":::2")
Catch ex As SocketException
ToolStripStatusLabel1.Text = "ERROR : SocketException: {0}" + ex.Message
'MsgBox(ex.Message + ":::1")
End Try
'tcpServer.Stop()
'client.Close()
logger.Debug("The Server's listening handler has come to an end.")
End Sub
End Class
When I try to connect a second client to this, the server drops the connection 1 and behaves unpredictably.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519560",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Window background color: appears darker than specified? I'm trying to play around with colors in WPF and the form's background color. Without doing ANYTHING ELSE (no code behind, deriving from another class, etc), I create a brand new default Windows Form. I change the background to some light blue color. Save the form. Run the program and open that form.. The form shows up in some other much darker color like it's not even respecting the XAML of
<Window x:Class="MyProjectNamespace.AnotherWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="AnotherWindow" Height="300" Width="300" Background="#4800A8A6">
<Grid>
</Grid>
</Window>
Additionally, if I try to take this same background value of #4800A8A6 and try to create a brush and do a BrushConverter.ConvertFrom( "#4800A8A6" );
and run the form, I STILL get the incorrect color as displayed via the designer... what gives...
A: The first byte of your color code, the '48' is an alpha value, so you're allowing alpha blending on your Window (not a "Windows Form" btw, that's a different technology ;) ), which means the color of your window is going to be blended with the colors of things behind it.
Try changing to: #FF00A8A6, see if that gives you a better result.
A: Your problem is the inclusion of an Alpha channel in the background color (i.e. #AARRGGBB). In the designer you're seeing the background being composited against whatever the background color is in VS (in my case White), which will "lighten" the background in comparison to when you run it as standalone.
To see this for yourself, try Background="#00A8A6", or you could try adding AllowsTransparency="True" (but this has an onerous requirement of WindowStyle.None).
A: That's probably because of the alpha component in your color. If you are trying to make your windows transparent, you have to use AllowsTransparency="True". If you don't, WPF will merge the default windows background color with your windows background.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519561",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: get href value from a website to chrome extension I am making an extension and i want to do the following-
suppose i want my extension to work only on say, xyz.com, which contains the following line-
<a href="xyz.com/abcd" class="abcd">abcd</a>
How do I retrieve href value from xyz.com's code into my extension using javascript?
A: Your question is a little confusing: if you are trying to have your extension loaded whenever a page in the domain xyz.com is opened then you can just set your permissions appropriately and it should work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519563",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to set the google custom search to dispaly the results of search on a paticular page like search.php? I have implemented google custom search engine on my website http://www.finalyearondesk.com/
What I want is that when user enters his query into my own defined search bar, then the results [By result I mean the result that is displayed right after just entering the query and hitting enter, for example "ubuntu"] must be displayed in this page... http://www.finalyearondesk.com/search.php . At now the result are just displayed where I have inserted the code that google has given me.
A: The Google custom search is a JavaScript Ajax widget. The browser talks to Google independent of your site.
If you want results in your search.php page, either put the search-box on the search.php page, or query Google server side, then display the formatted results any way you like. This is very not ideal because Google limits the number of queries you can do.
Long story short, you have to live with the ads and limited placement options google gives you.
You can always attempt to write your own web search engine if you don't like it [/sarcasm]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519565",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How should I allow others to dynamically find web services? I have been fighting with this for a while now. I need to prototype SOA, and with it, the registry. I have been fiddling with jUDDIv3 on JBoss SOA Platform 5, but there don't appear to be any tools that allow me to publish to a v3 jUDDI registry. See my related questions here and here.
I realize after reading comments on those questions, and some articles on the internet (like this one) that UDDI is failing or dead, however my organization has some legacy tech we need to work with.
Also, my supervisor (I'm an intern) is adamant about sticking to standards. In principle, I agree with this, but perhaps a dead standard really isn't a much of a standard if nobody uses it.
In short, I need to provide the registry component of Service Oriented Architecture. It probably needs to be UDDI, so that it fits with the legacy tech, and satisfies the standard. Whatever the solution, it would be best if there were tools available that allow me to publish web services to that registry.
This problem has dragged on much longer than I would have liked. Any small piece of advice is really appreciated.
A: You may use WS-Discovery. WS-Discovery is a standard protocol for discovering services and service endpoints. This enables service clients to search for services based on a given criteria and bind with the discovered services. There are tow modes of WS-Discovery,
ad-hoc - servers advertise the services they have using a UDP multicast protocol
managed mode - servers and clients use an intermediary known as the discovery proxy for all service discovery purposes.
You can simply try this out with WSO2 Platform (free and open source under apache2 license). Please follow [1] to see a simple scenario of WS-Discovery in managed mode.
[1] http://charithaka.blogspot.com/2010/04/ws-discovery-with-wso2-carbon.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519566",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jQuery Greater than non-selector? I am trying to figure out how to use greater than in jQuery without a selector ?
$('.myClass').gt(2).css('width','100px');
My problem is that I am using this in a for statement and I can't use the selector :gt().
So how would I do this ?
A: Use the slice method:
myItems.slice(2).css('width', '100px');
A: I think you're looking for the slice method, which behaves as you would expect:
$('.myClass').slice(2).css('width','100px'); // get the third elements and all subsequent elements and change their styles
This has the added advantage of being able to specify a range, rather than just a start point:
$('.myClass').slice(2, 5).css('width', '100px'); // select elements 2 through to 5
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519571",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Twitter image sharing How to share images in twitter using php? I know its using image upload api of twitter. But i have no idea how to implement this ? Please help to find a solution.Thanks in advance.
A: Here's the Doc on twitter image sharing .
https://dev.twitter.com/docs/api/1/post/statuses/update_with_media
Here's the only PHP library that supports twitter image uploads.
https://github.com/themattharris/tmhOAuth
And Here's a working example of image sharing. With a couple edits your set.
<?php
if ($_POST['message'] && $_FILES['image']['tmp_name'])
{
require 'tmhOAuth.php';
list($oauth_token, $oauth_token_secret) = explode('|', $GLOBALS['user']['password']);
$tmhOAuth = new tmhOAuth(array(
'consumer_key' => OAUTH_CONSUMER_KEY,
'consumer_secret' => OAUTH_CONSUMER_SECRET,
'user_token' => $oauth_token,
'user_secret' => $oauth_token_secret,
));
$image = "{$_FILES['image']['tmp_name']};type={$_FILES['image']['type']};filename={$_FILES['image']['name']}";
$code = $tmhOAuth->request('POST', 'https://upload.twitter.com/1/statuses/update_with_media.json',
array(
'media[]' => "@{$image}",
'status' => " " . $status //A space is needed because twitter b0rks if first char is an @
),
true, // use auth
true // multipart
);
if ($code == 200) {
$json = json_decode($tmhOAuth->response['response']);
if ($_SERVER['HTTPS'] == "on") {
$image_url = $json->entities->media[0]->media_url_https;
}
else {
$image_url = $json->entities->media[0]->media_url;
}
$text = $json->text;
$content = "<p>Upload success. Image posted to Twitter.</p>
<p><img src=\"" . IMAGE_PROXY_URL . "x50/" . $image_url . "\" alt='' /></p>
<p>". twitter_parse_tags($text) . "</p>";
} else {
$content = "Damn! Something went wrong. Sorry :-("
."<br /> code=" . $code
."<br /> status=" . $status
."<br /> image=" . $image
."<br /> response=<pre>"
. print_r($tmhOAuth->response['response'], TRUE)
. "</pre><br /> info=<pre>"
. print_r($tmhOAuth->response['info'], TRUE)
. "</pre><br /> code=<pre>"
. print_r($tmhOAuth->response['code'], TRUE) . "</pre>";
}
} ?>
A: https://dev.twitter.com/docs/api/1/post/statuses/update_with_media
Above link has all the necessary information I believe.
A: There is one other library (it is forked) that can be used for image upload, see: TwitterOauth
*
*Download: Oauth File
*Use code:
$path = '/absolute/path/to/background.jpg';
$meta = getimagesize($path);
$raw['image'] = $path.';type='.$meta['mime'];
$param['tile'] = 'true';
$status = $connection->post('account/update_profile_background_image',$param,$raw);
A: Initially I got the same error when I simply provided the path of media file. Actually you need to provide the byte read. So set your media parameter as follows and it will work:
$filename = "image.jpg";
$handle = fopen($filename, "rb");
$image = fread($handle, filesize($filename));
fclose($handle);
$params = array('media[]' => "{$image};type=image/jpeg;filename={$filename}" ,
'status' => 'my status');
$response =$twitteroauth->post('statuses/update_with_media', $params,true,true);
You can visit this link for complete reference http://net.tutsplus.com/tutorials/php/how-to-authenticate-users-with-twitter-oauth/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519572",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails 3 - URL Helpers With Scoped Resource I have a scoped resource in my routes file:
scope :module => "physical" do
resources :mymodels
end
Using '> rake routes' I get the standard routes, including:
mymodel GET /mymodels/:id(.:format) {:action=>"show", :controller=>"physical/mymodels"}
However when I use the console (and this is what's failing in my tests) to get the url for instances of Mymodel I get errors:
> m = Physical::Mymodel.new
> => {...model_attributes...}
> m.save
> => true
> app.url_for(m)
> NoMethodError: undefined method `physical_mymodel_url' for #<ActionDispatch::Integration::Session:0x00000105b15228>
from /usr/local/lib/ruby/gems/1.9.1/gems/actionpack-3.0.7/lib/action_dispatch/testing/assertions/routing.rb:175:in `method_missing'
from /usr/local/lib/ruby/gems/1.9.1/gems/actionpack-3.0.7/lib/action_dispatch/routing/polymorphic_routes.rb:114:in `polymorphic_url'
from /usr/local/lib/ruby/gems/1.9.1/gems/actionpack-3.0.7/lib/action_dispatch/routing/url_for.rb:133:in `url_for'
from (irb):13
from /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.7/lib/rails/commands/console.rb:44:in `start'
from /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.7/lib/rails/commands/console.rb:8:in `start'
from /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.7/lib/rails/commands.rb:23:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
This might be a gotcha, but Mymodel is also a subclass using the standard Rails single table inheritance.
Any thoughts? Why is it looking for physical_mymodel_url instead of mymodel_url? Any ideas for workarounds so that I can still use the unprefixed routes?
A: You're only using the scope to tell it the module where the controller can be found in. If you want to use the physical prefix on your routes then you could do this:
scope :module => "physical", :as => "physical" do
resources :mymodel
end
Alternatively, you could just use the namespace method which will do the same thing:
namespace :physical do
resources :mymodel
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519573",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to Clip Text in a TTreeview (Continued) I have taken the advice, or at least I think I have, that I got in my previous question.
To summarize, I replaced the THTMLTreeList from TMS with a TTreeList and made two columns in it. I set the first column to 150 pixels and I overrode the AdvancedCustomDrawItem event with this code:
procedure TForm1.trXMLAdvancedCustomDrawItem(Sender: TCustomTreeView;
Node: TTreeNode; State: TCustomDrawState; Stage: TCustomDrawStage;
var PaintImages, DefaultDraw: Boolean);
var hContext: HDC;
s: PChar;
iLength: Integer;
uRect: TRect;
begin
DefaultDraw := False;
hContext := trXML.Canvas.Handle;
s := PChar(Node.Text);
iLength := Length(Node.Text);
uRect := Node.DisplayRect(True);
DrawText(hContext, s, iLength, uRect, DT_END_ELLIPSIS);
end;
I got the result I expected, that is, when I draw the tree, the text in the first column is clipped. And when I change the size of the first column, the text is appropriately clipped. But when the TreeList is not wide enough and has a scroll bar on the bottom and I scroll to the right, the text now extends into the second column by the same amount as the scroll bar has been moved. It's like the text is drawn relative to the client area of the TreeList rather than the partially hidden first column so it always extends 150 pixels into the TreeList.
It seems to me that I am using the wrong thing for the device context handle or the TRect but I do very little graphic type programming so I don't know what to change. Any help would be appreciated.
A: I just checked TMS's source code and
TTreeList already uses the DT_END_ELLIPSIS flag
and does per-column clipping of drawn text when the DefaultDraw parameter is set to True, so you don't need to draw the text yourself manually.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519578",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Output caching _ViewStart.cshtml and _Layout.cshtml in MVC 3 I am trying to cache the MVC 3 _ViewStart and _Layout pages, am I right in thinking these are not cached by default? The problem is the VS bult in web server or IIS should be caching my images in these site master pages but it seems to be loading them everytime.
I can put OutputCache attributes on controller but I can't on these pages above as they have no controllers. Is it possible?
A: _ViewStart and _Layout are only composing elements of the final markup. So by using the [OutputCache] attribute on some controller action you are caching the entire generated HTML from this action, including the view, and you are in fact caching those elements as well.
Unfortunately ASP.NET MVC 3 doesn't support Donut Caching. It supports only Donut Hole Caching. I guess this is something that is going to be improved and added support to in future versions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Continuously Auto-Scrolling ListView I have a Listview in Android. I want that the Listview continuously scrolls from top to bottom by itself. It should happen infinitely
And obviously I want to capture the click on any of the items of the Listview, post that the scroll will continue
Anybody having experience with such an implementation. Please help !!
A: http://groups.google.com/group/android-developers/msg/753a317a8a0adf03
To scroll automatically, you can use this: listView.smoothScrollToPosition(position);
private void scrollMyListViewToBottom() {
myListView.post(new Runnable() {
@Override
public void run() {
// Select the last row so it will scroll into view...
listView.smoothScrollToPosition(myListAdapter.getCount() - 1);
// Just add something to scroll to the top ;-)
}
});
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519597",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Acts_as_taggable_on fails in rails 3.1 I am using acts_as_taggable_on on my rails 3.1 app. This is my model
class User < ActiveRecord::Base
acts_as_taggable_on :skills
end
I get this error the moment I try anything with the user object.
NoMethodError: undefined method `acts_as_taggable_on' for #<Class:0x90bfd84>
I even tried just using acts_as_taggable but didnt work. Am i doing anything wrong or is this a known issue?
A: I am using acts_as_taggable_on with rails 3.1 and it works ok. I am using acts_as_taggable 2.1.1
I defined acts_as_taggable in model I want to tag (ie Books) and acts_as_tagger in model that acts as tagger (ie User).
Gem documentation may be confusing because it tags users in the examples. ¿Do you want to tag users or another thing?
Did you make Post Installation steps?
rails generate acts_as_taggable_on:migration
rake db:migrate
In my case looking to table in database used by acts_as_taggable_on was helpful
https://github.com/mbleigh/acts-as-taggable-on/blob/master/generators/acts_as_taggable_on_migration/templates/migration.rb
Hope this helps
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519599",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Rhino Mock List constraint I'm trying to asssert that a method was called on a stub. The method I'm trying to assert was called takes an IEnumerable<string>. I don't care about the exact contents, but I just want to test that the count is a certain number. I can't get the assertion correct, I get
Rhino.Mocks.Exceptions.ExpectationViolationException : Bob.DoThings(collection count equal to 10); Expected #1, Actual #0.
I know that DoThings() is indeed being called... I just can't get the constraint correct..
var myBob= MockRepository.GenerateStub<Bob>();
var countConstraint = Rhino.Mocks.Constraints.List.Count(Rhino.Mocks.Constraints.Is.Equal(10));
// execution code....
Joe myJoe = new Joe(myBob);
myJoe.MethodThatShouldCallDoThingWith10();
myBob.AssertWasCalled(s => s.DoThings(null), o => Constraints(countConstraint));
I've also tried adding "IgnoreArguments" as a constraint. What am I missing?
A: This problem was alredy reported Here. I've been able to reproduce this problem with the following Bob and Joe:
public interface Bob
{ void DoThings(IEnumrable<int> list); }
public class Joe
{
private readonly Bob bob;
public Joe(Bob bob)
{ this.bob = bob; }
public void MethodThatShouldCallDoThingWith10()
{
var values = Enumerable.Range(1, 100).Where(x => x > 0 && x < 11);
bob.DoThings(values);
}
}
It seems there's some problem in Rhino Mocks after all, when it comes to LINQ: either report the bug to Ayende or add ToList() in your production code (not really recommended)...
A: The issue here is with deferred execution. It's not until the IEnumerable<string> is enumerated that the list of items is "built". Since Rhino.Mocks just records what gets called, it never "uses" the method arguments and therefore, the list is never built nor enumerated. As you've seen, adding a ToList() or ToArray() enumerates and builds the list so the test will pass if you use one of those methods.
One workaround is to grab the list that was passed to the method and do your check on that:
var list = (IEnumerable<int>) myBob.GetArgumentsForCallsMadeOn(b => b.DoThings(null))[0][0];
Assert.AreEqual(10, list.Count());
This test passes and doesn't require any changes to your code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Get the client id of the message sender in socket.io? on the server side i got
socket.on('chat', function (data) {
io.sockets.socket(data.clientid).emit('chat', {
msg: data.msg,
senderid : senderid
});
});
How can I get the get the senderid without the sender having to post their clientid through with the message?
A: It turns out I can just use socket.id of the user sending through a msg to get their clientid, such as:
socket.on('chat', function (data) {
io.sockets.socket(data.clientid).emit('chat', {
msg: data.msg,
senderid : socket.id
});
});
Originally I thought I could just fetch the clientid by doing :
io.sockets.on('connection', function (socket) {
clientid = socket.id;
But clientid will be the last person who connected in this instance, not the last person who sent through a chat
A: I'd suggest sending over a username (make sure it's unique) and keeping an object of client ids associated with usernames in memory.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Display XML content in HTML page How to display XML and other type of data in same page ?
<?xml version="1.0" encoding="ISO-8859-1"?>
<catalog>
<cd>
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<country>USA</country>
<country>Columbia</country>
<price>10.90</price>
<year>1985</year>
</cd>
</catalog>
The above XML should be displayed as it is with formatting. Also , I would like to display HTML tables and other stuff in my page. How to achieve this ?
*
*I do get XML in STRING not through file.
*I do not want to parse it
*I want to display (that's it)
*If you say about XSLT ( please give example )
*I'm thinking to use Jquery plugin ( any examples?)
A: You can use the old <xmp> tag. I don't know about browser support, but it should still work.
<HTML>
your code/tables
<xmp>
<catalog>
<cd>
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<country>USA</country>
<country>Columbia</country>
<price>10.90</price>
<year>1985</year>
</cd>
</catalog>
</xmp>
Output:
your code/tables
<catalog>
<cd>
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<country>USA</country>
<country>Columbia</country>
<price>10.90</price>
<year>1985</year>
</cd>
</catalog>
A: <pre lang="xml" >{{xmlString}}</pre>
This worked for me.
Thanks to http://www.codeproject.com/Answers/998872/Display-XML-in-HTML-Div#answer1
A: If you treat the content as text, not HTML, then DOM operations should cause the data to be properly encoded. Here's how you'd do it in jQuery:
$('#container').text(xmlString);
Here's how you'd do it with standard DOM methods:
document.getElementById('container')
.appendChild(document.createTextNode(xmlString));
If you're placing the XML inside of HTML through server-side scripting, there are bound to be encoding functions to allow you to do that (if you add what your server-side technology is, we can give you specific examples of how you'd do it).
A: Simple solution is to embed inside of a <textarea> element, which will preserve both the formatting and the angle brackets. I have also removed the border with style="border:none;" which makes the textarea invisible.
Here is a sample: http://jsfiddle.net/y9fqf/1/
A: 2017 Update I guess. textarea worked fine for me using Spring, Bootstrap and a bunch of other things. Got the SOAP payload stored in a DB, read by Spring and push via Spring-MVC. xmp didn't work at all.
A: A simple solution for displaying XML data on an HTML page is that:
go the this website
Paste your code and generate the XML code which you can use in pre-tag in HTML to display.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "69"
} |
Q: WHERE - IS NULL not working in SQLite? Here's a strange one:
I can filter on NOT NULLS from SQLite, but not NULLS:
This works:
SELECT * FROM project WHERE parent_id NOT NULL;
These don't:
SELECT * FROM project WHERE parent_id IS NULL;
SELECT * FROM project WHERE parent_id ISNULL;
SELECT * FROM project WHERE parent_id NULL;
All return:
There is a problem with the syntax of your query (Query was not
executed) ...
UPDATE:
I am doing this with PHP- through my code with ezSQl and using the PHPLiteAdmin interface
Using the PHPLiteAdmin demo, this expression works- so now I'm suspecting a version issue with my PHP's SQLite? Could that be? Wasn't this expression always valid?
UPDATE 2:
When I run the code from PHP using ezSQL, the PHP warning is:
PHP Warning: SQL logic error or missing database
Is there a way to get more information out of PHP? This is maddeningly opaque and weird, especially because the same statement in the CLI works fine...
UPDATE 3
The only other possible clue I have is that the databases that I create with PHP cannot be read by the CLI, and vice versa. I get:
Error: file is encrypted or is not a database
So there's definitly two SQlite flavors butting heads here. (See this) Still, why the invalid statment??
UPDATE 4
OK I think I've traced the problem to the culprit, if not the reason- The DB I created with PHP ezSQL is the one where the IS NULL statement fails. If I create the DB using PHP's SQLite3 class, the statement works fine, and moreover, I can access the DB from the CLI, whereas ezSQL created DB gave the file is encrypted error.
So I did a little digging into ezSQL code- Off the bat I see it uses PDO methods, not the newer SQLite3 class. Maybe that's something- I'm not gonna waste further time on it...
In any case, I've found my solution, which is to steer clear of ezSQL, and just use PHPs SQLite3 class.
A: The problem could stem from how SQLite handles empty columns. For instance just because a column is empty does not mean it is NULL. Have you tested against ""?
SELECT * FROM project WHERE parent_id = ""
That query might return results.
A: In Android SQLite, field IS NULL doesn't work either.
field = 'null' does. Give it a try in your environment
A: a IS b and a IS NOT b is the general form where a and b are expressions.
This is generally only seen in a IS NULL and a IS NOT NULL cases. There are also ISNULL and NOTNULL (also NOT NULL) operators which are short-hands for the previous expressions, respectively (they only take in a single operand).
The SQL understood in SQLite expressions is covered in SQLite Query Language: Expressions.
Make sure that (previous) statements have been terminated with a ; first if using the CLI.
These are all valid to negate a "null match":
expr NOT NULL
expr NOTNULL
expr IS NOT NULL
These are all valid to "match null":
expr ISNULL
expr IS NULL
Since all of the above constructs are themselves expressions the negations are also valid (e.g. NOT (expr NOT NULL) is equivalent to expr IS NULL).
Happy coding.
The proof in the pudding:
SQLite version 3.7.7.1 2011-06-28 17:39:05
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> create table x (y int null);
sqlite> select * from x where y isnull;
sqlite> select * from x where y notnull;
sqlite> select * from x where y not null;
sqlite> select * from x where y is null;
sqlite> select * from x where y is not null;
sqlite>
A: This works on SQLite in SQLite Manager for Firefox:
select * from foo where not baz is not null
The query above returns rows where column [baz] is null. :-) Yarin, maybe it will work for you?
(The 'not' before the column name is not a typo).
This query too finds rows where baz is null:
select * from foo where [baz] is null
A: If you are testing perhaps the PK column (?) and the column is being treated as synonym for rowid, then no rows will have a rowid that's null.
A: try where your_col_name ISNULL
wheres ISNULL contains no space
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519621",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "34"
} |
Q: How can I create an Activity that encompasses other Activities? SO. I am starting out in WF4 and I have a design/flow question. I created a custom code activity that takes an "in argument" and stores a result to an "out argument". Pretty basic. Next I use an "If" flow operator using the result of the "out argument". All of that works great. But my question is, can I create a custom code activity that combines these two steps together? I looked into extending from the System.Activities.Statements.If class, but the class is sealed. Any suggestions?
Thanks.
A: It looks like Custom Control Flow. You may find Authoring Custom Control Flow Activities in WF 4 article to be useful.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519622",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Iterating over javascript object and valueOf toString methods var x = {
article: "bla bla bla ",
journal: "le monde ",
magazine: "playboy"
};
for (var i in x) {
alert(i + " "+ x[i]);
}
Every JS object has a valueOf and a toString method. Why can't I see them when I iterate over the properties of the x object?
A: The engine specifically hides these methods from enumeration.
The purpose of this is to allow to iterate over Object properties without being annoyed by the object's prototypal properties. This way you can iterate over Array indices, use Objects as hash tables and iterate over its properties.
This can however be easily broken. For example if you use a custom method in Object.property, it will suddenly appear during the enumeration of all objects' properties:
var obj = { foo: 0 };
Object.prototype.bar = 1;
// prints 'foo' and 'bar'
for (var k in obj) {
console.log(k);
}
This is makes it dangerous to extend Object.prototype.
You can test if a property comes from the object itself or it's prototype by using the Object.hasOwnProperty method:
// prints 'foo'
for (var k in obj) {
if (!obj.hasOwnProperty(a)) continue;
console.log(k);
}
Alternatively, you could use Object.defineProperty do define non-enumerable properties, if you don't care of old browsers:
Object.defineProperty(Object.prototype, 'bar', {value: 1, enumerable: false});
// prints 'foo'
for (var k in obj) {
console.log(k);
}
A: They are not enumerable properties. Try Object.getOwnPropertyNames. Only works in some browsers:
This DOESNT check proto though, so you need to do something very complicated:
var x, y, z, getAllKeys;
getAllKeys = function (obj,ar) {
ar = ar || [new Array];
ar[0] = ar[0].concat(Object.getOwnPropertyNames(obj));
if (obj !== Function.prototype && Object.getPrototypeOf(obj)) {
getAllKeys(Object.getPrototypeOf(obj),ar);
}
return ar[0];
}
console.log (getAllKeys(new Array));
for (x in y = getAllKeys(z = new Array)) {
var key = y[x];
var value = z[y[x]];
}
Blame JavaScript for being ridiculous and looking like assembly, maybe jASM would be a better name? (joke)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519624",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: PHP/MySQL: Handling Questionnaire Input I have a questionnaire for users to be matched by similar interests: 40 categories, each with 3 to 10 subcategories. Each of the subcategories has a 0 - 5 value related to how interested they are in that subcategory (0 being not even remotely interested, 5 being a die-hard fan). Let's take an example for a category, sports:
<input type="radio" name="int_sports_football" value="0">0</input>
<input type="radio" name="int_sports_football" value="1">1</input>
<input type="radio" name="int_sports_football" value="2">2</input>
<input type="radio" name="int_sports_football" value="3">3</input>
<input type="radio" name="int_sports_football" value="4">4</input>
<input type="radio" name="int_sports_football" value="5">5</input>
With so many of these, I have a table with the interest categories, but due to the size, have been using CSV format for the subcategory values (Bad practice for numerous reasons, I know).
Right now, I don't have the resources to create an entire database devoted to interests, and having 40 tables of data in the profiles database is messy. I've been pulling the CSV out (Which looks like 0,2,4,1,5,1), exploding them, and using the numbers as I desire, which seems really inefficient.
If it were simply yes/no I could see doing bit masking (which I do in another spot – maybe there's a way to make this work with 6-ary values? ). Is there another way to store this sort of categorized data efficiently?
A: You do not do this by adding an extra field per question to the user table, but rather you create a table of answers where each answer record stores a unique identifier for the user record. You can then query the two tables together using joins in order to isolate only those answers for a specific user. In addition, you want to create a questions table so you can link the answer to a specific question.
table 1) user: (uniqueID, identifying info)
table 2) answers: (uniqueID, userID, questionID, text) links to unique userID and unique questionID
table 3) question: (uniqueID, subcategoryID, text) links to uniqueID of a subcategory (e.g. football)
table 4) subcategories: (uniqueID, maincategoyID, text) links to uniqueID of a mainCategory (e.g sports)
table 5) maincategories: (uniqueID,text)
An individual user has one user record, but MANY answer records. As the user answers a question, a new record is created in the answers table, storing the uniqueID of the user, the uniqueID of the question, and the value of their answer.
An answer record is linked to a single user record (by referencing the user's uniqueID field) and a single question record (via uniqueID of question).
A question record is linked to a single subcategory record.
A subcategory record is linked to a single category record.
Note this scheme only handles two levels of categories: sports->football. If you have 3 levels, then add another level in the same manner. If your levels are arbitrary, there may be some other scheme more suited.
A: okay, so, given that you have 40 categories and let's assume 10 subcategories, that leaves us with 400 question-answer pairs per user.
now, in order to design the best intermediary data storage, I would suggest starting out with a few questions:
1) what type of analysis will I need
2) what resources do I have
3) is this one time solution or should it be reused in future
Well, if I were you, I would stick to very simple database structure e.g.:
question_id | user_id | answer
if I would foresee more this kind of polls going on with same questions and probably having same respondents, I would further extend the structure with "campaign_id". This would work as raw data storage which would allow quick and easy statistics of any kind.
now, you said database is no option. well, you can mimic this very same structure using arrays and create your own statistical interface that would work based on the array storage type, BUT, you would save their and your time if you could get sql. as others suggest, there is always sqlite (file based database engine), which, is easy to use and setup.
now, if all that does not make you happy, then there is another interesting approach. if data set is fixed, meaning, that there are pretty much no conditional questions, then, given that you could create question index, you could further create funny 400byte answer chunk, where each byte would represent answer in any of the given values. then what you do is you create your statistical methods that, based on the question id, can easily operate with $answer[$user][$nth] byte (or $answer[$nth][$user] -- again, based on the type of statistics you need)
this should help you get your mind set on the goal you want to achieve.
A: I know you said you don't have the resources to create a database, but I disagree. Using SQL seems like your best bet and PHP includes SQLite (http://us2.php.net/manual/en/book.sqlite.php) which means you wouldn't need to set up a MySQL database if that were a problem.
There are also tools for both MySQL and SQLite which would allow you to create tables and import your data from the CSV files without any effort.
A: maybe I am confused but it seems like you need a well designed relational database.
for example:
tblCategories (pkCategoryID, fldCategoryName)
tblSubCategory (pkSubCategoryID, fkdSubCategoryName)
tblCategorySubCategory(fkCategoryID,fkSubCategoryID)
then use inner joins to populate the pages. hopefully this helps you :)
A: i consider NoSQL architecture as a solution to scaling MySQL field in agile solutions.
To get it done asap, I'd create a class for "interest" category that constructs sub-categories instance which extends from category parent class, carrying properties of answers, which would be stored as a JSON object in that field, example:
{
"music": { // category
"instruments": { // sub category
"guitar": 5, //intrest answers
"piano": 2,
"violin": 0,
"drums": 4
},
"fav artist":{
"lady gaga": 1,
"kate perry": 2,
"Joe satriani": 5
}
}
"sports": {
"fav sport":{
"soccer": 5,
"hockey": 2,
}
"fav player":{
"messi": 5,
"Jordan": 5,
}
}
}
NOTE that you need to use "abstraction" for the "category" class to keep the object architecture right
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519632",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Creating custom magento webservices I'm having some trouble creating some custom web services in Magento. I'm trying to get the module configured properly and I can't seem to make the web services I've defined in the api.xml file show up under the user role setup in the admin area.
I've defined a custom module in app/etc shown here
ctp_GiftCards.xml:
<?xml version="1.0"?>
<config>
<modules>
<ctp_GiftCards>
<active>true</active>
<codePool>local</codePool>
</ctp_GiftCards>
</modules>
</config>
The module code is located in app/local/ctp/GiftCards/
Here is an example of the etc/api.xml:
<?xml version="1.0"?>
<config>
<api>
<resources>
<GiftCards translate="title" module="ctp_GiftCards">
<title>GiftCard webservices</title>
<acl>GiftCards/GiftCard</acl>
<methods>
<update translate="title" module="ctp_GiftCards">
<title>updates a giftcard account</title>
</update>
</methods>
<faults module="ctp_GiftCards">
<invalid_data>
<code>100</code>
<message>giftcard data invalid</message>
</invalid_data>
<card_pool_error>
<code>101</code>
<message>card pool for entry not updated</message>
</card_pool_error>
<cache_error>
<code>102</code>
<message>cache not reset</message>
</cache_error>
</faults>
</GiftCards>
</resources>
<acl>
<resources>
<GiftCards translate="title" module="ctp_GiftCards">
<title>GiftCards</title>
<sort_order>6</sort_order>
<GiftCard translate="title" module="ctp_GiftCards">
<title>GiftCard</title>
<update translate="title" module="ctp_GiftCards">
<title>Update</title>
</update>
</GiftCard>
</GiftCards>
</resources>
</acl>
</api>
</config>
and the etc/config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<config>
<modules>
<ctp_GiftCards>
<version>0.1.0</version>
</ctp_GiftCards>
</modules>
<global>
<models>
<GiftCard>
<class>CTP_GiftCards_Model</class>
</GiftCard>
</models>
</global>
</config>
Any help would be much appreciated.
--edit--
I'm using mangeto pro 1.10
A: Don't use capital letter (GiftCards) in the name of xml tag inside the node. Moreover, your module's name contains both underscope (_) and capital letter (ctp_GiftCards) which will lead Magento to misunderstand.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519633",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Javascript - seeing all javascript loaded Suppose I have a line like this on a HTML page:
<script src="/script/myscript.js" type="text/javascript"></script>
and suppose the server is not allowing me to load myscript.js directly from the browser.
Is there a way to see the javascript code inside this script from within the browser?
thanks.
A: If Firefox, VIEW SOURCE, then click on the .js file you see highlighted in the page.
A: Tools/Developer Tools in Chrome. Select the Scripts tab.
Firebug in Firefox (this is an extension you have to add).
F12 or Tools/Developer Tools in Internet Explorer.
A: You can use the Web Developer tools in Chrome/FF to view the contents of scripts that are loaded for the current page.
A: just type it in your address bar http://example.com/script/myscript.js (of course replacing example.com with whatever the rest of the path is).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: add html value when creating sharepoint list instance I have created a Sharepoint list definition, and an instance of that definition. In the instance I need to store some HTML as the value of a field in my list instance. I know I can do this through the UI, but I need this list created on deployment. When I wrap my HTML value in CDATA tags, the item is simply not created. I get a deployment error if I Just have my HTML inline with my XML.
Elements.xml:
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<ListInstance Title="ListName"
OnQuickLaunch="TRUE"
TemplateType="10051"
Url="Lists/ListName"
Description="List Description">
<Data>
<Rows>
<Row>
<Field Name="Title">My Title</Field>
<Field Name="Value">
<p>Some HTML HERE</p>
<table border="1"; cellpadding="10";>
<tr style="font-family:Arial; font-size:10pt;">
<th>header1</th>
<th> ... </th>
</tr>
<tr style="font-family:Arial; font-size:8pt;">
<td>Vaue1</td>
<td> ... </td>
</tr>
</table>
</Field>
</Row>
</Rows>
</Data>
</ListInstance>
</Elements>
Any help would be appreciated.
A: You need to HTML encode the value:
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<ListInstance Title="ListName"
OnQuickLaunch="TRUE"
TemplateType="10051"
Url="Lists/ListName"
Description="List Description">
<Data>
<Rows>
<Row>
<Field Name="Title">My Title</Field>
<Field Name="Value">
<p>Some HTML HERE</p>
<table border="1"; cellpadding="10";>
<tr style="font-family:Arial; font-size:10pt;">
<th>header1</th>
<th> ... </th>
</tr>
<tr style="font-family:Arial; font-size:8pt;">
<td>Vaue1</td>
<td> ... </td>
</tr>
</table>
</Field>
</Row>
</Rows>
</Data>
</ListInstance>
</Elements>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Create a CSV from Text File useing Linux Console I have a text file that looks like this:
line1
line2
line3
line4
line5
"" "" keep going for a long time
I'm trying to come up with a script that would give me:
line1,line2,line3,line4,line5
line6,line7,line8,line9,line10
So comma separate them all and add a newline every 5.
Any ideas?
A: paste -d, - - - - - < filename
man page
A: A bit rough but workable w/out resorting to the, perhaps more pleasing, perl solution. The -n 5 arg to xargs makes it just send 5 arguments to the shell script, which we print.
$ cat echo.sh
echo $1,$2,$3,$4,$5
$ $ cat file.txt
a
b
c
d
e
1
2
3
4
5
$ cat file | xargs -n 5 ./echo.sh
a,b,c,d,e
1,2,3,4,5
$
A: cat foo.txt | xargs -L 5 | tr ' ' ','
The plus side here is that you can also modify the '5' arguments to an arbitrary value and the script works as expected.
A: If you have perl, try this:
perl -ane '++$i; chomp; $line.=$_; if($i==5) {print "$line\n"; $line=""; $i=0;} else {$line.=","} ' <infile >outfile
A: Python is installed by default on every linux distro these days.
I'd suggest the following python script:
#!/usr/bin/env python
import argparse, csv
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='convert text to csv', version='%(prog)s 1.0')
parser.add_argument('infile', nargs='+', type=str, help='list of input files')
parser.add_argument('--out', type=str, default='temp.csv', help='name of output file')
args = parser.parse_args()
writer = csv.DictWriter(open(args.out, "wb"), ["field 1","field 2","field 3","field 4","field 5"], dialect='excel')
# write the header at the top of the file
writer.writeheader()
row = []
for fname in args.infile:
with open(fname) as df:
for line in df.readlines():
row.append(line.strip('\n'))
if len(row) = 5:
writer.writerow(row)
row = []
del writer
You should be able to copy the code into a file and run it right off the command line. For instance: text2csv.py yourinput.txt if, of course, you called the file text2csv.py.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519660",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Unable to cast object of type 'ASP.Default_aspx' to type 'BasePage' public partial class Default : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
BasePage page = (BasePage)this.Page;
In my Default.aspx:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Default.ascx.cs" Inherits="Default" %>
It complains about this code: BasePage page = (BasePage)this.Page;
Any ideas on how I can fix this error?
Edit:
Basepage definition:
public class BasePage : Page
A: Does your ASP.Default.aspx.cs inherit from the BasePage?
The page which this control is rendered in must inherit from BasePage class, not Web.Ui.Page class.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is passing an unexecuted IEnumerable as a parameter bad practice? Looking through some of our business logic code I've found where some methods are being passed an un-executed IEnumerables as a parameters such as this:
GetDetails(IEnumerable <Entity> item) { // do something with the item }
Now the code works fine as is, but what I'm seeing when I'm in debug is that the parameter is passing a raw query, not a collection of anything. To me this seems a little wrong since you could be hitting the database every time that this IEnumberable is used if the query is pointed at a database.
So what i'm asking, is passing an un-executed IEnumerable as a parameter to a method bad practice?
After more investigation
I've read around more on stackoverflow, and found this particular question where Eric Lippert says:
Remember, a query expression gives you an object which represents the query itself. The object does not represent the RESULTS of the query, the object represents a query. Think of it as a SQL query string, only smarter. You ask the query for its results, and the query executes. You ask it again, the query executes again; no guarantees that the results are the same the second time you ask; the world might have changed since then
To me, this seems to say that if you're going ot use a defered query such as an IEnumberable, to be careful where you use it, and when you use as you might not get the results which are expected. But further into the answers I see that Bevan says he personally does this:
Parameters to methods - use IEnumerable unless there's a need for a more specific interface.
So my question still stands, is passing an un-executed IEnumerable as a parameter to a method bad practice or should I not care about the when the data is requested, just that it is requested.
A: Once the data leaves the business logic layer, it should IMHO be a hard collection that is no longer connected to the database. Passing a collection between methods in the Business Logic should be ok because you may want to add criteria/filtering to your query without loading the entire data set from the database.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519662",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Nibble shifting I was working on an encryption algorithm and I wonder how I can change the following code into something simpler and how to reverse this code.
typedef struct
{
unsigned low : 4;
unsigned high : 4;
} nibles;
static void crypt_enc(char *data, int size)
{
char last = 0;
//...
// Pass 2
for (i = 0; i < size; i++)
{
nibles *n = (nibles *)&data[i];
n->low = last;
last = n->high;
n->high = n->low;
}
((nibles *)&data[0])->low = last;
}
data is the input and the output for this code.
A: You are setting both nibbles of every byte to the same thing, because you set the high nibble to the same as the low nibble in the end. I'll assume this is a bug and that your intention was to shift all the nibbles in the data, carrying from one byte to the other, and rolling around. Id est, ABCDEF (nibbles order from low to high) would become FABCDE. Please correct me if I got that wrong.
The code should be something like:
static void crypt_enc(char *data, int size)
{
char last = 0;
//...
// Pass 2
for (i = 0; i < size; i++)
{
nibles *n = (nibles *)&data[i];
unsigned char old_low = n->low;
n->low = last;
last = n->high;
n->high = old_low;
}
((nibles *)&data[0])->low = last;
}
Is everything okay now? No. The cast to nibbles* is only well-defined if the alignment of nibbles is not stricter than the alignment of char. And that is not guaranteed (however, with a small change, GCC generates a type with the same alignment).
Personally, I'd avoid this issue altogether. Here's how I'd do it:
void set_low_nibble(char& c, unsigned char nibble) {
// assumes nibble has no bits set in the four higher bits)
unsigned char& b = reinterpret_cast<unsigned char&>(c);
b = (b & 0xF0) | nibble;
}
void set_high_nibble(char& c, unsigned char nibble) {
unsigned char& b = reinterpret_cast<unsigned char&>(c);
b = (b & 0x0F) | (nibble << 4);
}
unsigned char get_low_nibble(unsigned char c) {
return c & 0x0F;
}
unsigned char get_high_nibble(unsigned char c) {
return (c & 0xF0) >> 4;
}
static void crypt_enc(char *data, int size)
{
char last;
//...
// Pass 2
for (i = 0; i < size; ++i)
{
unsigned char old_low = get_low_nibble(data[i]);
set_low_nibble(data[i], last);
last = get_high_nibble(data[i]);
set_high_nibble(data[i], old_low);
}
set_low_nibble(data[0], last);
}
Doing the reverse amounts to changing "low" to "high" and vice-versa; rolling to the last nibble, not the first; and going through the data in the opposite direction:
for (i = size-1; i >= 0; --i)
{
unsigned char old_high = get_high_nibble(data[i]);
set_high_nibble(data[i], last);
last = get_low_nibble(data[i]);
set_low_nibble(data[i], old_high);
}
set_high_nibble(data[size-1], last);
If you want you can get rid of all the transfers to the temporary last. You just need to save the last nibble of all, and then shift the nibbles directly without the use of another variable:
last = get_high_nibble(data[size-1]);
for (i = size-1; i > 0; --i) // the last one needs special care
{
set_high_nibble(data[i], get_low_nibble(data[i]));
set_low_nibble(data[i], get_high_nibble(data[i-1]));
}
set_high_nibble(data[0], get_low_nibble(data[0]));
set_low_nibble(data[0], last);
A: It looks like you're just shifting each nibble one place and then taking the low nibble of the last byte and moving it to the beginning. Just do the reverse to decrypt (start at the end of data, move to the beginning)
A: As you are using bit fields, it is very unlikely that there will be a shift style method to move nibbles around. If this shifting is important to you, then I recommend you consider storing them in an unsigned integer of some sort. In that form, bit operations can be performed effectively.
A: Kevin's answer is right in what you are attempting to do. However, you've made an elementary mistake. The end result is that your whole array is filled with zeros instead of rotating nibbles.
To see why that is the case, I'd suggest you first implement a byte rotation ({a, b, c} -> {c, a, b}) the same way - which is by using a loop counter increasing from 0 to array size. See if you can do better by reducing transfers into the variable last.
Once you see how you can do that, you can simply apply the same logic to nibbles ({al:ah, bl:bh, cl:ch} -> {ch:al, ah:bl, bh:cl}). My representation here is incorrect if you think in terms of hex values. The hex value 0xXY is Y:X in my notation. If you think about how you've done the byte rotation, you can figure out how to save only one nibble, and simply transfer nibbles without actually moving them into last.
A: Reversing the code is impossible as the algorithm nukes the first byte entirely and discards the lower half of the rest.
On the first iteration of the for loop, the lower part of the first byte is set to zero.
n->low = last;
It's never saved off anywhere. It's simply gone.
// I think this is what you were trying for
last = ((nibbles *)&data[0])->low;
for (i = 0; i < size-1; i++)
{
nibbles *n = (nibbles *)&data[i];
nibbles *next = (nibbles *)&data[i+1];
n->low = n->high;
n->high = next->low;
}
((nibbles *)&data[size-1])->high = last;
To reverse it:
last = ((nibbles *)&data[size-1])->high;
for (i = size-1; i > 0; i--)
{
nibbles *n = (nibbles *)&data[i];
nibbles *prev = (nibbles *)&data[i-1];
n->high = n->low;
n->low = prev->high;
}
((nibbles *)&data[0])->low = last;
... unless I got high and low backwards.
But anyway, this is NOWHERE near the field of encryption. This is obfuscation at best. Security through obscurity is a terrible terrible practice and home-brew encryption get's people in trouble. If you're playing around, all the more power to you. But if you actually want something to be secure, please for the love of all your bytes use a well known and secure encryption scheme.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519665",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to arrange the data in a Pivot Chart? (stacked column chart) I generated a pivot chart from a pivot table. The chart type is stacked columns. The problem with the pivot is that it generated automatically the order of the stacks and I can't set them in the order I want
Do you know if I can rearrange the stacks order in a Pivot Chart?
I want to do this because I have some other chart type for some data (line) and the lines need to be on the same level with the stacks.
Any idea?
Thanks!
A: The most straight forward way to do this is to rearrange their order in the associated pivot table. You should be able to drag the labels in the table and see the result in the chart.
There is also another way using the sort options within the legend drop down menu. But I've always found dragging items around the chart to be really difficult
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519667",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Using the Drupal commerce module for super simple single page checkout for one item There are a mass of options when it comes to customizing the Drupal commerce module.
What modules do I need to enable for a super simple checkout that looks like this (all on the same page):
*
*Single Item, with a few variations which modify the price (Is this better to do with multiple items? Ultimately I want RULES To publish nodes based on what is purchased.)
*Credit card info / checkout with Paypal
*Checkout
A: The best advice I could give is don't use Commerce just yet, it's not mature enough. The base modules are (I believe) out of beta now but there are so many contributed modules that aren't finished yet or are currently unstable.
Have you come across the Ubercart module by any chance? It is also dependant on and heavily integrated with Rules, and a lot of contributed modules are available.
For your purposes you could use Ubercart to define a single product category to which you add all of your products, and use the attributes module that's included to add differing price options for each. Paypal integration is also built right in.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519672",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cocoa: Accessibility (VoiceOver) for buttons with image only I use NSButton with empty title and image on it, and it cannot be accessed with VoiceOver.
But when I'm setting title (VoiceOver seems to use title), NSButton tries to show it.
I think there should be an easy way to not display title, or to set button text, used by VoiceOver, however quick search didn't give any results yet.
P.S. I'm creating button programmatically.
A: you must assign the accessibilityLabel to the image object directly, It works this way.
A: Solved issue - added subclass for NSButtonCell, which does nothing in drawTitle: method and returns NSZeroRect. Seems to work ok.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519673",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Replacing the getHomeLink in Magento Can I just replace code <?php echo $this->getHomeLink() ?> in the header.phtml file copied below with http://ourdomainname.com?
Since our magento store is linked through navigation within our site, we want to use a link to our main domain in the header INSTEAD of using the store domain name.
Thanks for your help.
<div class="header-top">
<a href="<?php echo $this->getHomeLink() ?>"><img src="<?php echo $this->getSkinUrl($this->__('images/logo.gif')) ?>” alt="<?php echo $this->__('Magento Logo') ?>” class="logo"/></a>
<div class="header-right">
<p class="super">
<?php echo $this->__("Logged in as %s", $this->getUser()->getUsername()) ?><span class="separator">|</span><?php echo $this->formatDate(null, 'full') ?><span class="separator">|</span><a href="<?php echo $this->getLogoutLink() ?>” class="link-logout"><?php echo $this->__('Log Out') ?></a>
</p>
<?php if ( Mage::getSingleton('admin/session')->isAllowed('admin/global_search') ): ?>
<fieldset>
<legend>Search</legend>
<span id="global_search_indicator" class="autocomplete-indicator" style="display: none">
<img src="<?php echo $this->getSkinUrl('images/ajax-loader.gif') ?>” alt="<?php echo $this->__('Loading...') ?>” class="v-middle"/>
</span>
<?php $defSearch = $this->__('Global Record Search') ?>
<input id="global_search" name="query" type="text" class="input-text" value="<?php if(!empty($query)): ?><?php echo $query ?><?php else: ?><?php echo $defSearch ?><?php endif ?>” onfocus="if(this.value==’<?php echo $defSearch ?>’)this.value=’’; “ onblur="if(this.value==’’)this.value=’<?php echo $defSearch ?>’;” />
<div id="global_search_autocomplete" class="autocomplete"></div>
<script type="text/javascript\">
new Ajax.Autocompleter(
‘global_search’,
‘global_search_autocomplete’,
‘<?php echo $this->getUrl('*/index/globalSearch') ?>’,
{
paramName:"query",
minChars:2,
indicator:"global_search_indicator",
updateElement:getSelectionId,
evalJSON:’force’
}
);
function getSelectionId(li) {
location.href = li.getAttribute(’url’);
}
</script>
</fieldset>
<?php endif; ?>
</div>
</div>
A: Of course you can. You can do whatever you want, you just need to live with the consequences of whatever action you take.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519677",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Jquery Selectors based on the Value of Three Drop Down Menus I am working on with three drop-down menus each of which have three options. Together these three drop-down menus create a system that can be in any one of twenty seven states. For each drop-down, there is option 1, option 2, and all (which is the union of option 1 and 2).
Depending on what state these three drop-down menus are in, I want to display or hide different divs. These divs have classes of this form class="distribution-(select-1)-(select-2)-(select-3)"
I am trying to find a DRY way of coding this up without relying on 27 different conditionals.
Here are the drop-down menus:
<div style = "margin-top:1cm; font-size:125%">
<strong>Clickout Type </strong>
<select class = "clickouts" >
<option value = "all" selected="selected">All</option>
<option value = "clickouts" >Clickouts</option>
<option value = "preferred" >Preferred Clickouts</option>
</select>
<strong>Graph Type </strong>
<select class = "graph-type" >
<option value = "all" selected="selected">All</option>
<option value = "hist" >Histograms</option>
<option value = "percent" >Percent</option>
</select>
<strong>Roll-up Type </strong>
<select class = "roll-up" >
<option value = "all" selected="selected">All</option>
<option value = "aggregate" >Aggregate</option>
<option value = "granular" >Granular</option>
</select>
</div>
Here are some examples of the div classes:
distribution-hist-clickouts-aggregate, distribution-percent-clickouts-aggregate, class="distribution-hist-clickouts-granular", distribution-percent-clickouts-granular
Here is the jquery for the first seven states:
$('.clickouts, .graph-type, .roll-up').change(function(){
var graph_type = $('.graph-type').val();
var roll_up = $('.roll-up').val();
var clickouts = $('.clickouts').val();
if (graph_type == 'all' & roll_up == 'all' & clickouts == 'all'){
$('div[class*="distribution"]').css('display', 'block');
}
if (graph_type == 'all' & roll_up == 'all' & clickouts == 'clickouts'){
$('div[class*="clickout"]').css('display', 'block');
$('div[class*="preferred"]').css('display', 'none');
}
else if (graph_type == 'all' & roll_up == 'all' & clickouts == 'preferred'){
$('div[class*="clickout"]').css('display', 'none');
$('div[class*="preferred"]').css('display', 'block');
}
else if (graph_type == 'hist' & roll_up == 'all' & clickouts == 'all'){
$('div[class*="hist"]').css('display', 'block');
$('div[class*="percent"]').css('display', 'none');
}
else if (graph_type == 'percent' & roll_up == 'all' & clickouts == 'all'){
$('div[class*="hist"]').css('display', 'none');
$('div[class*="percent"]').css('display', 'block');
}
else if (graph_type == 'all' & roll_up == 'aggregate' & clickouts == 'all'){
$('div[class*="aggregate"]').css('display', 'block');
$('div[class*="granular"]').css('display', 'none');
}
else if (graph_type == 'all' & roll_up == 'granular' & clickouts == 'all'){
$('div[class*="aggregate"]').css('display', 'none');
$('div[class*="granular"]').css('display', 'block');
}
});
A: If you will change your complex class class="distribution-(select-1)-(select-2)-(select-3) to set of classes class="distribution (select-1) (select-2) (select-3) you can use the following script:
$('.clickouts, .graph-type, .roll-up').change(function(){
var graph_type = $('.graph-type').val();
var roll_up = $('.roll-up').val();
var clickouts = $('.clickouts').val();
graph_type = (graph_type == "all" ? "" : "." + graph_type);
roll_up = (roll_up == "all" ? "" : "." + roll_up);
clickouts = (clickouts == "all" ? "" : "." + clickouts);
var selector = '#container div' + graph_type + roll_up + clickouts;
$('#container div:visible').hide();
$(selector).show();
});
Code: http://jsfiddle.net/9R5zj/9/
A: Ok, there are several things that will help to refactor this.
An easy thing that you should remember is that elements can have more than one class. That means, instead of having a div with the distribution-hist-clickouts-aggregate class, you can give the div four classes, like this:
<div class="distribution hist clickouts aggregate"></div>
Also, instead of having the value of the select options as all, you make it easier for your program to understand by putting the selectors in the values:
<option value = ".aggregate, .granular" selected="selected">All</option>
<option value = ".aggregate" >Aggregate</option>
<option value = ".granular" >Granular</option>
I'm not sure I completely understand the logic behind all of the if statements, but you can do something to this effect:
$("div.distribution").hide();
$(graph_type).show();
$(roll_up).show();
$(clickouts).show();
You can see what I'm suggesting in action on this demo.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: redirect to a specific view from method controller I have a controller called "products_controllers.rb" that have this method:
def create
...
...
respond_to do |format|
if @product.save
???????
else
format.html { render :action => "new" }
format.xml { render :xml => @product.errors, :status => :unprocessable_entity }
end
end
Whenever the product is save I want to redirect it to an specific view called "suppliers", that belongs to the product views, how can I do that?
Thanks in advance!
A: If you're using restful routes and there is a relationship where product has many suppliers, you could use:
format.html { redirect_to product_suppliers_url(@product) }
with something like this in your routes.rb:
map.resource :products do |product|
product.resource :suppliers
end
or you could also just use this:
format.html { redirect_to :action => 'suppliers', :id => @product.id }
A: Something like
redirect_to 'product/suppliers'
Source:
http://guides.rubyonrails.org/layouts_and_rendering.html#using-redirect_to
Comment: Next time make sure to specify "in rails" in the text of your question since views and controllers are used by many frameworks.
A: In your controller:
def create
...
...
respond_to do |format|
if @product.save
???????
else
format.html { render :action => "suppliers" }
format.xml { render :xml => @product.errors, :status => :unprocessable_entity }
end
end
def suppliers
#Your suppliers code goes here
end
In routes.rb
resources :venues do
member do
get 'suppliers'
end
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519680",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Schema and fixtures not being loaded when running rake:test from new Rails plugin I am creating a brand new full gem plugin using Rails 3.1.0 on ruby 1.9.2p290 (2011-07-09 revision 32553) [x86_64-linux]. I am having trouble with the schema and fixtures not being loaded for running rake test. Following are the steps I am taking:
Create the plugin:
rails plugin new core --full
From the plugin, generate a new scaffold:
rails g scaffold user
Run the db create and migrate:
rake db:create
rake db:migrate
Run the tests:
rake test
When running the functional tests, I am receiving a set of error like the following from the controller tests:
1) Error:
test_should_create_user(UsersControllerTest):
NoMethodError: undefined method `users' for #<UsersControllerTest:0x00000003babca8>
This error seems to stem from the fact that the test doesn't seem to understand the fixture call. It doesn't look like the test db is getting the schema loaded or having the fixtures loaded. Is this expected behavior? Is there something I'm missing in this scenario? All the fixtures are there. Is there some process I need to follow to get these tests to run correctly?
A: OK, I think I've made some progress. It looks like I can resolve it with the following changes.
I've added the following to test_helper:
#Run any available migration
ActiveRecord::Migrator.migrate 'up'
# Set fixtures root
ActiveSupport::TestCase.fixture_path=(File.expand_path("../fixtures", __FILE__))
ActiveSupport::TestCase.fixtures :all
This allows the test environment to find my fixtures outside of the dummy application.
After this change, I was still having an issue where the test database was not being prepared for the test. I resolved this by dropping into the test/dummy directory and running:
rake db:test:prepare
After this, I am able to run "rake test" successfully. It's somewhat a pain to have to drop in to the dummy app to prepare the db. There has to be a way around this. Any suggestions?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Set default image if no image is selected to upload in codeigniter I'm doing a script that will upload an image and save the image path in the database. The only problem that I have is if a user doesn't upload an image I want to set a default image.
But in codeigniter when an image is not selected it automatically gives an error saying that the input file hasn't been selected.
my controller
if ( !$this->upload->do_upload('image'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_success', $error);
}
else {
$image_data=array('image_info' => $this->upload->data('image'));
$image_path=$image_data['image_info']['full_path'];
$data =array(
'submitedby'=>$username,
'city'=>$this->input->post('towncity'),
'image' => $image_path
);
}
Can someone please suggest me how to set a default image if the user hasn't selected an image without displaying the default error?
A: In the clause where do_upload() fails, check to see if the file was uploaded.
if (!$this->upload->do_upload('image')) {
if (!empty($_FILES['image']['name'])) {
// Name isn't empty so a file must have been selected
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_success', $error);
} else {
// No file selected - set default image
$data = array(
'submitedby' => $username,
'city' => $this->input->post('towncity'),
'image' => 'path/to/default/image',
);
}
} else {
$image_data = array('image_info' => $this->upload->data('image'));
$image_path = $image_data['image_info']['full_path'];
$data = array(
'submitedby' => $username,
'city' => $this->input->post('towncity'),
'image' => $image_path,
);
}
This could be refactored further but the point is that you can check $_FILES['field_name']['name'] to see if a file was selected.
A: You could just not make the image field required and then you can set a default image in your view if there is no image found. That way you don't have all kinds of duplicate images being uploaded and you'll be able to update your default image for everyone easily whenever you want.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519688",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Team Foundation server configuration I'm trying to configure Visual Studio 2010 with team foundation server.
I'm getting following screen
I can add only windows users into user groups
Now, I need to create windows user for every remote user or is there any way get it work?
How can I give access permissions to remote users?
A: This set of users is specifically meant to have root control access to your TFS configuration. Only provide the names of people that need to be admin for your TFS farm.
Regular remote users are configured in the TFS system itself, not here. When a TFS administrator creates a collection he can delegate the administrative rights to another (group of) person(s). These persons can create TFS projects in that collection and assign roles for administrator, contributor or reader at project level.
See How to add new users to TFS 2010 for more details.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519689",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Defining JPA Default Table Qualifier All of my tables (MSSQL) use a schema/qualifier/prefix (e.g., abc.Table1, abc.Table2). This qualifier is the same for all of the tables and I would like to specify it as a default to JPA so that I do not need to annotate each class with a custom name string.
This can be done with XML configuration like so:
<entity-mappings>
<persistence-unit-metadata>
<persistence-unit-defaults>
<schema name="abc"/>
</persistence-unit-defaults>
</persistence-unit-metadata>
</entity-mappings>
However, I am using the Play Framework where JPA configuration is done in the webapps's application.conf file. Is it possible to declare this attribute?
A: Have you tried to add hibernate.default_schema=abc to your application.conf? Play should support setting additional Hibernate properties this way.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: CONCAT with GROUP_CONCAT in mysql So I have looked everywhere for an answer to this, but so far no luck. Any help is much appreciated. I am new to mysql (transferring from a filemaker pro background).
I have a database where I keep information for prospects for our business. I have a question about listing information for our users to see. The INQUIRY table holds the information for each inquiry (i.e. date inquiry came in, status of the inquiry, etc.). The PROSPECT table holds the information on each prospect (potential client) (i.e. first name, last name, age, etc.). A third table, INQUIRYNOTES, hold information on our contacts with the prospect (i.e. next contact date, notes, next action, etc.). Each of these tables are related with the key inquiryID.
Each day a user will come to a screen where they will be presented with the leads/inquiries that he/she will follow up on for that day which are those inquiries who's action date is less than or equal to today. I want the list to contain the inquiryID, listed names of all prospects related to that inquiryID (max 2), and the action date.
Here is what I've tried so far:
SELECT inquiry.inquiryID,
CASE WHEN prospect.lastName = '' THEN prospect.firstName
WHEN prospect.firstName = '' THEN prospect.lastName
ELSE CONCAT(prospect.lastName, ', ',prospect.firstName) END as fullName, inquiryNote.actionDate
FROM inquiry, prospect, inquiryNote
WHERE inquiry.inquiryID = prospect.inquiryID
AND inquiry.inquiryID = inquirynote.inquiryID
AND inquirynote.actionDate != \"0000-00-00\"
AND actionDate <= \"".date("Y-m-d")."\"
GROUP BY inquiryID ORDER BY actionDate";
This returns the information that I am looking for, but it only lists one of the prospect (even if there are 2 for the inquiry).
Next I tried putting the GROUP_CONCAT(firstname) in this and it gave me a list of the first names of the prospect listed in a row separated by commas (I'm getting closer). Then I tried GROUP_CONCAT(last name, ', ', firstname) and then GROUP_CONCAT(lastname,firstname), but again it would only list one prospect, not the multiple prospects separated by commas.
I want the variable that I named fullName in the code above to be included in the GROUP_CONCAT so that in the rows returned I see a list of all prospect related to an inquiry listed and divided by a comma.
I want the table in the webpage I have created to have these columns:
inquiryID | prospects name(s) (last name first) | Next Action Date
Again so far I can only seem to get:
inquiryID | 1 prospect name | Next Action Date
The solution could be something easy, but since I am new to mysql I am lost.
Please let me know if you need more detail.
UPDATE WITH SOLUTION, BUT SIMILAR QUESTION AT THE END
The problem was that some of the first name and last name fields had NULL values. Apparently, GROUP_CONCAT will now work with null values. This is the query that I ended with that worked once I got rid of all of the NULL values:
SELECT
inquiry.inquiryID,
inquiry.initialDate,
inquiryNote.actionDate,
GROUP_CONCAT(DISTINCT
CONCAT(
CASE WHEN prospect.lastName = '' THEN prospect.firstName
WHEN prospect.firstName = '' THEN prospect.lastName
ELSE CONCAT(
prospect.firstName, ' ',prospect.lastName
) END
) SEPARATOR ', '
) AS prospectList,
GROUP_CONCAT(DISTINCT
CONCAT(
CASE WHEN influencer.lastName = '' THEN influencer.firstName
WHEN influencer.firstName = '' THEN influencer.lastName
ELSE CONCAT(
influencer.firstName, ' ',influencer.lastName
) END
) SEPARATOR ', '
) AS influencerList
FROM inquiry, prospect, inquiryNote, influencer WHERE inquiry.inquiryID = prospect.inquiryID
AND inquiry.inquiryID = inquirynote.inquiryID
AND inquiry.inquiryID = influencer.inquiryID
AND inquirynote.actionDate != "0000-00-00" AND actionDate <= "2011-09-22"
GROUP BY inquiryID
ORDER BY actionDate;
So the final question is, can I make GROUP_CONCAT work even when it encounters NULL values?
A: You can COALESCE the columns in case the contain NULLs:
COALESCE(lastname, '') would return an empty string if lastname was null, or whatever the value of lastname is if it is not.
A: GROUP_CONCAT simply ignores(skips) NULL values http://thinkdiff.net/mysql/mysql-the-group_concat-function/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: NSDate issue, the date is the day before then it should be I want to implement method, that will count the number of days in month. Everything is fine except my date is the day before then it should be. In the following example date is "2012-09-14 21:00:00 +0000" and should be 2012-09-15 21:00:00 +0000 Will appreciate for your help. My code is:
NSDictionary *curDay = [NSDictionary dictionaryWithObjectsAndKeys:
@"9",@"mounthNumber",@"15",@"day",@"2012",@"year", nil];
NSDateComponents *selectedMounth = [[[NSDateComponents alloc] init] autorelease];
NSCalendar *calendar = [[[NSCalendar alloc]initWithCalendarIdentifier:
NSGregorianCalendar] autorelease];
NSTimeZone *timezone = [NSTimeZone systemTimeZone];
[calendar setTimeZone: timezone];
[selectedMounth setYear:[[curDay objectForKey:@"year"] integerValue]];
[selectedMounth setMonth:[[curDay objectForKey:@"mounthNumber"] integerValue]];
[selectedMounth setDay:[[curDay objectForKey:@"day"] integerValue]];
NSDate *date = [calendar dateFromComponents:selectedMounth];
A: Your timeZone seems to be something like GMT-3 (or GMT+3, I never remember). Instead of the systemTimeZone use the GMT one:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]; and it solves your problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Function Definitions as Arguments var cancel = setTimeout(function(){clearTimeout(cancel);}, 500);
var cancel = setTimeout(clearTimeout(cancel), 500);
Scholastic question: The first of these two expressions work, while the second does not. The setTimeout() method is accepting a function and a duration as its arguments and both of these examples are clearly providing that. The only difference is that the first is a function definition while the second is a function invocation.
If functions designed to take a function as an argument can only handle function definitions, how do you go about providing that function with the variables it may need? For example:
stop = function(y){clearInterval(y)};
count = function(x){
var t = 0,
cancel = setInterval(function(){console.log(++t);},1000);
setTimeout(stop(cancel),x);
};
count(5000);
The function above doesn't work because it's invoking the function
stop = function(){clearInterval(cancel)};
count = function(x){
var t = 0,
cancel = setInterval(function(){console.log(++t);},1000);
setTimeout(stop,x);
};
count(5000);
The function above doesn't work because the stop() doesn't have access to the cancel variable.
Thank you in advance for attempting to educate me on the work-around for this type of issue.
A:
The setTimeout() method is accepting a function and a duration as its
arguments and both of these examples are clearly providing that. The
only difference is that the first is a function definition while the
second is a function invocation.
Yes but when you invoke a function you return the result which could be a string, integer, etc..., so you are no longer passing a function pointer but some string, integer, ... which is not what the setTimeout function expects as first argument.
Think of the second example like this:
var result = clearTimeout(cancel); // result is now an integer
setTimeout(result, 500); // invalid because setTimeout expects a function pointer
If functions designed to take a function as an argument can only
handle function definitions, how do you go about providing that
function with the variables it may need?
You could use closures:
var stop = function(y) { clearInterval(y); };
var count = function(x) {
var t = 0,
var cancel = setInterval(function() { console.log(++t); }, 1000);
setTimeout(function() { stop(cancel); }, x);
};
count(5000);
or simply:
var count = function(x) {
var t = 0,
var cancel = setInterval(function() { console.log(++t); }, 1000);
setTimeout(function() { clearInterval(cancel); }, x);
};
count(5000);
A: You get around it exactly as you have in the first line of code by wrapping the function call with an anonymous function.
A: Try passing in the cancel variable to the anonymous function.
stop = function(cancel){clearInterval(cancel)};
count = function(x){
var t = 0,
cancel = setInterval(function(){console.log(++t);},1000);
setTimeout(stop(cancel),x);
};
count(5000);
A: Local variables are always injected into nested scopes, for example those introduced by function declarations via function () { }. This is what is commonly called a closure and it forms an important tool in Javascript programming.
Therefore, setTimeout( function() { stop(cancel); },x); will do, the inner function has access to the cancel variable defined in the outer scope (it can even change its value).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519711",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: div box inside div box. Relative positioning, and equal padding, space between all sides I have this div box right now:
div#main-edit{
padding:2px 6px 4px 6px;
color: #555555;
background-color: #FFF8F8;
border: #dddddd 2px solid;
width: 750px;
height: 500px;
margin-left: 10%;
margin-right: 10%;
}
What I wanted now was to have another div box inside this div box, with its position being relative to its parent. Like This:
A: Make your second div height: 100%, and give your outer div padding all around.
http://jsfiddle.net/P2VGk/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: The symbols I should be aware of for SQL injection I know that you cure all of the stuff with mysql_real_escape_string() (and with htmlspecialchars()), but I want to know the symbols that cause all this mess everyone wants to get rid of?
The thing here is, that we here had to transfer a website not built by us from one host to another.
It has been coded from ground up, to utilize php's now deprecated and never loved one - magic_quotes.
After the host change there have been php.ini changes also, we encountered a lot of unexpected results. We don't have access to php.ini, there is no user.ini (5.2.x) and the host is is not responsive enough to enable us some extra features. There is a problem with hosting services here in Latvia, a major one.
But yeah, that's off-topic already. I simply want to know, which symbols are the ones that with no escaping, no magic quotes and no protection can cause all this mess?
Plus, there were error when text contained stuff like - /ls which resembles UNIX (the host OS) directory listing command - Method Not Implemented.
And it looks like the website interacts with database in CLI environment, hence the /ls problem. And I want to confirm that whenever you input a value that starts with / and follows UNIX command- "Method Not Implemented" errors comes up.
P.S. I'm not looking for a solution, I've already fixed the error. Just want to know the symbols.
Update to clarify
1) As of writing the question, I was calling CLI what looks to be socket call- unix-domain / TCP. Live and learn!
2) If you read the question fully, you'll see that I'm fixing bugs/holes left behind other developers. Sine we took over this clients IT servicing, they wanted us to take over their website too.
3) Because they have paid a lot of money for current website, they don't want to pay even more for a new one on a newer, better built system.
4) The connection line inside the scripts is - $this->db = DB::connect('mysql://'._DB_USER.':'._DB_PASS.'@'._DB_HOST.'/'._DB_NAME.''); - unix-domain I guess.
A: From the PHP Manual:
mysql_real_escape_string() calls MySQL's library function
mysql_real_escape_string, which prepends backslashes to the following
characters: \x00, \n, \r, \, ', " and \x1a.
A: Each DB will have its own metacharacters as extensions to standard SQL syntax. Some will use -- for comments, some use c-style /* */, etc... Each DB has its own escaping requirements, which is why there's an escape function for every DB type in PHP. What works for MySQL may be completely useless for (say) Oracle.
The only "definitive" list of characters will be the ones listed in the SQL standards. But using only those in your own custom escape function would be useless, because it won't include the DB-specific non-standard metacharacters that the DB understands.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519717",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get count on ths query I'm doing an
INSERT INTO table1...
SELECT...
FROM table2
However, I need to retrieve the identity from a table3 and do an insert into it just before inserting into table1. These two inserts need to occur together, with table3 insert going first. I've tried something like this:
INSERT INTO table1 (col1, col2, col3)
SELECT (
col1=(insert into table3(col1, col2)values(1,1) select SCOPE_IDENTITY(),
col2, col3)
FROM table2
But that doesn't work. table1.col1 does need the identity value from the new insert into table3. Amount of data to insert probably no more than a few 100 rows. Any suggestions?
A: It looks like you might be able to use the Output Clause.
BEGIN TRANSACTION
DECLARE @MyResults table(col1 int, col2 int, col3 int);
INSERT INTO table3 (col1, col2)
OUTPUT SCOPE_IDENTITY(), table2.col2, table2.col3 INTO @MyResults
SELECT 1, 1 FROM table2
INSERT INTO table1 (col1, col2, col3)
SELECT col1, col2, col3 FROM @MyResults
COMMIT
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519722",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to grab a specific SHA from the git log output Executing the following command git log --before "Feb 01 2011" returns all of the commits from before the specified date, including their SHA
I'm trying to write a cygwin script that syncs my head to the last commit of a specific month, without me having to find and enter the SHA myself. Any ideas? Thanks!
A: Just use rev-list with the same options as you would pass to log, plus -n 1 to return just the first one.
sha1=$(git rev-list --before "Feb 01 2011" -n 1 HEAD)
A: In bash on linux the following works, I think it should also work on cygwin:
git checkout $(git log --before='Feb 01 2011' -n1 | head -n 1 |sed s/commit\ //)
It may be a good idea to immediately create a branch when you do that
git checkout $(git log --before='Feb 01 2011' -n1 | head -n 1 |sed s/commit\ //) -b 2011-02
Or alternatively if you intend to create a script tagging is perhaps a better option. Eg:
git checkout $(git log --before='Feb 01 2011' -n1 | head -n 1 |sed s/commit\ //)
git tag 2011-01
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7519725",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.