qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
38,238
|
<p>I'm teaching myself Python and my most recent lesson was that <a href="http://dirtsimple.org/2004/12/python-is-not-java.html" rel="noreferrer">Python is not Java</a>, and so I've just spent a while turning all my Class methods into functions.</p>
<p>I now realise that I don't need to use Class methods for what I would done with <code>static</code> methods in Java, but now I'm not sure when I would use them. All the advice I can find about Python Class methods is along the lines of newbies like me should steer clear of them, and the standard documentation is at its most opaque when discussing them.</p>
<p>Does anyone have a good example of using a Class method in Python or at least can someone tell me when Class methods can be sensibly used?</p>
|
[
{
"answer_id": 38276,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 9,
"selected": true,
"text": "MyClass classmethod"
},
{
"answer_id": 38303,
"author": "Wayne Werner",
"author_id": 4080,
"author_profile": "https://Stackoverflow.com/users/4080",
"pm_score": 6,
"selected": false,
"text": "Path.cwd() Path(\"/tmp/my_temp_dir\") .chdir() cwd cwd Path Path.cwd() Path"
},
{
"answer_id": 2311096,
"author": "Drachenfels",
"author_id": 278709,
"author_profile": "https://Stackoverflow.com/users/278709",
"pm_score": 3,
"selected": false,
"text": "\nclass A\n{\n\n static protected $inner_var = null;\n\n static public function echoInnerVar()\n {\n echo self::$inner_var.\"\\n\";\n }\n\n static public function setInnerVar($v)\n {\n self::$inner_var = $v;\n }\n\n}\n\nclass B extends A\n{\n}\n\nA::setInnerVar(10);\nB::setInnerVar(20);\n\nA::echoInnerVar();\nB::echoInnerVar();\n \nclass A(object):\n inner_var = 0\n\n @classmethod\n def setInnerVar(cls, value):\n cls.inner_var = value\n\n @classmethod\n def echoInnerVar(cls):\n print cls.inner_var\n\n\nclass B(A):\n pass\n\n\nA.setInnerVar(10)\nB.setInnerVar(20)\n\nA.echoInnerVar()\nB.echoInnerVar()\n"
},
{
"answer_id": 2807576,
"author": "Marvo",
"author_id": 337819,
"author_profile": "https://Stackoverflow.com/users/337819",
"pm_score": 5,
"selected": false,
"text": "@classmethod Logger._level = Logger.DEBUG\n Logger.debug( \"this is some annoying message I only want to see while debugging\" )\n Logger.error( \"Wow, something really awful happened.\" )\n Logger._level = Logger.ERROR\n class Logger :\n ''' Handles logging of debugging and error messages. '''\n\n DEBUG = 5\n INFO = 4\n WARN = 3\n ERROR = 2\n FATAL = 1\n _level = DEBUG\n\n def __init__( self ) :\n Logger._level = Logger.DEBUG\n\n @classmethod\n def isLevel( cls, level ) :\n return cls._level >= level\n\n @classmethod\n def debug( cls, message ) :\n if cls.isLevel( Logger.DEBUG ) :\n print \"DEBUG: \" + message\n\n @classmethod\n def info( cls, message ) :\n if cls.isLevel( Logger.INFO ) :\n print \"INFO : \" + message\n\n @classmethod\n def warn( cls, message ) :\n if cls.isLevel( Logger.WARN ) :\n print \"WARN : \" + message\n\n @classmethod\n def error( cls, message ) :\n if cls.isLevel( Logger.ERROR ) :\n print \"ERROR: \" + message\n\n @classmethod\n def fatal( cls, message ) :\n if cls.isLevel( Logger.FATAL ) :\n print \"FATAL: \" + message\n def logAll() :\n Logger.debug( \"This is a Debug message.\" )\n Logger.info ( \"This is a Info message.\" )\n Logger.warn ( \"This is a Warn message.\" )\n Logger.error( \"This is a Error message.\" )\n Logger.fatal( \"This is a Fatal message.\" )\n\nif __name__ == '__main__' :\n\n print \"Should see all DEBUG and higher\"\n Logger._level = Logger.DEBUG\n logAll()\n\n print \"Should see all ERROR and higher\"\n Logger._level = Logger.ERROR\n logAll()\n"
},
{
"answer_id": 3504391,
"author": "Pierre",
"author_id": 140280,
"author_profile": "https://Stackoverflow.com/users/140280",
"pm_score": 3,
"selected": false,
"text": "all() find() User.all() User.find(firstname='Guido')"
},
{
"answer_id": 3521920,
"author": "Brandon Rhodes",
"author_id": 85360,
"author_profile": "https://Stackoverflow.com/users/85360",
"pm_score": 6,
"selected": false,
"text": "myobj.foo() foo() myobj MyClass.foo() foo() MyClass dbapi() dbapi()"
},
{
"answer_id": 6001200,
"author": "firephil",
"author_id": 449946,
"author_profile": "https://Stackoverflow.com/users/449946",
"pm_score": 3,
"selected": false,
"text": "module.py (file 1)\n---------\ndef f1() : pass\ndef f2() : pass\ndef f3() : pass\n\n\nusage.py (file 2)\n--------\nfrom module import *\nf1()\nf2()\nf3()\ndef f4():pass \ndef f5():pass\n\nusage1.py (file 3)\n-------------------\nfrom usage import f4,f5\nf4()\nf5()\n class FileUtil ():\n def copy(source,dest):pass\n def move(source,dest):pass\n def copyDir(source,dest):pass\n def moveDir(source,dest):pass\n\n//usage\nFileUtil.copy(\"1.txt\",\"2.txt\")\nFileUtil.moveDir(\"dir1\",\"dir2\")\n"
},
{
"answer_id": 9867663,
"author": "Rusty Rob",
"author_id": 632088,
"author_profile": "https://Stackoverflow.com/users/632088",
"pm_score": 3,
"selected": false,
"text": "class User():\n #lots of code\n #...\n # more code\n\n @classmethod\n def get_by_username(cls, username):\n return cls.query(cls.username == username).get()\n\n @classmethod\n def get_by_auth_id(cls, auth_id):\n return cls.query(cls.auth_id == auth_id).get()\n"
},
{
"answer_id": 12312026,
"author": "Peter Moore",
"author_id": 1223946,
"author_profile": "https://Stackoverflow.com/users/1223946",
"pm_score": 2,
"selected": false,
"text": "class M():\n @classmethod\n def m(cls, arg):\n print \"arg was\", getattr(cls, \"arg\" , None),\n cls.arg = arg\n print \"arg is\" , cls.arg\n\n M.m(1) # prints arg was None arg is 1\n M.m(2) # prints arg was 1 arg is 2\n m1 = M()\n m2 = M() \n m1.m(3) # prints arg was 2 arg is 3 \n m2.m(4) # prints arg was 3 arg is 4 << this breaks the factory pattern theory.\n M.m(5) # prints arg was 4 arg is 5\n"
},
{
"answer_id": 14042417,
"author": "yet",
"author_id": 373451,
"author_profile": "https://Stackoverflow.com/users/373451",
"pm_score": 4,
"selected": false,
"text": "@classmethod\ndef get_name(cls):\n print cls.name\n\nclass C:\n name = \"tester\"\n\nC.get_name = get_name\n\n#call it:\nC.get_name()\n @classmethod def get_name(self):\n print self.name\n\nclass C:\n name = \"tester\"\n\nC.get_name = get_name\n\n#call it:\nC().get_name() #<-note the its an instance of class C\n"
},
{
"answer_id": 43008840,
"author": "starfry",
"author_id": 712506,
"author_profile": "https://Stackoverflow.com/users/712506",
"pm_score": 2,
"selected": false,
"text": "obj.meth() @classmethod class class Foo():\n def foo(x):\n print(x)\n foo Foo().foo()\n<__main__.Foo instance at 0x7f4dd3e3bc20>\n Foo.foo()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: unbound method foo() must be called with Foo instance as first argument (got nothing instead)\n @classmethod class Foo():\n @classmethod\n def foo(x):\n print(x)\n Foo().foo()\n__main__.Foo\n Foo.foo()\n__main__.Foo\n self cls self class Foo\n def foo()\n puts \"instance method #{self}\"\n end\n def self.foo()\n puts \"class method #{self}\"\n end\nend\n\nFoo.foo()\nclass method Foo\n\nFoo.new.foo()\ninstance method #<Foo:0x000000020fe018>\n @classmethod"
},
{
"answer_id": 58878894,
"author": "psilocybin",
"author_id": 4147666,
"author_profile": "https://Stackoverflow.com/users/4147666",
"pm_score": 1,
"selected": false,
"text": "@classmethod import settings\n\nclass SomeClass:\n @classmethod\n def from_settings(cls):\n return cls(settings=settings)\n\n def __init__(self, settings=None):\n if settings is not None:\n self.x = settings['x']\n self.y = settings['y']\n from some_package import SomeClass\n\ninst = SomeClass.from_settings()\n"
},
{
"answer_id": 64445340,
"author": "sebtac",
"author_id": 8227979,
"author_profile": "https://Stackoverflow.com/users/8227979",
"pm_score": 3,
"selected": false,
"text": "a3c_workers = [A3C_Worker(self.master_model, self.optimizer, i, self.env_name, self.model_dir) for i in range(multiprocessing.cpu_count())]\n class A3C_Worker(threading.Thread):\n global_shared_total_episodes_across_all_workers = 0\n class A3C_Worker(threading.Thread):\n @classmethod\n def reset(cls):\n A3C_Worker.global_shared_total_episodes_across_all_workers = 0\n A3C_Worker.reset()\n def play(self):"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3171/"
] |
38,288
|
<p>Specifically, what commands do I run from the terminal?</p>
|
[
{
"answer_id": 38289,
"author": "quackingduck",
"author_id": 3624,
"author_profile": "https://Stackoverflow.com/users/3624",
"pm_score": 8,
"selected": true,
"text": "sudo useradd myuser\n sudo useradd -m myuser\n sudo passwd myuser\n sudo usermod -s /bin/bash myuser\n"
},
{
"answer_id": 2080709,
"author": "Liberty",
"author_id": 252553,
"author_profile": "https://Stackoverflow.com/users/252553",
"pm_score": 5,
"selected": false,
"text": "useradd -d /home/kevin -s /bin/bash -m kevin\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3624/"
] |
38,302
|
<p>I'm currently working on a ray-tracer in C# as a hobby project. I'm trying to achieve a decent rendering speed by implementing some tricks from a c++ implementation and have run into a spot of trouble.</p>
<p>The objects in the scenes which the ray-tracer renders are stored in a KdTree structure and the tree's nodes are, in turn, stored in an array. The optimization I'm having problems with is while trying to fit as many tree nodes as possible into a cache line. One means of doing this is for nodes to contain a pointer to the left child node only. It is then implicit that the right child follows directly after the left one in the array.</p>
<p>The nodes are structs and during tree construction they are succesfully put into the array by a static memory manager class. When I begin to traverse the tree it, at first, seems to work just fine. Then at a point early in the rendering (about the same place each time), the left child pointer of the root node is suddenly pointing at a null pointer. I have come to the conclusion that the garbage collecter has moved the structs as the array lies on the heap.</p>
<p>I've tried several things to pin the addresses in memory but none of them seems to last for the entire application lifetime as I need. The 'fixed' keyword only seems to help during single method calls and declaring 'fixed' arrays can only be done on simple types which a node isn't. Is there a good way to do this or am I just too far down the path of stuff C# wasn't meant for.</p>
<p>Btw, changing to c++, while perhaps the better choice for a high performance program, is not an option.</p>
|
[
{
"answer_id": 38584,
"author": "Morten Christiansen",
"author_id": 4055,
"author_profile": "https://Stackoverflow.com/users/4055",
"pm_score": 0,
"selected": false,
"text": "Marshal.AllocHGlobal"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4055/"
] |
38,345
|
<p>I recently "needed" a zip function in Perl 5 (while I was thinking about <a href="https://stackoverflow.com/questions/11/how-do-i-calculate-relative-time">How do I calculate relative time?</a>), i.e. a function that takes two lists and "zips" them together to one list, interleaving the elements.</p>
<p>(Pseudo)example: </p>
<pre><code>@a=(1, 2, 3);
@b=('apple', 'orange', 'grape');
zip @a, @b; # (1, 'apple', 2, 'orange', 3, 'grape');
</code></pre>
<p><a href="http://www.haskell.org/onlinereport/standard-prelude.html" rel="nofollow noreferrer">Haskell has zip in the Prelude</a> and <a href="http://ferreira.nfshost.com/perl6/zip.html" rel="nofollow noreferrer">Perl 6 has a zip operator</a> built in, but how do you do it in an elegant way in Perl 5?</p>
|
[
{
"answer_id": 38365,
"author": "Jason Navarrete",
"author_id": 3920,
"author_profile": "https://Stackoverflow.com/users/3920",
"pm_score": 5,
"selected": false,
"text": "use List::MoreUtils qw(zip);\n\nmy @numbers = (1, 2, 3);\nmy @fruit = ('apple', 'orange', 'grape');\n\nmy @zipped = zip @numbers, @fruit;\n sub mesh (\\@\\@;\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@) {\n my $max = -1;\n $max < $#$_ && ($max = $#$_) for @_;\n\n map { my $ix = $_; map $_->[$ix], @_; } 0..$max; \n}\n"
},
{
"answer_id": 71895,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 6,
"selected": true,
"text": "sub zip2 {\n my $p = @_ / 2; \n return @_[ map { $_, $_ + $p } 0 .. $p - 1 ];\n}\n $p map @_ 'a', 'b', 'c', 1, 2, 3 zip2 'a', 1, 'b', 2, 'c', 3 sub zip2 { @_[map { $_, $_ + @_/2 } 0..(@_/2 - 1)] }\n"
},
{
"answer_id": 100082,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 2,
"selected": false,
"text": "Algorithm::Loops sub zip { @_[map $_&1 ? $_>>1 : ($_>>1)+($#_>>1), 1..@_] }\n"
},
{
"answer_id": 171391,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 1,
"selected": false,
"text": "package zip;\n\nsub TIEARRAY {\n my ($class, @self) = @_;\n bless \\@self, $class;\n}\n\nsub FETCH {\n my ($self, $index) = @_;\n $self->[$index % @$self][$index / @$self];\n}\n\nsub STORE {\n my ($self, $index, $value) = @_;\n $self->[$index % @$self][$index / @$self] = $value;\n}\n\nsub FETCHSIZE {\n my ($self) = @_;\n my $size = 0;\n @$_ > $size and $size = @$_ for @$self;\n $size * @$self;\n}\n\nsub CLEAR {\n my ($self) = @_;\n @$_ = () for @$self;\n}\n\npackage main;\n\nmy @a = qw(a b c d e f g);\nmy @b = 1 .. 7;\n\ntie my @c, zip => \\@a, \\@b;\n\nprint \"@c\\n\"; # ==> a 1 b 2 c 3 d 4 e 5 f 6 g 7\n STORESIZE PUSH POP SHIFT UNSHIFT SPLICE"
},
{
"answer_id": 486162,
"author": "jmcnamara",
"author_id": 10238,
"author_profile": "https://Stackoverflow.com/users/10238",
"pm_score": 3,
"selected": false,
"text": "my @zipped = ( @a, @b )[ map { $_, $_ + @a } ( 0 .. $#a ) ];\n"
},
{
"answer_id": 544390,
"author": "Frank",
"author_id": 60628,
"author_profile": "https://Stackoverflow.com/users/60628",
"pm_score": 4,
"selected": false,
"text": "@a = (1, 2, 3);\n@b = ('apple', 'orange', 'grape');\n@zipped = map {($a[$_], $b[$_])} (0 .. $#a);\n @a @b"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2905/"
] |
38,352
|
<p>I need to store contact information for users. I want to present this data on the page as an <a href="http://en.wikipedia.org/wiki/Hcard" rel="nofollow noreferrer">hCard</a> and downloadable as a <a href="http://en.wikipedia.org/wiki/VCard" rel="nofollow noreferrer">vCard</a>. I'd also like to be able to search the database by phone number, email, etc. </p>
<p>What do you think is the best way to store this data? Since users could have multiple addresses, etc complete normalization would be a mess. I'm thinking about using XML, but I'm not familiar with querying XML db fields. Would I still be able to search for users by contact info?</p>
<p>I'm using SQL Server 2005, if that matters.</p>
|
[
{
"answer_id": 61103,
"author": "Alan",
"author_id": 5878,
"author_profile": "https://Stackoverflow.com/users/5878",
"pm_score": 4,
"selected": true,
"text": "People (pid, prefix, firstName, lastName, suffix, DOB, ... primaryAddressTag )\n\nAddressBook (pid, tag, address1, address2, city, stateProv, postalCode, ... )\n pid (pid, tag) 1, Kirk\n\n2, Spock\n 1, home, '123 Main Street', Iowa\n\n1, work, 'USS Enterprise NCC-1701'\n\n2, other, 'Mt. Selaya, Vulcan'\n People primaryAddressTag primaryAddressTag"
},
{
"answer_id": 11313185,
"author": "Alexx Roche",
"author_id": 1153645,
"author_profile": "https://Stackoverflow.com/users/1153645",
"pm_score": 0,
"selected": false,
"text": "vcards name_or_letter vcard timestamp username CREATE TABLE `vCards` ( \n `card_id` int(255) unsigned NOT NULL AUTO_INCREMENT, \n `card_peid` int(255) DEFAULT NULL COMMENT 'link back to user table', \n `card_acid` int(255) DEFAULT NULL COMMENT 'link back to account table', \n `card_language` varchar(5) DEFAULT NULL COMMENT 'en en_GB',\n `card_encoding` varchar(32) DEFAULT 'UTF-8' COMMENT 'why use anything else?',\n `card_created` datetime NOT NULL, \n `card_updated` datetime NOT NULL,\n PRIMARY KEY (`card_id`) )\n ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='These are the contact cards'\n\n create table vCard_profile (\n vcprofile_id int(255) unsigned auto_increment NOT NULL,\n vcprofile_version enum('rfc2426') DEFAULT \"rfc2426\" COMMENT \"defaults to vCard 3.0\",\n vcprofile_feature char(16) COMMENT \"FN to CATEGORIES\",\n vcprofile_type enum('text','bin') DEFAULT \"text\" COMMENT \"if it is too large for vcd_value then user vcd_bin\",\n PRIMARY KEY (`vcprofile_id`)\n) COMMENT \"These are the valid types of card entry\";\nINSERT INTO vCard_profile VALUES('','rfc2426','FN','text'),('','rfc2426','N','text'),('','rfc2426','NICKNAME','text'),('','rfc2426','PHOTO','bin'),('','rfc2426','BDAY','text'),('','rfc2426','ADR','text'),('','rfc2426','LABEL','text'),('','rfc2426','TEL','text'),('','rfc2426','EMAIL','text'),('','rfc2426','MAILER','text'),('','rfc2426','TZ','text'),('','rfc2426','GEO','text'),('','rfc2426','TITLE','text'),('','rfc2426','ROLE','text'),('','rfc2426','LOGO','bin'),('','rfc2426','AGENT','text'),('','rfc2426','ORG','text'),('','rfc2426','CATEGORIES','text'),('','rfc2426','NOTE','text'),('','rfc2426','PRODID','text'),('','rfc2426','REV','text'),('','rfc2426','SORT-STRING','text'),('','rfc2426','SOUND','bin'),('','rfc2426','UID','text'),('','rfc2426','URL','text'),('','rfc2426','VERSION','text'),('','rfc2426','CLASS','text'),('','rfc2426','KEY','bin');\n\ncreate table vCard_data (\n vcd_id int(255) unsigned auto_increment NOT NULL,\n vcd_card_id int(255) NOT NULL,\n vcd_profile_id int(255) NOT NULL,\n vcd_prof_detail varchar(255) COMMENT \"work,home,preferred,order for e.g. multiple email addresses\",\n vcd_value varchar(255),\n vcd_bin blob COMMENT \"for when varchar(255) is too small\",\n PRIMARY KEY (`vcd_id`)\n) COMMENT \"The actual vCard data\";\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/521/"
] |
38,357
|
<p>If I get an error code result from a Cocoa function, is there any easy way to figure out what it means (other than by grepping through all the .h files in the framework bundles)?</p>
|
[
{
"answer_id": 38497,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 6,
"selected": true,
"text": "<Framework/FrameworkErrors.h> NSError code <Foundation/FoundationErrors.h> <AppKit/AppKitErrors.h> <CoreData/CoreDataErrors.h> NSError"
},
{
"answer_id": 19369662,
"author": "Mark Amery",
"author_id": 1709587,
"author_profile": "https://Stackoverflow.com/users/1709587",
"pm_score": 3,
"selected": false,
"text": "ENOMEM /* Cannot allocate memory */ NSCocoaErrorDomain <Foundation/FoundationErrors.h> <AppKit/AppKitErrors.h> <CoreData/CoreDataErrors.h> NSURLErrorDomain NSURLError.h NSXMLParserErrorDomain NSXMLParser.h NSMachErrorDomain /usr/include/mach/kern_return.h NSPOSIXErrorDomain /usr/include/sys/errno.h NSOSStatusErrorDomain /System/Library/Frameworks/CoreServices.framework/Frameworks/CarbonCore.framework/Headers/MacErrors.h\n"
},
{
"answer_id": 24833116,
"author": "Will",
"author_id": 1299429,
"author_profile": "https://Stackoverflow.com/users/1299429",
"pm_score": 0,
"selected": false,
"text": "NSError *error;\n\n// ... Some code that returns an error\n\n// Get the error as a string\nNSString *s = [error localizedDescription];\n\n// Observe the code for yourself or display to the user. \n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1175/"
] |
38,362
|
<p>I have 3 Linux machines, and want some way to keep the dotfiles in their home directories in sync. Some files, like .vimrc, are the same across all 3 machines, and some are unique to each machine.</p>
<p>I've used SVN before, but all the buzz about DVCSs makes me think I should try one - is there a particular one that would work best with this? Or should I stick with SVN?</p>
|
[
{
"answer_id": 731430,
"author": "hillu",
"author_id": 72344,
"author_profile": "https://Stackoverflow.com/users/72344",
"pm_score": 0,
"selected": false,
"text": "git rebase .gitignore"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2461/"
] |
38,370
|
<p>I've to admin a small website for my alumni group which is hosted by my ISV. The url is something like www.myIsv.com/myWebSite/ which is quite ugly and very forgetable. The main admin of the webserver has registered a domain name www.mysmallwebsite.com and put a index.html with this content:</p>
<pre><code><html>
<head>
<title>www.mysmallwebsite.com</title>
</head>
<frameset>
<frame src="http://www.myIsv.com/myWebSite/" name="redir">
<noframes>
<p>Original location:
<a href="www.myIsv.com/myWebSite/">http://www.myIsv.com/myWebSite/</a>
</p>
</noframes>
</frameset>
</html>
</code></pre>
<p>It works fine, but some features like PHP Session variables doesn't work anymore! Anyone has a suggestion for correcting that?</p>
<p>Edit:
This doesn't work both on IE and on Firefox (no plugins)</p>
<p>Thanks</p>
|
[
{
"answer_id": 38382,
"author": "Alexandru Nedelcu",
"author_id": 3280,
"author_profile": "https://Stackoverflow.com/users/3280",
"pm_score": 0,
"selected": false,
"text": "www.myIsv.com/myWebSite/?PHPSESSID=<?=session_id()?>\n"
},
{
"answer_id": 38417,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 0,
"selected": false,
"text": "www.myIsv.com/myWebSite/?PHPSESSID=<?=session_id()?>"
},
{
"answer_id": 38774,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 0,
"selected": false,
"text": "<?php header('Location: http://www.myIsv.com/myWebSite/'); ?>\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1578/"
] |
38,408
|
<p>I'm using Flash to play an .flv movieclip on my site, but I want to have the .swf send trigger an event in my javascript when it start loading, starts playing and ends playing.</p>
<p>What is the best way to do that in Flash CS3 using Actionscript 3.0 ?</p>
|
[
{
"answer_id": 38515,
"author": "David Crow",
"author_id": 2783,
"author_profile": "https://Stackoverflow.com/users/2783",
"pm_score": 2,
"selected": false,
"text": "<script language=\"JavaScript\">\n function startsPlaying()\n {\n // do something when the FLV starts playing\n }\n</script>\n // inform JavaScript that the FLV has started playing\nExternalInterface.call(\"startsPlaying\");\n"
},
{
"answer_id": 586560,
"author": "Jon Romero",
"author_id": 42153,
"author_profile": "https://Stackoverflow.com/users/42153",
"pm_score": 2,
"selected": false,
"text": "import flash.external.*;\n getUrl(\"javascript:startsPlaying();\");\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4112/"
] |
38,409
|
<p>I would like to convert the following string into an array/nested array: </p>
<pre><code>str = "[[this, is],[a, nested],[array]]"
newarray = # this is what I need help with!
newarray.inspect # => [['this','is'],['a','nested'],['array']]
</code></pre>
|
[
{
"answer_id": 38477,
"author": "Ben Childs",
"author_id": 2925,
"author_profile": "https://Stackoverflow.com/users/2925",
"pm_score": 0,
"selected": false,
"text": "base case (input doesn't begin with '[') return the input\nrecursive case:\n split the input on ',' (you will need to find commas only at this level)\n for each sub string call this method again with the sub string\n return array containing the results from this recursive method\n"
},
{
"answer_id": 38483,
"author": "user3868",
"author_id": 3868,
"author_profile": "https://Stackoverflow.com/users/3868",
"pm_score": 0,
"selected": false,
"text": "s = \"[[this, is],[a, nested],[array]]\"\n\nyourFunc(s, 1) # returns ['this', 'is'] and 11.\nyourFunc(s, 2) # returns 'this' and 6.\n"
},
{
"answer_id": 38520,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 2,
"selected": false,
"text": " ary = eval(\"[[this, is],[a, nested],[array]]\".gsub(/(\\w+?)/, \"'\\\\1'\") )\n => [[\"this\", \"is\"], [\"a\", \"nested\"], [\"array\"]]\n eval"
},
{
"answer_id": 40849,
"author": "Wieczo",
"author_id": 4195,
"author_profile": "https://Stackoverflow.com/users/4195",
"pm_score": 5,
"selected": true,
"text": "str = \"[[this, is], [a, nested], [array]]\"\n require 'yaml'\nstr = \"[[this, is],[a, nested],[array]]\"\n### transform your string in a valid YAML-String\nstr.gsub!(/(\\,)(\\S)/, \"\\\\1 \\\\2\")\nYAML::load(str)\n# => [[\"this\", \"is\"], [\"a\", \"nested\"], [\"array\"]]\n"
},
{
"answer_id": 89602,
"author": "glenn mcdonald",
"author_id": 7919,
"author_profile": "https://Stackoverflow.com/users/7919",
"pm_score": 2,
"selected": false,
"text": "JSON.parse(yourarray.gsub(/([a-z]+)/,'\"\\1\"'))\n JSON.parse(\"[[this, is],[a, nested],[array]]\".gsub(/, /,\",\").gsub(/([^\\[\\]\\,]+)/,'\"\\1\"'))\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4082/"
] |
38,431
|
<p>Using MVC out of the box I found the generated URLs can be misleading and I wanted to know if this can be fixed or if my approach/understanding is wrong.</p>
<p>Suppose I have a CreateEgg page, which has a form on it, and once the form is filled in and submitted the user is taken to a ListEggs page with the new egg in it.</p>
<p>So my egg controller will look some thing like this:</p>
<pre><code>public class EggController : Controller
{
public void Add()
{
//do stuff
RenderView("CreateEgg", viewData);
}
public void Create()
{
//do stuff
RenderView("ListEggs", viewData);
}
}
</code></pre>
<p>So my first page will have a url of something like <a href="http://localhost/egg/add" rel="nofollow noreferrer">http://localhost/egg/add</a> and the form on the page will have an action of:</p>
<pre><code>using (Html.Form<EggController>(c => c.Create())
</code></pre>
<p>Meaning the second page will have a url of <a href="http://localhost/Egg/Create" rel="nofollow noreferrer">http://localhost/Egg/Create</a>, to me this is misleading, the action should be called Create, because im creating the egg, but a list view is being displayed so the url of <a href="http://localhost/Egg/List" rel="nofollow noreferrer">http://localhost/Egg/List</a> would make more scene. How do I achieve this without making my view or action names misleading?</p>
|
[
{
"answer_id": 43456,
"author": "Dan",
"author_id": 230,
"author_profile": "https://Stackoverflow.com/users/230",
"pm_score": 0,
"selected": false,
"text": "[AcceptVerbs(\"GET\")]\npublic object Create() {}\n[AcceptVerbs(\"POST\")]\npublic object Create(string productName, Decimal unitPrice) {}\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/230/"
] |
38,435
|
<p>Given an Oracle table created using the following:</p>
<pre><code>CREATE TABLE Log(WhenAdded TIMESTAMP(6) WITH TIME ZONE);
</code></pre>
<p>Using the Python ODBC module from its <a href="http://www.python.org/download/windows/" rel="nofollow noreferrer">Win32 extensions</a> (from the win32all package), I tried the following:</p>
<pre><code>import dbi, odbc
connection = odbc.odbc("Driver=Oracle in OraHome92;Dbq=SERVER;Uid=USER;Pwd=PASSWD")
cursor = connection.cursor()
cursor.execute("SELECT WhenAdded FROM Log")
results = cursor.fetchall()
</code></pre>
<p>When I run this, I get the following:</p>
<pre><code>Traceback (most recent call last):
...
results = cursor.fetchall()
dbi.operation-error: [Oracle][ODBC][Ora]ORA-00932: inconsistent datatypes: expected %s got %s
in FETCH
</code></pre>
<p>The other data types I've tried (VARCHAR2, BLOB) do not cause this problem. Is there a way of retrieving timestamps?</p>
|
[
{
"answer_id": 38442,
"author": "Jason Etheridge",
"author_id": 2193,
"author_profile": "https://Stackoverflow.com/users/2193",
"pm_score": 1,
"selected": false,
"text": "cursor.execute(\"SELECT TO_CHAR(WhenAdded, 'YYYY-MM-DD HH:MI:SSAM') FROM Log\")\n"
},
{
"answer_id": 38718,
"author": "David Sykes",
"author_id": 3154,
"author_profile": "https://Stackoverflow.com/users/3154",
"pm_score": 3,
"selected": true,
"text": "TIMESTAMP WITH (LOCAL) TIME ZONE TIMESTAMP TO_CHAR TIMESTAMP TIMESTAMP WITH TIME ZONE TIMESTAMP TIMESTAMP WITH TIME ZONE TIMESTAMP"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2193/"
] |
38,447
|
<p>Do any asynchronous connectors exist for Mysql that can be used within a C or C++ application? I'm looking for something that can be plugged into a <a href="http://en.wikipedia.org/wiki/Reactor_pattern" rel="noreferrer" title="reactor pattern">reactor pattern</a> written in <a href="http://www.boost.org/doc/libs/release/libs/asio/index.html" rel="noreferrer" title="Boost.Asio">Boost.Asio</a>.</p>
<p>[Edit:] Running a synchronous connector in threads is not an option.</p>
|
[
{
"answer_id": 149326,
"author": "Vlagged",
"author_id": 6727,
"author_profile": "https://Stackoverflow.com/users/6727",
"pm_score": 2,
"selected": false,
"text": "libmysqlclient / mysqlclient.dll"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4059/"
] |
38,502
|
<p>Say you want a simple maze on an N by M grid, with one path through, and a good number of dead ends, but that looks "right" (i.e. like someone made it by hand without too many little tiny dead ends and all that). Is there a known way to do this?</p>
|
[
{
"answer_id": 61666821,
"author": "Sihat Afnan",
"author_id": 11837247,
"author_profile": "https://Stackoverflow.com/users/11837247",
"pm_score": 2,
"selected": false,
"text": "Cell current = cells[0][0] , next;\n current.visited=true;\n do{\n next = getNeighbour(current);\n if(next!=null){\n removeWall(current , next);\n st.push(current);\n current = next;\n current.visited = true;\n }\n else {\n current = st.pop();\n }\n }\n while (!st.empty());\n\n\n private Cell getNeighbour(Cell cell){\n ArrayList<Cell> ara = new ArrayList<>();\n if(cell.col>0 && !cells[cell.col-1][cell.row].visited)\n ara.add(cells[cell.col-1][cell.row]);\n\n if(cell.row>0 && !cells[cell.col][cell.row-1].visited)\n ara.add(cells[cell.col][cell.row-1]);\n\n if(cell.col<col-1 && !cells[cell.col+1][cell.row].visited)\n ara.add(cells[cell.col+1][cell.row]);\n if(cell.row<row-1 && !cells[cell.col][cell.row+1].visited)\n ara.add(cells[cell.col][cell.row+1]); \n\n\n if(ara.size()>0){\n return ara.get(new Random().nextInt(ara.size()));\n }else{\n return null;\n }\n}\nprivate void removeWall(Cell curr , Cell nxt){\n if((curr.col == nxt.col) && (curr.row == nxt.row+1)){/// top\n curr.top=nxt.botttom=false;\n }\n if(curr.col==nxt.col && curr.row == nxt.row-1){///bottom\n curr.botttom = nxt.top = false;\n }\n if(curr.col==nxt.col-1 && curr.row==nxt.row ){///right\n curr.right = nxt.left = false;\n }\n if(curr.col == nxt.col+1 && curr.row == nxt.row){///left\n curr.left = nxt.right = false;\n }\n}\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4123/"
] |
38,508
|
<p>I have a function where I need to do something to a string. I need the function to return a boolean indicating whether or not the operation succeeded, and I also need to return the modified string. </p>
<p>In C#, I would use an out parameter for the string, but there is no equivalent in Python. I'm still very new to Python and the only thing I can think of is to return a tuple with the boolean and modified string.</p>
<p>Related question: <a href="https://stackoverflow.com/questions/61605/is-it-pythonic-for-a-function-to-return-multiple-values">Is it pythonic for a function to return multiple values?</a></p>
|
[
{
"answer_id": 38514,
"author": "rmmh",
"author_id": 3694,
"author_profile": "https://Stackoverflow.com/users/3694",
"pm_score": 4,
"selected": false,
"text": "def f(x):\n # do stuff\n return (True, modified_string)\n\nsuccess, modified_string = f(something)\n"
},
{
"answer_id": 38516,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 8,
"selected": true,
"text": "def f(in_str):\n out_str = in_str.upper()\n return True, out_str # Creates tuple automatically\n\nsucceeded, b = f(\"a\") # Automatic tuple unpacking\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3880/"
] |
38,549
|
<p>Also, how do <code>LEFT OUTER JOIN</code>, <code>RIGHT OUTER JOIN</code>, and <code>FULL OUTER JOIN</code> fit in?</p>
|
[
{
"answer_id": 38565,
"author": "Brian Boatright",
"author_id": 3747,
"author_profile": "https://Stackoverflow.com/users/3747",
"pm_score": 7,
"selected": false,
"text": "SELECT Orders.OrderID, Orders.CustomerName\n FROM Orders \n INNER JOIN OrderDetails\n ON Orders.OrderID = OrderDetails.OrderID\n SELECT Orders.OrderID, Orders.CustomerName\n FROM Orders \n LEFT JOIN OrderDetails\n ON Orders.OrderID = OrderDetails.OrderID\n WHERE OrderDetails.OrderID IS NULL"
},
{
"answer_id": 38578,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 14,
"selected": true,
"text": "A B\n- -\n1 3\n2 4\n3 5\n4 6\n select * from a INNER JOIN b on a.a = b.b;\nselect a.*, b.* from a,b where a.a = b.b;\n\na | b\n--+--\n3 | 3\n4 | 4\n select * from a LEFT OUTER JOIN b on a.a = b.b;\nselect a.*, b.* from a,b where a.a = b.b(+);\n\na | b\n--+-----\n1 | null\n2 | null\n3 | 3\n4 | 4\n select * from a RIGHT OUTER JOIN b on a.a = b.b;\nselect a.*, b.* from a,b where a.a(+) = b.b;\n\na | b\n-----+----\n3 | 3\n4 | 4\nnull | 5\nnull | 6\n select * from a FULL OUTER JOIN b on a.a = b.b;\n\n a | b\n-----+-----\n 1 | null\n 2 | null\n 3 | 3\n 4 | 4\nnull | 6\nnull | 5\n"
},
{
"answer_id": 3625912,
"author": "naga",
"author_id": 437795,
"author_profile": "https://Stackoverflow.com/users/437795",
"pm_score": 6,
"selected": false,
"text": "INNER JOIN LEFT OUTER JOIN LEFT JOIN RIGHT OUTER JOIN RIGHT JOIN FULL JOIN LEFT OUTER JOIN RIGHT OUTER JOIN"
},
{
"answer_id": 12616294,
"author": "vijikumar",
"author_id": 1126071,
"author_profile": "https://Stackoverflow.com/users/1126071",
"pm_score": 6,
"selected": false,
"text": "INNER JOIN OUTER JOIN LEFT RIGHT LEFT OUTER JOIN RIGHT OUTER JOIN"
},
{
"answer_id": 20030933,
"author": "Lajos Veres",
"author_id": 1665673,
"author_profile": "https://Stackoverflow.com/users/1665673",
"pm_score": 5,
"selected": false,
"text": "INNER JOIN INNER JOIN"
},
{
"answer_id": 21380648,
"author": "Tushar Gupta - curioustushar",
"author_id": 2224265,
"author_profile": "https://Stackoverflow.com/users/2224265",
"pm_score": 7,
"selected": false,
"text": "A intersect B SELECT *\nFROM dbo.Students S\nINNER JOIN dbo.Advisors A\n ON S.Advisor_ID = A.Advisor_ID\n SELECT *\nFROM dbo.Students S\nLEFT JOIN dbo.Advisors A\n ON S.Advisor_ID = A.Advisor_ID\n SELECT *\nFROM dbo.Students S\nFULL JOIN dbo.Advisors A\n ON S.Advisor_ID = A.Advisor_ID\n"
},
{
"answer_id": 27458534,
"author": "Martin Smith",
"author_id": 73226,
"author_profile": "https://Stackoverflow.com/users/73226",
"pm_score": 10,
"selected": false,
"text": "on true CROSS JOIN ON A.Colour NOT IN ('Green','Blue') NULL B.Colour IS NULL B IS NULL NULL NULL 1=0 UNION ALL WHERE NULL= 'Green'"
},
{
"answer_id": 27540786,
"author": "ajitksharma",
"author_id": 2778527,
"author_profile": "https://Stackoverflow.com/users/2778527",
"pm_score": 8,
"selected": false,
"text": "select * from employee inner join location on employee.empID = location.empID\nOR\nselect * from employee, location where employee.empID = location.empID\n select * from employee left outer join location on employee.empID = location.empID;\n//Use of outer keyword is optional\n select * from employee right outer join location on employee.empID = location.empID;\n//Use of outer keyword is optional\n"
},
{
"answer_id": 28598795,
"author": "Pratik",
"author_id": 3326275,
"author_profile": "https://Stackoverflow.com/users/3326275",
"pm_score": 6,
"selected": false,
"text": "1.Take All records from left Table\n2.for(each record in right table,) {\n if(Records from left & right table matching on primary & foreign key){\n use their values as it is as result of join at the right side for 2nd table.\n } else {\n put value NULL values in that particular record as result of join at the right side for 2nd table.\n }\n }\n No matter what 1.employees , 2.phone_numbers_employees employees : id , name \n\nphone_numbers_employees : id , phone_num , emp_id \n emp_id employee.id SELECT e.id , e.name , p.phone_num FROM employees AS e INNER JOIN phone_numbers_employees AS p ON e.id = p.emp_id;\n SELECT e.id , e.name , p.phone_num FROM employees AS e LEFT JOIN phone_numbers_employees AS p ON e.id = p.emp_id;\n SELECT e.id , e.name , p.phone_num FROM employees AS e OUTER JOIN phone_numbers_employees AS p ON e.id = p.emp_id;\n"
},
{
"answer_id": 29606109,
"author": "shA.t",
"author_id": 4519059,
"author_profile": "https://Stackoverflow.com/users/4519059",
"pm_score": 6,
"selected": false,
"text": "SQLite RIGHT OUTER JOIN FULL OUTER JOIN MySQL FULL OUTER JOIN --[table1] --[table2]\nid | name id | name\n---+------- ---+-------\n1 | a1 1 | a2\n2 | b1 3 | b2\n CROSS JOIN , SELECT * FROM table1, table2\n--[OR]\nSELECT * FROM table1 CROSS JOIN table2\n\n--[Results:]\nid | name | id | name \n---+------+----+------\n1 | a1 | 1 | a2\n1 | a1 | 3 | b2\n2 | b1 | 1 | a2\n2 | b1 | 3 | b2\n table1.id = table2.id INNER JOIN SELECT * FROM table1, table2 WHERE table1.id = table2.id\n--[OR]\nSELECT * FROM table1 INNER JOIN table2 ON table1.id = table2.id\n\n--[Results:]\nid | name | id | name \n---+------+----+------\n1 | a1 | 1 | a2\n LEFT JOIN SELECT * FROM table1, table2 WHERE table1.id = table2.id \nUNION ALL\nSELECT *, Null, Null FROM table1 WHERE Not table1.id In (SELECT id FROM table2)\n--[OR]\nSELECT * FROM table1 LEFT JOIN table2 ON table1.id = table2.id\n\n--[Results:]\nid | name | id | name \n---+------+------+------\n1 | a1 | 1 | a2\n2 | b1 | Null | Null\n FULL OUTER JOIN SELECT * FROM table1, table2 WHERE table1.id = table2.id\nUNION ALL\nSELECT *, Null, Null FROM table1 WHERE Not table1.id In (SELECT id FROM table2)\nUNION ALL\nSELECT Null, Null, * FROM table2 WHERE Not table2.id In (SELECT id FROM table1)\n--[OR] (recommended for SQLite)\nSELECT * FROM table1 LEFT JOIN table2 ON table1.id = table2.id\nUNION ALL\nSELECT * FROM table2 LEFT JOIN table1 ON table2.id = table1.id\nWHERE table1.id IS NULL\n--[OR]\nSELECT * FROM table1 FULL OUTER JOIN table2 On table1.id = table2.id\n\n--[Results:]\nid | name | id | name \n-----+------+------+------\n1 | a1 | 1 | a2\n2 | b1 | Null | Null\nNull | Null | 3 | b2\n"
},
{
"answer_id": 34950096,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": 5,
"selected": false,
"text": "TableB OUTER JOIN"
},
{
"answer_id": 40486913,
"author": "S.Serpooshan",
"author_id": 2803565,
"author_profile": "https://Stackoverflow.com/users/2803565",
"pm_score": 5,
"selected": false,
"text": "INNER JOIN LEFT/RIGHT OUTER JOIN a (a, b[i]) ON ... ON( a, b[i] ) = true/false? true (a, b[i]) Outer Join Null (a, Null) (Null, b) ON ... ON T1.title = T2.title AND T1.version < T2.version ... ON T1.y IS NULL ... ON 1 = 0"
},
{
"answer_id": 45011393,
"author": "Laxmi",
"author_id": 6755093,
"author_profile": "https://Stackoverflow.com/users/6755093",
"pm_score": 3,
"selected": false,
"text": "SELECT\n e1.emp_name,\n e2.emp_salary \nFROM emp1 e1\nINNER JOIN emp2 e2\n ON e1.emp_id = e2.emp_id\n SELECT\n e1.emp_name,\n e2.emp_salary \nFROM emp1 e1\nFULL OUTER JOIN emp2 e2\n ON e1.emp_id = e2.emp_id\n"
},
{
"answer_id": 46091641,
"author": "philipxy",
"author_id": 3404097,
"author_profile": "https://Stackoverflow.com/users/3404097",
"pm_score": 3,
"selected": false,
"text": "left join on inner join on union all null right join on inner join on union all null full join on inner join on union all null union all null outer outer join on inner join on inner join on"
},
{
"answer_id": 46790107,
"author": "rashedcs",
"author_id": 6714430,
"author_profile": "https://Stackoverflow.com/users/6714430",
"pm_score": 2,
"selected": false,
"text": "inner join outer join Inner join outer join Inner join outer join Inner join outer join Inner join outer join outer join inner join"
},
{
"answer_id": 47981412,
"author": "Premraj",
"author_id": 1697099,
"author_profile": "https://Stackoverflow.com/users/1697099",
"pm_score": 5,
"selected": false,
"text": "INNER JOIN OUTER JOIN INNER JOIN NULL LEFT JOIN INNER JOIN Null RIGHT JOIN INNER JOIN Null FULL JOIN INNER JOIN Null INNER JOIN OUTER JOIN SELECT * \nFROM tablea a \n INNER JOIN tableb b \n ON a.primary_key = b.foreign_key \n INNER JOIN tablec c \n ON b.primary_key = c.foreign_key \n"
},
{
"answer_id": 53468691,
"author": "Mayank Porwal",
"author_id": 5820814,
"author_profile": "https://Stackoverflow.com/users/5820814",
"pm_score": 2,
"selected": false,
"text": "empid name dept_id salary\n1 Rob 1 100\n2 Mark 1 300\n3 John 2 100\n4 Mary 2 300\n5 Bill 3 700\n6 Jose 6 400\n deptid name\n1 IT\n2 Accounts\n3 Security\n4 HR\n5 R&D\n Select a.empid, a.name, b.name as dept_name\nFROM emp a\nJOIN department b\nON a.dept_id = b.deptid\n;\n\nempid name dept_name\n1 Rob IT\n2 Mark IT\n3 John Accounts\n4 Mary Accounts\n5 Bill Security\n Jose 6 HR R&D Select a.empid, a.name, b.name as dept_name\nFROM emp a\nLEFT JOIN department b\nON a.dept_id = b.deptid\n;\n\nempid name dept_name\n1 Rob IT\n2 Mark IT\n3 John Accounts\n4 Mary Accounts\n5 Bill Security\n6 Jose \n HR R&D"
},
{
"answer_id": 58563070,
"author": "ForguesR",
"author_id": 1980659,
"author_profile": "https://Stackoverflow.com/users/1980659",
"pm_score": 2,
"selected": false,
"text": "JOIN SELECT A INNER JOIN B LEFT JOIN B"
},
{
"answer_id": 61647208,
"author": "Scratte",
"author_id": 12695027,
"author_profile": "https://Stackoverflow.com/users/12695027",
"pm_score": 5,
"selected": false,
"text": "FULL OUTER JOIN RIGHT OUTER JOIN LEFT OUTER JOIN JOIN SELECT *\n FROM citizen\n CROSS JOIN postalcode\n JOIN INNER JOIN JOIN SELECT *\n FROM citizen c\n JOIN postalcode p ON c.postal = p.postal\n JOIN LEFT OUTER JOIN LEFT JOIN SELECT *\n FROM citizen c\n LEFT JOIN postalcode p ON c.postal = p.postal\n citizen postalcode JOIN CREATE TABLE citizen (id NUMBER,\n name VARCHAR2(20),\n postal NUMBER, -- <-- could do with a redesign to postalcode.id instead.\n leader NUMBER);\n\nCREATE TABLE postalcode (id NUMBER,\n postal NUMBER,\n city VARCHAR2(20),\n area VARCHAR2(20));\n\nINSERT INTO citizen (id, name, postal, leader)\n SELECT 1, 'Smith', 2200, null FROM DUAL\n UNION SELECT 2, 'Green', 31006, 1 FROM DUAL\n UNION SELECT 3, 'Jensen', 623, 1 FROM DUAL;\n\nINSERT INTO postalcode (id, postal, city, area)\n SELECT 1, 2200, 'BigCity', 'Geancy' FROM DUAL\n UNION SELECT 2, 31006, 'SmallTown', 'Snizkim' FROM DUAL\n UNION SELECT 3, 31006, 'Settlement', 'Moon' FROM DUAL -- <-- Uuh-uhh.\n UNION SELECT 4, 78567390, 'LookoutTowerX89', 'Space' FROM DUAL;\n JOIN WHERE CROSS JOIN INNER JOIN SELECT *\n FROM citizen c\n CROSS JOIN postalcode p\n WHERE c.postal = p.postal -- < -- The WHERE condition is limiting the resulting rows\n CROSS JOIN LEFT OUTER JOIN NULL INNER JOIN CROSS JOIN SELECT *\n FROM citizen c\n JOIN postalcode p ON 1 = 1 -- < -- The ON condition makes it a CROSS JOIN\n INNER JOIN LEFT OUTER JOIN LEFT JOIN CROSS JOIN SELECT *\n FROM citizen c\n LEFT JOIN postalcode p ON 1 = 1 -- < -- The ON condition makes it a CROSS JOIN\n LEFT JOIN INNER JOIN SELECT *\n FROM citizen c\n LEFT JOIN postalcode p ON c.postal = p.postal\n WHERE p.postal IS NOT NULL -- < -- removed the row where there's no mathcing result from postalcode\n A citizen B postalcode A B B A UNION UNION SQL CROSS JOIN INTERSECTION INTERSECTION CROSS JOIN INTERSECTION JOIN id=x A citizen B postalcode JOIN CROSS JOIN JOIN JOIN INNER JOIN ON 1 = 1 CROSS JOIN JOIN A B JOIN A ON A.parent = B.child A B SQL SELECT *\n FROM citizen c1\n JOIN citizen c2 ON c1.id = c2.leader\n OUTER JOIN C C LEFT OUTER JOIN A A B A CROSS JOIN SELECT *\n FROM citizen c\n CROSS JOIN postalcode p\n WHERE c.name = 'Smith'\n AND p.area = 'Moon';\n JOIN WHERE INNER JOIN INTERSECT INTERSECT SQL WHERE SELECT *\n FROM citizen c\n CROSS JOIN postalcode p\n WHERE c.name = 'Smith'\nINTERSECT\nSELECT *\n FROM citizen c\n CROSS JOIN postalcode p\n WHERE p.area = 'Moon';\n OUTER JOIN UNION UNION INTERSECT SELECT SELECT *\n FROM citizen c\n CROSS JOIN postalcode p\n WHERE c.name = 'Smith'\nUNION\nSELECT *\n FROM citizen c\n CROSS JOIN postalcode p\n WHERE p.area = 'Moon';\n SELECT *\n FROM citizen c\n CROSS JOIN postalcode p\n WHERE c.name = 'Smith'\n OR p.area = 'Moon';\n SELECT *\n FROM citizen\n WHERE name = 'Smith'\n SELECT *\n FROM postalcode\n WHERE area = 'Moon';\n UNION ORA-01790: expression must have same datatype as corresponding expression\n EXCEPT"
},
{
"answer_id": 67235945,
"author": "Nathan Long",
"author_id": 4376,
"author_profile": "https://Stackoverflow.com/users/4376",
"pm_score": 1,
"selected": false,
"text": "psql CREATE DATABASE catdb;\n\\c catdb;\n\\pset null '[NULL]' -- how to display null values\n\nCREATE TABLE humans (\n name text primary key\n);\nCREATE TABLE cats (\n human_name text references humans(name),\n name text\n);\n\nINSERT INTO humans (name)\nVALUES ('Abe'), ('Ann'), ('Ben'), ('Jen');\n\nINSERT INTO cats (human_name, name)\nVALUES\n('Abe', 'Axel'),\n(NULL, 'Bitty'),\n('Jen', 'Jellybean'),\n('Jen', 'Juniper');\n [SOMETHING JOIN] SELECT\nhumans.name AS human_name,\ncats.name AS cat_name\nFROM humans\n[SOMETHING JOIN] cats ON humans.name = cats.human_name\nORDER BY humans.name;\n INNER JOIN human_name | cat_name\n------------+-----------\n Abe | Axel\n Jen | Jellybean\n Jen | Juniper\n FULL OUTER JOIN NULL human_name | cat_name\n------------+-----------\n Abe | Axel\n Ann | [NULL]\n Ben | [NULL]\n Jen | Jellybean\n Jen | Juniper\n [NULL] | Bitty\n LEFT OUTER JOIN NULL cat_name human_name | cat_name\n------------+-----------\n Abe | Axel\n Ann | [NULL]\n Ben | [NULL]\n Jen | Jellybean\n Jen | Juniper\n RIGHT OUTER JOIN NULL human_name human_name | cat_name\n------------+-----------\n Abe | Axel\n Jen | Jellybean\n Jen | Juniper\n [NULL] | Bitty\n INNER JOIN OUTER INNER OUTER JOIN INNER LEFT JOIN RIGHT JOIN OUTER JOIN OUTER"
},
{
"answer_id": 73510726,
"author": "Braiam",
"author_id": 792066,
"author_profile": "https://Stackoverflow.com/users/792066",
"pm_score": 0,
"selected": false,
"text": "from tableA join tableB on tableA.idB = tableB.idB\n from tableA left join tableB on tableA.idB = tableB.idB\n from tableA right join tableB on tableA.idB = tableB.idB\n from tableA full join tableB on tableA.idB = tableB.idB\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3836/"
] |
38,561
|
<p>The <code>printf</code> function takes an argument type, such as <code>%d</code> or <code>%i</code> for a <code>signed int</code>. However, I don't see anything for a <code>long</code> value.</p>
|
[
{
"answer_id": 38566,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 4,
"selected": false,
"text": "%ld printf"
},
{
"answer_id": 38570,
"author": "postfuturist",
"author_id": 1892,
"author_profile": "https://Stackoverflow.com/users/1892",
"pm_score": 11,
"selected": true,
"text": "l unsigned long n;\nlong m;\n\nprintf(\"%lu %ld\", n, m);\n"
},
{
"answer_id": 38607,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 8,
"selected": false,
"text": "unsigned long n;\nprintf(\"%lu\", n); // unsigned long\n long n;\nprintf(\"%ld\", n); // signed long\n"
},
{
"answer_id": 13112207,
"author": "Dolan Antenucci",
"author_id": 318870,
"author_profile": "https://Stackoverflow.com/users/318870",
"pm_score": 4,
"selected": false,
"text": "unsigned long long unsigned long long n;\nprintf(\"%llu\", n);\n printf(\"%llu\", n)"
},
{
"answer_id": 14610883,
"author": "Dave Dopson",
"author_id": 407731,
"author_profile": "https://Stackoverflow.com/users/407731",
"pm_score": 7,
"selected": false,
"text": "long int long n;\nunsigned long un;\nprintf(\"%ld\", n); // signed\nprintf(\"%lu\", un); // unsigned\n long long long long n;\nunsigned long long un;\nprintf(\"%lld\", n); // signed\nprintf(\"%llu\", un); // unsigned\n printf(\"%l64d\", n); // signed\nprintf(\"%l64u\", un); // unsigned\n unsigned long long n;\nprintf(\"0x%016llX\", n); // \"0x\" followed by \"0-padded\", \"16 char wide\", \"long long\", \"HEX with 0-9A-F\"\n 0x00000000DEADBEEF\n char c; // 8 bits\nshort s; // 16 bits\nint i; // 32 bits (on modern platforms)\nlong l; // 32 bits\nlong long ll; // 64 bits \n"
},
{
"answer_id": 15237828,
"author": "krato",
"author_id": 2130213,
"author_profile": "https://Stackoverflow.com/users/2130213",
"pm_score": 4,
"selected": false,
"text": "\"%lu\" \"%ld\""
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] |
38,571
|
<p>I find myself doing this sort of thing all the time. I've been considering writing a macro/function to make this sort of thing easier, but it occurs to me that I'm probably reinventing the wheel.</p>
<p>Is there an existing function that will let me accomplish this same sort of thing more succinctly?</p>
<pre><code>(defun remove-low-words (word-list)
"Return a list with words of insufficient score removed."
(let ((result nil))
(dolist (word word-list)
(when (good-enough-score-p word) (push word result)))
result))
</code></pre>
|
[
{
"answer_id": 38594,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": -1,
"selected": false,
"text": "(defun remove-low-words (word-list)\n (if (good-enough-score-p (car word-list))\n (list word (remove-low-words (cdr word-list)))\n (remove-low-words (cdr word-list))))\n mapcar reduce nil nil"
},
{
"answer_id": 38823,
"author": "Luís Oliveira",
"author_id": 2967,
"author_profile": "https://Stackoverflow.com/users/2967",
"pm_score": 6,
"selected": true,
"text": "(remove-if-not 'good-enough-score-p word-list)\n (loop for word in word-list \n when (good-enough-score-p word)\n collect word)\n (mapcan (lambda (word)\n (when (good-enough-score-p word)\n (list word)))\n word-list)\n (collect (choose-if 'good-enough-score-p (scan word-list))))\n"
},
{
"answer_id": 84036,
"author": "Nathan Shively-Sanders",
"author_id": 7851,
"author_profile": "https://Stackoverflow.com/users/7851",
"pm_score": 3,
"selected": false,
"text": "remove-if-not (defun remove-low-words (word-list)\n (remove-if-not #'good-enough-score-p word-list))\n remove-if-not"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/56456/"
] |
38,592
|
<p>I'd like to be able to write a ruby program that can restart without dropping it's socket connections.</p>
|
[
{
"answer_id": 38599,
"author": "ryantm",
"author_id": 823,
"author_profile": "https://Stackoverflow.com/users/823",
"pm_score": 2,
"selected": true,
"text": "#!/usr/bin/ruby\n#simple_connector.rb\nrequire 'socket'\n\nputs \"Started.\"\n\nif ARGV[0] == \"restart\"\n sock = IO.open(ARGV[1].to_i)\n puts sock.read\n exit\nelse\n sock = TCPSocket.new('google.com', 80)\n sock.write(\"GET /\\n\")\nend\n\nSignal.trap(\"INT\") do\n puts \"Restarting...\"\n exec(\"ruby simple_connector.rb restart #{sock.fileno}\")\nend\n\nwhile true\n sleep 1\nend\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/823/"
] |
38,596
|
<p>What is the best way to keep a PHP script running as a daemon, and what's the best way to check if needs restarting.</p>
<p>I have some scripts that need to run 24/7 and for the most part I can run them using <a href="http://en.wikipedia.org/wiki/Nohup" rel="noreferrer">nohup</a>. But if they go down, what's the best way to monitor it so it can be automatically restarted?</p>
|
[
{
"answer_id": 39609,
"author": "Gary Richardson",
"author_id": 2506,
"author_profile": "https://Stackoverflow.com/users/2506",
"pm_score": 2,
"selected": false,
"text": "* * * * * USER ps auxww | grep SCRIPTNAME > /dev/null || SCRIPTNAME\n /etc/cron.d/restart_php_daemon * */2 */5 crontab -e * * * * * ps auxwww | grep SCRIPTNAME > /dev/null || SCRIPTNAME\n"
},
{
"answer_id": 110787,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 2,
"selected": false,
"text": "php daemon.php | mail -s \"daemon stopped\" foo@example.org\n"
},
{
"answer_id": 22238374,
"author": "sergioska",
"author_id": 2496366,
"author_profile": "https://Stackoverflow.com/users/2496366",
"pm_score": 1,
"selected": false,
"text": "// Daemonize\n$pid = pcntl_fork(); // parent gets the child PID and child gets 0\nif($pid){ // if pid is not 0\n // Only the parent will know the PID. Kids aren't self-aware\n // Parent says goodbye!\n print \"Parent : \" . getmypid() . \" exiting\\n\";\n exit();\n}\nprint \"Child : \" . getmypid() . \"\\n\";\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4133/"
] |
38,598
|
<p>How are people unit testing their business applications? I've seen a lot of examples of unit testing with "simple to test" examples. Ex. a calculator. How are people unit testing data-heavy applications? How are you putting together your sample data? In many cases, data for one test may not work at all for another test which makes it hard to just have one test database?</p>
<p>Testing the data access portion of the code is fairly straightforward. It's testing out all the methods that work against the data that seem to be hard to test. For example, imagine a posting process where there is heavy data access to determine what is posted, numbers are adjusted, etc. There are a number of interim steps that occur (and need to be tested) along with tests afterwards that ensure the posting was successful. Some of those steps may actually be stored procedures.</p>
<p>In the past I've tried inserting the test data in a test database, then running the test, but honestly it's pretty painful to write this kind of code (and error prone). I've also tried just building a test database up front and rolling back the changes. That works OK but in a number of places you can't easily do this either (and many people would say that's integration testing; so be it, I still need to be able to test this somehow).</p>
<p>If the answer is that there isn't a nice way of handling this and it currently just sort of sucks, that would be useful to know as well.</p>
<p>Any thoughts, ideas, suggestions, or tips are appreciated.</p>
|
[
{
"answer_id": 38682,
"author": "Jay Stramel",
"author_id": 3547,
"author_profile": "https://Stackoverflow.com/users/3547",
"pm_score": 3,
"selected": false,
"text": "findCustomerByName()"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3656/"
] |
38,601
|
<p>How can I use the nifty JavaScript date and time widgets that the default admin uses with my custom view?</p>
<p>I have looked through <a href="https://docs.djangoproject.com/en/dev/topics/forms/" rel="noreferrer">the Django forms documentation</a>, and it briefly mentions django.contrib.admin.widgets, but I don't know how to use it?</p>
<p>Here is my template that I want it applied on.</p>
<pre><code><form action="." method="POST">
<table>
{% for f in form %}
<tr> <td> {{ f.name }}</td> <td>{{ f }}</td> </tr>
{% endfor %}
</table>
<input type="submit" name="submit" value="Add Product">
</form>
</code></pre>
<p>Also, I think it should be noted that I haven't really written a view up myself for this form, I am using a generic view. Here is the entry from the url.py:</p>
<pre><code>(r'^admin/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}),
</code></pre>
<p>And I am relevantly new to the whole Django/MVC/MTV thing, so please go easy...</p>
|
[
{
"answer_id": 38916,
"author": "Carl Meyer",
"author_id": 3207,
"author_profile": "https://Stackoverflow.com/users/3207",
"pm_score": 8,
"selected": true,
"text": "ModelForm AdminDateWidget AdminTimeWidget AdminSplitDateTime from django import forms\n from my_app.models import Product\n from django.contrib.admin import widgets \n\n class ProductForm(forms.ModelForm):\n class Meta:\n model = Product\n def __init__(self, *args, **kwargs):\n super(ProductForm, self).__init__(*args, **kwargs)\n self.fields['mydate'].widget = widgets.AdminDateWidget()\n self.fields['mytime'].widget = widgets.AdminTimeWidget()\n self.fields['mydatetime'].widget = widgets.AdminSplitDateTime()\n 'form_class': ProductForm 'model': Product create_object from my_app.forms import ProductForm from my_app.models import Product {{ form.media }} {{ form.media }} <script type=\"text/javascript\" src=\"/my_admin/jsi18n/\"></script>\n <script type=\"text/javascript\" src=\"/media/admin/js/core.js\"></script>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"/media/admin/css/forms.css\"/>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"/media/admin/css/base.css\"/>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"/media/admin/css/global.css\"/>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"/media/admin/css/widgets.css\"/>\n ADMIN_MEDIA_PREFIX (r'^my_admin/jsi18n', 'django.views.i18n.javascript_catalog'),\n {% load adminmedia %} /* At the top of the template. */\n\n/* In the head section of the template. */\n<script type=\"text/javascript\">\nwindow.__admin_media_prefix__ = \"{% filter escapejs %}{% admin_media_prefix %}{% endfilter %}\";\n</script>\n"
},
{
"answer_id": 408230,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": " (r'^admin/jsi18n', i18n_javascript),\n from django.contrib import admin\ndef i18n_javascript(request):\n return admin.site.i18n_javascript(request)\n"
},
{
"answer_id": 719583,
"author": "Alex. S.",
"author_id": 18300,
"author_profile": "https://Stackoverflow.com/users/18300",
"pm_score": 3,
"selected": false,
"text": "{% block extra_head %}\n\n<link rel=\"stylesheet\" type=\"text/css\" href=\"/media/admin/css/forms.css\"/>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"/media/admin/css/base.css\"/>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"/media/admin/css/global.css\"/>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"/media/admin/css/widgets.css\"/>\n\n<script type=\"text/javascript\" src=\"/admin/jsi18n/\"></script>\n<script type=\"text/javascript\" src=\"/media/admin/js/core.js\"></script>\n<script type=\"text/javascript\" src=\"/media/admin/js/admin/RelatedObjectLookups.js\"></script>\n\n{{ form.media }}\n\n{% endblock %}\n"
},
{
"answer_id": 1392329,
"author": "monkut",
"author_id": 24718,
"author_profile": "https://Stackoverflow.com/users/24718",
"pm_score": 4,
"selected": false,
"text": "from django import forms\nfrom my_app.models import Product\nfrom django.contrib.admin import widgets \n\n\nclass ProductForm(forms.ModelForm):\n mydate = forms.DateField(widget=widgets.AdminDateWidget)\n mytime = forms.TimeField(widget=widgets.AdminTimeWidget)\n mydatetime = forms.SplitDateTimeField(widget=widgets.AdminSplitDateTime)\n\n class Meta:\n model = Product\n"
},
{
"answer_id": 1833247,
"author": "Sam A.",
"author_id": 318368,
"author_profile": "https://Stackoverflow.com/users/318368",
"pm_score": 1,
"selected": false,
"text": "from django import forms\n\nclass SplitDateTimeJSField(forms.SplitDateTimeField):\n def __init__(self, *args, **kwargs):\n super(SplitDateTimeJSField, self).__init__(*args, **kwargs)\n self.widget.widgets[0].attrs = {'class': 'vDateField'}\n self.widget.widgets[1].attrs = {'class': 'vTimeField'} \n\n\nclass AnyFormOrModelForm(forms.Form):\n date = forms.DateField(widget=forms.TextInput(attrs={'class':'vDateField'}))\n time = forms.TimeField(widget=forms.TextInput(attrs={'class':'vTimeField'}))\n timestamp = SplitDateTimeJSField(required=False,)\n <script type=\"text/javascript\" src=\"/admin/jsi18n/\"></script>\n<script type=\"text/javascript\" src=\"/admin_media/js/core.js\"></script>\n<script type=\"text/javascript\" src=\"/admin_media/js/calendar.js\"></script>\n<script type=\"text/javascript\" src=\"/admin_media/js/admin/DateTimeShortcuts.js\"></script>\n (r'^admin/jsi18n/', 'django.views.i18n.javascript_catalog'),\n"
},
{
"answer_id": 2396907,
"author": "Dennis Kioko",
"author_id": 263501,
"author_profile": "https://Stackoverflow.com/users/263501",
"pm_score": 3,
"selected": false,
"text": "class PaymentsForm(forms.ModelForm):\n class Meta:\n model = Payments\n\n def __init__(self, *args, **kwargs):\n super(PaymentsForm, self).__init__(*args, **kwargs)\n self.fields['date'].widget = SelectDateWidget()\n class PaymentsForm(forms.ModelForm):\n date = forms.DateField(widget=SelectDateWidget())\n\n class Meta:\n model = Payments\n from django.forms.extras.widgets import SelectDateWidget"
},
{
"answer_id": 2818128,
"author": "mshafrir",
"author_id": 5675,
"author_profile": "https://Stackoverflow.com/users/5675",
"pm_score": 3,
"selected": false,
"text": "{% load adminmedia %} /* At the top of the template. */\n\n/* In the head section of the template. */\n<script type=\"text/javascript\">\nwindow.__admin_media_prefix__ = \"{% filter escapejs %}{% admin_media_prefix %}{% endfilter %}\";\n</script>\n"
},
{
"answer_id": 9139017,
"author": "trubliphone",
"author_id": 1060339,
"author_profile": "https://Stackoverflow.com/users/1060339",
"pm_score": 2,
"selected": false,
"text": "class MyForm(forms.ModelForm):\n\n class Meta:\n model = MyModel\n\n def __init__(self, *args, **kwargs):\n super(MyForm, self).__init__(*args, **kwargs)\n self.fields['my_date_field'].widget.attrs['class'] = 'datepicker'\n $(\".datepicker\").datepicker();\n"
},
{
"answer_id": 11446609,
"author": "Romamo",
"author_id": 1508578,
"author_profile": "https://Stackoverflow.com/users/1508578",
"pm_score": 4,
"selected": false,
"text": "{% block extrahead %}\n\n<link rel=\"stylesheet\" type=\"text/css\" href=\"{{ STATIC_URL }}admin/css/forms.css\"/>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"{{ STATIC_URL }}admin/css/base.css\"/>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"{{ STATIC_URL }}admin/css/global.css\"/>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"{{ STATIC_URL }}admin/css/widgets.css\"/>\n\n<script type=\"text/javascript\" src=\"/admin/jsi18n/\"></script>\n<script type=\"text/javascript\" src=\"{{ STATIC_URL }}admin/js/core.js\"></script>\n<script type=\"text/javascript\" src=\"{{ STATIC_URL }}admin/js/admin/RelatedObjectLookups.js\"></script>\n<script type=\"text/javascript\" src=\"{{ STATIC_URL }}admin/js/jquery.js\"></script>\n<script type=\"text/javascript\" src=\"{{ STATIC_URL }}admin/js/jquery.init.js\"></script>\n<script type=\"text/javascript\" src=\"{{ STATIC_URL }}admin/js/actions.js\"></script>\n<script type=\"text/javascript\" src=\"{{ STATIC_URL }}admin/js/calendar.js\"></script>\n<script type=\"text/javascript\" src=\"{{ STATIC_URL }}admin/js/admin/DateTimeShortcuts.js\"></script>\n\n{% endblock %}\n"
},
{
"answer_id": 39946546,
"author": "Jose Luis Quichimbo",
"author_id": 5833286,
"author_profile": "https://Stackoverflow.com/users/5833286",
"pm_score": 0,
"selected": false,
"text": " from django.views.i18n import JavaScriptCatalog\n\nurlpatterns = [\n url(r'^jsi18n/$', JavaScriptCatalog.as_view(), name='javascript-catalog'),\n.\n.\n.]\n {% load staticfiles %}\n\n <script src=\"{% static \"js/jquery-2.2.3.min.js\" %}\"></script>\n <script src=\"{% static \"js/bootstrap.min.js\" %}\"></script>\n {# Loading internazionalization for js #}\n {% load i18n admin_modify %}\n <script type=\"text/javascript\" src=\"{% url 'javascript-catalog' %}\"></script>\n <script type=\"text/javascript\" src=\"{% static \"/admin/js/jquery.init.js\" %}\"></script>\n\n <link rel=\"stylesheet\" type=\"text/css\" href=\"{% static \"/admin/css/base.css\" %}\">\n <link rel=\"stylesheet\" type=\"text/css\" href=\"{% static \"/admin/css/forms.css\" %}\">\n <link rel=\"stylesheet\" type=\"text/css\" href=\"{% static \"/admin/css/login.css\" %}\">\n <link rel=\"stylesheet\" type=\"text/css\" href=\"{% static \"/admin/css/widgets.css\" %}\">\n\n\n\n <script type=\"text/javascript\" src=\"{% static \"/admin/js/core.js\" %}\"></script>\n <script type=\"text/javascript\" src=\"{% static \"/admin/js/SelectFilter2.js\" %}\"></script>\n <script type=\"text/javascript\" src=\"{% static \"/admin/js/admin/RelatedObjectLookups.js\" %}\"></script>\n <script type=\"text/javascript\" src=\"{% static \"/admin/js/actions.js\" %}\"></script>\n <script type=\"text/javascript\" src=\"{% static \"/admin/js/calendar.js\" %}\"></script>\n <script type=\"text/javascript\" src=\"{% static \"/admin/js/admin/DateTimeShortcuts.js\" %}\"></script>\n"
},
{
"answer_id": 51459403,
"author": "potemkin",
"author_id": 10115957,
"author_profile": "https://Stackoverflow.com/users/10115957",
"pm_score": 1,
"selected": false,
"text": "from django.db import models\n name=models.CharField(max_length=100)\n create_date=models.DateField(blank=True)\n start_time=models.TimeField(blank=False)\n end_time=models.TimeField(blank=False)\n from django import forms\nfrom .models import Guide\nfrom django.contrib.admin import widgets\n\nclass GuideForm(forms.ModelForm):\n start_time = forms.DateField(widget=widgets.AdminTimeWidget)\n end_time = forms.DateField(widget=widgets.AdminTimeWidget)\n create_date = forms.DateField(widget=widgets.AdminDateWidget)\n class Meta:\n model=Guide\n fields=['name','categorie','thumb']\n"
},
{
"answer_id": 51893533,
"author": "Munim Munna",
"author_id": 9276329,
"author_profile": "https://Stackoverflow.com/users/9276329",
"pm_score": 3,
"selected": false,
"text": "javascript-catalog urls.py from django.views.i18n import JavaScriptCatalog\n\nurlpatterns = [\n path('jsi18n', JavaScriptCatalog.as_view(), name='javascript-catalog'),\n]\n <script type=\"text/javascript\" src=\"{% url 'javascript-catalog' %}\"></script>\n<script type=\"text/javascript\" src=\"{% static '/admin/js/core.js' %}\"></script>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"{% static '/admin/css/widgets.css' %}\">\n<style>.calendar>table>caption{caption-side:unset}</style><!--caption fix for bootstrap4-->\n{{ form.media }} {# Form required JS and CSS #}\n forms.py from django.contrib.admin import widgets\nfrom .models import Product\n\nclass ProductCreateForm(forms.ModelForm):\n class Meta:\n model = Product\n fields = ['name', 'publish_date', 'publish_time', 'publish_datetime']\n widgets = {\n 'publish_date': widgets.AdminDateWidget,\n 'publish_time': widgets.AdminTimeWidget,\n 'publish_datetime': widgets.AdminSplitDateTime,\n }\n"
},
{
"answer_id": 55099684,
"author": "Arindam Roychowdhury",
"author_id": 1076965,
"author_profile": "https://Stackoverflow.com/users/1076965",
"pm_score": 0,
"selected": false,
"text": "{% extends 'base.html' %}\n{% load static %}\n{% load i18n %}\n\n{% block head %}\n <title>Add Interview</title>\n{% endblock %}\n\n{% block content %}\n\n<script type=\"text/javascript\" src=\"{% url 'javascript-catalog' %}\"></script>\n<script type=\"text/javascript\" src=\"{% static 'admin/js/core.js' %}\"></script>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"{% static 'admin/css/forms.css' %}\"/>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"{% static 'admin/css/widgets.css' %}\"/>\n<link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\" >\n<script type=\"text/javascript\" src=\"{% static 'js/jquery.js' %}\"></script>\n <script type=\"text/javascript\" src=\"/admin/jsi18n/\"></script>\n<script type=\"text/javascript\" src=\"{% static 'admin/js/vendor/jquery/jquery.min.js' %}\"></script>\n<script type=\"text/javascript\" src=\"{% static 'admin/js/jquery.init.js' %}\"></script>\n<script type=\"text/javascript\" src=\"{% static 'admin/js/actions.min.js' %}\"></script>\n{% endblock %}\n"
},
{
"answer_id": 62181628,
"author": "sandeep",
"author_id": 10084728,
"author_profile": "https://Stackoverflow.com/users/10084728",
"pm_score": 0,
"selected": false,
"text": "Charfield Form ModelForm class TimeSlotForm(forms.ModelForm):\n start = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'HH:MM'}))\n end = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'HH:MM'}))\n\n class Meta:\n model = TimeSlots\n fields = ('start', 'end', 'provider')\n import datetime\ndef slots():\n if request.method == 'POST':\n form = create_form(request.POST)\n if form.is_valid(): \n slot = form.save(commit=False)\n start = form.cleaned_data['start']\n end = form.cleaned_data['end']\n start = datetime.datetime.strptime(start, '%H:%M').time()\n end = datetime.datetime.strptime(end, '%H:%M').time()\n slot.start = start\n slot.end = end\n slot.save()\n"
},
{
"answer_id": 63823273,
"author": "andyw",
"author_id": 960471,
"author_profile": "https://Stackoverflow.com/users/960471",
"pm_score": 2,
"selected": false,
"text": "class EditAssessmentBaseForm(forms.ModelForm):\n class Meta:\n model = Assessment\n fields = '__all__'\n\n begin = DateTimeField(widget=MinimalSplitDateTimeMultiWidget())\n"
},
{
"answer_id": 68451933,
"author": "rrretry",
"author_id": 11354529,
"author_profile": "https://Stackoverflow.com/users/11354529",
"pm_score": 2,
"selected": false,
"text": "{% load static %}\n\n{% block extrahead %}\n{{ block.super }}\n<script type=\"text/javascript\" src=\"{% static 'admin/js/cancel.js' %}\"></script>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"{% static 'admin/css/forms.css' %}\">\n<script src=\"{% url 'admin:jsi18n' %}\"></script>\n<script src=\"{% static 'admin/js/jquery.init.js' %}\"></script>\n<script src=\"{% static 'admin/js/core.js' %}\"></script>\n{{ form.media }}\n{% endblock %}\n\n<form action=\"\" method=\"post\">\n{% csrf_token %}\n{{ form.as_p }}\n<input type=\"submit\" value=\"Сохранить\">\n</form>\n from django.contrib.admin import widgets\ndate_time = forms.SplitDateTimeField(widget=widgets.AdminSplitDateTime)\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2592/"
] |
38,602
|
<p>I am attempting to set an asp.net textbox to a SQL 2005 money data type field, the initial result displayed to the user is 40.0000 instead of 40.00.
In my asp.net textbox control I would like to only display the first 2 numbers after the decimal point e.g. 40.00</p>
<p>What would be the best way to do this?
My code is below:</p>
<pre><code>this.txtPayment.Text = dr["Payment"].ToString();
</code></pre>
|
[
{
"answer_id": 38611,
"author": "YonahW",
"author_id": 3821,
"author_profile": "https://Stackoverflow.com/users/3821",
"pm_score": 3,
"selected": true,
"text": "this.txtPayment.Text = string.Format(\"{0:c}\", dr[Payment\"].ToString());\n"
},
{
"answer_id": 38613,
"author": "Jason Navarrete",
"author_id": 3920,
"author_profile": "https://Stackoverflow.com/users/3920",
"pm_score": 0,
"selected": false,
"text": "this.txtPayment.Text = dr[\"Payment\"].ToString(\"c\");\n"
},
{
"answer_id": 38616,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 2,
"selected": false,
"text": "txtPayment.Text = dr[\"Payment\"].ToString(\"00.00\")\n"
},
{
"answer_id": 39799,
"author": "Ron Skufca",
"author_id": 4096,
"author_profile": "https://Stackoverflow.com/users/4096",
"pm_score": 0,
"selected": false,
"text": "string pmt = dr[\"Payment\"].ToString();\ndouble dblPmt = System.Convert.ToDouble(pmt);\nthis.txtPayment.Text = dblPmt.ToString(\"c\",CultureInfo.CurrentCulture.NumberFormat);\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4096/"
] |
38,612
|
<p>I have a asp.net 2.0 web site with numerous asp:DropDownList controls.
The DropDownList control contains the standard info city, state, county etc... info.
In addition to the standard codes the site also has custom codes that the users can configure themselves.
For example a animal dropdown may contain the values Dog, Cat, Fish, ect...</p>
<p>I am popluating the DropDownList from a SQL 2005 table that I created e.g. tblCodes</p>
<p>Everything works great and users are able to add orders using the numerous DropDownList controls to choose items from the list.</p>
<p>The problem occurrs if a user wants to change one of their custom dropdowns. For example a user would like to change the verbage
on a animal type control from Dog to K9. This is where the problem starts.</p>
<p>For all new orders the drop down works fine. When the user retrieved an old order
I get the following error in the C# codebehind
"'DropDownList1' has a SelectedValue which is invalid because it does not exist in the list of items."</p>
<p>What's happening is the old order has a database field value of Dog and the DropDownList no longer has Dog in its list since the user changed it to K9.</p>
<p>Any ideas on a workaround?<br>
Is there a way to make the asp:DropDownList accept items not seeded in its list?
Is there another control I could use?</p>
|
[
{
"answer_id": 38655,
"author": "Josh Hinman",
"author_id": 2527,
"author_profile": "https://Stackoverflow.com/users/2527",
"pm_score": 3,
"selected": false,
"text": "protected void ddSpecialty_PreRender(object sender, EventArgs e)\n{\n if (!ddSpecialty.Items.Contains(new ListItem(registration.Specialty)))\n ddSpecialty.Items.Add(registration.Specialty);\n ddSpecialty.SelectedValue = registration.Specialty;\n}\n"
},
{
"answer_id": 556158,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "if (ddl.Items.Contains(new ListItem(selectedFacility)))\n ddl.SelectedValue = selectedFacility;\n"
},
{
"answer_id": 783436,
"author": "Joshua Shannon",
"author_id": 69077,
"author_profile": "https://Stackoverflow.com/users/69077",
"pm_score": 3,
"selected": false,
"text": "ddl.SelectedIndex = ddl.Items.IndexOf(ddl.Items.FindByValue(value));\n ddl.DataBound += (o,e) => ddl.SelectedIndex = ddl.Items.IndexOf(ddl.Items.FindByValue(value));\n"
},
{
"answer_id": 7522066,
"author": "rspring1975",
"author_id": 960073,
"author_profile": "https://Stackoverflow.com/users/960073",
"pm_score": 0,
"selected": false,
"text": "ddl.ClearSelection(); ddl.SelectedValue = null ddl.Items.Clear();"
},
{
"answer_id": 9032372,
"author": "HGMamaci",
"author_id": 960887,
"author_profile": "https://Stackoverflow.com/users/960887",
"pm_score": 0,
"selected": false,
"text": "<asp:DropDownList ID=\"edtDepartureIDKey\" runat=\"server\" CssClass=\"textbox\" \nToolTip='<%# Eval(\"DepartureIDKey\") %>' DataSource=\"<%# DLL1DataSource() %>\" DataTextField=\"DisplayField\" DataValueField=\"IDKey\"\nonprerender=\"edtDepartureIDKey_PreRender\">\n protected void edtDepartureIDKey_PreRender(object sender, EventArgs e)\n{\n DropDownList ddl = (sender as DropDownList);\n if (ddl.Items.FindByValue(ddl.ToolTip) == null)\n {\n //I am pulling Departure Data through the ID which is saved in ToolTip, and insert it into the 1st row of the DropDownList\n TODepartureData v = new TODepartureData(DBSERVER.ConnStrName);\n TODeparture d = v.Select(Convert.ToInt32(ddl.ToolTip));\n ddl.Items.Insert(0, new ListItem(d.DeptCode, ddl.ToolTip));\n }\n ddl.Items.FindByValue(ddl.ToolTip).Selected = true;\n}\n"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4096/"
] |
38,635
|
<p>What tools are there available for static analysis against C# code? I know about FxCop and StyleCop. Are there others? I've run across NStatic before but it's been in development for what seems like forever - it's looking pretty slick from what little I've seen of it, so it would be nice if it would ever see the light of day. </p>
<p>Along these same lines (this is primarily my interest for static analysis), tools for testing code for multithreading issues (deadlocks, race conditions, etc.) also seem a bit scarce. Typemock Racer just popped up so I'll be looking at that. Anything beyond this?</p>
<p>Real-life opinions about tools you've used are appreciated.</p>
|
[
{
"answer_id": 100350,
"author": "Julien Hoarau",
"author_id": 12248,
"author_profile": "https://Stackoverflow.com/users/12248",
"pm_score": 9,
"selected": true,
"text": "Program Files\\Microsoft SDKs\\Windows\\ [v7.1] \\Bin\\FXCop\\FxCopSetup.exe"
}
] |
2008/09/01
|
[
"https://Stackoverflow.com/questions/38635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3656/"
] |
38,645
|
<p>I want to combine two structures with differing fields names.</p>
<p>For example, starting with:</p>
<pre><code>A.field1 = 1;
A.field2 = 'a';
B.field3 = 2;
B.field4 = 'b';
</code></pre>
<p>I would like to have:</p>
<pre><code>C.field1 = 1;
C.field2 = 'a';
C.field3 = 2;
C.field4 = 'b';
</code></pre>
<p>Is there a more efficient way than using "fieldnames" and a for loop?</p>
<p><strong>EDIT:</strong> Let's assume that in the case of field name conflicts we give preference to <code>A</code>.</p>
|
[
{
"answer_id": 38659,
"author": "pbh101",
"author_id": 1266,
"author_profile": "https://Stackoverflow.com/users/1266",
"pm_score": 2,
"selected": false,
"text": "A.field1 = 1;\nA.field2 = 'a';\nA.field3 = struct B;\n C.A = struct A;\nC.B = struct B;\n C.A.field1;\nC.A.field2;\nC.B.field3;\nC.B.field4;\n matlab"
},
{
"answer_id": 39678,
"author": "SCFrench",
"author_id": 4928,
"author_profile": "https://Stackoverflow.com/users/4928",
"pm_score": 5,
"selected": true,
"text": "M = [fieldnames(A)' fieldnames(B)'; struct2cell(A)' struct2cell(B)'];\nC=struct(M{:});\n struct unique M = [fieldnames(A)' fieldnames(B)'; struct2cell(A)' struct2cell(B)'];\n\n[tmp, rows] = unique(M(1,:), 'last');\nM=M(:, rows);\n\nC=struct(M{:});\n struct"
},
{
"answer_id": 357381,
"author": "Jason S",
"author_id": 44330,
"author_profile": "https://Stackoverflow.com/users/44330",
"pm_score": 2,
"selected": false,
"text": "setdefaults.m % SETDEFAULTS sets the default structure values \n% SOUT = SETDEFAULTS(S, SDEF) reproduces in S \n% all the structure fields, and their values, that exist in \n% SDEF that do not exist in S. \n% SOUT = SETDEFAULTS(S, SDEF, OVERRIDE) does\n% the same function as above, but if OVERRIDE is 1,\n% it copies all fields of SDEF to SOUT.\n\nfunction sout = setdefaults(s,sdef,override)\nif (not(exist('override','var')))\n override = 0;\nend\n\nsout = s;\nfor f = fieldnames(sdef)'\n cf = char(f);\n if (override | not(isfield(sout,cf)))\n sout = setfield(sout,cf,getfield(sdef,cf));\n end\nend\n setdefaults2.m % SETDEFAULTS2 sets the default structure values \n% SOUT = SETDEFAULTS(S, SDEF) reproduces in S \n% all the structure fields, and their values, that exist in \n% SDEF that do not exist in S. \n\nfunction sout = setdefaults2(s,sdef)\nsout = sdef;\nfor f = fieldnames(s)'\n sout = setfield(sout,f{1},getfield(s,f{1}));\nend\n >> S1 = struct('a',1,'b',2,'c',3);\n>> S2 = struct('b',4,'c',5,'d',6);\n>> setdefaults2(S1,S2)\n\nans = \n\n b: 2\n c: 3\n d: 6\n a: 1\n\n>> setdefaults2(S2,S1)\n\nans = \n\n a: 1\n b: 4\n c: 5\n d: 6\n"
},
{
"answer_id": 18893739,
"author": "Dennis Jaheruddin",
"author_id": 983722,
"author_profile": "https://Stackoverflow.com/users/983722",
"pm_score": 3,
"selected": false,
"text": "a.f1 = 1;\na.f2 = 2;\nb.f2 = 3;\nb.f4 = 4;\n\ns = catstruct(a,b)\n s = \n\n f1: 1\n f2: 3\n f3: 4\n"
},
{
"answer_id": 23767610,
"author": "chappjc",
"author_id": 2778484,
"author_profile": "https://Stackoverflow.com/users/2778484",
"pm_score": 3,
"selected": false,
"text": "setstructfields setstructfields help setstructfields setstructfields Set fields of a structure using another structure\n setstructfields(STRUCTIN, NEWFIELDS) Set fields of STRUCTIN using\n another structure NEWFIELDS fields. If fields exist in STRUCTIN\n but not in NEWFIELDS, they will not be changed.\n fieldnames for % struct with fields 'color' and 'count'\ns = struct('color','orange','count',2)\n\ns = \n color: 'orange'\n count: 2\n 'count' 'shape' % struct with fields 'count' and 'shape'\ns2 = struct('count',4,'shape','round')\n\ns2 = \n count: 4\n shape: 'round'\n setstructfields >> s = setstructfields(s,s2)\ns = \n color: 'orange'\n count: 4\n shape: 'round'\n 'count' 'shape' 'color'"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/38645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4135/"
] |
38,647
|
<p><strong>When using the Entity Framework, does ESQL perform better than Linq to Entities?</strong> </p>
<p>I'd prefer to use Linq to Entities (mainly because of the strong-type checking), but some of my other team members are citing performance as a reason to use ESQL. I would like to get a full idea of the pro's/con's of using either method.</p>
|
[
{
"answer_id": 356511,
"author": "Royd Brayshay",
"author_id": 35043,
"author_profile": "https://Stackoverflow.com/users/35043",
"pm_score": 5,
"selected": true,
"text": "ObjectQuery<DbDataRecord> query = DynamicQuery(context,\n \"Products\",\n \"it.ProductName = 'Chai'\",\n \"it.ProductName, it.QuantityPerUnit\");\n\npublic static ObjectQuery<DbDataRecord> DynamicQuery(MyContext context, string root, string selection, string projection)\n{\n ObjectQuery<object> rootQuery = context.CreateQuery<object>(root);\n ObjectQuery<object> filteredQuery = rootQuery.Where(selection);\n ObjectQuery<DbDataRecord> result = filteredQuery.Select(projection);\n return result;\n}\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/38647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/708/"
] |
38,651
|
<p>Is there any way to have a binary compiled from an ActionScript 3 project print stuff to <em>stdout</em> when executed?</p>
<p>From what I've gathered, people have been going around this limitation by writing hacks that rely on local socket connections and AIR apps that write to files in the local filesystem, but that's pretty much it -- it's obviously not possible with the Flash Player and AIR runtimes from Adobe.</p>
<p>Is there any project (e.g. based on the Tamarin code) that is attempting to implement something that would provide this kind of functionality?</p>
|
[
{
"answer_id": 324348,
"author": "hasseg",
"author_id": 4111,
"author_profile": "https://Stackoverflow.com/users/4111",
"pm_score": 1,
"selected": false,
"text": "test.as import avmplus.System;\nimport redtamarin.version;\n\ntrace( \"hello world\" );\ntrace( \"avmplus v\" + System.getAvmplusVersion() );\ntrace( \"redtamarin v\" + redtamarin.version );\n $ ./buildEXE.sh test.as \n\ntest.abc, 243 bytes written\ntest.exe, 2191963 bytes written\n\ntest.abc, 243 bytes written\ntest.exe, 2178811 bytes written\n\n$ ./test\nhello world\navmplus v1.0 cyclone (redshell)\nredtamarin v0.1.0.92\n"
},
{
"answer_id": 528831,
"author": "David Lichteblau",
"author_id": 23370,
"author_profile": "https://Stackoverflow.com/users/23370",
"pm_score": 4,
"selected": true,
"text": "/dev/fd/1 /dev/stdout FileStream var stdout : FileStream = new FileStream();\nstdout.open(new File(\"/dev/fd/1\"), FileMode.WRITE);\nstdout.writeUTFBytes(\"test\\n\");\nstdout.close();\n writeUTF() writeUTFBytes()"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/38651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4111/"
] |
38,661
|
<p>Is there any way in IIS to map requests to a particular URL with no extension to a given application.</p>
<p>For example, in trying to port something from a Java servlet, you might have a URL like this...</p>
<p><a href="http://[server]/MyApp/HomePage?some=parameter" rel="nofollow noreferrer">http://[server]/MyApp/HomePage?some=parameter</a></p>
<p>Ideally I'd like to be able to map everything under MyApp to a particular application, but failing that, any suggestions about how to achieve the same effect would be really helpful.</p>
|
[
{
"answer_id": 324348,
"author": "hasseg",
"author_id": 4111,
"author_profile": "https://Stackoverflow.com/users/4111",
"pm_score": 1,
"selected": false,
"text": "test.as import avmplus.System;\nimport redtamarin.version;\n\ntrace( \"hello world\" );\ntrace( \"avmplus v\" + System.getAvmplusVersion() );\ntrace( \"redtamarin v\" + redtamarin.version );\n $ ./buildEXE.sh test.as \n\ntest.abc, 243 bytes written\ntest.exe, 2191963 bytes written\n\ntest.abc, 243 bytes written\ntest.exe, 2178811 bytes written\n\n$ ./test\nhello world\navmplus v1.0 cyclone (redshell)\nredtamarin v0.1.0.92\n"
},
{
"answer_id": 528831,
"author": "David Lichteblau",
"author_id": 23370,
"author_profile": "https://Stackoverflow.com/users/23370",
"pm_score": 4,
"selected": true,
"text": "/dev/fd/1 /dev/stdout FileStream var stdout : FileStream = new FileStream();\nstdout.open(new File(\"/dev/fd/1\"), FileMode.WRITE);\nstdout.writeUTFBytes(\"test\\n\");\nstdout.close();\n writeUTF() writeUTFBytes()"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/38661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
] |
38,669
|
<p>I'm not sure I'm using all the correct terminology here so be forgiving.</p>
<p>I just put up a site with a contact form that sends an email using the PHP mail() function. Simple enough. However the live site doesn't actually send the email, the test site does. So it's not my code. </p>
<p>It's a shared host and we have another site that has the same function that works perfectly, so it's not the server. </p>
<p>The only difference between the two is that the site that doesn't work just has the name server pointing to us and so the MX record never touches our server. </p>
<p>So my question is, could some one please confirm that the mail() function wont work if we don't have the MX record pointing to our server. Thanks</p>
|
[
{
"answer_id": 432807,
"author": "user19471",
"author_id": 19471,
"author_profile": "https://Stackoverflow.com/users/19471",
"pm_score": 1,
"selected": false,
"text": "mail() mail()"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/38669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/910/"
] |
38,670
|
<p>Ok, so, my visual studio is broken. I say this NOT prematurely, as it was my first response to see where I had messed up in my code. When I add controls to the page I can't reference all of them in the code behind. Some of them I can, it seems that the first few I put on a page work, then it just stops. </p>
<p>I first thought it may be the type of control as initially I was trying to reference a repeater inside an update panel. I know I am correctly referencing the code behind in my aspx page. But just in case it was a screw up on my part I started to recreate the page from scratch and this time got a few more controls down before VS stopped recognizing my controls.</p>
<p>After creating my page twice and getting stuck I thought maybe it was still the type of controls. I created a new page and just threw some labels on it. No dice, build fails when referencing the control from the code behind. </p>
<p>In a possibly unrelated note when I switch to the dreaded "design" mode of the aspx pages VS 2008 errors out and restarts. </p>
<p>I have already put a trouble ticket in to Microsoft. I uninstalled all add-ins, I reinstalled visual studio. </p>
<p>Anyone that wants to see my code just ask, but I am using the straight WYSIWYG visual studio "new aspx page" nothing fancy.</p>
<p>I doubt anyone has run into this, but have you? </p>
<p>Has anyone had success trouble shooting these things with Microsoft? Any way to expedite this ticket without paying??? I have been talking to a rep from Microsoft for days with no luck yet and I am dead in the water. </p>
<hr>
<p><strong>Jon Limjap:</strong> I edited the title to both make it clear and descriptive <em>and</em> make sure that nobody sees it as offensive. "Foo-barred" doesn't exactly constitute a proper question title, although your question is clearly a valid one.</p>
|
[
{
"answer_id": 38688,
"author": "Sean Lynch",
"author_id": 4043,
"author_profile": "https://Stackoverflow.com/users/4043",
"pm_score": 4,
"selected": false,
"text": "<asp:Repeater ID=\"Repeater1\" runat=\"server\">\n <ItemTemplate>\n <asp:LinkButton ID=\"LinkButton1\" runat=\"server\">stest</asp:LinkButton>\n </ItemTemplate>\n</asp:Repeater>\n LinkButton lb = Repeater1.FindControl(\"LinkButton1\");\n"
},
{
"answer_id": 38704,
"author": "Brian Boatright",
"author_id": 3747,
"author_profile": "https://Stackoverflow.com/users/3747",
"pm_score": 5,
"selected": true,
"text": "%Temp%\\VWDWebCache\n %LocalAppData%\\Microsoft\\WebsiteCache\n"
},
{
"answer_id": 2140905,
"author": "LorettoDave",
"author_id": 160819,
"author_profile": "https://Stackoverflow.com/users/160819",
"pm_score": 5,
"selected": false,
"text": "PageName.aspx.designer.cs"
},
{
"answer_id": 3021053,
"author": "Daan",
"author_id": 7922,
"author_profile": "https://Stackoverflow.com/users/7922",
"pm_score": 3,
"selected": false,
"text": "designer.cs"
},
{
"answer_id": 5374093,
"author": "Leah",
"author_id": 5506,
"author_profile": "https://Stackoverflow.com/users/5506",
"pm_score": 2,
"selected": false,
"text": "<asp:TextBox ID=\"txtTitle\" runat=\"server\" /> <asp:TextBox ID=\"txtTitle2\" runat=\"server\" />"
},
{
"answer_id": 6883044,
"author": "Dennis",
"author_id": 870634,
"author_profile": "https://Stackoverflow.com/users/870634",
"pm_score": 0,
"selected": false,
"text": "C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\Temporary ASP.NET Files\\myvirtualwebsite\\e331e0a9 \n"
},
{
"answer_id": 34755346,
"author": "Tony L.",
"author_id": 3347858,
"author_profile": "https://Stackoverflow.com/users/3347858",
"pm_score": 1,
"selected": false,
"text": "Inherits <%@ Control AutoEventWireup=\"false\" CodeBehind=\"myControl.ascx.vb\" Inherits=\"myProject.myWrongControl\" %>\n Partial Public Class myControl\n"
},
{
"answer_id": 39342380,
"author": "Alberto Belfanti",
"author_id": 5889239,
"author_profile": "https://Stackoverflow.com/users/5889239",
"pm_score": 0,
"selected": false,
"text": "runat=\"server\"\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/38670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4140/"
] |
38,680
|
<p>Feel free to edit the title if you know how to formulate the question better. (Tagging is a problem as well.) The problem may be too difficult in this general form, so let us consider a concrete example.</p>
<p>You get a screenful of stackoverflow questions by requesting <code>/questions ?sort=newest</code> page. Next page link leads to <code>/questions?page=2 &sort=newest</code>. I suppose that at server side, the request is translated into an SQL query with LIMIT clause. Problem with this approach is, that if new question were added while user browses first page, his second page will start with some questions he already saw. (If he has 10 question per page, and 10 new questions happened to be added, he’ll get exactly the same content second time!)</p>
<p>Is there an elegant way to solve this common problem? I realize that it is not that big a problem, at least not for stackoverflow, but still.</p>
<p>The best idea I have (apart from storing request history per client) is to use <code>/questions?answer_id=NNN</code> format. Server returns a page that starts with the requested answer, and puts the id of the first answer on the next page into next page link. There must be a way to write SQL for that, right? </p>
<p>Is it how it usually done? Or there is a better way?</p>
|
[
{
"answer_id": 38687,
"author": "dmckee --- ex-moderator kitten",
"author_id": 2509,
"author_profile": "https://Stackoverflow.com/users/2509",
"pm_score": 0,
"selected": false,
"text": "n n+displaynum"
},
{
"answer_id": 153722,
"author": "AJ.",
"author_id": 7211,
"author_profile": "https://Stackoverflow.com/users/7211",
"pm_score": 0,
"selected": false,
"text": "SELECT * \nFROM entries \nWHERE entry_id >= @last_viewed_entry_id \nORDER BY entry_id \nLIMIT 50\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/38680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2515/"
] |
38,691
|
<p>Hey so what I want to do is snag the content for the first paragraph. The string <code>$blog_post</code> contains a lot of paragraphs in the following format:</p>
<pre><code><p>Paragraph 1</p><p>Paragraph 2</p><p>Paragraph 3</p>
</code></pre>
<p>The problem I'm running into is that I am writing a regex to grab everything between the first <code><p></code> tag and the first closing <code></p></code> tag. However, it is grabbing the first <code><p></code> tag and the <strong>last</strong> closing <code></p></code> tag which results in me grabbing everything.</p>
<p>Here is my current code:</p>
<pre><code>if (preg_match("/[\\s]*<p>[\\s]*(?<firstparagraph>[\\s\\S]+)[\\s]*<\\/p>[\\s\\S]*/",$blog_post,$blog_paragraph))
echo "<p>" . $blog_paragraph["firstparagraph"] . "</p>";
else
echo $blog_post;
</code></pre>
|
[
{
"answer_id": 38696,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 1,
"selected": false,
"text": " <p>\n </p>\n $paragraph_start = strpos($blog_post, '<p>');\n $paragraph_end = strpos($blog_post, '</p>', $paragraph_start);\n $paragraph = substr($blog_post, $paragraph_start + strlen('<p>'), $paragraph_end - $paragraph_start - strlen('<p>'));\n"
},
{
"answer_id": 38697,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 5,
"selected": true,
"text": "<p>.*?</p>\n ? * </p>"
},
{
"answer_id": 38847,
"author": "Erik Öjebo",
"author_id": 276,
"author_profile": "https://Stackoverflow.com/users/276",
"pm_score": 3,
"selected": false,
"text": "preg_match preg_match(\"/<p>(.*)<\\/p>/U\", $blog_post, &$matches);\n $matches[1]"
},
{
"answer_id": 47850655,
"author": "eLRuLL",
"author_id": 858913,
"author_profile": "https://Stackoverflow.com/users/858913",
"pm_score": 0,
"selected": false,
"text": "$string = <<<XML\n<a>\n <b>\n <c>texto</c>\n <c>cosas</c>\n </b>\n <d>\n <c>código</c>\n </d>\n</a>\nXML;\n\n$xml = new SimpleXMLElement($string);\n\n/* Busca <a><b><c> */\n$resultado = $xml->xpath('//p[1]');\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/38691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/428190/"
] |
38,713
|
<p>I'm trying to pick up ruby by porting a medium-sized (non-OO) perl program. One of my personal idioms is to set options like this:</p>
<pre><code>use Getopt::Std;
our $opt_v; # be verbose
getopts('v');
# and later ...
$opt_v && print "something interesting\n";
</code></pre>
<p>In perl, I kind of grit my teeth and let $opt_v be (effectively) a global. </p>
<p>In ruby,the more-or-less exact equivalent would be </p>
<pre><code>require 'optparse'
opts.on("-v", "--[no-]verbose", TrueClass, "Run verbosely") {
|$opt_verbose|
}
opts.parse!
end
</code></pre>
<p>where $opt_verbose is a global that classes could access. Having classes know about global flags like that seems ... er ... wrong. What's the OO-idiomatic way of doing this?</p>
<ul>
<li>Let the main routine take care of all option-related stuff and have the classes just return things to it that it decides how to deal with?</li>
<li>Have classes implement optional behaviour (e.g., know how to be verbose) and set a mode via an attr_writer sort of thing?</li>
</ul>
<p><em>updated:</em> Thanks for the answers suggesting optparse, but I should have been clearer that it's not <em>how</em> to process command-line options I'm asking about, but more the relationship between command-line options that effectively set a global program state and classes that should ideally be independent of that sort of thing.</p>
|
[
{
"answer_id": 38761,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 2,
"selected": false,
"text": "script/console"
},
{
"answer_id": 41033,
"author": "Nathan Fritz",
"author_id": 4142,
"author_profile": "https://Stackoverflow.com/users/4142",
"pm_score": 3,
"selected": true,
"text": "thingy thingy.verbose=true thingy.process(true)"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/38713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3979/"
] |
38,729
|
<p>I decided to make a system for a client using <a href="https://web.archive.org/web/20080517021542/http://www.castleproject.org/activerecord/index.html" rel="nofollow noreferrer">Castle ActiveRecord</a>, everything went well until I found that the transactions do not work, for instance;</p>
<pre><code> TransactionScope t = new TransactionScope();
try
{
member.Save();
//This is just to see transaction working
throw new Exception("Exception");
foreach (qfh.Beneficiary b1 in l)
{
b1.Create();
}
}
catch (Exception ex)
{
t.VoteRollBack();
MessageBox.Show(ex.Message);
}
finally
{
t.Dispose();
}
</code></pre>
<p>But it doesn't work, I throw an Exception just to try the transaction rolls back, but for my surprise I see that the first [Save] records into the database. What is happening?</p>
<p>I'm new on Castle and NHibernate, firstly I saw it very attractive and I decided to go on with it and MySQL (I've never worked with this DB), I tried ActiveWriter and it seemed very promising but after a long and effortly week I see this issue and now I feel like I'm stuck and like I've wasted my time. It is supposed to be easy but right now I'm feeling a frustated cause I cannot find enough information to make this workout, can you help me?</p>
|
[
{
"answer_id": 38740,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 3,
"selected": false,
"text": "using(new SessionScope())\n{\n a.Save();\n b.Save();\n c.Save();\n}\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/38729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1130097/"
] |
38,746
|
<p>Over at <a href="https://stackoverflow.com/questions/38664/can-you-modify-text-files-when-committing-to-subversion">Can you modify text files when committing to subversion?</a> <a href="https://stackoverflow.com/questions/38664/can-you-modify-text-files-when-committing-to-subversion#38666">Grant</a> suggested that I block commits instead.</p>
<p>However I don't know how to check a file ends with a newline. How can you detect that the file ends with a newline?</p>
|
[
{
"answer_id": 39185,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "bash x=`tail -n 1 your_textfile`\nif [ \"$x\" == \"\" ]; then echo \"empty line\"; fi\n \\n \\n\\n vim \\n"
},
{
"answer_id": 40919,
"author": "grom",
"author_id": 486,
"author_profile": "https://Stackoverflow.com/users/486",
"pm_score": 6,
"selected": true,
"text": "$ cat test_no_newline.txt\nthis file doesn't end in newline$ \n\n$ cat test_with_newline.txt\nthis file ends in newline\n$\n #!/bin/sh\nc=`tail -c 1 $1`\nif [ \"$c\" != \"\" ]; then\n echo \"no newline\"\nfi\n"
},
{
"answer_id": 2421790,
"author": "FelipeC",
"author_id": 10474,
"author_profile": "https://Stackoverflow.com/users/10474",
"pm_score": 4,
"selected": false,
"text": "#!/bin/sh\ntest \"$(tail -c 1 \"$1\")\" && echo \"no newline at eof: '$1'\"\n test \"$(tail -c 1 \"$1\" | wc -l)\" -eq 0 && echo \"no newline at eof: '$1'\"\n"
},
{
"answer_id": 10415403,
"author": "KarolDepka",
"author_id": 170451,
"author_profile": "https://Stackoverflow.com/users/170451",
"pm_score": 2,
"selected": false,
"text": "tail -n 1 /path/to/newline_at_end.txt | wc --lines\n# according to \"man wc\" : --lines - print the newline counts\n"
},
{
"answer_id": 25749716,
"author": "Steve Kehlet",
"author_id": 296829,
"author_profile": "https://Stackoverflow.com/users/296829",
"pm_score": 4,
"selected": false,
"text": "function file_ends_with_newline() {\n [[ $(tail -c1 \"$1\" | wc -l) -gt 0 ]]\n}\n if ! file_ends_with_newline myfile.txt\nthen\n echo \"\" >> myfile.txt\nfi\n# continue with other stuff that assumes myfile.txt ends with a newline\n"
},
{
"answer_id": 60911655,
"author": "Koichi Nakashima",
"author_id": 11267590,
"author_profile": "https://Stackoverflow.com/users/11267590",
"pm_score": 0,
"selected": false,
"text": "read if tail -c 1 \"$1\" | read -r line; then\n echo \"newline\"\nfi\n if [ $(tail -c 1 \"$1\" | od -An -b) = 012 ]; then\n echo \"newline\"\nfi\n"
},
{
"answer_id": 61667168,
"author": "Nicolae Iotu",
"author_id": 10828773,
"author_profile": "https://Stackoverflow.com/users/10828773",
"pm_score": 0,
"selected": false,
"text": "nl=$(printf '\\012')\nnls=$(wc -l \"${target_file}\")\nlastlinecount=${nls%% *}\nlastlinecount=$((lastlinecount+1))\nlastline=$(sed ${lastlinecount}' !d' \"${target_file}\")\nif [ \"${lastline}\" = \"${nl}\" ]; then\n echo \"${target_file} ends with a new line!\"\nelse\n echo \"${target_file} does NOT end with a new line!\"\nfi\n"
},
{
"answer_id": 61876217,
"author": "thanos.a",
"author_id": 2110865,
"author_profile": "https://Stackoverflow.com/users/2110865",
"pm_score": 0,
"selected": false,
"text": "tail -c 1 my_file=\"/path/to/my/file\"\n\n if [[ $(tail -c 1 \"$my_file\") != \"\" ]]; then\n echo \"File doesn't end with a new line: $my_file\"\n fi\n"
},
{
"answer_id": 63398061,
"author": "Olivier Pirson",
"author_id": 1333666,
"author_profile": "https://Stackoverflow.com/users/1333666",
"pm_score": 2,
"selected": false,
"text": "tail #!/bin/bash\n# Return 0 if file $1 exists and ending by end of line character,\n# else return 1\n[[ -s \"$1\" && -z \"$(tail -c 1 \"$1\")\" ]]\n -s \"$1\" -z \"$(tail -c 1 \"$1\")\" [[...]] # Return 0 if file $1 exists and ending by end of line character,\n# else return 1\ncheck_ending_eol() {\n [[ -s \"$1\" && -z \"$(tail -c 1 \"$1\")\" ]]\n}\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/38746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/486/"
] |
38,756
|
<p>I'm looking for a way of getting a <strong>concurrent collection</strong> in <strong>C#</strong> or at least a collection which supports a <strong>concurrent enumerator</strong>. Right now I'm getting an <code>InvalidOperationException</code> when the collection over which I'm iterating changes. </p>
<p>I could just deep copy the collection and work with a private copy but I'm wondering if there is perhaps a better way</p>
<p>Code snippet:</p>
<pre class="lang-cs prettyprint-override"><code>foreach (String s in (List<String>) callingForm.Invoke(callingForm.delegateGetKillStrings))
{
//do some jazz
}
</code></pre>
<p>--edit--</p>
<p>I took the answer but also found that I needed to ensure that the code which was writing to the collection needed to attempt to get a lock as well.</p>
<pre class="lang-cs prettyprint-override"><code>private void addKillString(String s)
{
lock (killStrings)
{
killStrings.Add(s);
}
}
</code></pre>
|
[
{
"answer_id": 38765,
"author": "Damian",
"author_id": 3390,
"author_profile": "https://Stackoverflow.com/users/3390",
"pm_score": 4,
"selected": true,
"text": " List<string> theList = (List<String> )callingForm.Invoke(callingForm.delegateGetKillStrings);\n lock(theList.SyncRoot) {\n foreach(string s in theList) {\n // Do some Jazz\n }\n }\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/38756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/361/"
] |
38,769
|
<p>I need to extract data from a .mpp file on the network and combine it with other data from several different databases. The application can be written in Perl, VB6, VB.net or C# but must be easily scheduled from a Windows based server.</p>
<p>What would you recommend to extract the MS Project data with no user intervention? </p>
<p>Is there any ODBC drivers available for MS Project? </p>
<p>Are there any modules (for Perl, VB, VB.net or C#) for opening a .mpp and reading activity data?</p>
|
[
{
"answer_id": 277232,
"author": "Michael ",
"author_id": 33427,
"author_profile": "https://Stackoverflow.com/users/33427",
"pm_score": 1,
"selected": false,
"text": "oConn.Open \"Provider=Microsoft.Project.OLEDB.9.0;\" & _\n \"Project Name=c:\\somepath\\myProject.mpp\"\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/38769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4134/"
] |
38,779
|
<p>I have a wcf application hosted in a windows service running a local windows account. Do I need to set an SPN for this account? If so, what's the protocol the SPN needs to be set under? I know how to do this for services over HTTP, but have never done it for net.tcp.</p>
|
[
{
"answer_id": 71039,
"author": "softveda",
"author_id": 11711,
"author_profile": "https://Stackoverflow.com/users/11711",
"pm_score": 3,
"selected": false,
"text": "<identity>\n <serviceprincipalname value=\"fooservice/servermachinename\" />\n</identity>\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/38779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/781/"
] |
38,784
|
<p>I use <strong>Delphi</strong> for many years, and although I have now moved on to Visual Studio I still fondly remember numbered bookmarks (<kbd>CTRL</kbd>+<kbd>K</kbd>+<kbd>1</kbd> to set bookmark 1, <kbd>CTRL</kbd>+<kbd>Q</kbd>+<kbd>1</kbd> to goto bookmark 1).</p>
<p>Is there a <strong>Visual Studio</strong> equivalent? I'm find the dumb bookmarks in VS a chore after Delphi. I want to bookmark then return to a specific place in the file.</p>
|
[
{
"answer_id": 62277725,
"author": "AlainD",
"author_id": 2377399,
"author_profile": "https://Stackoverflow.com/users/2377399",
"pm_score": 0,
"selected": false,
"text": "Delphi"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/38784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4149/"
] |
38,791
|
<p>Which Database table Schema is more efficient and why?</p>
<pre><code>"Users (UserID, UserName, CompamyId)"
"Companies (CompamyId, CompanyName)"
</code></pre>
<p>OR</p>
<pre><code>"Users (UserID, UserName)"
"Companies (CompamyId, CompanyName)"
"UserCompanies (UserID, CompamyId)"
</code></pre>
<p>Given the fact that user and company have one-to-one relation.</p>
|
[
{
"answer_id": 38796,
"author": "Kevin Lamb",
"author_id": 3149,
"author_profile": "https://Stackoverflow.com/users/3149",
"pm_score": 1,
"selected": false,
"text": "SELECT userid, username, companyid, companyname\nFROM companies c, users u\nWHERE userid = companyid\n SELECT userid, username, companyid, companyname\nFROM companies c, users u, usercompanies uc\nWHERE u.userid = uc.userid\nAND c.companyid = uc.companyid\n"
},
{
"answer_id": 83365,
"author": "JacquesB",
"author_id": 7488,
"author_profile": "https://Stackoverflow.com/users/7488",
"pm_score": 0,
"selected": false,
"text": "(ID, UserName, CompanyName)\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/38791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191/"
] |
38,801
|
<p>What are the ways that you use to model and retrieve hierarchical info in a database? </p>
|
[
{
"answer_id": 38804,
"author": "Josh",
"author_id": 3166,
"author_profile": "https://Stackoverflow.com/users/3166",
"pm_score": 4,
"selected": false,
"text": "create table person (\nperson_id integer autoincrement primary key,\nname varchar(255) not null,\ndob date,\nmother integer,\nfather integer\n);\n person_id name dob mother father \n1 Pops 1900/1/1 null null \n2 Grandma 1903/2/4 null null \n3 Dad 1925/4/2 2 1 \n4 Uncle Kev 1927/3/3 2 1\n5 Cuz Dave 1953/7/8 null 4\n6 Billy 1954/8/1 null 3\n create table person (\nperson_id integer autoincrement primary key,\nname varchar(255) not null,\ndob date\n);\n\ncreate table ancestor (\nancestor_id integer,\ndescendant_id integer,\ndistance integer\n);\n person_id name dob \n1 Pops 1900/1/1 \n2 Grandma 1903/2/4 \n3 Dad 1925/4/2 \n4 Uncle Kev 1927/3/3\n5 Cuz Dave 1953/7/8 \n6 Billy 1954/8/1 \n\nancestor_id descendant_id distance\n1 1 0\n2 2 0\n3 3 0\n4 4 0\n5 5 0\n6 6 0\n1 3 1\n2 3 1\n1 4 1\n2 4 1\n1 5 2\n2 5 2\n4 5 1\n1 6 2\n2 6 2\n3 6 1\n select * from person where person_id in \n (select descendant_id from ancestor where distance=2);\n select * from person where person_id in \n (select descendant_id from ancestor \n where ancestor_id=1 and distance>0);\n select decendant_id uncle from ancestor \n where distance=1 and ancestor_id in \n (select ancestor_id from ancestor \n where distance=2 and not exists\n (select ancestor_id from ancestor \n where distance=1 and ancestor_id=uncle)\n )\n"
},
{
"answer_id": 38807,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 2,
"selected": false,
"text": "select * from my_table\n start with parent = :TOP\n connect by prior child = parent;\n"
},
{
"answer_id": 38869,
"author": "NakedBrunch",
"author_id": 3742,
"author_profile": "https://Stackoverflow.com/users/3742",
"pm_score": 3,
"selected": false,
"text": "--Create table of dummy data\ncreate table #person (\npersonID integer IDENTITY(1,1) NOT NULL,\nname varchar(255) not null,\ndob date,\nfather integer\n);\n\nINSERT INTO #person(name,dob,father)Values('Pops','1900/1/1',NULL); \nINSERT INTO #person(name,dob,father)Values('Grandma','1903/2/4',null);\nINSERT INTO #person(name,dob,father)Values('Dad','1925/4/2',1);\nINSERT INTO #person(name,dob,father)Values('Uncle Kev','1927/3/3',1);\nINSERT INTO #person(name,dob,father)Values('Cuz Dave','1953/7/8',4);\nINSERT INTO #person(name,dob,father)Values('Billy','1954/8/1',3);\n\nDECLARE @OldestPerson INT; \nSET @OldestPerson = 1; -- Set this value to the ID of the oldest person in the family\n\nWITH PersonHierarchy (personID,Name,dob,father, HierarchyLevel) AS\n(\n SELECT\n personID\n ,Name\n ,dob\n ,father,\n 1 as HierarchyLevel\n FROM #person\n WHERE personID = @OldestPerson\n\n UNION ALL\n\n SELECT\n e.personID,\n e.Name,\n e.dob,\n e.father,\n eh.HierarchyLevel + 1 AS HierarchyLevel\n FROM #person e\n INNER JOIN PersonHierarchy eh ON\n e.father = eh.personID\n)\n\nSELECT *\nFROM PersonHierarchy\nORDER BY HierarchyLevel, father;\n\nDROP TABLE #person;\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/38801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2027/"
] |
38,820
|
<p>Which class design is better and why?</p>
<pre><code>public class User
{
public String UserName;
public String Password;
public String FirstName;
public String LastName;
}
public class Employee : User
{
public String EmployeeId;
public String EmployeeCode;
public String DepartmentId;
}
public class Member : User
{
public String MemberId;
public String JoinDate;
public String ExpiryDate;
}
</code></pre>
<p>OR</p>
<pre><code>public class User
{
public String UserId;
public String UserName;
public String Password;
public String FirstName;
public String LastName;
}
public class Employee
{
public User UserInfo;
public String EmployeeId;
public String EmployeeCode;
public String DepartmentId;
}
public class Member
{
public User UserInfo;
public String MemberId;
public String JoinDate;
public String ExpiryDate;
}
</code></pre>
|
[
{
"answer_id": 38905,
"author": "liammclennan",
"author_id": 2785,
"author_profile": "https://Stackoverflow.com/users/2785",
"pm_score": 4,
"selected": false,
"text": "myEmployee.UserInfo.UserName\n myEmployee.UserName\n"
},
{
"answer_id": 13124792,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 0,
"selected": false,
"text": "User ID User User ISupplementalInfo ISupplementalInfo ISupplementalEmployeeInfo ISupplementalMemberInfo User User User User ISupplementalInfo Member Dictionary<Type, ISupplementalInfo>"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/38820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191/"
] |
38,842
|
<p>I need to do a simple mail merge in OpenOffice using C++, VBScript, VB.Net or C# via OLE or native API. Are there any good examples available?</p>
|
[
{
"answer_id": 42760,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 4,
"selected": true,
"text": " Dim xContext As XComponentContext\n\n xContext = Bootstrap.bootstrap()\n\n Dim xFactory As XMultiServiceFactory\n xFactory = DirectCast(xContext.getServiceManager(), _\n XMultiServiceFactory)\n\n 'Create the Desktop\n Dim xDesktop As unoidl.com.sun.star.frame.XDesktop\n xDesktop = DirectCast(xFactory.createInstance(\"com.sun.star.frame.Desktop\"), _\n unoidl.com.sun.star.frame.XDesktop)\n\n 'Open a new empty writer document\n Dim xComponentLoader As unoidl.com.sun.star.frame.XComponentLoader\n xComponentLoader = DirectCast(xDesktop, unoidl.com.sun.star.frame.XComponentLoader)\n Dim arProps() As unoidl.com.sun.star.beans.PropertyValue = _\n New unoidl.com.sun.star.beans.PropertyValue() {}\n Dim xComponent As unoidl.com.sun.star.lang.XComponent\n xComponent = xComponentLoader.loadComponentFromURL( _\n \"private:factory/swriter\", \"_blank\", 0, arProps)\n Dim xTextDocument As unoidl.com.sun.star.text.XTextDocument\n xTextDocument = DirectCast(xComponent, unoidl.com.sun.star.text.XTextDocument)\n Dim storer As unoidl.com.sun.star.frame.XStorable = DirectCast(xTextDocument, unoidl.com.sun.star.frame.XStorable)\n arProps = New unoidl.com.sun.star.beans.PropertyValue() {}\n storer.storeToURL(\"file:///C:/Users/me/Desktop/OpenOffice Investigation/saved doc.odt\", arProps)\n Dim xComponent As unoidl.com.sun.star.lang.XComponent\n xComponent = xComponentLoader.loadComponentFromURL( _\n \"file:///C:/Users/me/Desktop/OpenOffice Investigation/saved doc.odt\", \"_blank\", 0, arProps)\n Dim t_OOo As Type\n t_OOo = Type.GetTypeFromProgID(\"com.sun.star.ServiceManager\")\n Dim objServiceManager As Object\n objServiceManager = System.Activator.CreateInstance(t_OOo)\n\n Dim oMailMerge As Object\n oMailMerge = t_OOo.InvokeMember(\"createInstance\", _\n BindingFlags.InvokeMethod, Nothing, _\n objServiceManager, New [Object]() {\"com.sun.star.text.MailMerge\"})\n\n 'Now set up a new MailMerge using the settings extracted from that doc\n oMailMerge.DocumentURL = \"file:///C:/Users/me/Desktop/OpenOffice Investigation/mail merged.odt\"\n oMailMerge.DataSourceName = \"adds\"\n oMailMerge.CommandType = 0 ' http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html#CommandType\n oMailMerge.Command = \"adds\"\n oMailMerge.OutputType = 2 ' http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html#OutputType\n oMailMerge.execute(New [Object]() {})\n Dim t_OOo As Type\n t_OOo = Type.GetTypeFromProgID(\"com.sun.star.ServiceManager\")\n Dim objServiceManager As Object\n objServiceManager = System.Activator.CreateInstance(t_OOo)\n\n Dim oMailMerge As Object\n oMailMerge = t_OOo.InvokeMember(\"createInstance\", _\n BindingFlags.InvokeMethod, Nothing, _\n objServiceManager, New [Object]() {\"com.sun.star.text.MailMerge\"})\n\n 'Now set up a new MailMerge using the settings extracted from that doc\n oMailMerge.GetType().InvokeMember(\"DocumentURL\", BindingFlags.SetProperty, Nothing, oMailMerge, New [Object]() {\"file:///C:/Users/me/Desktop/OpenOffice Investigation/mail merged.odt\"})\n oMailMerge.GetType().InvokeMember(\"DataSourceName\", BindingFlags.SetProperty, Nothing, oMailMerge, New [Object]() {\"adds\"})\n oMailMerge.GetType().InvokeMember(\"CommandType\", BindingFlags.SetProperty, Nothing, oMailMerge, New [Object]() {0})\n oMailMerge.GetType().InvokeMember(\"Command\", BindingFlags.SetProperty, Nothing, oMailMerge, New [Object]() {\"adds\"})\n oMailMerge.GetType().InvokeMember(\"OutputType\", BindingFlags.SetProperty, Nothing, oMailMerge, New [Object]() {2})\n oMailMerge.GetType().InvokeMember(\"Execute\", BindingFlags.InvokeMethod Or BindingFlags.IgnoreReturn, Nothing, oMailMerge, New [Object]() {}) ' this line fails with a type mismatch error\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/38842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3146/"
] |
38,846
|
<p>What are the fundamentals to accomplish data encryption with exactly two keys (which could be password-based), but needing only one (either one) of the two keys to decrypt the data?</p>
<p>For example, data is encrypted with a user's password and his company's password, and then he or his company can decrypt the data. Neither of them know the other password. Only one copy of the encrypted data is stored.</p>
<p>I don't mean public/private key. Probably via symmetric key cryptography and maybe it involves something like XORing the keys together to use them for encrypting. </p>
<p>Update: I would also like to find a solution that does not involve storing the keys at all.</p>
|
[
{
"answer_id": 38863,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 0,
"selected": false,
"text": "D = data to encrypt\nh1 = hash(userpassword)\nh2 = hash(companyPassword)\nk = h1 concat h2\n\nE = function to encrypt\n//C is the encrypted data\nC = E_h1(h2) concat E_h2(h1) concat E_k(D)\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/38846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
] |
38,864
|
<p>Consider the following setup:
A windows PC with a LAN interface and a WiFi interface (the standard for any new laptop). Each of the interfaces might be connected or disconnected from a network. I need a way to determine which one of the adapters is the one connected to the internet - specifically, in case they are both connected to different networks, one with connection to the internet and one without.</p>
<p>My current solution involves using IPHelper's "<a href="http://msdn.microsoft.com/en-us/library/aa365920(VS.85).aspx" rel="noreferrer">GetBestInterface</a>" function and supplying it with the IP address "0.0.0.0".</p>
<p>Do you have any other solutions you might suggest to this problem?</p>
<p>Following some of the answers, let me elaborate:</p>
<ul>
<li>I need this because I have a product that has to choose which adapter to bind to. I have no way of controlling the setup of the network or the host where the product will run and so I need a solution that is as robust as possible, with as few assumptions as possible.</li>
<li>I need to do this in code, since this is part of a product.</li>
</ul>
<p>@Chris Upchurch: This makes me dependent on google.com being up (usually not a problem) and on any personal firewall that might be installed to allow pinging.</p>
<p>@Till: Like Steve Moon said, relying on the adapter's address is kind of risky because you make a lot of assumptions on the internal network setup.</p>
<p>@Steve Moon: Looking at the routing table sounds like a good idea, but instead of applying the routing logic myself, I am trying to use "GetBestInterface" as described above. I believe what it should do is exactly what you outlined in your answer, but I am not really sure. The reason I'm reluctant to implement my own "routing logic" is that there's a better chance that I'll get it wrong than if I use a library/API written and tested by more "hard-core" network people.</p>
|
[
{
"answer_id": 38872,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": 0,
"selected": false,
"text": "ipconfig /all"
},
{
"answer_id": 48460,
"author": "quux",
"author_id": 2383,
"author_profile": "https://Stackoverflow.com/users/2383",
"pm_score": 1,
"selected": false,
"text": "IPv4 Route Table\n===========================================================================\nActive Routes:\nNetwork Destination Netmask Gateway Interface Metric\n 0.0.0.0 0.0.0.0 10.0.0.10 10.0.0.51 20\n 0.0.0.0 0.0.0.0 10.0.0.10 10.0.0.50 25\n(much other stuff deleted)\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/38864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1596/"
] |
38,870
|
<p>I have the following tables in my database that have a many-to-many relationship, which is expressed by a connecting table that has foreign keys to the primary keys of each of the main tables:</p>
<ul>
<li>Widget: WidgetID (PK), Title, Price </li>
<li>User: UserID (PK), FirstName, LastName</li>
</ul>
<p>Assume that each User-Widget combination is unique. I can see two options for how to structure the connecting table that defines the data relationship:</p>
<ol>
<li>UserWidgets1: UserWidgetID (PK), WidgetID (FK), UserID (FK) </li>
<li>UserWidgets2: WidgetID (PK, FK), UserID (PK, FK)</li>
</ol>
<p>Option 1 has a single column for the Primary Key. However, this seems unnecessary since the only data being stored in the table is the relationship between the two primary tables, and this relationship itself can form a unique key. Thus leading to option 2, which has a two-column primary key, but loses the one-column unique identifier that option 1 has. I could also optionally add a two-column unique index (WidgetID, UserID) to the first table.</p>
<p>Is there any real difference between the two performance-wise, or any reason to prefer one approach over the other for structuring the UserWidgets many-to-many table?</p>
|
[
{
"answer_id": 39145,
"author": "Guy",
"author_id": 993,
"author_profile": "https://Stackoverflow.com/users/993",
"pm_score": 3,
"selected": false,
"text": "PRIMARY KEY PRIMARY KEY's"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/38870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/51/"
] |
38,875
|
<p>My website was recently attacked by, what seemed to me as, an innocent code:</p>
<pre><code><?php
if ( isset( $ _GET['page'] ) ) {
include( $ _GET['page'] . ".php" );
} else {
include("home.php");
}
?>
</code></pre>
<p>There where no SQL calls, so I wasn't afraid for SQL Injection. But, apparently, SQL isn't the only kind of injection.</p>
<p>This website has an explanation and a few examples of avoiding code injection: <a href="http://www.theserverpages.com/articles/webmasters/php/security/Code_Injection_Vulnerabilities_Explained.html" rel="noreferrer">http://www.theserverpages.com/articles/webmasters/php/security/Code_Injection_Vulnerabilities_Explained.html</a></p>
<p>How would you protect this code from code injection?</p>
|
[
{
"answer_id": 38884,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": 2,
"selected": false,
"text": "<?php\nif (isset($_GET['page']) && !empty($_GET['page'])) {\n $page = urldecode($_GET['page']);\n $page = basename($page);\n $file = dirname(__FILE__) . \"/{$page}.php\";\n if (!file_exists($file)) {\n $file = dirname(__FILE__) . '/home.php';\n }\n} else {\n $file = dirname(__FILE__) . '/home.php';\n}\ninclude $file;\n?>\n"
},
{
"answer_id": 38886,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 6,
"selected": true,
"text": " $whitelist = array('home', 'page');\n\n if (in_array($_GET['page'], $whitelist)) {\n include($_GET['page'].'.php');\n } else {\n include('home.php');\n }\n"
},
{
"answer_id": 39035,
"author": "BlaM",
"author_id": 999,
"author_profile": "https://Stackoverflow.com/users/999",
"pm_score": 4,
"selected": false,
"text": "$page = preg_replace('[^a-zA-Z0-9]', '', $page);\n RewriteEngine on\nRewriteCond %{QUERY_STRING} http[:%] [NC]\nRewriteRule .* /–http– [F,NC]\nRewriteRule http: /–http– [F,NC]\n"
},
{
"answer_id": 39164,
"author": "Cheekysoft",
"author_id": 1820,
"author_profile": "https://Stackoverflow.com/users/1820",
"pm_score": 1,
"selected": false,
"text": "/etc/passwd open_basedir allow_url_fopen ini-set"
},
{
"answer_id": 40458,
"author": "ceejayoz",
"author_id": 1902010,
"author_profile": "https://Stackoverflow.com/users/1902010",
"pm_score": 0,
"selected": false,
"text": "<?php\n\n$whitelist = array(\n 'home',\n 'page',\n);\n\nif(in_array($_GET['page'], $whitelist)) {\n include($_GET['page'] . '.php');\n} else {\n include('home.php');\n}\n\n?>\n file_exists()"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/38875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2644/"
] |
38,890
|
<p>Is there a way to enforce constraint checking in MSSQL only when inserting new rows? I.e. allow the constraints to be violated when removing/updating rows?</p>
<p>Update: I mean FK constraint.</p>
|
[
{
"answer_id": 38897,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 4,
"selected": true,
"text": "CREATE TRIGGER employee_insupd\nON employee\nFOR INSERT\nAS\n/* Get the range of level for this job type from the jobs table. */\nDECLARE @min_lvl tinyint,\n @max_lvl tinyint,\n @emp_lvl tinyint,\n @job_id smallint\nSELECT @min_lvl = min_lvl, \n @max_lvl = max_lvl, \n @emp_lvl = i.job_lvl,\n @job_id = i.job_id\nFROM employee e INNER JOIN inserted i ON e.emp_id = i.emp_id \n JOIN jobs j ON j.job_id = i.job_id\nIF (@job_id = 1) and (@emp_lvl <> 10) \nBEGIN\n RAISERROR ('Job id 1 expects the default level of 10.', 16, 1)\n ROLLBACK TRANSACTION\nEND\nELSE\nIF NOT (@emp_lvl BETWEEN @min_lvl AND @max_lvl)\nBEGIN\n RAISERROR ('The level for job_id:%d should be between %d and %d.',\n 16, 1, @job_id, @min_lvl, @max_lvl)\n ROLLBACK TRANSACTION\nEND\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/38890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
] |
38,922
|
<p>I have a rails application where each user has a separate database. (taking Joel Spolsky's advice on this). I want to run DB migrations from the rails application to create a new database and tables for this user. </p>
<p>What is the easiest way to do this? </p>
<p>Maybe the db migration is not the best for this type of thing. Thanks!</p>
<hr>
<p>It would be nice if it could be a completely automated process. The following process would be ideal.</p>
<ol>
<li>A user signs up on our site to use this web app</li>
<li>Migrations are run to create this users database and get tables setup correctly</li>
</ol>
<p>Is there a way of calling a rake task from a ruby application?</p>
|
[
{
"answer_id": 40015,
"author": "Jordi Bunster",
"author_id": 4272,
"author_profile": "https://Stackoverflow.com/users/4272",
"pm_score": 2,
"selected": true,
"text": "require 'rake'\nload 'path/to/task.rake'\n\nRake::Task['foo:bar:baz'].invoke\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/38922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2737/"
] |
38,934
|
<p>How to take screenshot programmically of desktop area in Mac OS X ?</p>
|
[
{
"answer_id": 67833,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "NSTask *theProcess;\ntheProcess = [[NSTask alloc] init];\n\n[theProcess setLaunchPath:@\"/usr/sbin/screencapture\"];\n// use arguments to set save location\n[theProcess setArguments:@\"blahblah\"];\n[theProcess launch];\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/38934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3911/"
] |
38,940
|
<p>If I've got a table containing Field1 and Field2 can I generate a new field in the select statement? For example, a normal query would be:</p>
<pre><code>SELECT Field1, Field2 FROM Table
</code></pre>
<p>And I want to also create Field3 and have that returned in the resultset... something along the lines of this would be ideal:</p>
<pre><code>SELECT Field1, Field2, Field3 = 'Value' FROM Table
</code></pre>
<p>Is this possible at all?</p>
|
[
{
"answer_id": 38942,
"author": "Josh",
"author_id": 257,
"author_profile": "https://Stackoverflow.com/users/257",
"pm_score": 5,
"selected": true,
"text": "SELECT Field1, Field2, 'Value' Field3 FROM Table\n SELECT Field1, Field2, 'Value' AS Field3 FROM Table\n"
},
{
"answer_id": 38944,
"author": "Whisk",
"author_id": 908,
"author_profile": "https://Stackoverflow.com/users/908",
"pm_score": 3,
"selected": false,
"text": "SELECT Field1, Field2, 'Value' AS `Field3` FROM Table\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/38940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/393028/"
] |
38,948
|
<p>Can I use <a href="http://struts.apache.org/" rel="nofollow noreferrer">Struts</a> as a backend and PHP as front end for a web application? If yes, what may be the implications.</p>
|
[
{
"answer_id": 43967,
"author": "Sam McAfee",
"author_id": 577,
"author_profile": "https://Stackoverflow.com/users/577",
"pm_score": 2,
"selected": false,
"text": "http://mydomain.com/rest/this-is-a-method-call?parameter1=foo\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/38948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
38,960
|
<p>I would like to test a string containing a path to a file for existence of that file (something like the <code>-e</code> test in Perl or the <code>os.path.exists()</code> in Python) in C#.</p>
|
[
{
"answer_id": 38962,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 9,
"selected": true,
"text": "File.Exists(path)\n"
},
{
"answer_id": 38971,
"author": "Peter Hoffmann",
"author_id": 720,
"author_profile": "https://Stackoverflow.com/users/720",
"pm_score": 6,
"selected": false,
"text": "using System.IO;\n\nif (File.Exists(path)) \n{\n Console.WriteLine(\"file exists\");\n} \n"
},
{
"answer_id": 22280061,
"author": "shivi",
"author_id": 2412200,
"author_profile": "https://Stackoverflow.com/users/2412200",
"pm_score": 3,
"selected": false,
"text": " return File.Exists(FinalPath);\n"
},
{
"answer_id": 65721211,
"author": "Jesus Hedo",
"author_id": 10952876,
"author_profile": "https://Stackoverflow.com/users/10952876",
"pm_score": 1,
"selected": false,
"text": "public bool FileExists(string fileName)\n{\n var workingDirectory = Environment.CurrentDirectory;\n var file = $\"{workingDirectory}\\{fileName}\";\n return File.Exists(file);\n}\n myfile.txt"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/38960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2260/"
] |
38,987
|
<p>I want to merge two dictionaries into a new dictionary.</p>
<pre><code>x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = merge(x, y)
>>> z
{'a': 1, 'b': 3, 'c': 4}
</code></pre>
<p>Whenever a key <code>k</code> is present in both dictionaries, only the value <code>y[k]</code> should be kept.</p>
|
[
{
"answer_id": 38989,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 7,
"selected": false,
"text": "x = {'a':1, 'b': 2}\ny = {'b':10, 'c': 11}\nz = dict(x.items() + y.items())\nprint z\n"
},
{
"answer_id": 38990,
"author": "Thomas Vander Stichele",
"author_id": 2900,
"author_profile": "https://Stackoverflow.com/users/2900",
"pm_score": 11,
"selected": false,
"text": "z = dict(list(x.items()) + list(y.items()))\n z b y >>> x = {'a':1, 'b': 2}\n>>> y = {'b':10, 'c': 11}\n>>> z = dict(list(x.items()) + list(y.items()))\n>>> z\n{'a': 1, 'c': 11, 'b': 10}\n\n list() >>> z = dict(x.items() + y.items())\n>>> z\n{'a': 1, 'c': 11, 'b': 10}\n x = {'a':1, 'b': 2}\ny = {'b':10, 'c': 11}\nz = x | y\nprint(z)\n {'a': 1, 'c': 11, 'b': 10}\n"
},
{
"answer_id": 39437,
"author": "Matthew Schinckel",
"author_id": 188,
"author_profile": "https://Stackoverflow.com/users/188",
"pm_score": 10,
"selected": false,
"text": "z = x.copy()\nz.update(y)\n"
},
{
"answer_id": 39858,
"author": "Carl Meyer",
"author_id": 3207,
"author_profile": "https://Stackoverflow.com/users/3207",
"pm_score": 9,
"selected": false,
"text": "z = dict(x, **y)\n y"
},
{
"answer_id": 44512,
"author": "rcreswick",
"author_id": 3446,
"author_profile": "https://Stackoverflow.com/users/3446",
"pm_score": 7,
"selected": false,
"text": "def merge(d1, d2, merge_fn=lambda x,y:y):\n \"\"\"\n Merges two dictionaries, non-destructively, combining \n values on duplicate keys as defined by the optional merge\n function. The default behavior replaces the values in d1\n with corresponding values in d2. (There is no other generally\n applicable merge strategy, but often you'll have homogeneous \n types in your dicts, so specifying a merge technique can be \n valuable.)\n\n Examples:\n\n >>> d1\n {'a': 1, 'c': 3, 'b': 2}\n >>> merge(d1, d1)\n {'a': 1, 'c': 3, 'b': 2}\n >>> merge(d1, d1, lambda x,y: x+y)\n {'a': 2, 'c': 6, 'b': 4}\n\n \"\"\"\n result = dict(d1)\n for k,v in d2.iteritems():\n if k in result:\n result[k] = merge_fn(result[k], v)\n else:\n result[k] = v\n return result\n"
},
{
"answer_id": 49492,
"author": "Tony Meyer",
"author_id": 4966,
"author_profile": "https://Stackoverflow.com/users/4966",
"pm_score": 8,
"selected": false,
"text": ">>> timeit.Timer(\"dict(x, **y)\", \"x = dict(zip(range(1000), range(1000)))\\ny=dict(zip(range(1000,2000), range(1000,2000)))\").timeit(100000)\n15.52571702003479\n>>> timeit.Timer(\"temp = x.copy()\\ntemp.update(y)\", \"x = dict(zip(range(1000), range(1000)))\\ny=dict(zip(range(1000,2000), range(1000,2000)))\").timeit(100000)\n15.694622993469238\n>>> timeit.Timer(\"dict(x.items() + y.items())\", \"x = dict(zip(range(1000), range(1000)))\\ny=dict(zip(range(1000,2000), range(1000,2000)))\").timeit(100000)\n41.484580039978027\n"
},
{
"answer_id": 228366,
"author": "zaphod",
"author_id": 13871,
"author_profile": "https://Stackoverflow.com/users/13871",
"pm_score": 8,
"selected": false,
"text": "z1 = dict(x.items() + y.items())\nz2 = dict(x, **y)\n z2 timeit % python -m timeit -s 'x=y=dict((i,i) for i in range(20))' 'z1=dict(x.items() + y.items())'\n100000 loops, best of 3: 5.67 usec per loop\n% python -m timeit -s 'x=y=dict((i,i) for i in range(20))' 'z2=dict(x, **y)' \n100000 loops, best of 3: 1.53 usec per loop\n z2 z2 -r % python -m timeit -s 'from htmlentitydefs import codepoint2name as x, name2codepoint as y' 'z1=dict(x.items() + y.items())'\n1000 loops, best of 3: 260 usec per loop\n% python -m timeit -s 'from htmlentitydefs import codepoint2name as x, name2codepoint as y' 'z2=dict(x, **y)' \n10000 loops, best of 3: 26.9 usec per loop\n z2 z1 from itertools import chain\nz3 = dict(chain(x.iteritems(), y.iteritems()))\n % python -m timeit -s 'from itertools import chain; from htmlentitydefs import codepoint2name as x, name2codepoint as y' 'z3=dict(chain(x.iteritems(), y.iteritems()))'\n10000 loops, best of 3: 66 usec per loop\n z3 z1 z2 update z0 = dict(x)\nz0.update(y)\n % python -m timeit -s 'from htmlentitydefs import codepoint2name as x, name2codepoint as y' 'z0=dict(x); z0.update(y)'\n10000 loops, best of 3: 26.9 usec per loop\n z0 z2 dict z0 = x.copy()\nz0.update(y)\n"
},
{
"answer_id": 3936548,
"author": "driax",
"author_id": 72476,
"author_profile": "https://Stackoverflow.com/users/72476",
"pm_score": 7,
"selected": false,
"text": "from itertools import chain\nx = {'a':1, 'b': 2}\ny = {'b':10, 'c': 11}\ndict(chain(x.iteritems(), y.iteritems()))\n dict(x.items() + y.items()) n = copy(a); n.update(b) iteritems() items()"
},
{
"answer_id": 7770473,
"author": "phobie",
"author_id": 509648,
"author_profile": "https://Stackoverflow.com/users/509648",
"pm_score": 6,
"selected": false,
"text": "x = {'a':1, 'b': 2}\ny = {'b':10, 'c': 11}\nz4 = {}\nz4.update(x)\nz4.update(y)\n"
},
{
"answer_id": 8247023,
"author": "EMS",
"author_id": 364984,
"author_profile": "https://Stackoverflow.com/users/364984",
"pm_score": 6,
"selected": false,
"text": "x = {'a':1, 'b':2}\ny = {'b':10, 'c':11}\nz = (lambda a, b: (lambda a_copy: a_copy.update(b) or a_copy)(a.copy()))(x, y)\nprint z\n{'a': 1, 'c': 11, 'b': 10}\nprint x\n{'a': 1, 'b': 2}\n"
},
{
"answer_id": 8310229,
"author": "Stan",
"author_id": 471393,
"author_profile": "https://Stackoverflow.com/users/471393",
"pm_score": 7,
"selected": false,
"text": "def deepupdate(original, update):\n \"\"\"\n Recursively update a dict.\n Subdict's won't be overwritten but also updated.\n \"\"\"\n for key, value in original.iteritems(): \n if key not in update:\n update[key] = value\n elif isinstance(value, dict):\n deepupdate(value, update[key]) \n return update pluto_original = {\n 'name': 'Pluto',\n 'details': {\n 'tail': True,\n 'color': 'orange'\n }\n}\n\npluto_update = {\n 'name': 'Pluutoo',\n 'details': {\n 'color': 'blue'\n }\n}\n\nprint deepupdate(pluto_original, pluto_update) {\n 'name': 'Pluutoo',\n 'details': {\n 'color': 'blue',\n 'tail': True\n }\n}"
},
{
"answer_id": 11825563,
"author": "Sam Watkins",
"author_id": 218294,
"author_profile": "https://Stackoverflow.com/users/218294",
"pm_score": 6,
"selected": false,
"text": "def dict_merge(a, b):\n c = a.copy()\n c.update(b)\n return c\n\nnew = dict_merge(old, extras)\n print dict_merge(\n {'color':'red', 'model':'Mini'},\n {'model':'Ferrari', 'owner':'Carl'})\n {'color': 'red', 'owner': 'Carl', 'model': 'Ferrari'}\n"
},
{
"answer_id": 12926103,
"author": "Mathieu Larose",
"author_id": 122894,
"author_profile": "https://Stackoverflow.com/users/122894",
"pm_score": 5,
"selected": false,
"text": "def union2(dict1, dict2):\n return dict(list(dict1.items()) + list(dict2.items()))\n def union(*dicts):\n return dict(itertools.chain.from_iterable(dct.items() for dct in dicts))\n sum"
},
{
"answer_id": 16259217,
"author": "Raymond Hettinger",
"author_id": 424499,
"author_profile": "https://Stackoverflow.com/users/424499",
"pm_score": 8,
"selected": false,
"text": "collections.ChainMap >>> from collections import ChainMap\n>>> x = {'a':1, 'b': 2}\n>>> y = {'b':10, 'c': 11}\n>>> z = dict(ChainMap({}, y, x))\n>>> for k, v in z.items():\n print(k, '-->', v)\n \na --> 1\nb --> 10\nc --> 11\n >>> x = {'a':1, 'b': 2}\n>>> y = {'b':10, 'c': 11}\n>>> {**x, **y}\n{'a': 1, 'b': 10, 'c': 11}\n >>> x = {'a':1, 'b': 2}\n>>> y = {'b':10, 'c': 11}\n>>> x | y\n{'a': 1, 'b': 10, 'c': 11}\n"
},
{
"answer_id": 16769722,
"author": "kiriloff",
"author_id": 1141493,
"author_profile": "https://Stackoverflow.com/users/1141493",
"pm_score": 3,
"selected": false,
"text": "x = {'a':1, 'b': 2}\ny = {'b':10, 'c': 11}\n\ndc = {xi:(x[xi] if xi not in list(y.keys()) \n else y[xi]) for xi in list(x.keys())+(list(y.keys()))}\n >>> dc\n{'a': 1, 'c': 11, 'b': 10}\n if else { (some_key if condition else default_key):(something_if_true if condition \n else something_if_false) for key, value in dict_.items() }\n"
},
{
"answer_id": 17738920,
"author": "Bijou Trouvaille",
"author_id": 375570,
"author_profile": "https://Stackoverflow.com/users/375570",
"pm_score": 4,
"selected": false,
"text": "def merge(*dicts, **kv): \n return { k:v for d in list(dicts) + [kv] for k,v in d.items() }\n assert (merge({1:11,'a':'aaa'},{1:99, 'b':'bbb'},foo='bar')==\\\n {1: 99, 'foo': 'bar', 'b': 'bbb', 'a': 'aaa'})\n\nassert (merge(foo='bar')=={'foo': 'bar'})\n\nassert (merge({1:11},{1:99},foo='bar',baz='quux')==\\\n {1: 99, 'foo': 'bar', 'baz':'quux'})\n\nassert (merge({1:11},{1:99})=={1: 99})\n"
},
{
"answer_id": 18114065,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 5,
"selected": false,
"text": ">>> x = {'a':1, 'b': 2}\n>>> y = {'b':10, 'c': 11}\n>>> z = (lambda f=x.copy(): (f.update(y), f)[1])()\n>>> z\n{'a': 1, 'c': 11, 'b': 10}\n lambda >>> x = {'a':1, 'b': 2}\n>>> y = {'b':10, 'c': 11}\n>>> z = (x.update(y), x)[1]\n>>> z\n{'a': 1, 'b': 10, 'c': 11}\n"
},
{
"answer_id": 19279501,
"author": "beardc",
"author_id": 386279,
"author_profile": "https://Stackoverflow.com/users/386279",
"pm_score": 6,
"selected": false,
"text": "items + dict(x.items() | y.items())\n viewitems items dict(x.viewitems() | y.viewitems())\n dict(x, **y) y In [1]: from collections import ChainMap\nIn [2]: from string import ascii_uppercase as up, ascii_lowercase as lo; x = dict(zip(lo, up)); y = dict(zip(up, lo))\nIn [3]: chainmap_dict = ChainMap(y, x)\nIn [4]: union_dict = dict(x.items() | y.items())\nIn [5]: timeit for k in union_dict: union_dict[k]\n100000 loops, best of 3: 2.15 µs per loop\nIn [6]: timeit for k in chainmap_dict: chainmap_dict[k]\n10000 loops, best of 3: 27.1 µs per loop\n"
},
{
"answer_id": 19950727,
"author": "John La Rooy",
"author_id": 174728,
"author_profile": "https://Stackoverflow.com/users/174728",
"pm_score": 4,
"selected": false,
"text": ">>> x = {'a':1, 'b': 2}\n>>> y = {'b':10, 'c': 11}\n>>> x, z = dict(x), x.update(y) or x\n>>> x\n{'a': 1, 'b': 2}\n>>> y\n{'c': 11, 'b': 10}\n>>> z\n{'a': 1, 'c': 11, 'b': 10}\n"
},
{
"answer_id": 20358548,
"author": "upandacross",
"author_id": 3062691,
"author_profile": "https://Stackoverflow.com/users/3062691",
"pm_score": 4,
"selected": false,
"text": "import timeit\n\nn=100000\nsu = \"\"\"\nx = {'a':1, 'b': 2}\ny = {'b':10, 'c': 11}\n\"\"\"\n\ndef timeMerge(f,su,niter):\n print \"{:4f} sec for: {:30s}\".format(timeit.Timer(f,setup=su).timeit(n),f)\n\ntimeMerge(\"dict(x, **y)\",su,n)\ntimeMerge(\"x.update(y)\",su,n)\ntimeMerge(\"dict(x.items() + y.items())\",su,n)\ntimeMerge(\"for k in y.keys(): x[k] = k in x and x[k]+y[k] or y[k] \",su,n)\n\n#confirm for loop adds b entries together\nx = {'a':1, 'b': 2}\ny = {'b':10, 'c': 11}\nfor k in y.keys(): x[k] = k in x and x[k]+y[k] or y[k]\nprint \"confirm b elements are added:\",x\n 0.049465 sec for: dict(x, **y)\n0.033729 sec for: x.update(y) \n0.150380 sec for: dict(x.items() + y.items()) \n0.083120 sec for: for k in y.keys(): x[k] = k in x and x[k]+y[k] or y[k]\n\nconfirm b elements are added: {'a': 1, 'c': 11, 'b': 12}\n"
},
{
"answer_id": 22122836,
"author": "GetFree",
"author_id": 25700,
"author_profile": "https://Stackoverflow.com/users/25700",
"pm_score": 4,
"selected": false,
"text": ".update def merge(dict1,*dicts):\n for dict2 in dicts:\n dict1.update(dict2)\n return dict1\n merge(dict1,dict2)\nmerge(dict1,dict2,dict3)\nmerge(dict1,dict2,dict3,dict4)\nmerge({},dict1,dict2) # this one returns a new copy\n"
},
{
"answer_id": 26111877,
"author": "bassounds",
"author_id": 3169972,
"author_profile": "https://Stackoverflow.com/users/3169972",
"pm_score": 3,
"selected": false,
"text": "{'a': 1, 'b': 2, 10, 'c': 11}\n x y x y x = {'a':1, 'b': 2}\ny = {'b':10, 'c': 11}\n\nz = {}\nfor k, v in x.items():\n if not k in z:\n z[k] = [(v)]\n else:\n z[k].append((v))\nfor k, v in y.items():\n if not k in z:\n z[k] = [(v)]\n else:\n z[k].append((v))\n\n{'a': [1], 'b': [2, 10], 'c': [11]}\n"
},
{
"answer_id": 26853961,
"author": "Russia Must Remove Putin",
"author_id": 541136,
"author_profile": "https://Stackoverflow.com/users/541136",
"pm_score": 14,
"selected": true,
"text": "x y z y x PEP-584 z = x | y\n z = {**x, **y}\n def merge_two_dicts(x, y):\n z = x.copy() # start with keys and values of x\n z.update(y) # modifies z with keys and values of y\n return z\n z = merge_two_dicts(x, y)\n x = {'a': 1, 'b': 2}\ny = {'b': 3, 'c': 4}\n z >>> z\n{'a': 1, 'b': 3, 'c': 4}\n z = {**x, **y}\n z = {**x, 'foo': 1, 'bar': 2, **y}\n >>> z\n{'a': 1, 'b': 3, 'foo': 1, 'bar': 2, 'c': 4}\n z = x.copy()\nz.update(y) # which returns None since it mutates z\n y x b 3 def merge_two_dicts(x, y):\n \"\"\"Given two dictionaries, merge them into a new dict as a shallow copy.\"\"\"\n z = x.copy()\n z.update(y)\n return z\n z = merge_two_dicts(x, y)\n def merge_dicts(*dict_args):\n \"\"\"\n Given any number of dictionaries, shallow copy and merge into a new dict,\n precedence goes to key-value pairs in latter dictionaries.\n \"\"\"\n result = {}\n for dictionary in dict_args:\n result.update(dictionary)\n return result\n a g z = merge_dicts(a, b, c, d, e, f, g) \n g a f z = dict(x.items() + y.items())\n dict_items >>> c = dict(a.items() + b.items())\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: unsupported operand type(s) for +: 'dict_items' and 'dict_items'\n z = dict(list(x.items()) + list(y.items())) items() viewitems() >>> c = dict(a.items() | b.items())\n >>> x = {'a': []}\n>>> y = {'b': []}\n>>> dict(x.items() | y.items())\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: unhashable type: 'list'\n y x >>> x = {'a': 2}\n>>> y = {'a': 1}\n>>> dict(x.items() | y.items())\n{'a': 2}\n z = dict(x, **y)\n dict frozenset >>> c = dict(a, **b)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: keyword arguments must be strings\n dict(**y) dict(a=1, b=10, c=11)\n {'a': 1, 'b': 10, 'c': 11}\n dict(x, **y) dict >>> foo(**{('a', 'b'): None})\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: foo() keywords must be strings\n>>> dict(**{('a', 'b'): None})\n{('a', 'b'): None}\n dict(x.items() + y.items()) merge_two_dicts(x, y) {**x, **y} from copy import deepcopy\n\ndef dict_of_dicts_merge(x, y):\n z = {}\n overlapping_keys = x.keys() & y.keys()\n for key in overlapping_keys:\n z[key] = dict_of_dicts_merge(x[key], y[key])\n for key in x.keys() - overlapping_keys:\n z[key] = deepcopy(x[key])\n for key in y.keys() - overlapping_keys:\n z[key] = deepcopy(y[key])\n return z\n >>> x = {'a':{1:{}}, 'b': {2:{}}}\n>>> y = {'b':{10:{}}, 'c': {11:{}}}\n>>> dict_of_dicts_merge(x, y)\n{'b': {2: {}, 10: {}}, 'a': {1: {}}, 'c': {11: {}}}\n copy update {k: v for d in dicts for k, v in d.items()} # iteritems in Python 2.7\n dict((k, v) for d in dicts for k, v in d.items()) # iteritems in Python 2\n itertools.chain from itertools import chain\nz = dict(chain(x.items(), y.items())) # iteritems in Python 2\n from timeit import repeat\nfrom itertools import chain\n\nx = dict.fromkeys('abcdefg')\ny = dict.fromkeys('efghijk')\n\ndef merge_two_dicts(x, y):\n z = x.copy()\n z.update(y)\n return z\n\nmin(repeat(lambda: {**x, **y}))\nmin(repeat(lambda: merge_two_dicts(x, y)))\nmin(repeat(lambda: {k: v for d in (x, y) for k, v in d.items()}))\nmin(repeat(lambda: dict(chain(x.items(), y.items()))))\nmin(repeat(lambda: dict(item for d in (x, y) for item in d.items())))\n >>> min(repeat(lambda: {**x, **y}))\n1.0804965235292912\n>>> min(repeat(lambda: merge_two_dicts(x, y)))\n1.636518670246005\n>>> min(repeat(lambda: {k: v for d in (x, y) for k, v in d.items()}))\n3.1779992282390594\n>>> min(repeat(lambda: dict(chain(x.items(), y.items()))))\n2.740647904574871\n>>> min(repeat(lambda: dict(item for d in (x, y) for item in d.items())))\n4.266070580109954\n $ uname -a\nLinux nixos 4.19.113 #1-NixOS SMP Wed Mar 25 07:06:15 UTC 2020 x86_64 GNU/Linux\n"
},
{
"answer_id": 28753078,
"author": "Bilal Syed Hussain",
"author_id": 852240,
"author_profile": "https://Stackoverflow.com/users/852240",
"pm_score": 7,
"selected": false,
"text": "x = {'a': 1, 'b': 1}\ny = {'a': 2, 'c': 2}\nfinal = {**x, **y} \nfinal\n# {'a': 2, 'b': 1, 'c': 2}\n final = {'a': 1, 'b': 1, **x, **y}\n d = {'spam': 1, 'eggs': 2, 'cheese': 3}\ne = {'cheese': 'cheddar', 'aardvark': 'Ethel'}\nd | e\n# {'spam': 1, 'eggs': 2, 'cheese': 'cheddar', 'aardvark': 'Ethel'}\n"
},
{
"answer_id": 31478567,
"author": "RemcoGerlich",
"author_id": 799163,
"author_profile": "https://Stackoverflow.com/users/799163",
"pm_score": 4,
"selected": false,
"text": ">>> x = {'a':1, 'b': 2}\n>>> y = {'b':10, 'c': 11}\n>>> { key: y[key] if key in y else x[key]\n for key in set(x) + set(y)\n }\n"
},
{
"answer_id": 31812635,
"author": "reubano",
"author_id": 408556,
"author_profile": "https://Stackoverflow.com/users/408556",
"pm_score": 5,
"selected": false,
"text": "# py2\nfrom itertools import chain, imap\nmerge = lambda *args: dict(chain.from_iterable(imap(dict.iteritems, args)))\n\n# py3\nfrom itertools import chain\nmerge = lambda *args: dict(chain.from_iterable(map(dict.items, args)))\n >>> x = {'a':1, 'b': 2}\n>>> y = {'b':10, 'c': 11}\n>>> merge(x, y)\n{'a': 1, 'b': 10, 'c': 11}\n\n>>> z = {'c': 3, 'd': 4}\n>>> merge(x, y, z)\n{'a': 1, 'b': 10, 'c': 3, 'd': 4}\n"
},
{
"answer_id": 33999337,
"author": "reetesh11",
"author_id": 3145137,
"author_profile": "https://Stackoverflow.com/users/3145137",
"pm_score": 4,
"selected": false,
"text": "from collections import Counter\ndict1 = {'a':1, 'b': 2}\ndict2 = {'b':10, 'c': 11}\nresult = dict(Counter(dict1) + Counter(dict2))\n"
},
{
"answer_id": 34899183,
"author": "Robino",
"author_id": 833208,
"author_profile": "https://Stackoverflow.com/users/833208",
"pm_score": 6,
"selected": false,
"text": "z={k: v for d in [x,y] for k, v in d.items()}\n\n>>> print z\n{'a': 1, 'c': 11, 'b': 10}\n"
},
{
"answer_id": 36263150,
"author": "kjo",
"author_id": 559827,
"author_profile": "https://Stackoverflow.com/users/559827",
"pm_score": 4,
"selected": false,
"text": "from functools import reduce\n\ndef merge_dicts(*dicts):\n return reduce(lambda a, d: a.update(d) or a, dicts, {})\n or a lambda dict.update None"
},
{
"answer_id": 37304637,
"author": "Alfe",
"author_id": 1281485,
"author_profile": "https://Stackoverflow.com/users/1281485",
"pm_score": 3,
"selected": false,
"text": "z = MergeDict(x, y)\n dict dict(z) a = { 'x': 3, 'y': 4 }\nb = MergeDict(a) # we merge just one dict\nb['x'] = 5\nprint b # will print {'x': 5, 'y': 4}\nprint a # will print {'y': 4, 'x': 3}\n MergeDict class MergeDict(object):\n def __init__(self, *originals):\n self.originals = ({},) + originals[::-1] # reversed\n\n def __getitem__(self, key):\n for original in self.originals:\n try:\n return original[key]\n except KeyError:\n pass\n raise KeyError(key)\n\n def __setitem__(self, key, value):\n self.originals[0][key] = value\n\n def __iter__(self):\n return iter(self.keys())\n\n def __repr__(self):\n return '%s(%s)' % (\n self.__class__.__name__,\n ', '.join(repr(original)\n for original in reversed(self.originals)))\n\n def __str__(self):\n return '{%s}' % ', '.join(\n '%r: %r' % i for i in self.iteritems())\n\n def iteritems(self):\n found = set()\n for original in self.originals:\n for k, v in original.iteritems():\n if k not in found:\n yield k, v\n found.add(k)\n\n def items(self):\n return list(self.iteritems())\n\n def keys(self):\n return list(k for k, _ in self.iteritems())\n\n def values(self):\n return list(v for _, v in self.iteritems())\n"
},
{
"answer_id": 40677646,
"author": "Mike Graham",
"author_id": 192839,
"author_profile": "https://Stackoverflow.com/users/192839",
"pm_score": 3,
"selected": false,
"text": "toolz.merge([x, y])"
},
{
"answer_id": 44262317,
"author": "gboffi",
"author_id": 2749397,
"author_profile": "https://Stackoverflow.com/users/2749397",
"pm_score": 0,
"selected": false,
"text": "python-3x $ python2\nPython 2.7.13 (default, Jan 19 2017, 14:48:08) \n[GCC 6.3.0 20170118] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> x = {'a':1, 'b': 2}\n>>> y = {'b':10, 'c': 11}\n>>> [z.update(d) for z in [{}] for d in (x, y)]\n[None, None]\n>>> z\n{'a': 1, 'c': 11, 'b': 10}\n>>> ...\n"
},
{
"answer_id": 46356150,
"author": "gilch",
"author_id": 4381487,
"author_profile": "https://Stackoverflow.com/users/4381487",
"pm_score": 5,
"selected": false,
"text": "x x.update(y) or x\n update() None x .update() None or (x.update(y), x)[-1]\n x lambda lambda (lambda x: x.update(y) or x)({'a': 1, 'b': 2})\n (x := {'a': 1, 'b': 2}).update(y) or x\n (lambda x={'a': 1, 'b': 2}: x.update(y) or x)()\n x | y {**x, **y} (lambda z=x.copy(): z.update(y) or z)()\n (z := x.copy()).update(y) or z"
},
{
"answer_id": 49420387,
"author": "litepresence",
"author_id": 3680588,
"author_profile": "https://Stackoverflow.com/users/3680588",
"pm_score": 3,
"selected": false,
"text": "import json\nimport yaml\nimport time\nfrom ast import literal_eval as literal\n\ndef merge_two_dicts(x, y):\n z = x.copy() # start with x's keys and values\n z.update(y) # modifies z with y's keys and values & returns None\n return z\n\nx = {'a':1, 'b': 2}\ny = {'b':10, 'c': 11}\n\nstart = time.time()\nfor i in range(10000):\n z = yaml.load((str(x)+str(y)).replace('}{',', '))\nelapsed = (time.time()-start)\nprint (elapsed, z, 'stringify yaml')\n\nstart = time.time()\nfor i in range(10000):\n z = literal((str(x)+str(y)).replace('}{',', '))\nelapsed = (time.time()-start)\nprint (elapsed, z, 'stringify literal')\n\nstart = time.time()\nfor i in range(10000):\n z = eval((str(x)+str(y)).replace('}{',', '))\nelapsed = (time.time()-start)\nprint (elapsed, z, 'stringify eval')\n\nstart = time.time()\nfor i in range(10000):\n z = {k:int(v) for k,v in (dict(zip(\n ((str(x)+str(y))\n .replace('}',' ')\n .replace('{',' ')\n .replace(':',' ')\n .replace(',',' ')\n .replace(\"'\",'')\n .strip()\n .split(' '))[::2], \n ((str(x)+str(y))\n .replace('}',' ')\n .replace('{',' ').replace(':',' ')\n .replace(',',' ')\n .replace(\"'\",'')\n .strip()\n .split(' '))[1::2]\n ))).items()}\nelapsed = (time.time()-start)\nprint (elapsed, z, 'stringify replace')\n\nstart = time.time()\nfor i in range(10000):\n z = json.loads(str((str(x)+str(y)).replace('}{',', ').replace(\"'\",'\"')))\nelapsed = (time.time()-start)\nprint (elapsed, z, 'stringify json')\n\nstart = time.time()\nfor i in range(10000):\n z = merge_two_dicts(x, y)\nelapsed = (time.time()-start)\nprint (elapsed, z, 'accepted')\n 7.693928956985474 {'c': 11, 'b': 10, 'a': 1} stringify yaml\n0.29134678840637207 {'c': 11, 'b': 10, 'a': 1} stringify literal\n0.2208399772644043 {'c': 11, 'b': 10, 'a': 1} stringify eval\n0.1106564998626709 {'c': 11, 'b': 10, 'a': 1} stringify replace\n0.07989692687988281 {'c': 11, 'b': 10, 'a': 1} stringify json\n0.005082368850708008 {'c': 11, 'b': 10, 'a': 1} accepted\n ast"
},
{
"answer_id": 49847631,
"author": "Josh Bode",
"author_id": 182469,
"author_profile": "https://Stackoverflow.com/users/182469",
"pm_score": 3,
"selected": false,
"text": "reduce >>> from functools import reduce\n>>> l = [{'a': 1}, {'b': 2}, {'a': 100, 'c': 3}]\n>>> reduce(lambda x, y: {**x, **y}, l, {})\n{'a': 100, 'b': 2, 'c': 3}\n lambda operator.ior >>> from functools import reduce\n>>> from operator import ior\n>>> l = [{'a': 1}, {'b': 2}, {'a': 100, 'c': 3}]\n>>> reduce(ior, l, {})\n{'a': 100, 'b': 2, 'c': 3}\n ior >>> from functools import reduce\n>>> l = [{'a': 1}, {'b': 2}, {'a': 100, 'c': 3}]\n>>> reduce(lambda x, y: x.update(y) or x, l, {})\n{'a': 100, 'b': 2, 'c': 3}\n"
},
{
"answer_id": 50289800,
"author": "Tigran Saluev",
"author_id": 999858,
"author_profile": "https://Stackoverflow.com/users/999858",
"pm_score": 1,
"selected": false,
"text": "z = next(z.update(y) or z for z in [x.copy()])\n# or\nz = (lambda z: z.update(y) or z)(x.copy())\n {**x, **y}"
},
{
"answer_id": 54930992,
"author": "ShadowRanger",
"author_id": 364696,
"author_profile": "https://Stackoverflow.com/users/364696",
"pm_score": 4,
"selected": false,
"text": ":= copy update newdict = dict1.copy()\nnewdict.update(dict2)\n (newdict := dict1.copy()).update(dict2)\n dict dict newdict myfunc((newdict := dict1.copy()).update(dict2)) or newdict update None newdict (newdict := dict1.copy()).update(dict2) or newdict\n newdict = {**dict1, **dict2}\n list tuple newdict = {}\nnewdict.update(dict1)\nnewdict.update(dict2)\n dict (newdict := dict1.copy()).update(dict2) dict newdict = {**dict1, **dict2, **dict3}\n (newdict := dict1.copy()).update(dict2), newdict.update(dict3)\n None None (newdict := dict1.copy()).update(dict2) or newdict.update(dict3)\n tuple None update None or set dict copy update dict dict myspecialdict({**speciala, **specialb}) dict myspecialdict dict dict dict dict1 dict"
},
{
"answer_id": 61116810,
"author": "Roushan",
"author_id": 3462681,
"author_profile": "https://Stackoverflow.com/users/3462681",
"pm_score": 3,
"selected": false,
"text": "dict >>> d = {'spam': 1, 'eggs': 2, 'cheese': 3}\n>>> e = {'cheese': 'cheddar', 'aardvark': 'Ethel'}\n>>> d | e\n{'spam': 1, 'eggs': 2, 'cheese': 'cheddar', 'aardvark': 'Ethel'}\n >>> d |= e\n>>> d\n{'spam': 1, 'eggs': 2, 'cheese': 'cheddar', 'aardvark': 'Ethel'}\n"
},
{
"answer_id": 62141222,
"author": "xjcl",
"author_id": 2111778,
"author_profile": "https://Stackoverflow.com/users/2111778",
"pm_score": 4,
"selected": false,
"text": "| dict set >>> d = {'a': 1, 'b': 2}\n>>> e = {'a': 9, 'c': 3}\n>>> d | e\n{'a': 9, 'b': 2, 'c': 3}\n dict |= dict >>> e |= d # e = e | d\n>>> e\n{'a': 1, 'c': 3, 'b': 2}\n"
},
{
"answer_id": 62820532,
"author": "Nico Schlömer",
"author_id": 353337,
"author_profile": "https://Stackoverflow.com/users/353337",
"pm_score": 6,
"selected": false,
"text": "x | y\n {**x, **y}\n temp = x.copy()\ntemp.update(y)\n from collections import ChainMap\nfrom itertools import chain\nimport perfplot\n\n\ndef setup(n):\n x = dict(zip(range(n), range(n)))\n y = dict(zip(range(n, 2 * n), range(n, 2 * n)))\n return x, y\n\n\ndef copy_update(x, y):\n temp = x.copy()\n temp.update(y)\n return temp\n\n\ndef add_items(x, y):\n return dict(list(x.items()) + list(y.items()))\n\n\ndef curly_star(x, y):\n return {**x, **y}\n\n\ndef chain_map(x, y):\n return dict(ChainMap({}, y, x))\n\n\ndef itertools_chain(x, y):\n return dict(chain(x.items(), y.items()))\n\n\ndef python39_concat(x, y):\n return x | y\n\n\nb = perfplot.bench(\n setup=setup,\n kernels=[\n copy_update,\n add_items,\n curly_star,\n chain_map,\n itertools_chain,\n python39_concat,\n ],\n labels=[\n \"copy_update\",\n \"dict(list(x.items()) + list(y.items()))\",\n \"{**x, **y}\",\n \"chain_map\",\n \"itertools.chain\",\n \"x | y\",\n ],\n n_range=[2 ** k for k in range(18)],\n xlabel=\"len(x), len(y)\",\n equality_check=None,\n)\nb.save(\"out.png\")\nb.show()\n"
},
{
"answer_id": 64228920,
"author": "disooqi",
"author_id": 2377431,
"author_profile": "https://Stackoverflow.com/users/2377431",
"pm_score": 3,
"selected": false,
"text": ">>> pycon = {2016: \"Portland\", 2018: \"Cleveland\"}\n>>> europython = {2017: \"Rimini\", 2018: \"Edinburgh\", 2019: \"Basel\"}\n\n>>> pycon | europython\n{2016: 'Portland', 2018: 'Edinburgh', 2017: 'Rimini', 2019: 'Basel'}\n\n>>> pycon |= europython\n>>> pycon\n{2016: 'Portland', 2018: 'Edinburgh', 2017: 'Rimini', 2019: 'Basel'}\n\n d1 | d2 {**d1, **d2} | >>> from collections import defaultdict\n>>> europe = defaultdict(lambda: \"\", {\"Norway\": \"Oslo\", \"Spain\": \"Madrid\"})\n>>> africa = defaultdict(lambda: \"\", {\"Egypt\": \"Cairo\", \"Zimbabwe\": \"Harare\"})\n\n>>> europe | africa\ndefaultdict(<function <lambda> at 0x7f0cb42a6700>,\n {'Norway': 'Oslo', 'Spain': 'Madrid', 'Egypt': 'Cairo', 'Zimbabwe': 'Harare'})\n\n>>> {**europe, **africa}\n{'Norway': 'Oslo', 'Spain': 'Madrid', 'Egypt': 'Cairo', 'Zimbabwe': 'Harare'}\n | {**europe, **africa} | + + |= .update() >>> libraries = {\n... \"collections\": \"Container datatypes\",\n... \"math\": \"Mathematical functions\",\n... }\n>>> libraries |= {\"zoneinfo\": \"IANA time zone support\"}\n>>> libraries\n{'collections': 'Container datatypes', 'math': 'Mathematical functions',\n 'zoneinfo': 'IANA time zone support'}\n | |= >>> libraries |= [(\"graphlib\", \"Functionality for graph-like structures\")]\n>>> libraries\n{'collections': 'Container datatypes', 'math': 'Mathematical functions',\n 'zoneinfo': 'IANA time zone support',\n 'graphlib': 'Functionality for graph-like structures'}\n"
},
{
"answer_id": 68883045,
"author": "Brian",
"author_id": 8126390,
"author_profile": "https://Stackoverflow.com/users/8126390",
"pm_score": 2,
"selected": false,
"text": "| new existing new existing def merge_dict_recursive(new: dict, existing: dict):\n merged = new | existing\n\n for k, v in merged.items():\n if isinstance(v, dict):\n if k not in existing:\n # The key is not in existing dict at all, so add entire value\n existing[k] = new[k]\n\n merged[k] = merge_dict_recursive(new[k], existing[k])\n return merged\n new\n{'dashboard': True,\n 'depth': {'a': 1, 'b': 22222, 'c': {'d': {'e': 69}}},\n 'intro': 'this is the dashboard',\n 'newkey': False,\n 'show_closed_sessions': False,\n 'version': None,\n 'visible_sessions_limit': 9999}\nexisting\n{'dashboard': True,\n 'depth': {'a': 5},\n 'intro': 'this is the dashboard',\n 'newkey': True,\n 'show_closed_sessions': False,\n 'version': '2021-08-22 12:00:30.531038+00:00'}\nmerged\n{'dashboard': True,\n 'depth': {'a': 5, 'b': 22222, 'c': {'d': {'e': 69}}},\n 'intro': 'this is the dashboard',\n 'newkey': True,\n 'show_closed_sessions': False,\n 'version': '2021-08-22 12:00:30.531038+00:00',\n 'visible_sessions_limit': 9999}\n"
},
{
"answer_id": 69335330,
"author": "worroc",
"author_id": 5871672,
"author_profile": "https://Stackoverflow.com/users/5871672",
"pm_score": 2,
"selected": false,
"text": "from typing import List, Dict\nfrom copy import deepcopy\n\ndef merge_dicts(*from_dicts: List[Dict], no_copy: bool=False) -> Dict :\n \"\"\" no recursion deep merge of two dicts\n\n By default creates fresh Dict and merges all to it.\n\n no_copy = True, will merge all dicts to a fist one in a list without copy.\n Why? Sometime I need to combine one dictionary from \"layers\".\n The \"layers\" are not in use and dropped immediately after merging.\n \"\"\"\n\n if no_copy:\n xerox = lambda x:x\n else:\n xerox = deepcopy\n\n result = xerox(from_dicts[0])\n\n for _from in from_dicts[1:]:\n merge_queue = [(result, _from)]\n for _to, _from in merge_queue:\n for k, v in _from.items():\n if k in _to and isinstance(_to[k], dict) and isinstance(v, dict):\n # key collision add both are dicts.\n # add to merging queue\n merge_queue.append((_to[k], v))\n continue\n _to[k] = xerox(v)\n\n return result\n print(\"=============================\")\nprint(\"merge all dicts to first one without copy.\")\na0 = {\"a\":{\"b\":1}}\na1 = {\"a\":{\"c\":{\"d\":4}}}\na2 = {\"a\":{\"c\":{\"f\":5}, \"d\": 6}}\nprint(f\"a0 id[{id(a0)}] value:{a0}\")\nprint(f\"a1 id[{id(a1)}] value:{a1}\")\nprint(f\"a2 id[{id(a2)}] value:{a2}\")\nr = merge_dicts(a0, a1, a2, no_copy=True)\nprint(f\"r id[{id(r)}] value:{r}\")\n\nprint(\"=============================\")\nprint(\"create fresh copy of all\")\na0 = {\"a\":{\"b\":1}}\na1 = {\"a\":{\"c\":{\"d\":4}}}\na2 = {\"a\":{\"c\":{\"f\":5}, \"d\": 6}}\nprint(f\"a0 id[{id(a0)}] value:{a0}\")\nprint(f\"a1 id[{id(a1)}] value:{a1}\")\nprint(f\"a2 id[{id(a2)}] value:{a2}\")\nr = merge_dicts(a0, a1, a2)\nprint(f\"r id[{id(r)}] value:{r}\")\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/38987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3207/"
] |
38,993
|
<p>Here's a basic regex technique that I've never managed to remember. Let's say I'm using a fairly generic regex implementation (e.g., grep or grep -E). If I were to do a list of files and match any that end in either <code>.sty</code> or <code>.cls</code>, how would I do that?</p>
|
[
{
"answer_id": 38994,
"author": "Peter Hoffmann",
"author_id": 720,
"author_profile": "https://Stackoverflow.com/users/720",
"pm_score": 2,
"selected": false,
"text": "egrep \"\\.sty$|\\.cls$\"\n"
},
{
"answer_id": 39004,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 3,
"selected": true,
"text": "ls | grep -E \"\\.(sty|cls)$\"\n \\. \".\" . (sty|cls) \"sty\" \"cls\" or $ grep -E egrep grep -e"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/38993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4161/"
] |
38,998
|
<p>I'm an Information Architect and JavaScript developer by trade nowadays, but recently I've been getting back into back-end coding again. And, whilst trying to get an HTML prototype integrated and working with our C#-based CMS, I've come to blows with our programmers over the HTML ID attributes being arbitrarily rewritten by .NET for form elements.</p>
<p>I can understand the code-behind reasoning for .NET changing IDs, but the fact you can no longer use IDs when trying to develop e.g. jQuery enhanced interfaces is causing some friction. What can I do to work around this?</p>
<p>I've tried using the class attribute instead, but that's really crappy, not what it's meant for and doesn't get around that problem of .NET effectively changing rendered source on the fly. It also means that CSS is less useful now and less efficient to create and maintain.</p>
<p>Any tips or advice greatly appreciated--anything for a few less sleepless nights...</p>
|
[
{
"answer_id": 39012,
"author": "Serhat Ozgel",
"author_id": 31505,
"author_profile": "https://Stackoverflow.com/users/31505",
"pm_score": 2,
"selected": false,
"text": "public class MyTextBox : TextBox\n{\n public override string ClientID { get { return ID; } }\n public override string UniqueID { get { return ID; } }\n}\n <%@ Register Assembly=\"MyLibrary\" NameSpace=\"MyLibrary.WebControls\" TagPrefix=\"MyPrefix\" %>\n <MyPrefix:MyTextBox ID=\"sampleTextBox\" runat=\"server\" />\n"
},
{
"answer_id": 39015,
"author": "Glenn Slaven",
"author_id": 2975,
"author_profile": "https://Stackoverflow.com/users/2975",
"pm_score": 6,
"selected": true,
"text": "<asp:button id=\"ImAButton\" runat=\"server\">Click Me</asp:button>\n\n<script type=\"text/javascript\">\nvar buttonId = \"<%=ImAButton.ClientId%>\";\n$(\"#\"+buttonId).bind('click', function() { alert('hi); });\n</script>\n"
},
{
"answer_id": 39019,
"author": "Jon Galloway",
"author_id": 5,
"author_profile": "https://Stackoverflow.com/users/5",
"pm_score": 4,
"selected": false,
"text": "public override string UniqueID\n{\n get { return this.ID; }\n}\npublic override string ClientID\n{\n get { return this.ID; }\n}\n"
},
{
"answer_id": 40143,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 1,
"selected": false,
"text": "public void RegisterControlClientID(Control control)\n{\n string variableDeclaration = string.Format(\"var {0} = \\\"{1}\\\";\", control.ID, control.ClientID);\n ClientScript.RegisterClientScriptBlock(GetType(), control.ID, variableDeclaration, true);\n}\n RegisterControlClientID(m_SomeTextBox);\n var m_SomeTextBox = \"ctl00_m_ContentPlaceHolder_m_SomeTextBox\";\n"
},
{
"answer_id": 47034,
"author": "Jesús E. Santos",
"author_id": 4547,
"author_profile": "https://Stackoverflow.com/users/4547",
"pm_score": 1,
"selected": false,
"text": "var elemPrefix = 'ctl00-ContentPlaceHolder-'; //replace the dashes for underscores\n\nvar o = function(name)\n{ \n return document.getElementById(elemPrefix + name)\n}\n $(o('buttonId')).bind('click', function() { alert('hi); });\n"
},
{
"answer_id": 51695,
"author": "Ian Oxley",
"author_id": 1904,
"author_profile": "https://Stackoverflow.com/users/1904",
"pm_score": 0,
"selected": false,
"text": "$('fieldset > input[type=\"submit\"]').click(function() {...});\n"
},
{
"answer_id": 112815,
"author": "Herb Caudill",
"author_id": 239663,
"author_profile": "https://Stackoverflow.com/users/239663",
"pm_score": 1,
"selected": false,
"text": " <div id=\"DataGridContainer\">\n <asp:datagrid runat=server id=\"DataGrid\" >\n ......\n <asp:datagrid>\n </div>\n"
},
{
"answer_id": 1836141,
"author": "Hogan",
"author_id": 215752,
"author_profile": "https://Stackoverflow.com/users/215752",
"pm_score": 0,
"selected": false,
"text": "<asp:button id=\"ImAButton\" runat=\"server\">Click Me</asp:button>\n\n<script type=\"text/javascript\">\nvar buttonId = <%=ImAButton.ClientId%>\n$(buttonId).bind('click', function() { alert('hi); });\n</script>\n <script type=\"text/javascript\">\nfunction MakeAClick(inid)\n{\n $(inid).bind('click', function() { alert('hi); });\n}\n</script>\n"
},
{
"answer_id": 35334302,
"author": "FanManPro",
"author_id": 4214582,
"author_profile": "https://Stackoverflow.com/users/4214582",
"pm_score": 0,
"selected": false,
"text": "static <%@ Page Title=\"\" ClientIDMode=\"Static\" Language=\"C#\" CodeBehind=\"...\" Inherits=\"WebApplication1.WebForm2\" %>\n <asp:Panel runat=\"server\" ClientIDMode=\"Static\"></asp:Panel>\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/38998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3212/"
] |
39,003
|
<p>If I have interface IFoo, and have several classes that implement it, what is the best/most elegant/cleverest way to test all those classes against the interface?</p>
<p>I'd like to reduce test code duplication, but still 'stay true' to the principles of Unit testing.</p>
<p>What would you consider best practice? I'm using NUnit, but I suppose examples from any Unit testing framework would be valid</p>
|
[
{
"answer_id": 39034,
"author": "Spoike",
"author_id": 3713,
"author_profile": "https://Stackoverflow.com/users/3713",
"pm_score": 5,
"selected": true,
"text": "public interface IFoo {\n\n public void CommonCode();\n\n public void SpecificCode();\n\n}\n public abstract class AbstractFoo : IFoo {\n\n public void CommonCode() {\n SpecificCode();\n }\n\n public abstract void SpecificCode();\n\n}\n [TestFixture]\npublic void TestClass {\n\n private class TestFoo : AbstractFoo {\n boolean hasCalledSpecificCode = false;\n public void SpecificCode() {\n hasCalledSpecificCode = true;\n }\n }\n\n [Test]\n public void testCommonCallsSpecificCode() {\n TestFoo fooFighter = new TestFoo();\n fooFighter.CommonCode();\n Assert.That(fooFighter.hasCalledSpecificCode, Is.True());\n }\n}\n [TestFixture]\npublic void TestClass : AbstractFoo {\n\n boolean hasCalledSpecificCode;\n public void specificCode() {\n hasCalledSpecificCode = true;\n }\n\n [Test]\n public void testCommonCallsSpecificCode() {\n AbstractFoo fooFighter = this;\n hasCalledSpecificCode = false;\n fooFighter.CommonCode();\n Assert.That(fooFighter.hasCalledSpecificCode, Is.True());\n } \n\n}\n CommonCode SpecificCode Page_Load Load"
},
{
"answer_id": 39036,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 2,
"selected": false,
"text": "public static ReturnType MethodName (this IMyinterface myImplementation, SomeObject someParameter)\n{\n //method body goes here\n}\n"
},
{
"answer_id": 39363,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 4,
"selected": false,
"text": "public interface List {\n\n // adds o and returns the list\n public List add(Object o);\n\n // removed the first occurrence of o and returns the list\n public List remove(Object o);\n\n}\n abstract class BaseListTest {\n\n abstract public List newListInstance();\n\n public void testAddToList() {\n // do some adding tests\n }\n\n public void testRemoveFromList() {\n // do some removing tests\n }\n\n}\n\nclass ArrayListTest < BaseListTest {\n List newListInstance() { new ArrayList(); }\n\n public void arrayListSpecificTest1() {\n // test something about ArrayLists beyond the List requirements\n }\n}\n"
},
{
"answer_id": 40959,
"author": "Emperor XLII",
"author_id": 2495,
"author_profile": "https://Stackoverflow.com/users/2495",
"pm_score": 1,
"selected": false,
"text": "CombinatorialTest UsingImplementations"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3024/"
] |
39,059
|
<p>Large pages are available in <code>Windows Server 2003</code> and <code>Windows Vista</code>. </p>
<p>But how do I enable large pages for my application? </p>
|
[
{
"answer_id": 39069,
"author": "Martin",
"author_id": 770,
"author_profile": "https://Stackoverflow.com/users/770",
"pm_score": 1,
"selected": false,
"text": "Lock pages in memory"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/988/"
] |
39,061
|
<p>I've convinced myself that they can't.</p>
<p>Take for example:</p>
<p>4 4 + 4 /</p>
<p>stack: 4
stack: 4 4
4 + 4 = 8
stack: 8
stack: 8 4
8 / 4 = 2
stack: 2</p>
<p>There are two ways that you could write the above expression with the
same operators and operands such that the operands all come first: "4
4 4 + /" and "4 4 4 / +", neither of which evaluate to 2.</p>
<p>"4 4 4 + /"
stack: 4
stack: 4 4
stack: 4 4 4
4 + 4 = 8
stack: 4 8
4 / 8 = 0.5
stack: 0.5</p>
<p>"4 4 4 / +"
stack: 4
stack: 4 4
stack: 4 4 4
4 / 4 = 1
stack: 4 1
4 + 1 = 5
stack: 5</p>
<p>If you have the ability to swap items on the stack then yes, it's possible, otherwise, no.</p>
<p>Thoughts?</p>
|
[
{
"answer_id": 39072,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": true,
"text": "(a + b) * (c + d)\n a b + c d + *\n a b c d +\na b S\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4175/"
] |
39,064
|
<p>I'm trying to call a 3rd party vendor's C DLL from vb.net 2005 and am getting <code>P/Invoke</code> errors. I'm successfully calling other methods but have hit a bottle-neck on one of the more complex. The structures involved are horrendous and in an attempt to simplify the troubleshooting I'd like to create a C++ DLL to replicate the problem. </p>
<p>Can somebody provide the smallest code snippet for a C++ DLL that can be called from .Net? I'm getting a <code>Unable to find entry point named XXX in DLL</code> error in my C++ dll. It should be simple to resolve but I'm not a C++ programmer.</p>
<p>I'd like to use a .net declaration for the DLL of</p>
<pre><code>Declare Function Multiply Lib "C:\MyDll\Debug\MyDLL.DLL" Alias "Multiply" (ByVal ParOne As Integer, ByVal byvalParTwo As Integer) As Integer
</code></pre>
|
[
{
"answer_id": 39079,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "__declspec(dllexport) WINAPI int Multiply(int p1, int p2)\n{\n return p1 * p2;\n}\n"
},
{
"answer_id": 43629,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "BOOL APIENTRY DllMain( HANDLE hModule, \n DWORD ul_reason_for_call, \n LPVOID lpReserved\n )\n{\n return TRUE;\n}\n\nint _stdcall multiply(int x , int y)\n{\n return x*y;\n}\n EXPORTS\n\nmultiply @1\n // stdafx.h : include file for standard system include files,\n// or project specific include files that are used frequently, but\n// are changed infrequently\n//\n\n#if !defined(AFX_STDAFX_H__5DB9057C_BAE6_48D8_8E38_464F6CB80026__INCLUDED_)\n#define AFX_STDAFX_H__5DB9057C_BAE6_48D8_8E38_464F6CB80026__INCLUDED_\n\n#if _MSC_VER > 1000\n#pragma once\n#endif // _MSC_VER > 1000\n\n\n// Insert your headers here\n#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers\n\n#include <windows.h>\n\n\n//{{AFX_INSERT_LOCATION}}\n// Microsoft Visual C++ will insert additional declarations immediately before the previous line.\n\n#endif // !defined(AFX_STDAFX_H__5DB9057C_BAE6_48D8_8E38_464F6CB80026__INCLUDED_)\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
39,065
|
<p>I am working on localization for a asp.net application that consists of several projects.</p>
<p>For this, there are some strings that are used in several of these projects. Naturally, I would prefer to have only one copy of the resource file in each project.</p>
<p>Since the resource files don't have an namespace (at least as far as I can tell), they can't be accessed like regular classes.</p>
<p>Is there any way to reference resx files in another project, within the same solution?</p>
|
[
{
"answer_id": 39169,
"author": "Mark Harris",
"author_id": 4026,
"author_profile": "https://Stackoverflow.com/users/4026",
"pm_score": 3,
"selected": false,
"text": "<Compile Include=\"path to shared file usually relative\">\n <Link>filename for Visual Studio To Dispaly.resx</Link>\n</Compile>\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1090/"
] |
39,066
|
<p>Whenever I use my MacBook away from my desk and later plug it into an external display (as primary), I get into the state of having windows deposited in both the notebook monitor and the external one.</p>
<p>To move all windows to a single screen, my current solution is to "Turn on mirroring" in the display preferences and then turn it off again. This is rather tedious, though. Does anyone know of a better way?</p>
<hr>
<p>I'm afraid the script posted by @<a href="https://stackoverflow.com/questions/39066/move-all-windows-to-a-single-monitor-with-two-attached-in-mac-os-x#39097">erlando</a> does absolutely nothing for me, running Mac OS X 10.5.4. (I.e., with windows on both screens, running the script moves not a single one of them, and it does not return any errors.) I guess I'll just have to stick with using the "mirror/unmirror" method mentioned above.</p>
<hr>
<p>@<a href="https://stackoverflow.com/questions/39066/move-all-windows-to-a-single-monitor-with-two-attached-in-mac-os-x#47233">Denton</a>: I'm afraid those links provide scripts for getting windows which are orphaned from <em>any</em> screen back onto the display. I ‘just’ want to move all windows from a secondary display onto the primary display.</p>
|
[
{
"answer_id": 39097,
"author": "erlando",
"author_id": 4192,
"author_profile": "https://Stackoverflow.com/users/4192",
"pm_score": 2,
"selected": false,
"text": "-- Source: http://www.jonathanlaliberte.com/2007/10/19/move-all-windows-to-your-main-screen/\n-- and: http://www.macosxhints.com/article.php?story=2007102012424539\n--\n-- Improvements:\n-- + code is more efficient and more elegant now\n-- + windows are moved also, if they are \"almost\" completely off-screen \n-- (in the orig. version, they would be moved only if they were completely off-screen)\n-- + windows are moved (if they are moved) to their closest position on-screen\n-- (in the orig. version, they would be moved to a \"home position\" (0,22) )\n-- Gabriel Zachmann, Jan 2008\n\n-- Example list of processes to ignore: {\"xGestures\"} or {\"xGestures\", \"OtherApp\", ...}\nproperty processesToIgnore : {\"Typinator\"}\n\n-- Get the size of the Display(s), only useful if there is one display\n-- otherwise it will grab the total size of both displays\ntell application \"Finder\"\n set _b to bounds of window of desktop\n set screen_width to item 3 of _b\n set screen_height to item 4 of _b\nend tell\n\ntell application \"System Events\"\n set allProcesses to application processes\n repeat with i from 1 to count allProcesses\n --display dialog (name of (process i)) as string\n if not (processesToIgnore contains ((name of (process i)) as string)) then\n try\n tell process i\n repeat with x from 1 to (count windows)\n set winPos to position of window x\n set _x to item 1 of winPos\n set _y to item 2 of winPos\n set winSize to size of window x\n set _w to item 1 of winSize\n set _h to item 2 of winSize\n --display dialog (name as string) & \" - width: \" & (_w as string) & \" height: \" & (_h as string)\n \n if (_x + _w < 40 or _y + _h < 50 or _x > screen_width - 40 or _y > screen_height - 40) then\n \n if (_x + _w < 40) then set _x to 0\n if (_y + _h < 50) then set _y to 22\n if (_x > screen_width - 40) then\n set _x to screen_width - _w\n if (_x < 0) then set _x to 0\n end if\n if (_y > screen_height - 40) then\n set _y to screen_height - _h\n if (_y < 22) then set _y to 22\n end if\n set position of window x to {_x, _y}\n \n end if\n end repeat\n \n end tell\n end try\n end if\n end repeat\nend tell\n"
},
{
"answer_id": 11380305,
"author": "failrat",
"author_id": 1509514,
"author_profile": "https://Stackoverflow.com/users/1509514",
"pm_score": 5,
"selected": false,
"text": "Cmd+F1 Cmd+Fn+F1"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4161/"
] |
39,070
|
<p>We need to move off traditional FTP for security purposes (it transmits it's passwords unencrypted). I am hearing SSH touted as the obvious alternative. However I have been driving FTP from an ASP.NET program interface to automate my web-site development, which is now quite a highly web-enabled process. </p>
<p>Can anyone recommend a secure way to transfer files around which has a program interface that I can drive from ASP.NET?</p>
|
[
{
"answer_id": 84138,
"author": "Martin Vobr",
"author_id": 16132,
"author_profile": "https://Stackoverflow.com/users/16132",
"pm_score": 3,
"selected": true,
"text": "// create client, connect and log in \nSftp client = new Sftp();\nclient.Connect(hostname);\nclient.Login(username, password);\n\n// upload the 'test.zip' file to the current directory at the server \nclient.PutFile(@\"c:\\data\\test.zip\", \"test.zip\");\n\n// upload the 'index.html' file to the specified directory at the server \nclient.PutFile(@\"c:\\data\\index.html\", \"/wwwroot/index.html\");\n\n// download the 'test.zip' file from the current directory at the server \nclient.GetFile(\"test.zip\", @\"c:\\data\\test.zip\");\n\n// download the 'index.html' file from the specified directory at the server \nclient.GetFile(\"/wwwroot/index.html\", @\"c:\\data\\index.html\");\n\n// upload a text using a MemoryStream \nstring message = \"Hello from Rebex SFTP for .NET!\";\nbyte[] data = System.Text.Encoding.Default.GetBytes(message);\nSystem.IO.MemoryStream ms = new System.IO.MemoryStream(data);\nclient.PutFile(ms, \"message.txt\");\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4180/"
] |
39,086
|
<p>I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it.</p>
<p>What is the best way to do this, within the following code?</p>
<pre><code>f = open(file)
for line in f:
if line.contains('foo'):
newline = line.replace('foo', 'bar')
# how to write this newline back to the file
</code></pre>
|
[
{
"answer_id": 39110,
"author": "Thomas Watnedal",
"author_id": 4059,
"author_profile": "https://Stackoverflow.com/users/4059",
"pm_score": 9,
"selected": true,
"text": "from tempfile import mkstemp\nfrom shutil import move, copymode\nfrom os import fdopen, remove\n\ndef replace(file_path, pattern, subst):\n #Create temp file\n fh, abs_path = mkstemp()\n with fdopen(fh,'w') as new_file:\n with open(file_path) as old_file:\n for line in old_file:\n new_file.write(line.replace(pattern, subst))\n #Copy the file permissions from the old file to the new file\n copymode(file_path, abs_path)\n #Remove original file\n remove(file_path)\n #Move new file\n move(abs_path, file_path)\n"
},
{
"answer_id": 39113,
"author": "hamishmcn",
"author_id": 3590,
"author_profile": "https://Stackoverflow.com/users/3590",
"pm_score": 4,
"selected": false,
"text": "fin = open(\"a.txt\")\nfout = open(\"b.txt\", \"wt\")\nfor line in fin:\n fout.write( line.replace('foo', 'bar') )\nfin.close()\nfout.close()\n"
},
{
"answer_id": 290494,
"author": "Eli Bendersky",
"author_id": 8206,
"author_profile": "https://Stackoverflow.com/users/8206",
"pm_score": 8,
"selected": false,
"text": "import fileinput\n\nfor line in fileinput.input(\"test.txt\", inplace=True):\n print('{} {}'.format(fileinput.filelineno(), line), end='') # for Python 3\n # print \"%d: %s\" % (fileinput.filelineno(), line), # for Python 2\n print fileinput sys.args[1:] with fileinput"
},
{
"answer_id": 315088,
"author": "Jason",
"author_id": 26860,
"author_profile": "https://Stackoverflow.com/users/26860",
"pm_score": 7,
"selected": false,
"text": "import fileinput\nimport sys\n\ndef replaceAll(file,searchExp,replaceExp):\n for line in fileinput.input(file, inplace=1):\n if searchExp in line:\n line = line.replace(searchExp,replaceExp)\n sys.stdout.write(line)\n replaceAll(\"/fooBar.txt\",\"Hello\\sWorld!$\",\"Goodbye\\sWorld.\")\n"
},
{
"answer_id": 1388570,
"author": "Kinlan",
"author_id": 1798387,
"author_profile": "https://Stackoverflow.com/users/1798387",
"pm_score": 6,
"selected": false,
"text": "import fileinput\n\n# Does a list of files, and\n# redirects STDOUT to the file in question\nfor line in fileinput.input(files, inplace = 1): \n print line.replace(\"foo\", \"bar\"),\n"
},
{
"answer_id": 11784227,
"author": "loi",
"author_id": 1572353,
"author_profile": "https://Stackoverflow.com/users/1572353",
"pm_score": 1,
"selected": false,
"text": "def replace(file, pattern, subst):\n #Create temp file\n fh, abs_path = mkstemp()\n print fh, abs_path\n new_file = open(abs_path,'w')\n old_file = open(file)\n for line in old_file:\n new_file.write(line.replace(pattern, subst))\n #close temp file\n new_file.close()\n close(fh)\n old_file.close()\n #Remove original file\n remove(file)\n #Move new file\n move(abs_path, file)\n"
},
{
"answer_id": 13641746,
"author": "Thijs",
"author_id": 1865688,
"author_profile": "https://Stackoverflow.com/users/1865688",
"pm_score": 5,
"selected": false,
"text": "import re\n\ndef replace(file, pattern, subst):\n # Read contents from file as a single string\n file_handle = open(file, 'r')\n file_string = file_handle.read()\n file_handle.close()\n\n # Use RE package to allow for replacement (also allowing for (multiline) REGEX)\n file_string = (re.sub(pattern, subst, file_string))\n\n # Write contents to file.\n # Using mode 'w' truncates the file.\n file_handle = open(file, 'w')\n file_handle.write(file_string)\n file_handle.close()\n"
},
{
"answer_id": 18676598,
"author": "Kiran",
"author_id": 959654,
"author_profile": "https://Stackoverflow.com/users/959654",
"pm_score": 4,
"selected": false,
"text": "from tempfile import mkstemp\nfrom shutil import move\nfrom os import remove\n\ndef replace(source_file_path, pattern, substring):\n fh, target_file_path = mkstemp()\n with open(target_file_path, 'w') as target_file:\n with open(source_file_path, 'r') as source_file:\n for line in source_file:\n target_file.write(line.replace(pattern, substring))\n remove(source_file_path)\n move(target_file_path, source_file_path)\n"
},
{
"answer_id": 21857132,
"author": "starryknight64",
"author_id": 1476057,
"author_profile": "https://Stackoverflow.com/users/1476057",
"pm_score": 4,
"selected": false,
"text": "import re\ndef replace( filePath, text, subs, flags=0 ):\n with open( filePath, \"r+\" ) as file:\n fileContents = file.read()\n textPattern = re.compile( re.escape( text ), flags )\n fileContents = textPattern.sub( subs, fileContents )\n file.seek( 0 )\n file.truncate()\n file.write( fileContents )\n"
},
{
"answer_id": 23123426,
"author": "Emmanuel",
"author_id": 3543537,
"author_profile": "https://Stackoverflow.com/users/3543537",
"pm_score": 2,
"selected": false,
"text": "import re \n\nfin = open(\"in.txt\", 'r') # in file\nfout = open(\"out.txt\", 'w') # out file\nfor line in fin:\n p = re.compile('[-][0-9]*[.][0-9]*[,]|[-][0-9]*[,]') # pattern\n newline = p.sub('',line) # replace matching strings with empty string\n print newline\n fout.write(newline)\nfin.close()\nfout.close()\n"
},
{
"answer_id": 23426834,
"author": "igniteflow",
"author_id": 343223,
"author_profile": "https://Stackoverflow.com/users/343223",
"pm_score": 3,
"selected": false,
"text": "import codecs \n\nfrom tempfile import mkstemp\nfrom shutil import move\nfrom os import remove\n\n\ndef replace(source_file_path, pattern, substring):\n fh, target_file_path = mkstemp()\n\n with codecs.open(target_file_path, 'w', 'utf-8') as target_file:\n with codecs.open(source_file_path, 'r', 'utf-8') as source_file:\n for line in source_file:\n target_file.write(line.replace(pattern, substring))\n remove(source_file_path)\n move(target_file_path, source_file_path)\n"
},
{
"answer_id": 58217364,
"author": "Akif",
"author_id": 950762,
"author_profile": "https://Stackoverflow.com/users/950762",
"pm_score": 4,
"selected": false,
"text": "fileinput import fileinput\n\ndef replace_in_file(file_path, search_text, new_text):\n with fileinput.input(file_path, inplace=True) as file:\n for line in file:\n new_line = line.replace(search_text, new_text)\n print(new_line, end='')\n fileinput file_path with print inplace=True STDOUT end='' print file_path = '/path/to/my/file'\nreplace_in_file(file_path, 'old-text', 'new-text')\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4166/"
] |
39,104
|
<p>I've written a Python package that includes a bsddb database of pre-computed values for one of the more time-consuming computations. For simplicity, my setup script installs the database file in the same directory as the code which accesses the database (on Unix, something like /usr/lib/python2.5/site-packages/mypackage/).</p>
<p>How do I store the final location of the database file so my code can access it? Right now, I'm using a hack based on the <code>__file__</code> variable in the module which accesses the database:</p>
<pre>
dbname = os.path.join(os.path.dirname(__file__), "database.dat")
</pre>
<p>It works, but it seems... hackish. Is there a better way to do this? I'd like to have the setup script just grab the final installation location from the distutils module and stuff it into a "dbconfig.py" file that gets installed alongside the code that accesses the database.</p>
|
[
{
"answer_id": 39659,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 5,
"selected": false,
"text": ">>> import pkg_resources\n>>> pkg_resources.resource_filename(__name__, \"foo.config\")\n'foo.config'\n>>> pkg_resources.resource_filename('tempfile', \"foo.config\")\n'/usr/lib/python2.4/foo.config'\n"
},
{
"answer_id": 9918496,
"author": "merwok",
"author_id": 821378,
"author_profile": "https://Stackoverflow.com/users/821378",
"pm_score": 4,
"selected": false,
"text": "pkgutil.get_data pkg_resources.resource_stream"
},
{
"answer_id": 56714420,
"author": "ankostis",
"author_id": 548792,
"author_profile": "https://Stackoverflow.com/users/548792",
"pm_score": 2,
"selected": false,
"text": "importlib.resources setuptools:pkg_resources importlib_resources __init__.py try:\n import importlib.resources as importlib_resources\nexcept ImportError:\n # In PY<3.7 fall-back to backported `importlib_resources`.\n import importlib_resources\n\n\n## Note that the actual package could have been used, \n# not just its (string) name, with something like: \n# from XXX import YYY as data_pkg\ndata_pkg = '.'\nfname = 'database.dat'\n\ndb_bytes = importlib_resources.read_binary(data_pkg, fname)\n# or if a file-like stream is needed:\nwith importlib_resources.open_binary(data_pkg, fname) as db_file:\n ...\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4198/"
] |
39,108
|
<p>What would be the best way to draw a simple animation just before showing a modal <a href="https://docs.oracle.com/javase/9/docs/api/javax/swing/JDialog.html" rel="nofollow noreferrer">JDialog</a>? (i.e. expanding borders from the mouse click point to the dialog location). I thought it would be possible to draw on the glasspane of the parent frame on the <code>setVisible</code> method of the dialog.</p>
<p>However, since the JDialog is modal to the parent, I couldn't find a way to pump drawing events into <a href="https://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html" rel="nofollow noreferrer">EDT</a> before the JDialog becomes visible, since the current event on the EDT has not been completed yet.</p>
|
[
{
"answer_id": 39868,
"author": "rcreswick",
"author_id": 3446,
"author_profile": "https://Stackoverflow.com/users/3446",
"pm_score": 1,
"selected": false,
"text": "SwingUtilities.invokeLater(new Runnable(){\n public void run(){\n doAnnimation();\n showDialog();\n }\n}\n"
},
{
"answer_id": 42959,
"author": "John Meagher",
"author_id": 3535,
"author_profile": "https://Stackoverflow.com/users/3535",
"pm_score": 0,
"selected": false,
"text": "void myShowDialog() {\n new Thread(new Runnable() {public void run() {\n SwingUtilities.invokeAndWait(new Runnable() { public void run() {\n doAnimation();\n } } );\n // Delay to wait for the animation to finish (if needed)\n Thread.sleep(500);\n SwingUtilities.invokeAndWait(new Runnable() { public void run() {\n showDialog();\n } } );\n } } ).start();\n}\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3993/"
] |
39,112
|
<p>I know in certain circumstances, such as long running processes, it is important to lock ASP.NET cache in order to avoid subsequent requests by another user for that resource from executing the long process again instead of hitting the cache.</p>
<p>What is the best way in c# to implement cache locking in ASP.NET? </p>
|
[
{
"answer_id": 40065,
"author": "a7drew",
"author_id": 4239,
"author_profile": "https://Stackoverflow.com/users/4239",
"pm_score": 8,
"selected": true,
"text": "private static object ThisLock = new object();\n\npublic string GetFoo()\n{\n\n // try to pull from cache here\n\n lock (ThisLock)\n {\n // cache was empty before we got the lock, check again inside the lock\n\n // cache is still empty, so retreive the value here\n\n // store the value in the cache here\n }\n\n // return the cached value here\n\n}\n"
},
{
"answer_id": 40106,
"author": "Seb Nilsson",
"author_id": 2429,
"author_profile": "https://Stackoverflow.com/users/2429",
"pm_score": 1,
"selected": false,
"text": "private static object _listLock = new object();\n\npublic List List() {\n string cacheKey = \"customers\";\n List myList = Cache[cacheKey] as List;\n if(myList == null) {\n lock (_listLock) {\n myList = Cache[cacheKey] as List;\n if (myList == null) {\n myList = DAL.ListCustomers();\n Cache.Insert(cacheKey, mList, null, SiteConfig.CacheDuration, TimeSpan.Zero);\n }\n }\n }\n return myList;\n}\n"
},
{
"answer_id": 41314,
"author": "John Owen",
"author_id": 2471,
"author_profile": "https://Stackoverflow.com/users/2471",
"pm_score": 5,
"selected": false,
"text": "private static object ThisLock = new object();\n...\nobject dataObject = Cache[\"globalData\"];\nif( dataObject == null )\n{\n lock( ThisLock )\n {\n dataObject = Cache[\"globalData\"];\n\n if( dataObject == null )\n {\n //Get Data from db\n dataObject = GlobalObj.GetData();\n Cache[\"globalData\"] = dataObject;\n }\n }\n}\nreturn dataObject;\n"
},
{
"answer_id": 3135475,
"author": "user378380",
"author_id": 378380,
"author_profile": "https://Stackoverflow.com/users/378380",
"pm_score": 4,
"selected": false,
"text": "private T GetOrAddToCache<T>(string cacheKey, GenericObjectParamsDelegate<T> creator, params object[] creatorArgs) where T : class, new()\n {\n T returnValue = HttpContext.Current.Cache[cacheKey] as T;\n if (returnValue == null)\n {\n lock (this)\n {\n returnValue = HttpContext.Current.Cache[cacheKey] as T;\n if (returnValue == null)\n {\n returnValue = creator(creatorArgs);\n if (returnValue == null)\n {\n throw new Exception(\"Attempt to cache a null reference\");\n }\n HttpContext.Current.Cache.Add(\n cacheKey,\n returnValue,\n null,\n System.Web.Caching.Cache.NoAbsoluteExpiration,\n System.Web.Caching.Cache.NoSlidingExpiration,\n CacheItemPriority.Normal,\n null);\n }\n }\n }\n\n return returnValue;\n }\n"
},
{
"answer_id": 23154648,
"author": "nfplee",
"author_id": 155899,
"author_profile": "https://Stackoverflow.com/users/155899",
"pm_score": 2,
"selected": false,
"text": "private static readonly object _lock = new object();\n\npublic static TResult GetOrAdd<TResult>(this Cache cache, string key, Func<TResult> action, int duration = 300) {\n TResult result;\n var data = cache[key]; // Can't cast using as operator as TResult may be an int or bool\n\n if (data == null) {\n lock (_lock) {\n data = cache[key];\n\n if (data == null) {\n result = action();\n\n if (result == null)\n return result;\n\n if (duration > 0)\n cache.Insert(key, result, null, DateTime.UtcNow.AddSeconds(duration), TimeSpan.Zero);\n } else\n result = (TResult)data;\n }\n } else\n result = (TResult)data;\n\n return result;\n}\n"
},
{
"answer_id": 26523173,
"author": "Tarık Özgün Güner",
"author_id": 1786056,
"author_profile": "https://Stackoverflow.com/users/1786056",
"pm_score": 0,
"selected": false,
"text": " private static readonly object _lock = new object();\n\n\n//If getOnly is true, only get existing cache value, not updating it. If cache value is null then set it first as running action method. So could return old value or action result value.\n//If getOnly is false, update the old value with action result. If cache value is null then set it first as running action method. So always return action result value.\n//With oldValueReturned boolean we can cast returning object(if it is not null) appropriate type on main code.\n\n\n public static object GetOrAdd<TResult>(this Cache cache, string key, Func<TResult> action,\n DateTime absoluteExpireTime, TimeSpan slidingExpireTime, bool getOnly, out bool oldValueReturned)\n{\n object result;\n var data = cache[key]; \n\n if (data == null)\n {\n lock (_lock)\n {\n data = cache[key];\n\n if (data == null)\n {\n oldValueReturned = false;\n result = action();\n\n if (result == null)\n { \n return result;\n }\n\n cache.Insert(key, result, null, absoluteExpireTime, slidingExpireTime);\n }\n else\n {\n if (getOnly)\n {\n oldValueReturned = true;\n result = data;\n }\n else\n {\n oldValueReturned = false;\n result = action();\n if (result == null)\n { \n return result;\n }\n\n cache.Insert(key, result, null, absoluteExpireTime, slidingExpireTime);\n }\n }\n }\n }\n else\n {\n if(getOnly)\n {\n oldValueReturned = true;\n result = data;\n }\n else\n {\n oldValueReturned = false;\n result = action();\n if (result == null)\n {\n return result;\n }\n\n cache.Insert(key, result, null, absoluteExpireTime, slidingExpireTime);\n } \n }\n\n return result;\n}\n"
},
{
"answer_id": 38907980,
"author": "cwills",
"author_id": 256475,
"author_profile": "https://Stackoverflow.com/users/256475",
"pm_score": 5,
"selected": false,
"text": "using System;\nusing System.Collections.Concurrent;\nusing System.Web.Caching;\n\npublic static class CacheExtensions\n{\n private static ConcurrentDictionary<string, object> keyLocks = new ConcurrentDictionary<string, object>();\n\n /// <summary>\n /// Get or Add the item to the cache using the given key. Lazily executes the value factory only if/when needed\n /// </summary>\n public static T GetOrAdd<T>(this Cache cache, string key, int durationInSeconds, Func<T> factory)\n where T : class\n {\n // Try and get value from the cache\n var value = cache.Get(key);\n if (value == null)\n {\n // If not yet cached, lock the key value and add to cache\n lock (keyLocks.GetOrAdd(key, new object()))\n {\n // Try and get from cache again in case it has been added in the meantime\n value = cache.Get(key);\n if (value == null && (value = factory()) != null)\n {\n // TODO: Some of these parameters could be added to method signature later if required\n cache.Insert(\n key: key,\n value: value,\n dependencies: null,\n absoluteExpiration: DateTime.Now.AddSeconds(durationInSeconds),\n slidingExpiration: Cache.NoSlidingExpiration,\n priority: CacheItemPriority.Default,\n onRemoveCallback: null);\n }\n\n // Remove temporary key lock\n keyLocks.TryRemove(key, out object locker);\n }\n }\n\n return value as T;\n }\n}\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2471/"
] |
39,116
|
<p>I'm working on a module for a CMS. This module is distributed as a class library DLL.</p>
<p>I have several utility libraries I'd like to use in this module. Is there anyway I can link these libraries statically so I won't have to distribute several DLL's (thereby distributing my utility libraries separately)?</p>
<p>I would like to have only one DLL.</p>
|
[
{
"answer_id": 9040079,
"author": "Kaganar",
"author_id": 873886,
"author_profile": "https://Stackoverflow.com/users/873886",
"pm_score": 4,
"selected": false,
"text": "resourceName AssemblyLoadingAndReflection"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4192/"
] |
39,119
|
<p>I have a .Net desktop application with a TreeView as one of the UI elements.</p>
<p>I want to be able to multi-select that TreeView, only that isn't supported at all.</p>
<p>So I'm adding check-boxes to the tree, My problem is that only some items are selectable, and those that aren't can't consistently cascade selections. </p>
<p>Is there any way to disable or hide some check-boxes while displaying others?</p>
|
[
{
"answer_id": 39158,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 1,
"selected": false,
"text": "TreeNode BackColor SelectionChanged Generic::List<>"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905/"
] |
39,125
|
<p>How can a .net class library project and resulting dll be protected so it cant be referenced by other applications (.net projects) except those projects in my own solution?</p>
|
[
{
"answer_id": 39129,
"author": "Glenn Slaven",
"author_id": 2975,
"author_profile": "https://Stackoverflow.com/users/2975",
"pm_score": 1,
"selected": false,
"text": "internal"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/254/"
] |
39,187
|
<p>I prefer dark backgrounds for coding, and I've downloaded a jar file containing an IntelliJ IDEA color theme that has a dark background. How do I tell IntelliJ about it?</p>
|
[
{
"answer_id": 23292020,
"author": "Alexander Suraphel",
"author_id": 1242842,
"author_profile": "https://Stackoverflow.com/users/1242842",
"pm_score": 6,
"selected": false,
"text": "File Import Settings... jar Settings Editor Colors and Fonts"
},
{
"answer_id": 49256413,
"author": "Bartek Lipinski",
"author_id": 1993204,
"author_profile": "https://Stackoverflow.com/users/1993204",
"pm_score": 3,
"selected": false,
"text": "xml Preferences Editor Color and Fonts Import"
},
{
"answer_id": 57894293,
"author": "Akshoy",
"author_id": 9169461,
"author_profile": "https://Stackoverflow.com/users/9169461",
"pm_score": 3,
"selected": false,
"text": "material theme theme"
},
{
"answer_id": 61304535,
"author": "Shahriyar",
"author_id": 8738937,
"author_profile": "https://Stackoverflow.com/users/8738937",
"pm_score": 3,
"selected": false,
"text": "Preferences -> Plugins -> GearIcon -> Install Plugin from disk -> Reset your IDE -> Preferences -> Appearance -> Theme -> Select your theme.\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4203/"
] |
39,222
|
<p>I'm working on porting a Visual C++ application to GCC (should build on MingW and Linux).</p>
<p>The existing code uses <code>__try { ... } __except(1) { ... }</code> blocks in a few places so that almost nothing (short of maybe out of memory type errors?) would make the program exit without doing some minimal logging.</p>
<p>What are the options for doing something similar with GCC?</p>
<p>Edit: Thanks for the pointer to /EH options in Visual Studio, what I need now is some examples on how to handle signals on Linux. I've found <a href="http://gcc.gnu.org/ml/gcc-help/2002-04/msg00003.html" rel="nofollow noreferrer">this message</a> from 2002.</p>
<p>What other signals besides <code>SIGFPE</code> and <code>SIGSEVG</code> should I watch out for? (Mostly care about ones that might be raised from <em>me</em> doing something wrong)</p>
<p><strong>Bounty Information</strong>:
I want my application to be able to self-log as many error conditions as possible before it exits. </p>
<p>What signals might I get and which would generally be impossible to log an error message after? (Out of memory, what else?)</p>
<p>How can I handle exceptions and (most importantly) signals in a portable way that the code at least works the same on Linux and MingW. #ifdef is OK.</p>
<p>The reason I don't just have a wrapper process that logs the failure is that for performance reasons I save writing some data to disk till the last minute, so if something goes wrong I want to make all possible attempts to write the data out before exiting.</p>
|
[
{
"answer_id": 39231,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "struct my_exception_type : public logic_error {\n my_exception_type(char const* msg) : logic_error(msg) { }\n};\n\ntry {\n throw my_exception_type(\"An error occurred\");\n} catch (my_exception_type& ex) {\n cerr << ex.what << endl;\n}\n try {\n // …\n}\ncatch (...) {\n}\n"
},
{
"answer_id": 46978,
"author": "Thomas Kammeyer",
"author_id": 4410,
"author_profile": "https://Stackoverflow.com/users/4410",
"pm_score": 0,
"selected": false,
"text": "int foo(int x) try {\n // body of foo\n} catch (...) {\n // be careful what's done here!\n}\n"
},
{
"answer_id": 1173441,
"author": "Partial",
"author_id": 127716,
"author_profile": "https://Stackoverflow.com/users/127716",
"pm_score": -1,
"selected": false,
"text": "try\n{\n /* code that may throw exceptions */\n}\ncatch (Error1 e1)\n{\n /* code if Error1 is thrown */\n}\ncatch (Error2 e2)\n{\n /* code if Error2 is thrown */\n}\ncatch (...)\n{\n /* any exception that was not expected will be caught here */\n}\n"
},
{
"answer_id": 1179382,
"author": "Hans Malherbe",
"author_id": 126225,
"author_profile": "https://Stackoverflow.com/users/126225",
"pm_score": 0,
"selected": false,
"text": "catch(...) catch(...) catch(...)"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/163/"
] |
39,240
|
<p>I have lots of article store in MS SQL server 2005 database in a table called Articles-</p>
<pre><code>"Articles (ArticleID, ArticleTitle, ArticleContent)"
</code></pre>
<p>Now I want some SP or SQL query which could return me similar Article against any user's input (very much like "Similar Posts" in blogs OR "Related Questions" in stackoverflow). The matching should work on both ArticleTitle and ArticleContent. The query should be intelligent enough to sort the result on the basis on their relevancy.</p>
<p>Is it possible to do this in MS SQL Server 2005?</p>
|
[
{
"answer_id": 39257,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 0,
"selected": false,
"text": "-- Assuming @Title contains title of current articles you can find related articles runnig this query \nSELECT * FROM Acticles WHERE CONTAINS(ArticleTitle, @Title)\n"
},
{
"answer_id": 39316,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 2,
"selected": true,
"text": "Select\nTop 10\nArticleID,\nArticleTitle,\nArticleContent\nFrom\nArticles\nOrder By\n(Case When ArticleTitle = 'Article Title' Then 1 Else 0 End) Desc,\n(Case When ArticleTitle = 'Article' Then 1 Else 0 End) Desc,\n(Case When ArticleTitle = 'Title' Then 1 Else 0 End) Desc,\n(Case When Soundex('Article Title') = Soundex(ArticleTitle) Then 1 Else 0 End) Desc,\n(Case When Soundex('Article') = Soundex(ArticleTitle) Then 1 Else 0 End) Desc,\n(Case When Soundex('Title') = Soundex(ArticleTitle) Then 1 Else 0 End) Desc,\n(Case When PatIndex('%Article%Title%', ArticleTitle) > 0 Then 1 Else 0 End) Desc,\n(Case When PatIndex('%Article%', ArticleTitle) > 0 Then 1 Else 0 End) Desc,\n(Case When PatIndex('%Title%', ArticleTitle) > 0 Then 1 Else 0 End) Desc,\n(Case When PatIndex('%Article%Title%', ArticleContent) > 0 Then 1 Else 0 End) Desc,\n(Case When PatIndex('%Article%', ArticleContent) > 0 Then 1 Else 0 End) Desc,\n(Case When PatIndex('%Title%', ArticleContent) > 0 Then 1 Else 0 End) Desc\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191/"
] |
39,243
|
<p>Is there any query which can return me the number of revisions made to the structure of a database table?</p>
<p>Secondly, how can I determine the number of pages (in terms of size) present in mdf or ldf files?</p>
|
[
{
"answer_id": 39269,
"author": "Christian Hagelid",
"author_id": 202,
"author_profile": "https://Stackoverflow.com/users/202",
"pm_score": 2,
"selected": false,
"text": "trigger"
},
{
"answer_id": 39291,
"author": "Matt Lacey",
"author_id": 1755,
"author_profile": "https://Stackoverflow.com/users/1755",
"pm_score": 0,
"selected": false,
"text": "SQL Server DDL triggers (v2005+)"
},
{
"answer_id": 39311,
"author": "pirho",
"author_id": 3911,
"author_profile": "https://Stackoverflow.com/users/3911",
"pm_score": 2,
"selected": true,
"text": "SQL Server SELECT * FROM sys.objects WHERE type='U'\n sys.database_files"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4021/"
] |
39,281
|
<p>We have a requirement in project to store all the revisions(Change History) for the entities in the database. Currently we have 2 designed proposals for this:</p>
<p>e.g. for "Employee" Entity</p>
<p><strong>Design 1:</strong></p>
<pre><code>-- Holds Employee Entity
"Employees (EmployeeId, FirstName, LastName, DepartmentId, .., ..)"
-- Holds the Employee Revisions in Xml. The RevisionXML will contain
-- all data of that particular EmployeeId
"EmployeeHistories (EmployeeId, DateModified, RevisionXML)"
</code></pre>
<p><strong>Design 2:</strong></p>
<pre><code>-- Holds Employee Entity
"Employees (EmployeeId, FirstName, LastName, DepartmentId, .., ..)"
-- In this approach we have basically duplicated all the fields on Employees
-- in the EmployeeHistories and storing the revision data.
"EmployeeHistories (EmployeeId, RevisionId, DateModified, FirstName,
LastName, DepartmentId, .., ..)"
</code></pre>
<p>Is there any other way of doing this thing? </p>
<p>The problem with the "Design 1" is that we have to parse XML each time when you need to access data. This will slow the process and also add some limitations like we cannot add joins on the revisions data fields.</p>
<p>And the problem with the "Design 2" is that we have to duplicate each and every field on all entities (We have around 70-80 entities for which we want to maintain revisions).</p>
|
[
{
"answer_id": 39296,
"author": "Matthew Watson",
"author_id": 3839,
"author_profile": "https://Stackoverflow.com/users/3839",
"pm_score": 3,
"selected": false,
"text": "Employees (EmployeeId, DateModified, < Employee Fields > , boolean isCurrent );\n"
},
{
"answer_id": 39300,
"author": "Chris Roberts",
"author_id": 475,
"author_profile": "https://Stackoverflow.com/users/475",
"pm_score": 6,
"selected": false,
"text": "[ID] [int] IDENTITY(1,1) NOT NULL,\n[UserID] [int] NULL,\n[EventDate] [datetime] NOT NULL,\n[TableName] [varchar](50) NOT NULL,\n[RecordID] [varchar](20) NOT NULL,\n[FieldName] [varchar](50) NULL,\n[OldValue] [varchar](5000) NULL,\n[NewValue] [varchar](5000) NULL\n"
},
{
"answer_id": 39313,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 3,
"selected": false,
"text": "Employee (Id, Name, ... , IsActive) \n"
},
{
"answer_id": 39358,
"author": "Kjetil Watnedal",
"author_id": 4116,
"author_profile": "https://Stackoverflow.com/users/4116",
"pm_score": 4,
"selected": false,
"text": "[ID] [int] IDENTITY(1,1) NOT NULL,\n[UserID] [int] NULL,\n[EventDate] [datetime] NOT NULL,\n[TableName] [varchar](50) NOT NULL,\n[RecordID] [varchar](20) NOT NULL,\n[FieldName] [varchar](50) NULL,\n[NewValue] [varchar](5000) NULL\n"
},
{
"answer_id": 39360,
"author": "Simon Munro",
"author_id": 3893,
"author_profile": "https://Stackoverflow.com/users/3893",
"pm_score": 6,
"selected": true,
"text": "CREATE VIEW EmployeeHistory\nAS\n, FirstName, , DepartmentId\n\nSELECT EmployeeId, RevisionXML.value('(/employee/FirstName)[1]', 'varchar(50)') AS FirstName,\n\n RevisionXML.value('(/employee/LastName)[1]', 'varchar(100)') AS LastName,\n\n RevisionXML.value('(/employee/DepartmentId)[1]', 'integer') AS DepartmentId,\n\nFROM EmployeeHistories \n"
},
{
"answer_id": 40412,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 2,
"selected": false,
"text": "UserName"
},
{
"answer_id": 1042848,
"author": "dariol",
"author_id": 3644960,
"author_profile": "https://Stackoverflow.com/users/3644960",
"pm_score": 2,
"selected": false,
"text": "// Holds Employee Entity\n\"Employees (EmployeeId, FirstName, LastName, DepartmentId, .., ..)\"\n\n// Holds the Employee revisions in rows.\n\"EmployeeHistories (HistoryId, EmployeeId, DateModified, OldValue, NewValue, FieldName)\"\n // Holds Employee Entity\n\"Employees (EmployeeId, FirstName, LastName, DepartmentId, .., ..)\"\n\n// Holds all entities revisions in rows.\n\"EntityChanges (EntityName, EntityId, DateModified, OldValue, NewValue, FieldName)\"\n // Holds Employee Entity\n\"Employees (EmployeeId, FirstName, LastName, DepartmentId, .., ..)\"\n\n// Holds all entities revisions in rows.\n\"EntityChanges (EntityName, EntityId, DateModified, XMLChanges)\"\n"
},
{
"answer_id": 17002243,
"author": "Tomas",
"author_id": 684229,
"author_profile": "https://Stackoverflow.com/users/684229",
"pm_score": 4,
"selected": false,
"text": "create table X like Y alter table RevisionId ModifiedBy DeletedBy DateModified DateDeleted RevisionId DateModified insert into EmployeeHistory select * from Employe where ID = XX\n"
},
{
"answer_id": 17043060,
"author": "Mehran",
"author_id": 866082,
"author_profile": "https://Stackoverflow.com/users/866082",
"pm_score": 2,
"selected": false,
"text": "latest obsolete deleted entity type entity_revision state SELECT"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191/"
] |
39,331
|
<p>What techniques can be applied effectively to improve the performance of SQL queries? Are there any general rules that apply?</p>
|
[
{
"answer_id": 78938,
"author": "EvilTeach",
"author_id": 7734,
"author_profile": "https://Stackoverflow.com/users/7734",
"pm_score": 1,
"selected": false,
"text": "WITH\nmaster AS\n(\n SELECT SSN, FIRST_NAME, LAST_NAME\n FROM MASTER_SSN\n WHERE STATE = 'PA' AND\n GENDER = 'M'\n),\ntaxReturns AS\n(\n SELECT SSN, RETURN_ID, GROSS_PAY\n FROM MASTER_RETURNS\n WHERE YEAR < 2003 AND\n YEAR > 2000\n)\nSELECT *\nFROM master,\n taxReturns\nWHERE master.ssn = taxReturns.ssn\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
] |
39,364
|
<p>I have inherited a client site which crashes every 3 or 4 days. It is built using the zend-framework with which I have no knowledge.</p>
<p>The following code:</p>
<pre><code><?php
// Make sure classes are in the include path.
ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . 'lib' . PATH_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'classes');
// Use autoload so include or require statements are not needed.
require_once 'Zend/Loader.php';
Zend_Loader::registerAutoload();
// Run the application.
App_Main::run('production');
</code></pre>
<p>Is causing the following error:</p>
<pre>
[Tue Sep 02 12:58:45 2008] [error] [client 78.***.***.32] PHP Warning: require_once(Zend/Loader.php) [function.require-once]: failed to open stream: No such file or directory in /srv/www/vhosts/example.co.uk/httpdocs/bootstrap.php on line 6
[Tue Sep 02 12:58:45 2008] [error] [client 78.***.***.32] PHP Fatal error: require_once() [function.require]: Failed opening required 'Zend/Loader.php' (include_path='.:.:/usr/share/php5:/usr/share/php5/PEAR') in /srv/www/vhosts/example.co.uk/httpdocs/bootstrap.php on line 6
</pre>
<p>I don't even know where to begin trying to fix this. My level of knowledge of PHP is intermediate but like I said, I have no experience with Zend. Also, contacting the original developer is not an option.</p>
<p>The interesting thing is that even though the code is run every time a page of the site is hit the error is only happening every now and then.</p>
<p>I believe it must be something to do with the include_path but I am not sure.</p>
|
[
{
"answer_id": 39387,
"author": "Robin Barnes",
"author_id": 1349865,
"author_profile": "https://Stackoverflow.com/users/1349865",
"pm_score": 3,
"selected": true,
"text": " set_include_path('../library/ZendFramework-1.5.2/library/:../application/classes/:../application/classes/excpetions/:../application/forms/'); \n"
},
{
"answer_id": 4401301,
"author": "cdnicoll",
"author_id": 248487,
"author_profile": "https://Stackoverflow.com/users/248487",
"pm_score": 0,
"selected": false,
"text": " ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . 'lib' . PATH_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'classes');\n\n require_once 'ThemeWidgets.php';\n require_once 'PHPUnit/Framework.php';\n\n require_once '../../library/Zend/Loader/AutoLoader.php';\n\n\n class ThemeWidgetsTest extends PHPUnit_Framework_TestCase\n {\n\n public function setUp() {\n Zend_Loader_Autoloader::getInstance();\n }\n...\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/319/"
] |
39,365
|
<p>Typically I develop my websites on trunk, then merge changes to a testing branch where they are put on a 'beta' website, and then finally they are merged onto a live branch and put onto the live website.</p>
<p>With a Facebook application things are a bit tricky. As you can't view a Facebook application through a normal web browser (it has to go through the Facebook servers) you can't easily give each developer their own version of the website to work with and test.</p>
<p>I have not come across anything about the best way to develop and test a Facebook application while continuing to have a stable live website that users can use. My question is this, what is the best practice for organising the development and testing of a Facebook application?</p>
|
[
{
"answer_id": 445197,
"author": "Arron S",
"author_id": 16628,
"author_profile": "https://Stackoverflow.com/users/16628",
"pm_score": 5,
"selected": false,
"text": "(for windows users @ c:\\windows\\System32\\Drivers\\etc\\hosts) 127.0.0.1 mywebappthatusesfacebook.com."
},
{
"answer_id": 25155137,
"author": "user706001",
"author_id": 706001,
"author_profile": "https://Stackoverflow.com/users/706001",
"pm_score": 0,
"selected": false,
"text": "./ngrok 3000\n http://630066fe.ngrok.com -> 127.0.0.1:3000 \n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2990/"
] |
39,374
|
<p>How do you write code that is easily read by other people and who have had no hand in writing any part of it?</p>
|
[
{
"answer_id": 39394,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 3,
"selected": false,
"text": "// add one to the count:\ni++;\n int x = i + j;\nint runSum = prevSum += newValue;\n if (x == y)\n{\n z = a;\n}\nelse\n{\n z = b;\n}\nz = (x == y) ? a : b;\n"
},
{
"answer_id": 39650,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 0,
"selected": false,
"text": " int total = 10;\n int sum = 0;\n\n for (int i = 0; i < total; i++)\n {\n sum += i;\n }\n\n // Next coding statement is a space below the bracket\n return sum;\n int total = 10;int sum = 0;\n for (int i = 0; i < total; i++)\n {\n sum += i;\n }\n return sum;\n if(true)\n // some action\n\nif(true)\n{\n // Some action\n}\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4021/"
] |
39,391
|
<p>If I create an HTTP <code>java.net.URL</code> and then call <code>openConnection()</code> on it, does it necessarily imply that an HTTP post is going to happen? I know that <code>openStream()</code> implies a GET. If so, how do you perform one of the other HTTP verbs without having to work with the raw socket layer?</p>
|
[
{
"answer_id": 39431,
"author": "WMR",
"author_id": 2844,
"author_profile": "https://Stackoverflow.com/users/2844",
"pm_score": 2,
"selected": false,
"text": "HttpURLConnection setRequestMethod"
},
{
"answer_id": 39449,
"author": "Herms",
"author_id": 1409,
"author_profile": "https://Stackoverflow.com/users/1409",
"pm_score": 5,
"selected": true,
"text": "URLConnection openConnection() URLConnection() setDoOutput(true) URL myURL = new URL(\"http://example.com/my/path\");\nURLConnection conn = myURL.openConnection();\nconn.setDoOutput(true);\nconn.setDoInput(true);\n\nOutputStream os = conn.getOutputStream();\nos.write(\"Hi there!\");\nos.close();\n\nInputStream is = conn.getInputStream();\n// read stuff here\n URL myURL = new URL(\"http://example.com/my/path\");\nURLConnection conn = myURL.openConnection();\nconn.setDoOutput(false);\nconn.setDoInput(true);\n\nInputStream is = conn.getInputStream();\n// read stuff here\n URLConnection URLConnection URLConnection getStream()"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4223/"
] |
39,392
|
<p>Can anyone (maybe an XSL-fan?) help me find any advantages with handling presentation of data on a web-page with XSL over ASP.NET MVC?</p>
<p>The two alternatives are:</p>
<ol>
<li><p><strong>ASP.NET (MVC/WebForms) with XSL</strong><br/>
Getting the data from the database and transforming it to XML which is then displayed on the different pages with XSL-templates.</p></li>
<li><p><strong>ASP.NET MVC</strong><br />
Getting the data from the database as C# objects (or LinqToSql/EF-objects) and displaying it with inline-code on MVC-pages.</p></li>
</ol>
<p>The main benefit of XSL has been consistent display of data on many different pages, like WebControls. So, correct me if I'm wrong, ASP.NET MVC can be used the same way, but with strongly typed objects. Please help me see if there are any benefits to XSL.</p>
|
[
{
"answer_id": 39423,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 3,
"selected": false,
"text": "<% %>"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2429/"
] |
39,395
|
<p>How can I calculate the value of PI using C#?</p>
<p>I was thinking it would be through a recursive function, if so, what would it look like and are there any math equations to back it up?</p>
<p>I'm not too fussy about performance, mainly how to go about it from a learning point of view.</p>
|
[
{
"answer_id": 39401,
"author": "Niyaz",
"author_id": 184,
"author_profile": "https://Stackoverflow.com/users/184",
"pm_score": 1,
"selected": false,
"text": "x = 1 - 1/3 + 1/5 - 1/7 + 1/9 (... etc as far as possible.)\nPI = x * 4\n"
},
{
"answer_id": 39404,
"author": "wvdschel",
"author_id": 2018,
"author_profile": "https://Stackoverflow.com/users/2018",
"pm_score": 7,
"selected": true,
"text": "PI = 2 * (1 + 1/3 * (1 + 2/5 * (1 + 3/7 * (...))))\n PI = 2 * F(1);\n double F (int i) {\n return 1 + i / (2.0 * i + 1) * F(i + 1);\n}\n"
},
{
"answer_id": 39424,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 5,
"selected": false,
"text": "double pi = Math.PI;\n"
},
{
"answer_id": 39497,
"author": "DrPizza",
"author_id": 2131,
"author_profile": "https://Stackoverflow.com/users/2131",
"pm_score": -1,
"selected": false,
"text": "public double PI = 22.0 / 7.0;\n"
},
{
"answer_id": 39579,
"author": "joel.neely",
"author_id": 3525,
"author_profile": "https://Stackoverflow.com/users/3525",
"pm_score": 1,
"selected": false,
"text": "pie(0,1) = 4/1\npie(0,2) = 4/1 - 4/3\npie(0,3) = 4/1 - 4/3 + 4/5\npie(0,4) = 4/1 - 4/3 + 4/5 - 4/7\n... and so on\n pie(h, w) = (pie(h-1,w) + pie(h-1,w+1)) / 2\n"
},
{
"answer_id": 4104365,
"author": "Dean Chalk",
"author_id": 498104,
"author_profile": "https://Stackoverflow.com/users/498104",
"pm_score": 1,
"selected": false,
"text": "Enumerable.Range(0, 100000000).Aggregate(0d, (tot, next) => tot += Math.Pow(-1d, next)/(2*next + 1)*4)\n"
},
{
"answer_id": 4283808,
"author": "Oliver",
"author_id": 1838048,
"author_profile": "https://Stackoverflow.com/users/1838048",
"pm_score": 3,
"selected": false,
"text": "static decimal ParallelPartitionerPi(int steps)\n{\n decimal sum = 0.0;\n decimal step = 1.0 / (decimal)steps;\n object obj = new object();\n\n Parallel.ForEach(\n Partitioner.Create(0, steps),\n () => 0.0,\n (range, state, partial) =>\n {\n for (int i = range.Item1; i < range.Item2; i++)\n {\n decimal x = (i - 0.5) * step;\n partial += 4.0 / (1.0 + x * x);\n }\n\n return partial;\n },\n partial => { lock (obj) sum += partial; });\n\n return step * sum;\n}\n"
},
{
"answer_id": 25638402,
"author": "ronalt MkDonalt",
"author_id": 4002951,
"author_profile": "https://Stackoverflow.com/users/4002951",
"pm_score": 1,
"selected": false,
"text": "using System;\n\nnamespace Strings\n{\n class Program\n {\n static void Main(string[] args)\n {\n\n/* decimal pie = 1; \n decimal e = -1;\n*/\n var stopwatch = new System.Diagnostics.Stopwatch();\n stopwatch.Start(); //added this nice stopwatch start routine \n\n //leibniz formula in C# - code written completely by Todd Mandell 2014\n/*\n for (decimal f = (e += 2); f < 1000001; f++)\n {\n e += 2;\n pie -= 1 / e;\n e += 2;\n pie += 1 / e;\n Console.WriteLine(pie * 4);\n }\n\n decimal finalDisplayString = (pie * 4);\n Console.WriteLine(\"pie = {0}\", finalDisplayString);\n Console.WriteLine(\"Accuracy resulting from approximately {0} steps\", e/4); \n*/\n\n// Nilakantha formula - code written completely by Todd Mandell 2014\n// π = 3 + 4/(2*3*4) - 4/(4*5*6) + 4/(6*7*8) - 4/(8*9*10) + 4/(10*11*12) - (4/(12*13*14) etc\n\n decimal pie = 0;\n decimal a = 2;\n decimal b = 3;\n decimal c = 4;\n decimal e = 1;\n\n for (decimal f = (e += 1); f < 100000; f++) \n // Increase f where \"f < 100000\" to increase number of steps\n {\n\n pie += 4 / (a * b * c);\n\n a += 2;\n b += 2;\n c += 2;\n\n pie -= 4 / (a * b * c);\n\n a += 2;\n b += 2;\n c += 2;\n\n e += 1;\n }\n\n decimal finalDisplayString = (pie + 3);\n Console.WriteLine(\"pie = {0}\", finalDisplayString);\n Console.WriteLine(\"Accuracy resulting from {0} steps\", e); \n\n stopwatch.Stop();\n TimeSpan ts = stopwatch.Elapsed;\n Console.WriteLine(\"Calc Time {0}\", ts); \n\n Console.ReadLine();\n\n }\n }\n }\n"
},
{
"answer_id": 26697642,
"author": "Curious",
"author_id": 2610539,
"author_profile": "https://Stackoverflow.com/users/2610539",
"pm_score": 1,
"selected": false,
"text": " public static string PiNumberFinder(int digitNumber)\n {\n string piNumber = \"3,\";\n int dividedBy = 11080585;\n int divisor = 78256779;\n int result;\n\n for (int i = 0; i < digitNumber; i++)\n {\n if (dividedBy < divisor)\n dividedBy *= 10;\n\n result = dividedBy / divisor;\n\n string resultString = result.ToString();\n piNumber += resultString;\n\n dividedBy = dividedBy - divisor * result;\n }\n\n return piNumber;\n }\n"
},
{
"answer_id": 49317760,
"author": "Slaven Tojić",
"author_id": 7308680,
"author_profile": "https://Stackoverflow.com/users/7308680",
"pm_score": 0,
"selected": false,
"text": "public static decimal GregoryLeibnizGetPI(int n)\n{\n decimal sum = 0;\n decimal temp = 0;\n for (int i = 0; i < n; i++)\n {\n temp = 4m / (1 + 2 * i);\n sum += i % 2 == 0 ? temp : -temp;\n }\n return sum;\n}\n public static decimal NilakanthaGetPI(int n)\n{\n decimal sum = 0;\n decimal temp = 0;\n decimal a = 2, b = 3, c = 4;\n for (int i = 0; i < n; i++)\n {\n temp = 4 / (a * b * c);\n sum += i % 2 == 0 ? temp : -temp;\n a += 2; b += 2; c += 2;\n }\n return 3 + sum;\n}\n n static void Main(string[] args)\n{\n const decimal pi = 3.1415926535897932384626433832m;\n Console.WriteLine($\"PI = {pi}\");\n\n //Nilakantha Series\n int iterationsN = 100;\n decimal nilakanthaPI = NilakanthaGetPI(iterationsN);\n decimal CalcErrorNilakantha = pi - nilakanthaPI;\n Console.WriteLine($\"\\nNilakantha Series -> PI = {nilakanthaPI}\");\n Console.WriteLine($\"Calculation error = {CalcErrorNilakantha}\");\n int numDecNilakantha = pi.ToString().Zip(nilakanthaPI.ToString(), (x, y) => x == y).TakeWhile(x => x).Count() - 2;\n Console.WriteLine($\"Number of correct decimals = {numDecNilakantha}\");\n Console.WriteLine($\"Number of iterations = {iterationsN}\");\n\n //Gregory-Leibniz Series\n int iterationsGL = 1000000;\n decimal GregoryLeibnizPI = GregoryLeibnizGetPI(iterationsGL);\n decimal CalcErrorGregoryLeibniz = pi - GregoryLeibnizPI;\n Console.WriteLine($\"\\nGregory-Leibniz Series -> PI = {GregoryLeibnizPI}\");\n Console.WriteLine($\"Calculation error = {CalcErrorGregoryLeibniz}\");\n int numDecGregoryLeibniz = pi.ToString().Zip(GregoryLeibnizPI.ToString(), (x, y) => x == y).TakeWhile(x => x).Count() - 2;\n Console.WriteLine($\"Number of correct decimals = {numDecGregoryLeibniz}\");\n Console.WriteLine($\"Number of iterations = {iterationsGL}\");\n\n Console.ReadKey();\n}\n"
},
{
"answer_id": 50304341,
"author": "Idan Rotbart",
"author_id": 6941443,
"author_profile": "https://Stackoverflow.com/users/6941443",
"pm_score": 0,
"selected": false,
"text": "static void Main(string[] args)\n {\n double counter = 0;\n for (double i = 1; i < 1000000; i++)\n {\n\n counter = counter + (1 / (Math.Pow(i, 2)));\n\n }\n counter = counter * 6;\n counter = Math.Sqrt(counter);\n Console.WriteLine(counter);\n }\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] |
39,399
|
<p>I have a struts-based webapp, and I would like the default "welcome" page to be an action. The only solutions I have found to this seem to be variations on making the welcome page a JSP that contains a redirect to the action. For example, in <code>web.xml</code>:</p>
<pre><code><welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</code></pre>
<p>and in <code>index.jsp</code>:</p>
<pre><code><%
response.sendRedirect("/myproject/MyAction.action");
%>
</code></pre>
<p>Surely there's a better way!</p>
|
[
{
"answer_id": 43879,
"author": "Martin McNulty",
"author_id": 4507,
"author_profile": "https://Stackoverflow.com/users/4507",
"pm_score": 5,
"selected": false,
"text": "<% \n response.sendRedirect(\"/myproject/MyAction.action\");\n%>\n <jsp:forward page=\"/MyAction.action\" />\n"
},
{
"answer_id": 318846,
"author": "Craig Wohlfeil",
"author_id": 22767,
"author_profile": "https://Stackoverflow.com/users/22767",
"pm_score": 4,
"selected": false,
"text": "<servlet>\n <servlet-name>MyController</servlet-name>\n <servlet-class>com.example.MyControllerServlet</servlet-class>\n</servlet>\n<servlet-mapping>\n <servlet-name>MyController</servlet-name>\n <url-pattern>*.action</url-pattern>\n</servlet-mapping>\n<welcome-file-list>\n <welcome-file>MyController</welcome-file>\n</welcome-file-list>\n"
},
{
"answer_id": 4842983,
"author": "Srikanth",
"author_id": 483628,
"author_profile": "https://Stackoverflow.com/users/483628",
"pm_score": 4,
"selected": false,
"text": "<s:action name=\"loadHomePage\" namespace=\"/load\" executeResult=\"true\" />\n"
},
{
"answer_id": 14811399,
"author": "Navathej",
"author_id": 2061197,
"author_profile": "https://Stackoverflow.com/users/2061197",
"pm_score": -1,
"selected": false,
"text": "<welcome-file-list>\n<welcome-file>/MyAction.action</welcome-file>\n</welcome-file-list>\n"
},
{
"answer_id": 15551450,
"author": "gavenkoa",
"author_id": 173149,
"author_profile": "https://Stackoverflow.com/users/173149",
"pm_score": 1,
"selected": false,
"text": "<servlet-mapping>\n <servlet-name>dispatcher</servlet-name>\n <url-pattern>/</url-pattern>\n <url-pattern>/index.htm</url-pattern> <<== *1*\n</servlet-mapping>\n<welcome-file-list>\n <welcome-file>index.htm</welcome-file> <<== *2*\n</welcome-file-list>\n redirect.jsp WEB-INF"
},
{
"answer_id": 15905476,
"author": "John Solomon",
"author_id": 932723,
"author_profile": "https://Stackoverflow.com/users/932723",
"pm_score": 0,
"selected": false,
"text": "web.xml <filter>\n <filter-name>customfilter</filter-name>\n <filter-class>com.example.CustomFilter</filter-class>\n</filter>\n<filter-mapping>\n <filter-name>customfilter</filter-name>\n <url-pattern>/*</url-pattern>\n</filter-mapping>\n public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,\n FilterChain filterChain) throws IOException, ServletException {\n HttpServletRequest httpRequest = (HttpServletRequest)servletRequest;\n HttpServletResponse httpResponse = (HttpServletResponse)servletResponse;\n if (! httpResponse.isCommitted()) {\n if ((httpRequest.getContextPath() + \"/\").equals(httpRequest.getRequestURI())) {\n httpResponse.sendRedirect(httpRequest.getContextPath() + \"/MyAction\");\n }\n else {\n filterChain.doFilter(servletRequest, servletResponse);\n }\n }\n}\n"
},
{
"answer_id": 16113198,
"author": "Lund Wolfe",
"author_id": 1247753,
"author_profile": "https://Stackoverflow.com/users/1247753",
"pm_score": -1,
"selected": false,
"text": "<welcome-file-list>\n<welcome-file>MyAction.action</welcome-file>\n</welcome-file-list>\n"
},
{
"answer_id": 16638674,
"author": "siva",
"author_id": 1830486,
"author_profile": "https://Stackoverflow.com/users/1830486",
"pm_score": 0,
"selected": false,
"text": "http://localhost:8080/myapp <action name=\"\">\n <result type=\"tiles\">/index.tiles</result>\n</action>\n <action name=\"\">\n <result>/index.jsp</result>\n</action>\n <welcome-file>index.action</welcome-file>"
},
{
"answer_id": 18162786,
"author": "msangel",
"author_id": 449553,
"author_profile": "https://Stackoverflow.com/users/449553",
"pm_score": 1,
"selected": false,
"text": "<welcome-file-list>\n <welcome-file>index.jsp</welcome-file>\n</welcome-file-list>\n<servlet>\n <servlet-name>TilesDispatchServlet</servlet-name>\n <servlet-class>org.apache.tiles.web.util.TilesDispatchServlet</servlet-class>\n</servlet>\n<servlet-mapping>\n <servlet-name>TilesDispatchServlet</servlet-name>\n <url-pattern>*.tiles</url-pattern>\n</servlet-mapping>\n index.jsp <jsp:forward page=\"index.tiles\" />\n index"
},
{
"answer_id": 33825842,
"author": "WesternGun",
"author_id": 4537090,
"author_profile": "https://Stackoverflow.com/users/4537090",
"pm_score": 0,
"selected": false,
"text": "<%@ page language=\"java\" contentType=\"text/html; charset=UTF-8\" pageEncoding=\"UTF-8\"%>\n<%@ taglib prefix=\"sec\" uri=\"http://www.springframework.org/security/tags\" %>\n\n<sec:authorize access=\"isAnonymous()\">\n <% response.sendRedirect(\"/myApp/login/login.action?error=false\"); %>\n</sec:authorize>\n<sec:authorize access=\"isAuthenticated() and (hasRole('ADMIN') or hasRole('USER'))\">\n <% response.sendRedirect(\"/myApp/principal/principal.action\"); %>\n</sec:authorize>\n<sec:authorize access=\"isAuthenticated() and hasRole('USER')\">\n <% response.sendRedirect(\"/myApp/user/userDetails.action\"); %>\n</sec:authorize>\n"
},
{
"answer_id": 36919549,
"author": "Ravi MCA",
"author_id": 1588361,
"author_profile": "https://Stackoverflow.com/users/1588361",
"pm_score": 0,
"selected": false,
"text": "<!-- welcome page configuration -begin -->\n <action name=\"\" class=\"com.LoginAction\">\n <result name=\"success\">login.jsp</result>\n </action>\n<!-- welcome page configuration -end -->\n <!-- welcome page configuration -begin -->\n <action name=\"\">\n <result name=\"success\">login.jsp</result>\n </action>\n<!-- welcome page configuration -end -->\n <welcome-file-list>"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3913/"
] |
39,419
|
<p>In Visual C++ a DWORD is just an unsigned long that is machine, platform, and SDK dependent. However, since DWORD is a double word (that is 2 * 16), is a DWORD still 32-bit on 64-bit architectures?</p>
|
[
{
"answer_id": 39430,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 4,
"selected": false,
"text": "typedef unsigned long DWORD;\n typdef unsigned _int64 DWORD64;\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44972/"
] |
39,438
|
<p>We are bringing a new project in house and whereas previously all our work was on SQL Server the new product uses an oracle back end.</p>
<p>Can anyone advise any crib sheets or such like that gives an SQL Server person like me a rundown of what the major differences are - Would like to be able to get up and running as soon as possible.</p>
|
[
{
"answer_id": 39463,
"author": "hamishmcn",
"author_id": 3590,
"author_profile": "https://Stackoverflow.com/users/3590",
"pm_score": 1,
"selected": false,
"text": "INSERT INTO atable (a_varchar_column) VALUES (''); INSERT INTO atable (a_varchar_column) VALUES (NULL);\n sqlserver"
},
{
"answer_id": 47730,
"author": "hamishmcn",
"author_id": 3590,
"author_profile": "https://Stackoverflow.com/users/3590",
"pm_score": 0,
"selected": false,
"text": "CREATE TABLE atable (acol VARCHAR(10));\nINsERT INTO atable VALUES( '' );\nSELECT * FROM atable WHERE acol IS NULL;\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/770/"
] |
39,447
|
<p>I have a class property exposing an internal IList<> through</p>
<pre><code>System.Collections.ObjectModel.ReadOnlyCollection<>
</code></pre>
<p>How can I pass a part of this <code>ReadOnlyCollection<></code> without copying elements into a new array (I need a live view, and the target device is short on memory)? I'm targetting Compact Framework 2.0.</p>
|
[
{
"answer_id": 39462,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 1,
"selected": false,
"text": "IEnumerable<object> FilteredList()\n{\n foreach( object item in FullList )\n {\n if( IsItemInPartialList( item )\n yield return item;\n }\n}\n"
},
{
"answer_id": 39467,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 5,
"selected": true,
"text": "IEnumerable<T> FilterCollection<T>( ReadOnlyCollection<T> input ) {\n foreach ( T item in input )\n if ( /* criterion is met */ )\n yield return item;\n}\n"
},
{
"answer_id": 39469,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 1,
"selected": false,
"text": "class EvenList: IList\n{\n private IList innerList;\n public EvenList(IList innerList)\n {\n this.innerList = innerList;\n }\n\n public object this[int index]\n {\n get { return innerList[2*i]; }\n set { innerList[2*i] = value; }\n }\n // and similarly for the other IList methods\n}\n"
},
{
"answer_id": 39481,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 3,
"selected": false,
"text": "return FullList.Where(i => IsItemInPartialList(i)).ToList();\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3205/"
] |
39,468
|
<p>I've got a Windows DLL that I wrote, written in C/C++ (all exported functions are 'C'). The DLL works fine for me in VC++. I've given the DLL to another company who do all their development in VB. They seem to be having a problem linking to the functions. I haven't used VB in ten years and I don't even have it installed. What could be the problem?</p>
<p>I've declared all my public functions as follows:</p>
<pre><code>#define MYDCC_API __declspec(dllexport)
MYDCCL_API unsigned long MYDCC_GetVer( void);
.
.
.
</code></pre>
<p>Any ideas?</p>
<hr>
<p>Finally got back to this today and have it working. The answers put me on the right track but I found this most helpful:</p>
<p><a href="http://www.codeproject.com/KB/DLL/XDllPt2.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/DLL/XDllPt2.aspx</a></p>
<p>Also, I had a few problems passing strings to the DLL functions, I found this helpful:</p>
<p><a href="http://www.flipcode.com/archives/Interfacing_Visual_Basic_And_C.shtml" rel="nofollow noreferrer">http://www.flipcode.com/archives/Interfacing_Visual_Basic_And_C.shtml</a></p>
<hr>
|
[
{
"answer_id": 39478,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": true,
"text": "__declspec LIBRARY mylibname\nEXPORTS\n myfirstfunction\n secondfunction\n stdcall"
},
{
"answer_id": 39479,
"author": "Re0sless",
"author_id": 2098,
"author_profile": "https://Stackoverflow.com/users/2098",
"pm_score": 2,
"selected": false,
"text": "#define MYDCC_API __declspec(dllexport) __stdcall\n"
},
{
"answer_id": 2742624,
"author": "tracker",
"author_id": 329506,
"author_profile": "https://Stackoverflow.com/users/329506",
"pm_score": 0,
"selected": false,
"text": " HRESULT hresult;\n CLSID clsid;\n _CTest *t; // a pointer to the CTest object\n _bstr_t bstrA = L\"hello\";\n _bstr_t bstrB = L\" world\"; \n _bstr_t bstrR;\n ::CoInitialize(NULL);\n hresult=CLSIDFromProgID(OLESTR(\"VBTestLib.CTest\"), &clsid);\n hresult= CoCreateInstance(clsid,NULL,CLSCTX_INPROC_SERVER,\n __uuidof(_CTest),(LPVOID*) &t);\n if(hresult == S_OK)\n {\n bstrR = t->vbConcat(bstrA , bstrB);\n AfxMessageBox((char*)bstrR);\n }\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3685/"
] |
39,474
|
<p>Does anyone know how to get IntelliSense to work reliably when working in C/C++ projects? It seems to work for about 1 in 10 files. Visual Studio 2005 seems to be a lot better than 2008.</p>
<p>Edit: Whilst not necessarily a solution, the work-around provided here: </p>
<p><a href="https://stackoverflow.com/questions/39474/how-to-get-intellisense-to-reliably-work-in-visual-studio-2008#39590">How to get IntelliSense to reliably work in Visual Studio 2008</a></p>
<p>Is probably the best bet if I want a decent IntelliSense system.</p>
|
[
{
"answer_id": 39534,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 1,
"selected": false,
"text": "class MyPredeclared;\n\nclass SomeOtherClass\n{\nprivate:\n MyPredeclared* m_pPointer;\n}\n"
},
{
"answer_id": 5455994,
"author": "Roberto Conte Rosito",
"author_id": 357561,
"author_profile": "https://Stackoverflow.com/users/357561",
"pm_score": 0,
"selected": false,
"text": "#include #include <myfile.h> \n #include \"myfile.h\"\n"
},
{
"answer_id": 6212905,
"author": "Francesco",
"author_id": 780887,
"author_profile": "https://Stackoverflow.com/users/780887",
"pm_score": 1,
"selected": false,
"text": "#ifndef CLASS_H\n#define CLASS_H\n...\n#endif\n #pragma once \n"
},
{
"answer_id": 20397412,
"author": "the swine",
"author_id": 1140976,
"author_profile": "https://Stackoverflow.com/users/1140976",
"pm_score": 1,
"selected": false,
"text": "#include #if 0 /* .. */ // static_assert<(size > 0)> static_assert<((size > 0))> static_assert<0 < size> function<type>(args) Matrix::MakeMatrixType<3, 3>::Result r; void main() {} math.h sin("
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/986/"
] |
39,475
|
<p>Hello I have the following error by git-fsck, which cannot be cleaned by git-gc even in --aggressive mode. What can I do next to fix this repository error? </p>
<pre><code>$ git-fsck
bad sha1 file: .git/objects/55/tmp_obj_a07724
</code></pre>
|
[
{
"answer_id": 44733,
"author": "Damien Diederen",
"author_id": 3844,
"author_profile": "https://Stackoverflow.com/users/3844",
"pm_score": 3,
"selected": false,
"text": "tmp_obj_a07724 .git"
},
{
"answer_id": 49404775,
"author": "Sergei Krivonos",
"author_id": 525578,
"author_profile": "https://Stackoverflow.com/users/525578",
"pm_score": 0,
"selected": false,
"text": "man git-fsck Any corrupt objects you will have to find in backups or other archives\n(i.e., you can just remove them and do an rsync with some other site in\nthe hopes that somebody else has the object you have corrupted).\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2313/"
] |
39,476
|
<p>In the <a href="https://stackoverflow.com/questions/39447/how-can-i-expose-only-a-fragment-of-ilist">How Can I Expose Only a Fragment of IList<></a> question one of the answers had the following code snippet:</p>
<pre><code>IEnumerable<object> FilteredList()
{
foreach(object item in FullList)
{
if(IsItemInPartialList(item))
yield return item;
}
}
</code></pre>
<p>What does the yield keyword do there? I've seen it referenced in a couple places, and one other question, but I haven't quite figured out what it actually does. I'm used to thinking of yield in the sense of one thread yielding to another, but that doesn't seem relevant here.</p>
|
[
{
"answer_id": 39488,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 5,
"selected": false,
"text": "item IEnumerable"
},
{
"answer_id": 39496,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 11,
"selected": true,
"text": "yield IEnumerable<object> foreach IEnumerable IEnumerator public void Consumer()\n{\n foreach(int i in Integers())\n {\n Console.WriteLine(i.ToString());\n }\n}\n\npublic IEnumerable<int> Integers()\n{\n yield return 1;\n yield return 2;\n yield return 4;\n yield return 8;\n yield return 16;\n yield return 16777216;\n}\n Integers() 1 2 yield return 1 public IEnumerable<T> Read<T>(string sql, Func<IDataReader, T> make, params object[] parms)\n{\n using (var connection = CreateConnection())\n {\n using (var command = CreateCommand(CommandType.Text, sql, connection, parms))\n {\n command.CommandTimeout = dataBaseSettings.ReadCommandTimeout;\n using (var reader = command.ExecuteReader())\n {\n while (reader.Read())\n {\n yield return make(reader);\n }\n }\n }\n }\n}\n"
},
{
"answer_id": 39600,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": -1,
"selected": false,
"text": " rubyArray = [1,2,3,4,5,6,7,8,9,10]\n rubyArray.each{|x| \n puts x # do whatever with x\n }\n //calling code\nforeach(int i in obCustomClass.Each())\n{\n Console.WriteLine(i.ToString());\n}\n\n// CustomClass implementation\nprivate int[] data = {1,2,3,4,5,6,7,8,9,10};\npublic IEnumerable<int> Each()\n{\n for(int iLooper=0; iLooper<data.Length; ++iLooper)\n yield return data[iLooper]; \n}\n"
},
{
"answer_id": 22021424,
"author": "RKS",
"author_id": 1733852,
"author_profile": "https://Stackoverflow.com/users/1733852",
"pm_score": 6,
"selected": false,
"text": "yield return yield static void Main(string[] args)\n{\n foreach (int fib in Fibs(6))//1, 5\n {\n Console.WriteLine(fib + \" \");//4, 10\n } \n}\n\nstatic IEnumerable<int> Fibs(int fibCount)\n{\n for (int i = 0, prevFib = 0, currFib = 1; i < fibCount; i++)//2\n {\n yield return prevFib;//3, 9\n int newFib = prevFib + currFib;//6\n prevFib = currFib;//7\n currFib = newFib;//8\n }\n}\n Fibs()"
},
{
"answer_id": 28000413,
"author": "Marquinho Peli",
"author_id": 2992192,
"author_profile": "https://Stackoverflow.com/users/2992192",
"pm_score": 7,
"selected": false,
"text": "class SomeData\n{\n public SomeData() { }\n\n static public IEnumerable<SomeData> CreateSomeDatas()\n {\n return new List<SomeData> {\n new SomeData(), \n new SomeData(), \n new SomeData()\n };\n }\n}\n class SomeData\n{\n public SomeData() { }\n\n static public IEnumerable<SomeData> CreateSomeDatas()\n {\n yield return new SomeData();\n yield return new SomeData();\n yield return new SomeData();\n }\n}\n"
},
{
"answer_id": 34096356,
"author": "Strydom",
"author_id": 5632496,
"author_profile": "https://Stackoverflow.com/users/5632496",
"pm_score": 6,
"selected": false,
"text": " public class ContactListStore : IStore<ContactModel>\n {\n public IEnumerable<ContactModel> GetEnumerator()\n {\n var contacts = new List<ContactModel>();\n Console.WriteLine(\"ContactListStore: Creating contact 1\");\n contacts.Add(new ContactModel() { FirstName = \"Bob\", LastName = \"Blue\" });\n Console.WriteLine(\"ContactListStore: Creating contact 2\");\n contacts.Add(new ContactModel() { FirstName = \"Jim\", LastName = \"Green\" });\n Console.WriteLine(\"ContactListStore: Creating contact 3\");\n contacts.Add(new ContactModel() { FirstName = \"Susan\", LastName = \"Orange\" });\n return contacts;\n }\n }\n\n static void Main(string[] args)\n {\n var store = new ContactListStore();\n var contacts = store.GetEnumerator();\n\n Console.WriteLine(\"Ready to iterate through the collection.\");\n Console.ReadLine();\n }\n public class ContactYieldStore : IStore<ContactModel>\n{\n public IEnumerable<ContactModel> GetEnumerator()\n {\n Console.WriteLine(\"ContactYieldStore: Creating contact 1\");\n yield return new ContactModel() { FirstName = \"Bob\", LastName = \"Blue\" };\n Console.WriteLine(\"ContactYieldStore: Creating contact 2\");\n yield return new ContactModel() { FirstName = \"Jim\", LastName = \"Green\" };\n Console.WriteLine(\"ContactYieldStore: Creating contact 3\");\n yield return new ContactModel() { FirstName = \"Susan\", LastName = \"Orange\" };\n }\n}\n\nstatic void Main(string[] args)\n{\n var store = new ContactYieldStore();\n var contacts = store.GetEnumerator();\n\n Console.WriteLine(\"Ready to iterate through the collection.\");\n Console.ReadLine();\n}\n static void Main(string[] args)\n{\n var store = new ContactYieldStore();\n var contacts = store.GetEnumerator();\n Console.WriteLine(\"Ready to iterate through the collection\");\n Console.WriteLine(\"Hello {0}\", contacts.First().FirstName);\n Console.ReadLine();\n}\n"
},
{
"answer_id": 36962062,
"author": "barlop",
"author_id": 385907,
"author_profile": "https://Stackoverflow.com/users/385907",
"pm_score": 3,
"selected": false,
"text": "public static IEnumerable<int> testYieldb()\n{\n for(int i=0;i<3;i++) yield return 4;\n}\n WriteLine yield return WriteLine IEnumerable int public static IEnumerable<int> testYieldb()\n{\n yield return 4;\n console.WriteLine(\"abc\");\n yield return 4;\n}\n IEnumerable IEnumerable int List<int> yield IEnumerable IEnumerable static void Main(string[] args)\n{\n testA();\n Console.Write(\"try again. the above won't execute any of the function!\\n\");\n\n foreach (var x in testA()) { }\n\n\n Console.ReadLine();\n}\n\n\n\n// static List<int> testA()\nstatic IEnumerable<int> testA()\n{\n Console.WriteLine(\"asdfa\");\n yield return 1;\n Console.WriteLine(\"asdf\");\n}\n"
},
{
"answer_id": 39273209,
"author": "kmote",
"author_id": 93394,
"author_profile": "https://Stackoverflow.com/users/93394",
"pm_score": 5,
"selected": false,
"text": "foreach yield"
},
{
"answer_id": 44801657,
"author": "Martin Liversage",
"author_id": 98607,
"author_profile": "https://Stackoverflow.com/users/98607",
"pm_score": 5,
"selected": false,
"text": "yield IEnumerable<T> foreach foreach IEnumerable<int> IteratorBlock()\n{\n Console.WriteLine(\"Begin\");\n yield return 1;\n Console.WriteLine(\"After 1\");\n yield return 2;\n Console.WriteLine(\"After 2\");\n yield return 42;\n Console.WriteLine(\"End\");\n}\n yield foreach foreach (var i in IteratorBlock())\n Console.WriteLine(i);\n foreach IEnumerator<int> enumerator = null;\ntry\n{\n enumerator = IteratorBlock().GetEnumerator();\n while (enumerator.MoveNext())\n {\n var i = enumerator.Current;\n Console.WriteLine(i);\n }\n}\nfinally\n{\n enumerator?.Dispose();\n}\n enumerator.MoveNext() var evenNumbers = IteratorBlock().Where(i => i%2 == 0);\n Where IEnumerable<T> IEnumerable<T> IteratorBlock foreach foreach (var evenNumber in evenNumbers)\n Console.WriteLine(eventNumber);\n ToList() ToArray() First() Count() foreach ToList() ToList()"
},
{
"answer_id": 58442021,
"author": "maxspan",
"author_id": 2209468,
"author_profile": "https://Stackoverflow.com/users/2209468",
"pm_score": 5,
"selected": false,
"text": "public static IEnumerable<int> CreateCollectionWithList()\n{\n var list = new List<int>();\n list.Add(10);\n list.Add(0);\n list.Add(1);\n list.Add(2);\n list.Add(20);\n\n return list;\n}\n public static IEnumerable<int> CreateCollectionWithYield()\n{\n yield return 10;\n for (int i = 0; i < 3; i++) \n {\n yield return i;\n }\n\n yield return 20;\n}\n var listItems = CreateCollectionWithList();\nvar yieldedItems = CreateCollectionWithYield();\n"
},
{
"answer_id": 69410126,
"author": "Pascal Carmoni",
"author_id": 2101398,
"author_profile": "https://Stackoverflow.com/users/2101398",
"pm_score": -1,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace ConsoleApp_demo_yield {\n class Program\n {\n static void Main(string[] args)\n {\n var letters = new List<string>() { \"a1\", \"b1\", \"c2\", \"d2\" };\n\n // Not yield\n var test1 = GetNotYield(letters);\n\n foreach (var t in test1)\n {\n Console.WriteLine(t);\n }\n\n // yield\n var test2 = GetWithYield(letters).ToList();\n\n foreach (var t in test2)\n {\n Console.WriteLine(t);\n }\n\n Console.ReadKey();\n }\n\n private static IList<string> GetNotYield(IList<string> list)\n {\n var temp = new List<string>();\n foreach(var x in list)\n {\n \n if (x.Contains(\"2\")) { \n temp.Add(x);\n }\n }\n\n return temp;\n }\n\n private static IEnumerable<string> GetWithYield(IList<string> list)\n {\n foreach (var x in list)\n {\n if (x.Contains(\"2\"))\n {\n yield return x;\n }\n }\n }\n } \n}\n"
},
{
"answer_id": 69866729,
"author": "H. Pauwelyn",
"author_id": 4551041,
"author_profile": "https://Stackoverflow.com/users/4551041",
"pm_score": 2,
"selected": false,
"text": "yield using System;\nusing System.Collections.Generic; \nusing System.Threading.Tasks;\n\npublic class Program\n{\n public static async Task Main()\n {\n List<int> numbers = new List<int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n \n await foreach(int number in YieldReturnNumbers(numbers))\n {\n Console.WriteLine(number);\n }\n }\n \n public static async IAsyncEnumerable<int> YieldReturnNumbers(List<int> numbers) \n {\n foreach (int number in numbers)\n {\n await Task.Delay(1000);\n yield return number;\n }\n }\n}\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1409/"
] |
39,485
|
<p>Does anyone know of anywhere I can find actual code examples of Software Phase Locked Loops (SPLLs) ? </p>
<p>I need an SPLL that can track a PSK modulated signal that is somewhere between 1.1 KHz and 1.3 KHz. A Google search brings up plenty of academic papers and patents but nothing usable. Even a trip to the University library that contains a shelf full of books on hardware PLL's there was only a single chapter in one book on SPLLs and that was more theoretical than practical.</p>
<p>Thanks for your time.</p>
<p>Ian</p>
|
[
{
"answer_id": 9118612,
"author": "Kragen Javier Sitaker",
"author_id": 176009,
"author_profile": "https://Stackoverflow.com/users/176009",
"pm_score": 4,
"selected": false,
"text": "main(a,b){for(;;)a+=((b+=16+a/1024)&256?1:-1)*getchar()-a/512,putchar(b);}\n arecord | ./pll | aplay b getchar() a b a a == 0 b putchar() b"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3875/"
] |
39,503
|
<p>I need to modify the MBR of Windows, and I would really like to do this from Windows.</p>
<p>Here are my questions. I know that I can get a handle on a physical device with a call to CreateFile. Will the MBR always be on \\.\PHYSICALDRIVE0? Also, I'm still learning the Windows API to read directly from the disk. Is readabsolutesectors and writeabsolutesectdors the two functions I'm going to need to use to read/write to the disk sectors which contain the MBR?</p>
<p>Edit from from what I've learned on my own.
The MBR will not always be on \\.\PHYSICALDRIVE0. Also, you can write to the bootsector (at least as Administrator on XP) by call CreateFile with the device name of the drive that contains the MBR. Also, you can write to this drive by simply calling WriteFile and passing the handle of the device created by calling CreateFile.</p>
<p>Edit to address Joel Coehoorn.
I need to edit the MBR because I'm working on a project that needs to modify hardware registers after POST in BIOS, but before Windows will be allowed to boot. Our plan is to make these changes by modifying the bootloader to execute our code before Windows boots up. </p>
<p>Edit for Cd-MaN.
Thanks for the info. There isn't anything in your answer, though, that I didn't know and your answer doesn't address my question. The registry in particular absolutely will not do what we need for multiple reasons. The big reason being that Windows is the highest layer among multiple software layers that will be running with our product. These changes need to occur even before the lower levels run, and so the registry won't work. </p>
<p>P.S. for Cd-MaN.
As I understand it, the information you give isn't quite correct. For Vista, I think you can write to a volume if the sectors being written to are boot sectors. See <a href="http://support.microsoft.com/kb/942448" rel="nofollow noreferrer">http://support.microsoft.com/kb/942448</a></p>
|
[
{
"answer_id": 40009,
"author": "Grey Panther",
"author_id": 1265,
"author_profile": "https://Stackoverflow.com/users/1265",
"pm_score": 2,
"selected": false,
"text": "OUT AX, BL\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2171/"
] |
39,533
|
<p>Is there a way to identify, from within a VM, that your code is running inside a VM?</p>
<p>I guess there are more or less easy ways to identify specific VM systems, especially if the VM has the provider's extensions installed (such as for VirtualBox or VMWare). But is there a general way to identify that you are not running directly on the CPU?</p>
|
[
{
"answer_id": 39542,
"author": "wvdschel",
"author_id": 2018,
"author_profile": "https://Stackoverflow.com/users/2018",
"pm_score": 3,
"selected": false,
"text": "/sys/devices/virtual/dmi/id/product_name dmidecode | grep Product"
},
{
"answer_id": 108504,
"author": "Charles Duffy",
"author_id": 14122,
"author_profile": "https://Stackoverflow.com/users/14122",
"pm_score": 4,
"selected": false,
"text": "virt-what"
},
{
"answer_id": 50945690,
"author": "Pritesh Mhatre",
"author_id": 3834496,
"author_profile": "https://Stackoverflow.com/users/3834496",
"pm_score": 2,
"selected": false,
"text": "import java.io.BufferedReader;\nimport java.io.InputStreamReader;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic abstract class OSUtil {\n\npublic static final List<String> readCmdOutput(String command) {\n List<String> result = new ArrayList<>();\n\n try {\n Process p=Runtime.getRuntime().exec(\"cmd /c \" + command);\n p.waitFor();\n BufferedReader reader=new BufferedReader(\n new InputStreamReader(p.getInputStream())\n );\n String line;\n while((line = reader.readLine()) != null) {\n if(line != null && !line.trim().isEmpty()) {\n result.add(line);\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return result;\n}\n\npublic static final String readCmdOutput(String command, int lineNumber) {\n List<String> result = readCmdOutput(command);\n if(result.size() < lineNumber) {\n return null;\n }\n\n return result.get(lineNumber - 1);\n}\n\npublic static final String getBiosSerial() {\n return readCmdOutput(\"WMIC BIOS GET SERIALNUMBER\", 2);\n}\n\npublic static final String getHardwareModel() {\n return readCmdOutput(\"WMIC COMPUTERSYSTEM GET MODEL\", 2);\n}\n\npublic static final String getHardwareManufacturer() {\n return readCmdOutput(\"WMIC COMPUTERSYSTEM GET MANUFACTURER\", 2);\n}\n\npublic static void main(String[] args) {\n System.out.println(\"BIOS Serial: \" + getBiosSerial());\n System.out.println(\"Hardware Model: \" + getHardwareModel());\n System.out.println(\"Hardware Manufacturer: \" + getHardwareManufacturer());\n}\n}\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/107/"
] |
39,536
|
<p>I have a fairly small MySQL database (a Textpattern install) on a server that I do not have SSH access to (I have FTP access only). I need to regularly download the live database to my local dev server on demand; i.e., I would like to either run a script and/or have a cron job running. What are some good ways of doing this?</p>
<p>Some points to note:</p>
<ul>
<li>Live server is running Linux, Apache 2.2, PHP 5.2 and MySQL 4.1</li>
<li>Local server is running the same (so using PHP is an option), but the OS is Windows</li>
<li>Local server has Ruby on it (so using Ruby is a valid option)</li>
<li>The live MySQL db <em>can</em> accept remote connections from different IPs</li>
<li>I cannot enable replication on the remote server</li>
</ul>
<p><strong><em>Update:</em></strong> I've accepted BlaM's answer; it is beautifully simple. Can't believe I didn't think of that. There was one problem, though: I wanted to automate the process, but the proposed solution prompts the user for a password. Here is a slightly modified version of the mysqldump command that passes in the password:</p>
<p><code>mysqldump -u USER --password=MYPASSWORD DATABASE_TO_DUMP -h HOST > backup.sql</code></p>
|
[
{
"answer_id": 39555,
"author": "Anders Sandvig",
"author_id": 1709,
"author_profile": "https://Stackoverflow.com/users/1709",
"pm_score": 0,
"selected": false,
"text": "SELECT * FROM ... DROP DATABASE ... INSERT SHOW DATABASES SHOW CREATE TABLE ... CREATE TABLE SHOW TABLES"
},
{
"answer_id": 39672,
"author": "BlaM",
"author_id": 999,
"author_profile": "https://Stackoverflow.com/users/999",
"pm_score": 4,
"selected": true,
"text": "cd \"into mysql directory\"\nmysqldump -u USERNAME -p -h YOUR_HOST_IP DATABASE_TO_MIRROR >c:\\backup\\database.sql\n"
},
{
"answer_id": 886452,
"author": "The Disintegrator",
"author_id": 92462,
"author_profile": "https://Stackoverflow.com/users/92462",
"pm_score": 2,
"selected": false,
"text": "mysqldump -hlive_server_addresss -ulive_server_user -plive_server_password --opt --compress live_server_db | mysql -ulocal_server_user -plocal_server_password local_server_db"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1944/"
] |
39,541
|
<p>Maybe I just don't know .NET well enough yet, but I have yet to see a satisfactory way to implement this simple VB6 code easily in .NET (assume this code is on a form with N CommandButtons in array Command1() and N TextBoxes in array Text1()):</p>
<pre><code>Private Sub Command1_Click(Index As Integer)
Text1(Index).Text = Timer
End Sub
</code></pre>
<p>I know it's not very useful code, but it demonstrates the ease with which control arrays can be used in VB6. What is the simplest equivalent in C# or VB.NET?</p>
|
[
{
"answer_id": 39544,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 0,
"selected": false,
"text": "TextBox[] textboxes = new TextBox[] {\n textBox1,\n textBox2,\n textBox3\n};\n"
},
{
"answer_id": 39548,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 2,
"selected": false,
"text": "Private Sub TextBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) _ \n Handles TextBox1.TextChanged, _\n\n TextBox2.TextChanged, _\n\n TextBox3.TextChanged\n\nEnd Sub\n"
},
{
"answer_id": 39552,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 1,
"selected": false,
"text": "List<YourControl> MyControlArray.\n"
},
{
"answer_id": 39553,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "Private Sub Command_Click(sender As Object, e As EventArgs) Handles Command1.Click, Command2.Click …\n Dim name As String = DirectCast(sender, Control).Name\n Dim index As Integer = Integer.Parse(name.Substring(\"Command\".Length))\n Controls(String.Format(\"Text {0}\", index)).Text = Timer.Value.ToString()\nEnd Sub\n"
},
{
"answer_id": 39556,
"author": "Seb Nilsson",
"author_id": 2429,
"author_profile": "https://Stackoverflow.com/users/2429",
"pm_score": 4,
"selected": true,
"text": "var textBoxes = new List<TextBox>();\n\n// Create 10 textboxes in the collection\nfor (int i = 0; i < 10; i++)\n{\n var textBox = new TextBox();\n textBox.Text = \"Textbox \" + i;\n textBoxes.Add(textBox);\n}\n\n// Loop through and set new values on textboxes in collection\nfor (int i = 0; i < textBoxes.Count; i++)\n{\n textBoxes[i].Text = \"New value \" + i;\n // or like this\n var textBox = textBoxes[i];\n textBox.Text = \"New val \" + i;\n}\n"
},
{
"answer_id": 39570,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 0,
"selected": false,
"text": "Private Sub AllButton_Click(sender As Object, e As EventArgs) Handles Button1.Click, Button2.Click, Button3.Click\n Dim c As Control = CType(sender, Control)\n Dim t As TextBox = FindControl(CType(c.Tag, String))\n If t Is Not Nothing Then\n t.Text = \"Clicked\"\n End If\nEnd Sub\n"
},
{
"answer_id": 2099212,
"author": "Tim Goodman",
"author_id": 254364,
"author_profile": "https://Stackoverflow.com/users/254364",
"pm_score": 0,
"selected": false,
"text": "sender myArray(index)"
},
{
"answer_id": 57372785,
"author": "Federico Navarrete",
"author_id": 1928691,
"author_profile": "https://Stackoverflow.com/users/1928691",
"pm_score": 0,
"selected": false,
"text": "'To declare the List of controls\nPrivate textBoxes As List(Of TextBox) = New List(Of TextBox)()\n\nPrivate Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)\n 'To get all controls in the form\n For Each control In Controls\n\n 'To search for the specific type that you want to create the array \n If control.[GetType]() = GetType(TextBox) Then\n textBoxes.Add(CType(control, TextBox))\n End If\n Next\n\n 'To sort the labels by the ID\n textBoxes = textBoxes.OrderBy(Function(x) x.Name).ToList()\nEnd Sub\n //To declare the List of controls\nprivate List<TextBox> textBoxes = new List<TextBox>();\nprivate void Form1_Load(object sender, EventArgs e)\n{\n //To get all controls in the form\n foreach (var control in Controls)\n {\n //To search for the specific type that you want to create the array \n if (control.GetType() == typeof(TextBox))\n {\n //To add the control to the List\n textBoxes.Add((TextBox)control);\n }\n }\n\n //To sort the labels by the ID\n textBoxes = textBoxes.OrderBy(x => x.Name).ToList();\n}\n List typeof(Control)"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4228/"
] |
39,561
|
<p>Trying to get my css / C# functions to look like this:</p>
<pre><code>body {
color:#222;
}
</code></pre>
<p>instead of this:</p>
<pre><code>body
{
color:#222;
}
</code></pre>
<p>when I auto-format the code.</p>
|
[
{
"answer_id": 17557791,
"author": "Gabriel Nahmias",
"author_id": 2285405,
"author_profile": "https://Stackoverflow.com/users/2285405",
"pm_score": 3,
"selected": false,
"text": "Tools -> Options -> Text Editor -> CSS -> Formatting"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26/"
] |
39,562
|
<p>A friend of mine is now building a web application with J2EE and Struts, and it's going to be prepared to display pages in several languages.</p>
<p>I was told that the best way to support a multi-language site is to use a properties file where you store all the strings of your pages, something like:</p>
<pre><code>welcome.english = "Welcome!"
welcome.spanish = "¡Bienvenido!"
...
</code></pre>
<p>This solution is ok, but what happens if your site displays news or something like that (a blog)? I mean, content that is not static, that is updated often... The people that keep the site have to write every new entry in each supported language, and store each version of the entry in the database. The application loads only the entries in the user's chosen language.</p>
<p>How do you design the database to support this kind of implementation?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 39587,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 4,
"selected": true,
"text": "SELECT NewsText FROM News INNER JOIN NewsText ON News.NewsID = NewsText.NewsID\nWHERE NewsText.NewsLanguageID = <<Session[\"UserLanguageID\"]>>\n"
},
{
"answer_id": 41379,
"author": "reefnet_alex",
"author_id": 2745,
"author_profile": "https://Stackoverflow.com/users/2745",
"pm_score": 4,
"selected": false,
"text": "echo _(\"Please do not press this button again\");\n #: myfolder/my.source:239\nmsgid \"Please do not press this button again\"\nmsgstr \"\"\n #: myfolder/my.source:239\nmsgid \"Please do not press this button again\"\nmsgstr \"s’il vous plaît ne pas appuyer sur le bouton ci-dessous à nouveau\"\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1679/"
] |
39,564
|
<p>In my host, I currently have installed 2 wordpress applications, 1 phpBB forum and one MediaWiki.</p>
<p>Is there a way to merge the login so that all applications share the same credentials?</p>
<p>For instance, I want to register only in my phpBB and then I want to access all other applications with the given username and password.</p>
<p>Even if you don't know a unified way, what other login integration do you know of? Pros and cons of each?</p>
|
[
{
"answer_id": 39595,
"author": "seanyboy",
"author_id": 1726,
"author_profile": "https://Stackoverflow.com/users/1726",
"pm_score": 2,
"selected": false,
"text": "require_once('includes/AuthPlugin.php');\nrequire_once('extensions/AuthPress.php');\n\n$wgAuth = new AuthPress();\n$wgAuth->setAuthPressTablePrefix('evo_');\n# Only include the following if you aren't using the same db as MediaWiki\n$wgAuth->setAuthPressDBServer ('localhost');\n$wgAuth->setAuthPressDBName('yourWordPressDB');\n$wgAuth->setAuthPressUser('mySQL user for same');\n$wgAuth->setAuthPressPassword('The password');\n"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2644/"
] |
39,567
|
<p>In Ruby, given an array in one of the following forms...</p>
<pre><code>[apple, 1, banana, 2]
[[apple, 1], [banana, 2]]
</code></pre>
<p>...what is the best way to convert this into a hash in the form of...</p>
<pre><code>{apple => 1, banana => 2}
</code></pre>
|
[
{
"answer_id": 39621,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 7,
"selected": false,
"text": "Hash[*array_variable.flatten] a1 = ['apple', 1, 'banana', 2]\nh1 = Hash[*a1.flatten(1)]\nputs \"h1: #{h1.inspect}\"\n\na2 = [['apple', 1], ['banana', 2]]\nh2 = Hash[*a2.flatten(1)]\nputs \"h2: #{h2.inspect}\"\n Array#flatten(1) Array"
},
{
"answer_id": 39625,
"author": "Dominik Grabiec",
"author_id": 3719,
"author_profile": "https://Stackoverflow.com/users/3719",
"pm_score": 3,
"selected": false,
"text": "a = [[:apple, 1], [:banana, 2]]\nh = a.inject({}) { |r, i| r[i.first] = i.last; r }\n a = [:apple, 1, :banana, 2]\nh = {}\na.each_slice(2) { |i| h[i.first] = i.last }\n"
},
{
"answer_id": 39629,
"author": "Anders Sandvig",
"author_id": 1709,
"author_profile": "https://Stackoverflow.com/users/1709",
"pm_score": 0,
"selected": false,
"text": "a = [\"apple\", 1, \"banana\", 2]\nm1 = {}\nfor x in (a.length / 2).times\n m1[a[x*2]] = a[x*2 + 1]\nend\n\nb = [[\"apple\", 1], [\"banana\", 2]]\nm2 = {}\nfor x,y in b\n m2[x] = y\nend\n"
},
{
"answer_id": 39641,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": -1,
"selected": false,
"text": " input = [\"cat\", 1, \"dog\", 2, \"wombat\", 3]\n hash = Hash.new\n input.each_with_index {|item, index|\n if (index%2 == 0) hash[item] = input[index+1]\n }\n hash #=> {\"cat\"=>1, \"wombat\"=>3, \"dog\"=>2}\n"
},
{
"answer_id": 3056424,
"author": "StevenJenkins",
"author_id": 210672,
"author_profile": "https://Stackoverflow.com/users/210672",
"pm_score": 2,
"selected": false,
"text": "Hash[*(\"a,b,c,d\".split(',').zip([1,2,3,4]).flatten)]\n \"a,b,c,d\" split zip [1,2,3,4] [[a,1],[b,2],[c,3],[d,4]]\n [\"a\",1,\"b\",2,\"c\",3,\"d\",4]\n *[\"a\",1,\"b\",2,\"c\",3,\"d\",4] \"a\",1,\"b\",2,\"c\",3,\"d\",4 Hash[] Hash[*(\"a,b,c,d\".split(',').zip([1,2,3,4]).flatten)]\n {\"a\"=>1, \"b\"=>2, \"c\"=>3, \"d\"=>4}\n"
},
{
"answer_id": 9571767,
"author": "Stew",
"author_id": 332936,
"author_profile": "https://Stackoverflow.com/users/332936",
"pm_score": 8,
"selected": true,
"text": "a3 = [ ['apple', 1], ['banana', 2], [['orange','seedless'], 3] ]\nh3 = Hash[*a3.flatten]\n ArgumentError: odd number of arguments for Hash\n from (irb):10:in `[]'\n from (irb):10\n h3 = Hash[a3.map {|key, value| [key, value]}]\nputs \"h3: #{h3.inspect}\"\n h3: {[\"orange\", \"seedless\"]=>3, \"apple\"=>1, \"banana\"=>2}\n"
},
{
"answer_id": 14279597,
"author": "Priyanka",
"author_id": 1970032,
"author_profile": "https://Stackoverflow.com/users/1970032",
"pm_score": 3,
"selected": false,
"text": "1.9.3p362 :005 > a= [[1,2],[3,4]]\n\n => [[1, 2], [3, 4]]\n\n1.9.3p362 :006 > h = Hash[a]\n\n => {1=>2, 3=>4} \n"
},
{
"answer_id": 20777227,
"author": "JanDintel",
"author_id": 2111438,
"author_profile": "https://Stackoverflow.com/users/2111438",
"pm_score": 5,
"selected": false,
"text": "Array#to_h Array Hash [[:foo, :bar], [1, 2]].to_h # => {:foo => :bar, 1 => 2}\n"
},
{
"answer_id": 20831486,
"author": "Marc-André Lafortune",
"author_id": 8279,
"author_profile": "https://Stackoverflow.com/users/8279",
"pm_score": 7,
"selected": false,
"text": "Array#to_h [ [:apple,1],[:banana,2] ].to_h #=> {apple: 1, banana: 2}\n to_h [:apple, :banana].to_h { |fruit| [fruit, \"I like #{fruit}s\"] } \n # => {apple: \"I like apples\", banana: \"I like bananas\"}\n to_h backports require 'backports/2.6.0/enumerable/to_h' to_h Hash[] array = [ [:apple,1],[:banana,2] ]\nHash[ array ] #= > {:apple => 1, :banana => 2}\n flatten"
},
{
"answer_id": 29008534,
"author": "user3588841",
"author_id": 3588841,
"author_profile": "https://Stackoverflow.com/users/3588841",
"pm_score": 0,
"selected": false,
"text": "data = [[\"foo\",1,2,3,4],[\"bar\",1,2],[\"foobar\",1,\"*\",3,5,:foo]]\n data_hash = Hash[data.map { |key| [key.shift, key] }]\n\n#=>{\"foo\"=>[1, 2, 3, 4], \"bar\"=>[1, 2], \"foobar\"=>[1, \"*\", 3, 5, :foo]}\n"
},
{
"answer_id": 47614488,
"author": "lindes",
"author_id": 313756,
"author_profile": "https://Stackoverflow.com/users/313756",
"pm_score": 3,
"selected": false,
"text": "flat_array = [ apple, 1, banana, 2 ] # count=4\nnested_array = [ [apple, 1], [banana, 2] ] # count=2 of count=2 k,v arrays\nincomplete_f = [ apple, 1, banana ] # count=3 - missing last value\nincomplete_n = [ [apple, 1], [banana ] ] # count=2 of either k or k,v arrays\n\n\n# there's one option for flat_array:\nh1 = Hash[*flat_array] # => {apple=>1, banana=>2}\n\n# two options for nested_array:\nh2a = nested_array.to_h # since ruby 2.1.0 => {apple=>1, banana=>2}\nh2b = Hash[nested_array] # => {apple=>1, banana=>2}\n\n# ok if *only* the last value is missing:\nh3 = Hash[incomplete_f.each_slice(2).to_a] # => {apple=>1, banana=>nil}\n# always ok for k without v in nested array:\nh4 = Hash[incomplete_n] # or .to_h => {apple=>1, banana=>nil}\n\n# as one might expect:\nh1 == h2a # => true\nh1 == h2b # => true\nh1 == h3 # => false\nh3 == h4 # => true\n a1 a2 apple banana a1 = [ 'apple', 1 , 'banana', 2 ] # flat input\na2 = [ ['apple', 1], ['banana', 2] ] # key/value paired input\n a3 a3 = [ [ 'apple', 1 ],\n [ 'banana', 2 ],\n [ ['orange','seedless'], 3 ],\n [ 'pear', [4, 5] ],\n ]\n a4 a4 = [ [ 'apple', 1],\n [ 'banana', 2],\n [ ['orange','seedless'], 3],\n [ 'durian' ], # a spiky fruit pricks us: no value!\n ]\n a1 #to_h a1.to_h # => TypeError: wrong element type String at 0 (expected array)\n Hash::[] Hash[*a1] # => {\"apple\"=>1, \"banana\"=>2}\n a1 a2 [key,value] Hash::[] *a1 Hash[a2] # => {\"apple\"=>1, \"banana\"=>2}\n #to_h a2.to_h # => {\"apple\"=>1, \"banana\"=>2}\n a3 Hash[a3] # => {\"apple\"=>1, \"banana\"=>2, [\"orange\", \"seedless\"]=>3, \"pear\"=>[4, 5]} \na3.to_h # => {\"apple\"=>1, \"banana\"=>2, [\"orange\", \"seedless\"]=>3, \"pear\"=>[4, 5]}\n #to_h a4.to_h # => ArgumentError: wrong array length at 3 (expected 2, was 1)\n Hash::[] nil durian Hash[a4] # => {\"apple\"=>1, \"banana\"=>2, [\"orange\", \"seedless\"]=>3, \"durian\"=>nil}\n a5 a6 flatten 1 a5 = a4.flatten\n# => [\"apple\", 1, \"banana\", 2, \"orange\", \"seedless\" , 3, \"durian\"] \na6 = a4.flatten(1)\n# => [\"apple\", 1, \"banana\", 2, [\"orange\", \"seedless\"], 3, \"durian\"] \n a4 a4.to_h flatten flatten a5 Hash[*a5] # => {\"apple\"=>1, \"banana\"=>2, \"orange\"=>\"seedless\", 3=>\"durian\"}\n# (This is the same as calling `Hash[*a4.flatten]`.)\n 3 durian a1 a5.to_h # => TypeError: wrong element type String at 0 (expected array)\n a4.flatten Hash[a4] flatten(1) a6 Hash::[] splat a6 Hash[a4] Hash[*a6] # => ArgumentError: odd number of arguments for Hash\n a6 a1 Hash[*a6] nil Enumerable#each_slice a7 = a6.each_slice(2).to_a\n# => [[\"apple\", 1], [\"banana\", 2], [[\"orange\", \"seedless\"], 3], [\"durian\"]] \n a4 a4.equal?(a7) # => false\na4 == a7 # => true\n Hash::[] Hash[a7] # => {\"apple\"=>1, \"banana\"=>2, [\"orange\", \"seedless\"]=>3, \"durian\"=>nil}\n# or Hash[a6.each_slice(2).to_a]\n each_slice(2) a4_plus = a4.dup # just to have a new-but-related variable name\na4_plus.push(['lychee', 4])\n# => [[\"apple\", 1],\n# [\"banana\", 2],\n# [[\"orange\", \"seedless\"], 3], # multi-value key\n# [\"durian\"], # missing value\n# [\"lychee\", 4]] # new well-formed item\n\na6_plus = a4_plus.flatten(1)\n# => [\"apple\", 1, \"banana\", 2, [\"orange\", \"seedless\"], 3, \"durian\", \"lychee\", 4]\n\na7_plus = a6_plus.each_slice(2).to_a\n# => [[\"apple\", 1],\n# [\"banana\", 2],\n# [[\"orange\", \"seedless\"], 3], # so far so good\n# [\"durian\", \"lychee\"], # oops! key became value!\n# [4]] # and we still have a key without a value\n\na4_plus == a7_plus # => false, unlike a4 == a7\n ap Hash[a4_plus] # prints:\n{\n \"apple\" => 1,\n \"banana\" => 2,\n [ \"orange\", \"seedless\" ] => 3,\n \"durian\" => nil, # correct\n \"lychee\" => 4 # correct\n}\n\nap Hash[a7_plus] # prints:\n{\n \"apple\" => 1,\n \"banana\" => 2,\n [ \"orange\", \"seedless\" ] => 3,\n \"durian\" => \"lychee\", # incorrect\n 4 => nil # incorrect\n}\n awesome_print ap each_slice [key, value] #to_h Hash::[] Hash::[] * value"
},
{
"answer_id": 68745099,
"author": "noraj",
"author_id": 5511315,
"author_profile": "https://Stackoverflow.com/users/5511315",
"pm_score": 0,
"selected": false,
"text": "reduce inject"
}
] |
2008/09/02
|
[
"https://Stackoverflow.com/questions/39567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4142/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.