Posts

Showing posts from March, 2012

javascript - JS / jQuery - Filtering divs with checkboxes -

i'm trying filter divs checkboxes using following code: $("#filtercontrols :checkbox").click(function() { $(".sectioncontent").hide(); $("#filtercontrols :checkbox:checked").each(function() { $("." + $(this).val()).show(); }); if($("#filtercontrols :checkbox").prop('checked') == false){ $(".sectioncontent").show(); } }); this works fine when check first checkbox, filters others when have first checkbox selected. it's hard explain try jsfiddle: http://jsfiddle.net/by9jl/ i don't want rely on having first checkbox checked, there way around this? try var sections = $('.sectioncontent'); function updatecontentvisibility(){ var checked = $("#filtercontrols :checkbox:checked"); if(checked.length){ sections.hide(); checked.each(function(){ $("." + $(this).val()).show(); }); } else { sections.s

Parsing ISO-8601 DateTime in java -

i have trouble parsing date time in java, have strange date time format. how can parse 2013-04-03t17:04:39.9430000+03:00 date time in java format dd.mm.yyyy hh:mm in java? the "strange" format you're speaking of iso-8601 format, used. can use simpledateformat reformat in way please: simpledateformat informat = new simpledateformat("yyyy-mm-dd't'hh:mm:ssz"); datetime dtin = informat.parse(datestring}); //where datestring date in iso-8601 format simpledateformat outformat = new simpledateformat("dd.mm.yyyy hh:mm"); string dtout = outformat.format(dtin); //parse datetime object if need interact such will give format mentioned.

asp.net mvc 3 - Extension method at Linq statement -

please see below: public content getcontentbypagetitle(string pagetitle) { return _db.contents.firstordefault( x => hnurlhelper.urlsafe(x.pagetitle).equals(pagetitle) ); } public class hnurlhelper { public static string urlsafe(string value) { if (!string.isnullorempty(value)) { value = value.replace("Å ", "s"); value = value.trim().tolower(); value = value.replace(" ", "-"); value = regex.replace(value, @"[^a-za-z0-9-_]", ""); return value.trim().tolower(); } return string.empty; } } server error in '/' application. linq entities not recognize method 'system.string urlsafe(system.string)' method, , method cannot translated store expression. description: unhandled exception occurred during execution of current web request. please review sta

c# - Assigning blank value to a DateTime filed -

i have written linq xml query, create entities xml, have datetime field in xml can possibly blank, , need assign same blank field in entity, getting error "string not recognized datetime" xdocument xdocument = xdocument.load(@"c:\sample.xml"); var _pndlist = plist in xdocument.descendants("header") select new pnd() { deliverydate = datetime.parseexact(convert(plist, "deliverydate"), "yyyymmdd", cultureinfo.invariantculture, datetimestyles.none), loadclosed = datetime.parseexact(convert(plist, "loadcloseddatetime"), "yyyymmddhhmmss", cultureinfo.invariantculture, datetimestyles.none), trailerid = convert(plist, "trailerid"),

asp.net - Deploying a Visual Studio website vs web application -

so i'm using visual studio 2010 build website formerly running on php, i'm pretty new environment. in starting project built website project, not web application project. know generate lot of "never use website project, use web application project instead" comments, bear me. i'm attempting provide our server team necessary files compile on our server first time. they're used working web application files, not website files. normally given source code , batch file compiles code deployment directories , move files server there. i'm pretty sure other teams use deployment packages this, isn't option website. my question is, equivalent steps getting source website ready deploy vs web application? have published website separate folder , has rendered think equivalent in many ways, wanted make sure. also, possible publish parts of website without others? please with-hold comments how should using web application instead, google seems assume th

c++ - How to forbidden using object to static member function -

i have simple class, , static member function: class matrix { public: static matrix returnsomething ( matrix &m ) { return matrix(2,2); } }; main function: int main() { matrix matrix(2,2); // matrix matrix m = matrix::returnsomething ( matrix ) // should use way m.print() // shows matrix // can use way // matrix m; m.returnsomething ( matrix ) // how make not allowed?? m.print() // here matrix null, wont show } how it? edit: i have added print function shows problem why not use helper class? class matrixhelper { public: static matrix returnsomething ( matrix &m ) { return matrix(2,2); } }; then invocation be: matrixhelper::returnsomething ( matrix )

python - Dynamically adding key-arguments to method -

i set default key-arguments of instance method dynamically. example, with class module(object): def __init__(self, **kargs): set-default-key-args-of-method(self.run, kargs) # change run arguments def run(self, **kargs): print kargs we have: m = module(ans=42) m.run.im_func.func_code.co_argcount # => 2 m.run.im_func.func_code.co_varnames # => ('self','ans','kargs') m.run.im_func.func_defaults # => (42,) m.run() # print {'ans':42} i tried types.codetype (which don't understand) function (not method) , got work (well not-to-fail ), added key-arguments did not show in kargs dictionary of function (it print {}) the change has done current instance only. actually, using class right (i'm oo in mind) class method, function maybe better. like: def wrapped_run(**kargs): def run(**key_args): print key_args return wrap-the-run-function(run, kargs) ru

java - Facing an issue for querying error as "HSQL Database : Unexpected token: END in statement" -

i have created activeobject query below: ao.find(ip.class, query.select().where("user=? , start>=? , end<=?",u,datefieldl,datefieldl)) but gives me below error: there sql exception thrown active objects library: database: - name:hsql database engine - version:1.8.0 - minor version:8 - major version:1 driver: - name:hsql database engine driver - version:1.8.0 java.sql.sqlexception: unexpected token: end in statement [select * public.ao_0371a8_ip user=? , start>=? , end<=?] create entity stuff below: ip pi = ao.executeintransaction(new transactioncallback() // (1) { @override public ip dointransaction() { logger.info("before ao.create"); ip pi = ao.create(enclass); .... pi.save(); return pi; } }); my entity looks below: @table("ip") @prelo

javascript - Round to nearest multiple with offset in JS -

i have number want round nearest multiple of x with offset . example, how round number nearest number 5 more multiple of 12 (ie 5, 17, 29...)? in case it'd this: var input = 34; var offset = 5; var multiple = 12; var result = (math.round((input - offset) / multiple) * multiple) + offset; this should find nearest number 34 5 more multiple of 12 (29)

haskell - Type Families extension does not work as described -

on the haskell wiki page type families , there following list of examples: type family f :: * type instance f [int] = int -- ok! type instance f string = char -- ok! type instance f (f a) = -- wrong: type parameter mentions type family type instance f (forall a. (a, b)) = b -- wrong: forall type appears in type parameter type instance f float = forall a.a -- wrong: right-hand side may not forall type type instance -- ok! f (maybe int) = int f (maybe bool) = bool f (maybe a) = string type instance -- wrong: conflicts earlier instances (see below) f int = float f = [a] type family g b :: * -> * type instance g int = (,) -- wrong: must 2 type parameters type instance g int char float = double -- wrong: must 2 type parameters this demonstrates type instance where valid syntax under extension. following code not compile m

c# - Why dataTokens are in Route? -

context.maproute("authorized-credit-card", "owners/{ownerkey}/authorizedcreditcard/{action}", new { controller = "authorizedcreditcard", action = "index" }, new { ownerkey = nameformat }, datatokens: new { scheme = uri.urischemehttps }); in route file having above kind of route. so, 1 tell me meaning of datatokens: new { scheme = uri.urischemehttps ? and usage of above datatokens inside controller's action method ? according the documentation : you use datatokens property retrieve or assign values associated route not used determine whether route matches url pattern. these values passed route handler, can used processing request. so datatokens kind of additional data can passed route. there 3 datatoken's keys being predefined (the class below comes form source code of asp.net mvc 4 same keys used in version 2): internal class routedatatokenkeys { public const string usenamespacefallback = "usena

c# - nhibernate criteria for selecting from different tables -

Image
i have following table model: i want following sql command nhibernate criteria: select * units oid in (select oid orders ponumber <> 0 order ponumber limit 5) -> in other words: last 5 orders edit: my mappings unit.hbm.xml <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="dcgordersystem" namespace="dcgordersystem.model"> <class name="unit" table="units"> <id name="id"> <column name="uid" /> <generator class="native" /> </id> <property name="division" /> <property name="date" /> <property name="itemordernr" /> <property name="description" /> <property name="amount" /> <property name="price" /> <property name="costcenter" />

encryption - SQL Server Compact database file decrypt unlock -

i got unique database local file name database.db this generated sql server comptact edition, in encrypted format. does knows tool decrypt password, or try decode brute force system? i have libraries / dll of asp.net software opens file. if decompile it, can find password static string value? thanks help. you should able find connection string if have source , config files. or can try sqlceconnection.open code - brute force. have never encountered tool this.

c# - Read all textBox in form in my custom textbox -

Image
i work custom textbox in winform project, added property in custom textbox : private textbox _nextcontrol; public textbox nextcontrol { set { _nextcontrol=value; } { return _nextcontrol; } } and got result form 2 textbox (textbox1 , textbox2) in custom textbox properties property nextcontrol ; can see textbox es in form: in case property nextcontrol show textbox in form select next control. but when want same in new wpf costum textbox got same condition(2 textbox es, textbox1 , textbox2): why don't have same result? , how in wpf project? update: for more explanation, in winform project use property nextcontrol select next control ui properties. protected override void onkeydown(keyeventargs e) { if(e.keycode==keys.down) // select next textbox chosen in textbox option _nextcontrol.select(); } because can choose name of next textbox in ui, i don't want code . but not work in wpf: can't see names of textbo

java - Resteasy client not closing connection -

i have found 1 scenario resteasy not closing connection. there way around this? have created client as: threadsafeclientconnmanager cm = new threadsafeclientconnmanager(); httpclient httpclient = new defaulthttpclient(cm); clientexecutor executor = new apachehttpclient4executor(httpclient); t proxiedservice = org.jboss.resteasy.client.proxyfactory.create(clazz, base, executor); i calling following method on service @delete @path("{id}") response deleteobject(@pathparam("id") long id); and service returning http/1.1 500 internal server error [content-length: 0, server: jetty(8.1.2.v20120308)] any ideas on missing connection close. note: other response types, connections closing. i know if don't return 500, work well. should such scenario accidentally happen, want client able handle it, without running out of connections. i assuming following method belongs on resteasy client's proxied interface (?): response deleteobject(@path

coldfusion - Error performing the action getAttachments on CFExchangemail -

i trying attachments using cfexchangemail tag getting error: error performing action. exchange error code : 501. error occurred in c:/coldfusion9/wwwroot/excgangecode/read.cfm: line 229 227 : uid="#getdata.uid#" 228 : name="attachdata" 229 : attachmentpath="c:\test\#i#" 230 : generateuniquefilenames="yes"> 231 : here code: <cfif getdata.hasattachment> <cfexchangemail action="getattachments" connection="conn1" uid="#getdata.uid#" name="attachdata" attachmentpath="c:\test\1" generateuniquefilenames="yes"> </cfif> the folder c:\test\1 created attachments not saved in location. saying error performing action.exchange error code : 501 . can me solve

How to add/modify database records using Cayenne API -

i seeking use apache cayenne implement database, , know how use cayenne's api perform "add" operation. i have been reading on query document 2 days. gives information on how list of objects in table, how search primary key, how use expressions modify searches, , many different ways can search database. it not tell how add new record table, or how make changes record. doco writers seem interested in documenting nice searches can do. can please either provide or point me example of doing adds , updates??? example of delete nice, too... someone please advise. adding , deleting "data" in cayenne done via objectcontext operations on corresponding "objects". examples available in tutorial here , here , in the main docs , here quick explanation: // create new object in memory artist = context.newobject(artist.class); // save db. generate insert sql context.commitchanges(); // delete object in memory context.deleteobjects(a); // sav

java - Is there a method that parses int or returns 0 if unable to do so? -

i having write in different places , projects. int appointmentid = integer.parseint(stringutils.isnotempty(request.getparameter ("appointmentid")) ? request.getparameter("appointmentid"): "0"); is there common class returns parsed int or 0 or specify default return value? apache commons' numberutils.toint() returns 0 if conversion fails. (and lets specify default value on conversion failure.)

php - CakePHP 2 form fields with same name -

i have form select user select / occupation, it`s not listed there can write on text field bellow. the data saves corretly, text field, it`s last one, believe. i using same name both field, saves this. $this->data['student']['occupation'] if user find option on select , leaves text field empty data database empty. how can save data field has value set? thanks. you need change name first: in form can put select name "occupation" , textfield name "occupation2". then in controller can that: $this->data["student"]["occupation"] = $this->data["student"]["occupation2"] == "" ? $this->data["student"]["occupation"] : $this->data["student"]["occupation2"]; this verify if textfield empty, if empty use select list option else use textfield value.

jaxb - Use interfaces in JAX-WS web methods -

i need use interface parameter , return type in jax-ws web method. when starting server receive illegalannotationsexception , tells me jaxb cannot handle interfaces. i tried annotate class, method result , method parameters @xmlrootelement , @xmlelement(type = ...) respectively, not work. how can use interface parameter , result type in jax-ws web method? take @ @xmljavatypeadapter . maybe trick. more information available in here .

c# - ICloudStorageAccessToken Open says Null reference -

i have problem of opening dropbox folder. code generates exe. when exe executed, starts download package stored in dropbox folder. here code: _storage = new cloudstorage(); var dropboxcredentials = new dropboxcredentials(); dropboxcredentials.consumerkey = "xxxxxxxxxxxxxxx"; dropboxcredentials.consumersecret = "xxxxxxxxxxxxxxx"; dropboxcredentials.username = "someusername"; dropboxcredentials.password = "somepassword"; dropboxconfiguration configuration = dropboxconfiguration.getstandardconfiguration(); //open dropbox connection _storage.open(configuration, dropboxcredentials); i sorry have hide confidential information, assume correct. problem occurs @ _storage.open(configuration, dropboxcredentials); says: ![enter image description here][1] i checked " configuration " , " dropboxcredentials ", , not null, , " _storage ". confused, problem here exactly? lot. ed

android - get horizontal and vertical spacing in gridview -

i implementing grid view in application.and want horizontal spacing between consecutive rows , vertical spacing between consecutive columns within grid view using java code. is possible? there direct methods spacing? you can use android:verticalspacing , android:horizontalspacing in gridview tag , provide spacing per requirement. for example: <gridview android:layout_height="wrap_content" android:id="@+id/gridview1" android:layout_width="match_parent" android:numcolumns="auto_fit" android:horizontalspacing="10dp" // space between 2 items (horizontal) android:verticalspacing="10dp"> // space between 2 rows (vertical) on java try: "gridviewname".gethorizontalspacing() "gridviewname".getverticalspacing()

Google Apps Script sendEmail: multiple recipients string? -

using sendemail, how can send email multiple comma-separated recipients combining 2 form fields? seems work when (lastrow,4) has 1 value (abc@domain.com) not more 1 (abc@domain.com, xyz@domain.com). current code below, , variable in question recipientsto . function formemail() { var ss = spreadsheetapp.getactivespreadsheet(); var sheetform = ss.getsheetbyname("sheet1"); // name of sheet contains results var lastrow = sheetform.getlastrow(); var recipientsto = sheetform.getrange(lastrow,3).getvalue() + "@domain.com"; var recipientscc = "" var team = sheetform.getrange(lastrow,5).getvalue(); var datestamp = utilities.formatdate(sheetform.getrange(lastrow,1).getvalue(), "gmt - 5", "yyyy-mm-dd"); var html = "intro text; //the questions order in email order of column in sheet (var = 2; < 11; ++i) { html = html + "<b>" + sheetform.getrange(1,i).getvalue() + "</b><br>&

jquery - How do I pass specific .on selector into function -

i have 2 versions of same code. first version works great not newly loaded content. // fancy ajax loading , url rewriting when link clicked var linkbutton = $(".jshistory a"); linkbutton.on("click", function() { // if link selected nothing if($(this).parent().hasclass("selected")) { return false; // else load new content , update url } else { linky = $(this).attr("href"); history.pushstate(null, null, linky); showactivelink(); loadcontent(linky); return false; } }); in second version need relate specific linkbutton clicked , think work. i'm struggling pass selector through though. // fancy ajax loading , url rewriting when link clicked var linkbutton = $(".jshistory a"); $(document).on({ click: function() { if link selected nothing if($(this).parent(

Android Out of Memory Error while loading Wallpaper -

i creating first android app , reason getting out of memory error in log saying 'no memory load current wallpaper'. funny thing is, app doesn't have wallpapers load. not find information on problem. have experienced in android app? ideas did fix it? here stack: 05-01 13:33:32.796: i/dalvikvm(65): "android.server.serverthread" prio=5 tid=9 runnable 05-01 13:33:32.796: i/dalvikvm(65): | group="main" scount=0 dscount=0 obj=0x4062f658 self=0x1452f0 05-01 13:33:32.806: i/dalvikvm(65): | systid=78 nice=-2 sched=0/0 cgrp=default handle=1332240 05-01 13:33:32.806: i/dalvikvm(65): | schedstat=( 192509168074 60642217424 29772 ) utm=16633 stm=2617 core=0 05-01 13:33:32.806: i/dalvikvm(65): @ android.graphics.bitmapfactory.nativedecodefiledescriptor(native method) 05-01 13:33:32.806: i/dalvikvm(65): @ android.graphics.bitmapfactory.decodefiledescriptor(bitmapfactory.java:568) 05-01 13:33:32.806: i/dalvikvm(65): @ android.app.wallpapermanager$

c++ - how to get day of week from sqlite date and time string? -

i using sqlite datetime commands get, set , manipulate date , time strings. first construct sql command in const char* , execute command using sqlite3_exec while using call function fetch results if (select from) commands. orderdatabaserc = sqlite3_exec(orderdatabase, psql[i], callback, 0, &zerrmsg); now want know day of week (mo-su) , month (jan-dec) date , time string. how do in sqlite? documentation says can wiser documentation , examples hard find. let me give examples of sql commands using: "create table ordertable (orderid integer primary key asc, customerid integer, ordervalue, orderdescription, orderdatetime date, orderduedatetime date)" "create trigger insert_ordertable_orderdate after insert on ordertable begin update ordertable set orderdatetime = datetime('now') rowid = new.rowid; end;" "update ordertable set orderduedatetime = datetime('" << iorderdatetime << "', '+1 day') orderid =

windows - How do I get the information shown in vmmap programatically? -

as has watched mark russovich talk "mysteries of memory management revealed" knows, vmmap tool can show things count against process limit (2gb on vanilla 32 bit windows) few other tools seem know about. i able programmatically monitor real total memory size (the 1 that's germane process limit) can @ least log what's going on when approach process limit. there information publicly available on how vmmap this? ... also, why information darn hard get?? things know (afaik) don't quite give full picture: ::getprocessmemoryinfo looks returns info private memory usage system.diagnostics.process.virtualmemorysize64 returns pretty large number still doesn't quite match total shown vmmap -- in fact doesn't match shown in vmmap :( i used dependency walker @ windows api functions imported kernel32.dll vmmap.exe , found following functions relevant: virtualalloc virtualallocex virtualfree virtualprotectex virtualqueryex take @ , see if

regex - Using sed to remove words with common prefix -

i'm trying extract information source code create api others use. can grep file list of variables common signatures, variables polymorphic, can't clean them out nicely. for example: public static foo bar = new foo(123, "bar"); public static foo baz = new foo(222, "baz"); public static foobar fbar = new foobar(135, "foo", "bar"); public static foobaz fbaz = new foobaz(256, "baz", "badger", "baz"); i simplify down to: bar 123 bar baz 222 baz fbar 135 bar fbaz 256 baz currently, i've done far: grep "public static foo" file.java | tr '(' ' ' | tr ')' ' ' | sed "s/public\ static\ //g" which gives me this: foo bar = new foo 123, "bar" ; foo baz = new foo 222, "baz" ; foobar fbar = new foobar 135, "foo", "bar" ; foobaz fbaz = new foobaz 256, "baz", "badger", &

php - Record video on browser and upload to LAMP server -

i have tried lot of things out there: red5, jquery webcam, html5 ... none of these solution record video , leave ready upload server. is there anyway (html5, flash, whatever ... better cross-broswer solution, best) upload video (+ audio!) , upload result server (i guess through ajax) ? summarize: jquerywebcam ( https://github.com/infusion/jquery-webcam ): has flash video, uploads server image, not video eric bidelman's solution ( http://ericbidelman.tumblr.com/post/31486670538/creating-webm-video-from-getusermedia):records video in html5 , allows download (so can upload server), no audio ! red5 ( http://www.red5-recorder.com/services.php ): paid services, not uploading in free version :( dmv ( https://github.com/rwldrn/dmv ): captures photo ... besides not cross-browser you use binary download via javascript. here 1 example as have not info video protocols cant give better answer

select - MySQL table to column list query -

i trying workout how query table have , produce specific output format in select statement. source table data follows +-----------+------------------------+ | prefix_id | description | | b | +-----------+------------------------+ | 55207 | test 1 | 1 | 0 | | 55363 | test 2 | 1 | 0 | | 55378 | test 3 | 0 | 1 | | 55379 | test 4 | 1 | 1 | +-----------+------------------------+ the output desire above data follows +-----------+------------+ | | b | +-----------+------------| | test 1 | test 3 | | test 2 | test 4 | | test 4 | null | +-----------+------------+ as can see test 4 description appears twice true column , b order unimportant. null characters should appear @ end of column or b. ids not important long each entry appears once under corresponding columns. maybe temporary table can't figure out how. separate queries column or b easy merging them output problem. imagine output

Kineticjs load json canvas -

i got error: "typeerror: kinetic[type] not constructor" "referenceerror: reference undefined property obj.nodetype" when try load 1 json. json = stage.tojson(); stage = kinetic.node.create(json, 'mycanvas'); the method _createnode kineticjs 4.3.3 var no = new kinetic[type](obj.attrs); on canvas have simple group var circle1 = new kinetic.circle({ x: 40, y: 50, radius: 42, fill: 'white', stroke: 'black', strokewidth: 1, draggable: false }); var polygon1tab1 = new kinetic.regularpolygon({ x: 40, y: 50, radius: 27, sides: 4, stroke: 'black', strokewidth: 4, draggable: false }); polygon1tab1.rota

f# - scripts don't recognize FSharp.Data -

somewhat of f# beginner. i'm trying test out of xmltypeprovider code in interactive window first entering in script (fsx) file. script file won't recognize following open fsharp.data // gives "the namespace or module 'fsharp' not defined" everything has been added reference, , .fs files seem not have problems finding xmltypeprovider reference reason, script in same project not. got code work in .fs file. i added fsharp.data nuget , seem add correctly. missing here? add reference in script nuget packages folder contains fsharp.data.dll. folder contains designer dll (fsharp.data.designtime.dll) #r @"<your nuget packages folder>\fsharp.data.2.1.0\lib\net40\fsharp.data.dll"

MySQL select and update in one query -

i'm trying select value mysql (total_points) add local variable (new_points) , update total_points in same query, know if possible... i have., cursor = database.cursor() cursor.execute("""select total_points g_ent e_id =%s , user =%s; update total_points = (total_points + %s)""" ,(e_id, user_name, new_points)) database.commit() the issue sql syntax not correct. query should be: update g_ent set total_points = total_points + %s e_id = %s , user = %s; the full example be: cursor = database.cursor() cursor.execute("""update g_ent set total_points = total_points + %s e_id = %s , user = %s;""", (new_points, e_id, user_name)) # order of params revised database.commit() please note order of query parameters revised.

Hide link using css bracket attribute, no access to HTML -

i don't have access html need hide link (#wall) <td class="status_value"><span class="online"> - <a href="#wall"> leave comment </a> <a href="#today"> join today </a> i have tried using td.status_value[href='#wall']{display:none;} target <a> inside table cell, instead of table cell itself: so td.status_value[href='#wall']{display:none;} becomes td.status_value a[href='#wall']{display:none;}

Ivy Retrieve with Classifiers -

i have following ivy.xml : <ivy-module version="1.0" xmlns:maven="http://maven.apache.org"> <configurations> ... </configurations> <dependencies> <dependency org="com.foo" name="fubur" rev="1.3" conf="runtime->default"/> <dependency org="com.snafu" name="barfu" rev="1.4" conf="runtime->default"> <artifact name="barfu" maven:classifier="id_10t" type="jar" ext="jar"/> </dependency> </dependencies> </ivy-module> in build.xml , want retrieve of jars war i'm building: <ivy:retrieve pattern="${lib.dir}/[artifact]-[classifier]-[revision].[ext]" conf="runtime"/> no, won't work... there's no classifier in

typetraits - c++11 type_traits: different result in INTEL 2013 and GCC 4.7.2 -

for following class, intel 2013 (update 3) , gcc 4.7.2 give different type_traits results. 1 right? #include <iostream> #include <type_traits> using namespace std; class { public: a() = default; private: double t_; }; int main() { cout << boolalpha; cout << "is_trivial<a> : " << is_trivial<a>::value << endl; cout << "is_compound<a> : " << is_compound<a>::value << endl; cout << "is_pod<a> : " << is_pod<a>::value << endl; cout << "is_standard_layout<a> : " << is_standard_layout<a>::value << endl; cout << "is_literal_type<a> : " << is_literal_type<a>::value << endl; return 0; } intel output: is_trivial<a> : true is_compound<a> : true is_pod<a> : fals

c# - convert inherited to generic base -

can explain why conversion in return in switch statement doesn't compile in .net 4? i've updated example more accurate situation. factory isn't generic actually. even casting "as baseproductprocessor" not work if i'm passing in base product (that's standardproduct). if explicitly pass standardproduct type factory, it's ok - have defined product type in calling methods anyway :| how around this? using system; using microsoft.visualstudio.testtools.unittesting; namespace testing { [testclass] public class test { [testmethod]//fails public void testfactorymethodwithbasetypepassed() { product product = new testing.standardproduct(); var pp = new testing.productprocessorfactory().create(product); assert.isnotnull(pp);//fails because t coming create wasn't derived type } [testmethod]//passes public void testfactorymethodwithexacttype() {

makefile - How to create directory if needed? -

i'm trying use makefile, problem have directory, src directory , makefile . use tmp directory have create. has object files in it. , performance, try not delete these when debugging. if create rule tmp create it, rebuilds c files. how this? there number of ways. depends on version of make you're using , operating system you're using. the 1 thing must never use directory simple prerequisite. rules filesystem uses update modified time on directories not work make . for simple make on posix system, can pre-create directory in rule perform compilation: obj/foo.o: foo.c @ mdkir -p obj $(cc) $(cppflags) $(cflags) -c -o $@ $< if have gnu make have 2 options. simplest 1 force directory created when makefile read in before else happens, adding line this: _dummy := $(shell mkdir -p obj) the easy, fast, , reliable. downside directory created always, if it's not needed. nevertheless way it. the fancy way, if have new-enough gnu

echo JavaScript inside PHP -

this question has answer here: what difference between client-side , server-side programming? 5 answers i using following code change button when clicked echoing javascript's document.getelemenbyid property button remains is: while($result=mysql_fetch_array($result1)) { $i=1; echo " <tr> <form action='student.php' method='post'> <td>$result[0]<input type=\"hidden\" name=\"company\" value=\"$result[0]\"></td> <td> <input type=\"checkbox\" name=\"yes\" /> <input type=\"submit\" name=\"apply$i\" id=\"apply$i\" c

javascript - Proper way to create a reusable jQuery Object -

i'm trying code first non-hacked jquery plug-in , i'm struggling create basic object constructor, public variables, private variables, , functions. http://jqueryboilerplate.com/ has great guide creating objects extend jquery, don't think right way go generic object not attached dom element. does have boilerplate template creating basic reusable object? i.e. var calc = new customcalculator({'starting_value': 42}); calc.add(3); calc.multiplyby(2); alert(calc.total); // alerts (42 + 3) * 2 = 90 from code sample seems need basic way of creating js object. trick (but there lots of other ways it): function customcalculator(options){ var self = this; self.total = options.starting_value; self.add = function(term){ self.total += term; }; self.multiplyby = function(term){ self.total = self.total * term; }; } var calc = new customcalculator({'starting_value': 42}); calc.add(3); calc.multiplyby(2); aler

how to create list of objects in javascript -

var employee = { column1: null, column2: null, create: function () { var obj = new object(); obj.column1 = ""; obj.column2 = ""; return obj; } }; in c# this: list<employee> employees = new list<employee>(); (int = 0; < 10; i++) { employee emp = new employee() { column1 = "column 1 of emp" + i; column2 = "column 2 of emp" + i; } employees.add(emp); } i need same in javascript. pretty straight forward approach creating array of objects. var employees = []; (var = 0; < 10; i++) { employees.push({ column1: 'column 1 of emp' + i, column2: 'column 1 of emp' + }); }

jquery - How to make slide move auto after the page is clicked? -

i use http://cssglobe.com/lab/easyslider1.7/02.html plugin slide show. when click on page, slide stops move automatic. $("#slider").easyslider({ auto: true, speed: 800, pause: 5000, continuous: true, numeric: true, prevtext: 'previous', nexttext: 'next' }); look javascript error on page, should reason script stoped work. many times javascript problems stop script execution

c# - Find text under caret position -

i find caret position in application need know text (word) there @ current caret position. how can text? if using winforms application, , caret position mean caret position in textbox. thing this. 1. attach event handlers keyup , mouseup events 2. current textbox text , caret position 3. pass function returns word under position private void textbox1_keyup(object sender, eventargs e) { getwordfromcaretposition(textbox1.text, textbox1.selectionstart); } private void textbox1_mouseup(object sender, eventargs e) { getwordfromcaretposition(textbox1.text, textbox1.selectionstart); } private string getwordfromcaretposition(string input, int position) { string word = string.empty; //yet implemented. return word; } for wpf textbox caret position represented textbox1.caretindex for wpf richtextbox see thread : wpf richtextbox - whole word @ current caret position for windows phone 7 caret pos

android - NullPointerException on GSON Parsing -

i use gson parse json data, , app able parse google geocoder this. but, whenever try parse json website gives nullpointerexception this eventresponse class makes connection btw gson , website public class eventresponse { public meta meta; public objects[] objects; public eventresponse() {} public class meta { public int limit; public string next; public int offset; public string previous; public int total_count; } public class objects { public string category; public string date; public string description; public int id; public string name; public string resource_uri; public string venue; } } this json { "meta": { "limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 7 }, "objects": [ { &quo

asp.net mvc - Getting userId of logged in user returns null -

i designing asp.net mvc4 application , need current user id i'll save in table in database owner id group. this code using: public actionresult creategroup(string groupname, string description) { if (request.isauthenticated) { group group = new group(); random random = new random(); int groupid = random.next(1, 2147483647); using (codeshareentities conn = new codeshareentities()) { try { int ownerid = (int) membership.getuser(system.web.httpcontext.current.user.identity.name).provideruserkey; group.groupid = groupid; group.groupname = groupname; group.description = description; group.ownerid = ownerid; conn.group.add(group); conn.savechanges(); } catch (exception e)

ruby on rails - Can I use the syntax parent.Childs.create multiple times, when declaring a parent and two child records? -

customer=customer.new #create new customer object customer.id =1000+i #id needs set first because otherwise automatically set customer.update_attributes( :fname=>'mike', :lname=>'hancock', :year=>1998, :model=>'buick', :engine=>'4 liter', :vinnum=>'h920129801298', :signupdate=>"#{date.today}", :password=>'fguygfyed', ) contact=contact.create( :customer_id=>customer.id, #set foreign primary key :contactmethod=>4567894561, :contacttype=>"sms", :dateadded=>"#{date.today}", ) customer.contacts.create( :contactmethod=> 4657894564, :contacttype=> 'email', :dateadded=> "#{date.today}", ) i+=1 end this code works. however, if instead of contact=contact.create( :customer_id=>customer.id, #set foreign primary key i wrote customer

Powershell function argument default: Weirdness when it has a type constaint -

if have function parameter without type constraint: > function ($s=$null) {if ($s -eq $null) {write-host "hi"} if ($s -eq "") {write-host "kk"}} > hi now if add type constraint it, $null interpreted differently: > function ([string]$s=$null) {if ($s -eq $null) {write-host "hi"} if ($s -eq "") {write-host "kk"}} > kk i can't find doc explain this. it's not consistent. in first example (function a ), $s equivalent $null - it's null. in second example (function b ), because you're casting $s [string] object, it's empty string (equivalent [string]::empty ), not $null . you can check adding following each of functions: if($s -eq [string]::empty){"empty!"}; only b print empty! - a evaluate $false alternately, add this: $s|get-member a throw error - same error you'll if run $null|get-member . b show $s string , list of members of class.

css3 - CSS set width of first element based on width of second element -

i'm not sure how work i'm trying accomplish bear me... i'm trying set width of element, based on width of proceeding element. visually this: container element -------------------------------------------- | | | | | | |<--auto width div1-->|<--div2 200px-->| | | | | | | -------------------------------------------- so, essentially, div2 set float on right of page, , div1 should span right edge of div2 automatically i've started fiddle at: http://jsfiddle.net/yuvjs/ any appreciated... in advance... just use tables. rid of float , set 2 box divs display:table-cell , container div display:table . first box should adjust width automatically based on width of second box. fiddle example

Hibernate java.lang.ClassNotFoundException: Annotations -

time basic question can't find answer. realize exception means class missing, find thing? stack trace: warn worker-0 org.hibernate.cfg.annotationconfiguration - unable apply constraints on ddl annotations java.lang.classnotfoundexception: annotations @ org.eclipse.osgi.internal.loader.bundleloader.findclassinternal(bundleloader.java:506) @ org.eclipse.osgi.internal.loader.bundleloader.findclass(bundleloader.java:422) @ org.eclipse.osgi.internal.loader.bundleloader.findclass(bundleloader.java:410) @ org.eclipse.osgi.internal.baseadaptor.defaultclassloader.loadclass(defaultclassloader.java:107) @ java.lang.classloader.loadclass(classloader.java:248) @ java.lang.class.forname0(native method) @ java.lang.class.forname(class.java:169) @ org.hibernate.util.reflecthelper.classforname(reflecthelper.java:192) @ org.hibernate.cfg.annotationconfiguration.applyhibernatevalidatorlegacyconstraintsonddl(annotationconfiguration.java:463) @ org.hiber

Grails Events Push Failed to Initialize Atmosphere Framework -

deploying grails project uses events push plugin . keep getting error. production environment: tomcat 7.39 server: centos, java version: openjdk runtime environment (icedtea6 1.10.8) (rhel-1.27.1.10.8.el5_8-x86_64) openjdk 64-bit server vm (build 20.0-b11, mixed mode) plugin version: events-push:1.0.m7 the project works fine in development mode. 2013-05-02 14:35:57,388 [localhost-startstop-1] error cpr.atmosphereframework - failed initialize atmosphere framework java.lang.noclassdeffounderror: org/grails/plugin/platform/events/push/eventspushhandler$1 @ org.grails.plugin.platform.events.push.eventspushhandler.init(eventspushhandler.java:111) @ org.atmosphere.util.atmospherefilterchain.init(atmospherefilterchain.java:125) @ org.atmosphere.handler.reflectorservletprocessor$filterchainservletwrapper.init(reflectorservletprocessor.java:318) @ org.atmosphere.handler.reflectorservletprocessor.init(reflectorservletprocessor.java:210) @ org.atm

java - Count occurence of a character in a String -

this question has answer here: hashmap implementation count occurences of each character 6 answers i have below program counts occurrence of character in string. example, given string - my name stack overflow , want output be f 1 e 2 c 1 2 n 1 o 2 l 1 m 2 k 1 1 w 1 v 1 t 1 s 2 r 1 y 1 however, seems wrong, , unable figure out what. also, please note - see few programs posted in past. possible duplicate . specific problem rather using else' solution. here's code: //count occurence of character in string package strings; import java.io.bufferedreader; import java.io.inputstreamreader; import java.util.arraylist; import java.util.hashmap; import java.util.list; import java.util.map; public class characteroccurenceinastring { private static map<integer, character> str = new hashmap<integer, character>(); private static list<charac

sql server - SQL "between" not inclusive -

i have query this: select * cases created_at between '2013-05-01' , '2013-05-01' but gives no results though there data on 1st. created_at looks 2013-05-01 22:25:19 , suspect has time? how resolved? it works fine if larger date ranges, should (inclusive) work single date too. it is inclusive. comparing datetimes dates. second date interpreted midnight when day starts . one way fix is: select * cases cast(created_at date) between '2013-05-01' , '2013-05-01' another way fix explicit binary comparisons select * cases created_at >= '2013-05-01' , created_at < '2013-05-02' aaron bertrand has long blog entry on dates ( here ), discusses , other date issues.