Posts

Showing posts from July, 2011

reporting services - Converting seconds to HH:MM:SS in SSRS using function -

i had function below working convert seconds hh:mm:ss in ssrs. needs work seconds in excess of 86400 i.e. total time greater 24 hours. function below returning strange values 00:00:.2 or 00:00:75 public function convertsecondstohourminsec(byval inttotalseconds) string dim hours string =int(inttotalseconds/3600) if len(hours) < 2 hours = right(("0" & hours), 2) end if dim mins string = right("0" & int((inttotalseconds mod 3600)/60), 2) dim secs string = right("0" & ((inttotalseconds mod 3600) mod 60), 2) convertsecondstohourminsec = hours & ":" & mins & ":" & secs end function passing function value of 227.16666 gives 00:03:67, example. any idea how can fix function give hh:mm:ss? realized wasn't converting seconds int on bottom. works now.

ruby on rails - select_tag, problems with the record in the database -

there 2 tables heading , beautysalon. in first table write name of beauty salons , second services provide. table beautysalon heading field associated head , idea there recorded id lounge tables heading, why there not writing. <%= select_tag 'beautysalon[head]', options_for_select(@hea.collect{ |s| [s.name, s.id] } ) %> it's model heading class heading < activerecord::base belongs_to :section has_many :beautysalons searchable text :name text :address text :phone end end , model beautysalon class beautysalon < activerecord::base belongs_to :heading end beauty salon shema create_table "beautysalons", force: true |t| t.string "services" t.datetime "created_at" t.datetime "updated_at" t.integer "heading_id" t.integer "head" end heading shema create_table "headings", force: true |t| t.string "name" t.string "

c++ - How to compute a least common ancestor algorithm's time complexity? -

i came article talking lca algorithms, code simple http://leetcode.com/2011/07/lowest-common-ancestor-of-a-binary-tree-part-i.html // return #nodes matches p or q in subtree. int countmatchespq(node *root, node *p, node *q) { if (!root) return 0; int matches = countmatchespq(root->left, p, q) + countmatchespq(root->right, p, q); if (root == p || root == q) return 1 + matches; else return matches; } node *lca(node *root, node *p, node *q) { if (!root || !p || !q) return null; if (root == p || root == q) return root; int totalmatches = countmatchespq(root->left, p, q); if (totalmatches == 1) return root; else if (totalmatches == 2) return lca(root->left, p, q); else /* totalmatches == 0 */ return lca(root->right, p, q); } but wondering how compute time complexity of algorithm,can me? the worst case algorithm if nodes sibling leave nodes. node *lca(node *root, node *p, node *q) { root call countmatchespq; for(r

ruby - Convert executed SQL result to a list of Model object -

i'm wondering possible convert executed query result list of models. i'm using ruby activerecord , need execute custom sql query join 2 or many tables. code looks below: connection = activerecord::base.connection sql = "select t1.f1, t2.f2 t1 left join t2 on t1.id = t2.id" @result = connection.execute(sql) in ruby code, defined models manage executed sql result: class model property :f1, :f2 end is there way convert @result list of model object? can deal each item in list following @result.each |item| puts item.f1 puts item.f2 end have model inherit activerecord::base class model < activerecord::base end then can this connection = activerecord::base.connection sql = "select t1.f1, t2.f2 t1 left join t2 on t1.id = t2.id" @result = model.find_by_sql(sql) puts @result.f1

clips - Modifying the current fact that fires a rule -

say have defined template , facts shown below: (deftemplate student (slot name (type symbol) (default ?none)) (slot grade (type symbol) (default c) (allowed-symbols b c d)) (slot graduated (type symbol) (default no) (allowed-symbols yes no)) ) (deffacts insert-facts (student (name george) (grade a)) (student (name nick) (grade c)) (student (name bob)) (student (name mary) (grade b)) ) say want create rule checks grade of each student , sets corresponding graduated variable symbol 'yes'. how this? here's less verbose version of rule came solve problem: clips> (deftemplate student (slot name (type symbol) (default ?none)) (slot grade (type symbol) (default c) (allowed-symbols b c d)) (slot graduated (type symbol) (default no) (allowed-symbols yes no))) clips> (deffacts insert-facts (student (name george) (grade a)) (student (name nick) (grade c)) (student (name bob)) (student (name mary) (grad

php - Add custom label "product listing sort by" magento 1.8 backend location -

i have been searching time seems location has been changed. according this thread , used in toolbar.php file (near line 40) yet not there anymore. does know new location is? just clear, there lot of threads adding custom sort frontend users. want set in backend. (system->configuration->catalog->frontend->product listing sort by) cheers

html - Bootstrap Box Spanning with div -

Image
i want divide web page area pic shown. have tried approach. extent right. appreciate clear doubts. <div class="row"> <div class="col-md-8"> <div class="well"> <div class="row"> <div class="col-md-12"><div class="well">canvas</div></div> </div> <div class="row"> <div class="col-md-8"><div class="well">edit text</div></div> <div class="col-md-4"><div class="well">button</div></div> </div> </div> </div> <div class="col-md-4"><div class="well" >control panel</div></div> </div> this tried in jsfiddle , working me (without class) <div class="container"> <div c

objective c - Create a simple Alert in swift -

it looks alertstatus cannot used in swift. can guys please me implementing alternative solution code below? [self alertstatus:@"message!" :@"alert title" :0]; try following code let alert = uialertview() alert.title = "title" alert.message = "my message" alert.addbuttonwithtitle("ok") alert.show() but in ios 8 uialertview deprecated. use uialertcontroller preferredstyle of uialertcontrollerstylealert . should var alert = uialertcontroller(title: "title", message: "message", preferredstyle: uialertcontrollerstyle.alert) alert.addaction(uialertaction(title: "ok", style: uialertactionstyle.default, handler: nil)) self.presentviewcontroller(alert, animated: true, completion: nil)

Android Getting Facebook friend list with SDK 3.0 -

i'm trying day facebook friend list using facebook sdk 3.0 don't want use friendpickerfragment, since don't want display picker, want create own list of friends (displaying name , image). according post facebook friends list returns empty possible if friend approves app, when tried wife's account , mine, i'm still not able friend list. any highly appreciated, i've spend time on , reach dead lock. thanks! precondition: 1. create app on facebook. 2. add hash code of android app facebook app. android app: permission (on fb account created fb app) authbutton.setreadpermissions(arrays.aslist("basic_info, user_friends")); authbutton com.facebook.widget.loginbutton (you can refer sample apps find out how login button works) method friend list: request r = new request(session, "/me/friends", null,httpmethod.get, new request.callback() { @override public void oncomple

c - Understanding input/output operands in GCC inline assembly syntax -

as part of writing os, implementing interrupt handling , i/o functions inb , outb . i had learn writing inline assembly in gcc , read lot online. based on understanding, wrote own code. meanwhile, looked linux's implementation of functions /usr/include/sys/io.h . outb : static __inline void outb (unsigned char __value, unsigned short int __port) { __asm__ __volatile__ ("outb %b0,%w1": :"a" (__value), "nd" (__port)); } here questions: the gcc manual says "n" unsigned 8-bit integer constant (for in , out instructions). but here __port unsigned short int believe 16 bits. how decided portion of 16 bits used in inline assembly ? this understanding of how works - value of __port used directly (because of "n") constant in place of %w1. value of __value copied eax . %bo replaced %al. instruction executed. correct ? how decided of "n" or "d" use second operand ? there preference order ? w

python - What happens in `list.__getslice__` and `list__setslice__` when slicing? -

i'm trying subclass list builtin, new list acting strangely , believe __setslice__ & __getslice__ blame. changes make list aren't invasive , behind-the-scenes; user, should behave regular list . the problem comes when user wants clear list. executed following test (at repl.it ) , got strange result: class ihatecoding(list): def __getslice__(self, *args): print 'get', args return super(ihatecoding, self).__getslice__(*args) def __setslice__(self, *args): print 'set', args super(ihatecoding, self).__setslice__(*args) >>> l = ihatecoding() >>> l.extend(xrange(5)) >>> l[:] = [] set (0, 2147483647, []) where 2147483647 value come from, , why return view? edit: there's 1 more strange output i've discovered. can explain this? >>> l[:-1] (0, 2) #expected `-1` that value of sys.maxint , "largest possible integer": >>> sys.maxint 21

python - Django dev environment to mimic production? -

i'm writing django app deployed iaas, amazon. i'd develop in environment that's both a) sandboxed local machine , b) similar target system possible -- kind of foreman heroku apps. i'm using virtualenv great, i'd start/stop postgres server, handle environment variables, manage helper processes celery if need them down line. i've looked docker impression it's not quite there yet. there other more tried , true options out there? i've come across vagrant, chef, , supervisor can't sense of what. tips appreciated.

ios - Wait until method run successfully -

i make sure [mapview addannotation: annotation1] has been run , call delegates , run rest of code. -(void) addannotations:(double)latit :(double)longit :(nsstring*)value{ annotation *annotation1=[[annotation alloc]init]; annotation1.coordinate = cllocationcoordinate2dmake(latit,longit); annotation1.title=[nsstring stringwithformat:@"%@", secondidarray]; [mapview addannotation:annotation1]; if([annotationarray count]==0) { annotationarray=[[nsmutablearray alloc]initwithobjects:annotation1,nil]; valuearray=[[nsmutablearray alloc]initwithobjects:secondidarray,nil]; } else{ [annotationarray addobject:annotation1]; [valuearray addobject:secondidarray]; } for(int i=0;i<[annotationarray count];i++) { annotation *a = ((annotation*)[annotationarray objectatindex:i]); mkannotationview *av1=[mapview viewforannotation:((annotation*)[annotationarray objectatindex:i])]; pi

python - using subprocess.call with mysqldump -

i have been scripting windows many years , have started @ python alternative in last few weeks. i'm trying write native python script backup mysql database mysqldump. command line piping output > without issue. i see many answers subprocess.popen , shell=true, equally see many statements should avoid shell=true so i'm trying following code redirect stdout file, without success sys.stdout=open("mysqldump.txt",'w') print("testing line1") subprocess.check_output(["mysqldump", "-u", "usernmae", "-ppassword", "-h", "dbserver_name", database_name]) if comment out sys.sdout line see sqldump outputting screen know have syntax correct part. added print statement , can see gets written file mysqldump.txt. when run in full there no dump screen or file any ideas? i'm trying avoid using shell solution what tried doesn't work because modifying sys.stdout affects pyt

c# - Winform Return Result -

i check if actions have done winform , done successfully. mainform form = new mainform(); form.show(); //continue in case form returns true how can return , check value after winform closed? you have use dialogresult that: mainform form = new mainform(); dialogresult result = form.showdialog(); if (result == dialogresult.ok) { } else { } you have set dialogresult of form, example using button click event handler: private void button1_click(object sender, eventargs e) { this.dialogresult = dialogresult.ok; }

pygtk - No module named xml.etree.ElementTree in GTK, python -

i'm working python 2.7.6, windows 8.1, in pycharm 3.1.3. trying run worked , error: file "c:\something\sources\paramswin.py", line 6, in import gtk importerror: no module named gtk tried download gtk through project settings, , got: importerror: no module named xml.etree.elementtree tried import element tree package , got same error. i've been googling quite bit , there seems problem python , element. anyone, ideas? tia you tried download gtk? i've had problems in past (and xml.etree... thing familiar) when installed gtk on own . best way of installing gtk in windows platform, in humble opinion, use 1 of the all-in-one downloaders here: http://ftp.acc.umu.se/pub/gnome/binaries/win32/pygtk/2.24/ . cheers, simon

Android/Java EditableTextView Line Count -

i trying teach myself android java programming , have started attempting create simple text editor. i wanted have line count down left hand side standard ides, , couldn't find anywhere on stackexchange or internet on definitive "best practice" way this. so created own logic based on read, wanted check best , efficient way -- , if happens out looking same thing. // start oncreate // @medittext = main autocompletetextview // @mlinecount = line count textview medittext.addtextchangedlistener(new textwatcher() { // set current line variable private int currentline; // text watcher public void beforetextchanged(charsequence s, int start, int count, int after) { // before new text inserted, current line count currentline = medittext.getlinecount(); } public void ontextchanged(charsequence s, int start, int before, int count) { // nothing } @override public void aftertextchanged(editable e) { // update line count // @meditt

utf 8 - How can I get the Unicode codepoint represented by an integer in Swift? -

so know how convert string utf8 format for character in strings.utf8 { // example converted 65 var utf8value = character } i read guide can't find how convert unicode code point represented integer string. example: converting 65 a. tried use "\u"+utf8value still failed. is there way this? if @ enum definition character can see following initializer: init(_ scalar: unicodescalar) if @ struct unicodescalar, see initializer: init(_ v: uint32) we can put them together, , whole character character(unicodescalar(65)) and if want in string, it's initializer away... 1> string(character(unicodescalar(65))) $r1: string = "a" or (although can't figure out why 1 works) can do string(unicodescalar(65))

c# - How to configure route in MVC to pagination list -

i have controller: public class restaurantcontroller : controller { public actionresult index(string name, int page = 0) { int pagesize = 4; @viewbag.dropcitys = _db.restaurantes.select(c => c.name).distinct(); var model = res in _db.restaurantes orderby res.name descending ( (!string.isnullorempty(name)? res.name.contains(name) : res.name!="") ) select res; return view(model.skip(pagesize * page).take(pagesize).tolist()); } this route: routes.maproute( "restaurant", "{controller}/{action}/{page}", new { controller = "restaurant", action = "index", page= urlparameter.optional }, namespaces: new string[] { "mvcintro.controllers" } //usa-se isso para funcionar area );} i try access page mysite.com/restaurant/1 or mysite.com/restaurant/2

Regex (with lookaround) optimization -

i trying pull out entities text, , have simple mechanism (until deploy nlp solution) avoid negation. e.g: i'd find patient has history of cynicisimitis but avoid no history of cynicisimitis and avoid family history of cynicisimitis to end using multiple lookbehinds make regex this: ((?<!(?i)no.{1,25}|denies.{1,35}|family.{1,35}|father.{1,10}|mother.{1,10})(?-i)${stringtomatch}) i tried adding \b negative lookbehind, thinking reduce entry points processor have, made performance worse. problem - appears performing badly. what can do: using \b avoid false matches (in particular word "no") removing useless (?-i) (an inline modifier applies group is.) factorizing when possible reduce performance impact of .{m,n} you obtain: (?<!(?i)\b(?:no\b.{1,25}|(?:denies|family)\b.{1,35}|(?:fa|mo)ther\b.{1,10})\b)history of cynicisimitis\b what can try: using lazy quantifiers instead of greedy quantifiers: \bno\b.{1,25}? p

objective c - For every 100 in int add 1 -

this super simple maths can't working. trying add 1 int every 100 stored in dynamic int. for example if myint = 350 intnumber = 3 . or myint = 570 intnumber = 5 to clarify don't want remainder hence why don't want x/100 i know similar obvious not: for (int = 0; < 100; i++) { } this trivial: int myint = 350; int intnumber = myint / 100; // 3

java - HSSFWorkbook object is not retaining the sheets added to it through different methods -

` class { private hssfworkbook workbook; public a() { workbook = new hssfworkbook(); } public void method1() { workbook.createsheet("sheet1"); system.out.println(" no of sheets: " + workbook.getnumberofsheets()); method2(); } public void method2() { system.out.println(" no of sheets: " + workbook.getnumberofsheets()); } } in above code m creating workbook object in constructor... , creating "sheet1" in method1 , printing no of sheets: 1 in method1 in method2 no of sheets: 0... why same workbook object behaves differently in different methods.. pls 1 me... i created times ago class myworkbook able add new sheet s , shorten following code show 2 methods add first , other sheet s import org.apache.poi.hssf.usermodel.hssfworkbook; public class myworkbook { private final hssfworkbook workbook; public myworkbook() { this.workbook = new hssfwork

datetime - Decoding date from integer in PHP -

in php, i'm saving date record string in order make conditions "more than", "less than"; know how decode it. want this: the moment record being saved 2014, 08/06 1:30 in 24-hours format, integer should 201408060130 , of course use date() function. but when comes decoding show 2014, 08/06 1:30 or format 08/06 2014, 1:30 stuck thinking on solution this. i thought like: $date = date('ydmhm'); //saving 201408060130 $this->savetodatabase($save, $mytable); $datedecoded = $this->getfromdatabase($mytable, $id, $thedateinteger); $result = date::getformat($datedecoded, 'ydmhm'); //decode date format echo $result->date('y d/m, h:m'); //show 2014 08/06, 1:30 this simple & works. use strtotime : $test_value = '201408060130'; echo date('y d/m, h:i', strtotime($test_value)); the output is: 2014 06/08, 01:30

ruby on rails - CarrierWave/Cloudinary cached images not working across form redisplays in dev environment -

when form has error cached image isn't displayed. trying go cloudinary servers , download image doesn't exist. here source ends as: <div class="form-group"> <label class="col-sm-3 control-label" for="guide_image">image</label> <div class="col-sm-9"> <img alt="ho97jzyhfjludw129u8m" src="http://res.cloudinary.com/memorycommit/image/upload/ho97jzyhfjludw129u8m.jpg" /> <input class="form-control" id="guide_image" name="guide[image]" type="file" /> <input id="guide_image_cache" name="guide[image_cache]" type="hidden" value="1402249607-3970-6368/mountain-top-med.jpg" /> </div> </div> here view code image: <div class="form-group"> <%= f.label :image, class: "col

asp.net - BreezeJS throwing error in Windows Azure -

i'm using breezejs on durandal spa framework application entityframework + asp.net webapi. have hosted application in azure cloud hosting. error: nullreference exception on performing data fetch using breeze. happens , not every time. , not limited 1 single breeze query. i thought connection drop , tried sqlazureexecution strategy - retry logic - still error occasionally. let me know should next

c++ - Does Re2 use string size or null termination? -

the title pretty it. if standard c++ string utf-8 characters has no 0 bytes scanning terminate @ end of string defined it's size? conversely, if string has 0 byte scanning stop @ byte, or continue full length of string? i've @ re2.h file , not seem address issue. a std::string containing utf-8 characters can´t have 0-bytes part of text (only termination), because utf-8 doesn´t allow 0´s anywhere. and given you´re using c++11-compliant, terminating 0 guaranteed (doesn´t matter if use data() or c_str() . , data original data, so...). see http://en.cppreference.com/w/cpp/string/basic_string/data or standard (21.4.7.1/1 etc.). => processing of string stop @ 0

javascript - Access DOM element inside $.getJSON -

i'm developing application iterates on dom elements, , performs ajax request each 1 of elements. problem cannot access each dom element inside callback function. $('.class').each(function() { $.getjson(url, function(data) { $(this).attr('id', data.id); // $(this) not accessible }); }); is there way solve this? you should use variable, value of this changes each function call, , inside callback $.getjson this no longer element. $('.class').each(function() { var self = this; $.getjson(url, function(data) { self.id = data.id; }); }); another option built in arguments in each() $('.class').each(function(index, element) { $.getjson(url, function(data) { element.id = data.id; }); });

c++ - same address for different variables of different functions in c -

while printing address , value of 'x' in function foo1 , address , value of y in foo2, why showing same values both of functions? #include <stdio.h void foo1(int xval) { int x; x = xval; /* print address , value of x here */ } void foo2(int dummy) { int y; /* print address , value of y here */ } int main() { foo1(7); foo2(11); return 0; } output of program is address of x is: 65518 value of x is: 7 address of y is: 65518 value of y is: 7 it's because they're created on stack, unwound after each function call. are created @ same memory address.

c++ - Array bug crashing the console -

i have no idea wrong here. problem array accessing last element contains terminating code. when use i <= sizeof(arr) limiter in for loop, 4 element list works, 3 element list crashes. if replace i < sizeof(arr) , 3 element list works last element in 4 element list ignored. int arraylist(string arr[]) { int choice; (unsigned int = 1; <= sizeof(arr); i++) { cout << << ". " << arr[i-1] << endl; } cout << "select number 1 " << sizeof(arr)-1 << ": "; cin >> choice; return choice; } here function calls array list, crashes when fourth element accessed. void titlescreen() { system("cls"); int choice = 0; { string arr[] = { "new game", "continue", "exit" }; choice = arraylist(arr); switch (choice) { case 1: newgame(); break; case 2:

javascript - Loading an Array from Java Script into Web page -

i have included fiddle here: jsfiddle.net/lge3n i have series of arrays in javascript file need import web page. seem able work arrays in script , have been able output totals of numbers page, however, not seem able figure out how print entire list web page. window.onload = function () { $("#contributions").html (totalcontributions.tofixed(2)); $("#amount").html (totalcontributors); var datestring = ""; (var j = 0; j < date.length; j++) { datestring += date[j]; $("#datearray").html (datestring); } } . <div id="data_list"> <table rules="rows" cellspacing='0'> <thead> <tr> <th>date</th> <th>amount</th> <th>first name</th> <th>last name</th> <th>address</th> </tr>

xslt - How to get XML element based on given value -

i want retrieve xml element node based on given string value. element node can described @ levels in nested xml, there no specific structure xml has. how in xslt transformation? i use key: <xsl:key name="k1" match="*[not(*)]" use="."/> then can use e.g. <xsl:param name="string-value" select="'foo'"/> and <xsl:variable name="elements" select="key('k1', $string-value)"/> if there can several elements same contents , interested in first use <xsl:variable name="element" select="key('k1', $string-value)[1]"/> that assumes want find elements no child elements string value matches variable, other approaches matching on name of element of course possible: <xsl:key name="k1" match="*" use="local-name()"/> .

ubuntu - get the user of the computer with php -

i'm trying name of user access webserver. know how name of computer connected server: $hostname = gethostbyaddr($_server['remote_addr']); and i'm looking way user opened session in computer. there way this? in 1 word: no. you cannot reach remote computers , pull out kind of information want. thank god. unless username voluntarily advertised remote computer part of protocol or another, cannot it. , username not typically disclosed part of regular http protocol traffic.

html5 - Text drawn in HTML canvas has edges -

Image
i draw text "hello world" inside text couple of times inside 'canvas' in html5. outmost text red, next yellow, inside green text, , inner text blue. what can sharp edges see on letter w? how can make text render smoothly? <canvas id="can" width="1200" height="500" dir="ltr"> <script> var can = document.getelementbyid("can"); var context = can.getcontext("2d"); context.font = "200px arial"; context.linewidth = 40; context.strokestyle = "red"; context.stroketext("hello world", 25, 200); context.linewidth = 30; context.strokestyle = "yellow"; context.stroketext("hello world", 25, 200); context.linewidth = 10;

ios8 - Slide Sidebar Menu IOS 8 Swift -

is there way implement slide sidebar menu (like facebook app) in ios swift without third party library? solutions founded feature implemented in objective-c. i believe can start form uisplitviewcontroller drastically updated in ios8. watch sessions view controller advancements in ios8 , building adaptive apps uikit details. provide code example second session (but not form first 1 :/). @ point feels natural me make kind of ui based on split view controller in ios8. update: looks not api talking landed yet. in current beta4 mentioned in video condensesbarsonswipe not presented, example.

antlr4 - how to transform recursive expressions? -

in anltr4 java grammar( https://github.com/antlr/grammars-v4/blob/master/java/java.g4 ) know when have complete expression. in example trying make transformation similar following: from: string foo = bar + ", " + baz + "; true"; to: string foo = string.format("{0}, {1}; true", bar, baz); the trouble begins in declaration grammar: expression ('+'|'-') expression" which child of expression well. given example above, callbacks following: 0: exp0:bar, exp1:"," 1: exp0:bar ",", exp1:baz 2: exp0:bar "," baz, exp1:"; true" i targeting line using #alias btw. awkwardly saying - how use listener able grab entire expression when rule expressed recursively in order transform entire expression? or there way haven't seen yet?

php - Delete Database records for visitor session save in database -

may common question, need explanation more solve it. i have database creates new records every visitor session. @ same time, when records being created, put ip address, , time well. problem : when visitor leave or close browser , visit again, brought new record , previous record still there in database. need delete manually every time save storage. php create records : public function savevisitordata() { $ses_id = session_id(); $ip = $_server['remote_addr']; $timer = date("y-m-d h:i:s"); $query = $this->db->prepare("insert `visitors`(`session`, `ipaddress`, `timer`) values (?,?,?)"); $query->bindvalue(1, $ses_id); $query->bindvalue(2, $ip); $query->bindvalue(3, $timer); try { $query->execute(); } catch(pdoexception $e){ die($e->getmessage()); } } how deal $_cookie? just use mysql delete query , delete records time older day? mysqli_query($con,"del

c# - Javascript redirect works in chrome but not IE -

the below javascript script registry works in chrome without issue. when used ie url missing / . for example, chrome correctly land on //sever-name/submit.aspx in ie land on //sever-namesubmit.aspx does have suggestions fixing issue scriptmanager.registerstartupscript(this, this.gettype(), "redirect", "alert('your request submitted successfully. redirected confirmation page.'); window.location='" + request.applicationpath + "submit.aspx';", true); shouldn't be: window.location='" + "/" + request.applicationpath + "/" + "submit.aspx';", true); also, in javascript, "/" used escape character. may have escape escape charecter well: var link = "site.com//mypage.aspx"

android - How can I achieve this ListView animation? -

Image
what's guys, need little one. i'm trying achieve simple(but not really) folding animation on listview being scrolled. basically, i'm attempting fold listview's first visible child backward if sheet of paper being folded downward along x axis. goes on on continuously user scrolls , down list. first time playing around matrix animations , android's camera graphics api, i'm off mark here. this effect i'm trying achieve and effect i'm getting. i want animation begin @ origin(0,0) both left , right side, animating top of list item instead of upper left corner. i'm not familiar matrix translations or animations if more experience these techniques myself can shed knowledge, it'll appreciated. basically i'm overriding ondrawchild method of listview, grabbing child's bitmap drawing cache, , using matrix perform animation. lighting , camera implementation code took sample app in order animation 3d possible. i tried playing around l

html - css inheritance in iframes -

i'm aware iframe can't inherit css styles of "main" webpage, if confused. have main page background plain black, white text. iframe doesn't have background colour specified , yet black, same main page. however, other css properties in main page have defined separately iframe if want them used. why this? if not set background of html document (by setting on html element or body element), browser default used, , can expected initial value, transparent . this means page embedded in page iframe element, can expect background of embedding page shine through.

logistic regression - R glm object and prediction using offsets -

so i'm using r logistic regression, i'm using offsets. mylogit <- glm(y ~ x1 + offset(0.2*x2) + offset(0.4*x3), data = test, family = "binomial") the output, shows single coefficient, intercept , 1 of predictors, x1. coefficients: (intercept) x1 0.5250748 0.0157259 my question: how raw prediction each observation model? more specifically, if use predict function, include features , coefficients, though model coefficients listed containing intercept , x1? prob = predict(mylogit,test,type=c("response")) do have use predict function? "mylogit" object contain can compute directly from? (yes looked @ documentation on glm, still confused). thank patients. i can report results of experiments glm , offset() . not appear (at least experiment) call predict give results take offset account. rather seems summary.glm needed purpose. started rather mangled modification of 1st example in

php - Woocommerce: add free product if cart has 3 items -

what i'm trying add free product if user have 3 product in cart. choosed woocommerce_add_cart_item hook this. here code : add_filter('woocommerce_add_cart_item', 'set_item_as_free', 99, 1); function set_item_as_free($cart_item) { global $woocommerce; $products_with_price = 0; foreach ( $woocommerce->cart->get_cart() $cart_item_key => $values ) { if($values['data']->price == 0) { continue; } else { $products_with_price++; } } if( $products_with_price > 1 && $products_with_price % 3 == 1) { $cart_item['data']->set_price(0); return $cart_item; } return $cart_item; } i tried $cart_item['data']->price = 0; doesn't work out either :( there wrong or maybe there other way done? thanks. try modified code: (have changed condition.) add_filter('woocommerce_add_cart_item', 'set_item_as_free

php - htaccess Redirect to another subfolder if URL contains blog in it -

i have sub folder named "blog" inside public_html. if url contains blog in either "blog.mydomain.com" or mydomain.com/blog, want redirect mydomain.com/blog/index.php. the problem using silversrtipe 3.x , have page created name "blog" whenever try mydomain.com/blog instead of redirecting mydomain.com/blog/index.php opens silverstripe page. how can redirect mydomain.com/blog "mydomain.com/blog/index.php"? any appreciated. thanks you can place rule first rule: rewritecond %{http_host} ^blog\. [or] rewritecond %{request_uri} ^/blog [nc] rewriterule ^ /blog/index.php [l]

c++ - How to inherit a member function so that it always returns a reference to the derived instance? -

i'm working on iterator family, iterator classes x have x& operator++() {++x; return *this} in common, seems idea place in common base class. unfortunately, return type changes, since should return reference derived class. the following illustrates problem. f() work, workarounds come g() , h() , not satisfactory: struct { a& f() {return *this;} template <typename t> t& g() {return *(t*)this;} template <typename t> t& h(t& unused) {return *(t*)this;} }; struct b : { int x; b(int x) : x(x) {} }; int main() { b b(12); //b b1 = b.f(); // error: conversion 'a' non-scalar type 'b' requested b b2 = b.g<b>(); // works b b3 = b.h(b); // works } is there way make b b1 = b.f(); work? maybe using c++11 features? use crtp : template<class derived> struct { derived& f() {return static_cast<derived&>(*this);} }; struct b : a<b> {

Java- how to temporarily store data in array-list -

i want cache arrlist values available in class, define empty arrlist instially , adding values on method , trying global defined arralist values.... class test{ arraylist list=new arraylist(); public void addvalues(){ list.add("one"); list.add("two"); list.add("three"); list.add("four"); list.add("five"); getarrlstvalues(); } public void getarrlstvalues(){ system.out.println("size of cache arralist=" +list.size()); //why showing 0 size } public static void main(string args[]) { test obj=new test(); obj.addvalues(); } } in code add values this.list , check obj.getarrlstvalues() , when this != obj . so never update same list at! you can use this.getarrlstvalues() (or getarrlstvalues() ) , remove line: test obj=new test()

ios - Set a UIView width twice another view using autolayout -

in screen have 2 view horizontally near each other. want width of first view twice of width of second view. i man example, if right view has width=200 second 1 show with=100 . as search , in auto-layout, has options alignments , spaces between views. has option defining such relationships too? you can programmatically adding manual constraints work autolayout. i'm sure using interfacebuilder option. uiview *firstview; uiview *secondview; [firstview addconstraint:[nslayoutconstraint constraintwithitem:secondview attribute:nslayoutattributewidth relatedby:nslayoutrelationequal toitem:firstview attribute:nslayoutattributewidth multiplier:2.0

html - How select an attribute inside list using css selector and Selenium -

i'm trying use css selector element inside <li> selenium that's have: <div id= "popup"> <ul> <li> <div id="item" option= "1" ....> </div> </li> <li> <div id="item" option= "2" ....> </div> </li> </ul> </div> i need second div, option=2. tried: webdriver.findelement(by.cssselector("#popup > ul li:nth-child(n) [option=2]"); that works fine in console of chrome not selenium :/ what's wrong this? two issues: :nth-child(n) means " any value of n" result in every child being matched. mean use :nth-child(2) if want make sure element under second li . or if doesn't matter li appears in, can rid of :nth-child() selector entirely. the value in attribute selector must quoted if begins digit, [option='2'] . the correct selector, therefore, is: web

c# - xpath query to select element where attribute not present -

what should xpath query select element attribute att not present. <root> <elem att='the value' /> <elem att='the value' /> <elem att='the value' /> **<elem />** <elem att='the value' /> <elem att='the value' /> </root> i want update element attribute att not present. thanks you can use [@att] test presence of attribute, need: //elem[not(@att)] ... test absence of it. ( tested using xpathtester )

java - Using org.apache in Matlab -

i trying use org.apache matlab doing this: javaaddpath('~/.m2/repository/org/apache/commons/commons-math3/3.2/commons-math3-3.2.jar'); import org.apache.commons.math3.stat.correlation.* c = org.apache.commons.math3.stat.correlation.kendallscorrelation(); i following error: undefined variable "org" or class "org.apache.commons.math3.stat.correlation.kendallscorrelation" how fix it? kendallscorrelation class present in math version 3.3 , trying use version 3.2. following code works: javaaddpath('~/matlab/jars/commons-math3-3.3/commons-math3-3.3.jar'); import org.apache.commons.math3.stat.correlation.* c = org.apache.commons.math3.stat.correlation.kendallscorrelation(); c.correlation([4 2 0], [3 2 1])

ios - Possible to "Save Draft" Programmatically in MFMailCompseViewController -

i know documentation mfmailcomposeviewcontroller says cannot send programmatically, same true "save draft"? have situation need dismiss mail composer programmatically, , great if save users email draft instead of losing it. tried looking in apple docs , not believe there methods call accomplish in mfmailcomposeviewcontroller . post question here before determine not possible.

excel - Get the nth word or the last word if apporopriate -

i using great little piece of code pull names out of 1 cell , separate them separate cells. number of names varies , such need automate as possible. i using following macro: function get_word(text_string string, nth_word) string dim lwordcount long application.worksheetfunction lwordcount = len(text_string) - len(.substitute(text_string, " ", "")) + 1 if isnumeric(nth_word) nth_word = nth_word - 1 get_word = mid(mid(mid(.substitute(text_string, " ", "^", nth_word), 1, 256), _ .find("^", .substitute(text_string, " ", "^", nth_word)), 256), 2, _ .find(" ", mid(mid(.substitute(text_string, " ", "^", nth_word), 1, 256), _ .find("^", .substitute(text_string, " ", "^", nth_word)), 256)) - 2) elseif nth_word = "first" get_word = l

bash - Way to change xargs arguments to include a flag per argument? -

i have passing experience xargs, don't quite know how this: i have list of archives retrieved tarsnap using tarsnap --list-archives i want delete archives day (there 24 made each day) i can use xargs accomplish this: tarsnap --list-archives | grep 2014-06-09 | xargs -n 1 tarsnap -df however runs tarsnap on , on again 1 argument @ time (which expected): tarsnap -df 2014-06-09-00 tarsnap -df 2014-06-09-01 tarsnap -df 2014-06-09-02 ... etc ... the tarsnap documentation states can delete multiple archives passing in multiple -f flags: tarsnap -d -f 2014-06-09-00 -f 2014-06-09-01 -f 2014-06-09-02 # ... , on is there way accomplish xargs? (aside: might pointless this, since have feeling running tarsnap multiple -f flags causes tarsnap run multiple times, 1 argument @ time... wrong) using idea quite similar @choroba's, can rid of grep altogether , use sed instead: tarsnap --list-archives | sed -n '/2014-06-09/s/^/-f /p' | xargs tarsnap -

excel vba - RUN VBS SAP from VBA Object required error -

i'm trying write macro start vbs sap script , possible change of variables of vbs code. great! below object required error public sub simplesapexport() set sapguiauto = getobject("sapgui") 'get sap gui scripting object set sapapp = sapguiauto.getscriptingengine 'get running sap gui set sapcon = sapapp.children(0) 'get first system connected set session = connection.children(0) 'get first session (window) on connection ' start transaction view table session.starttransaction "se16" end sub try code: set sapguiauto = getobject("sapgui") 'get sap gui scripting object set sapapp = sapguiauto.getscriptingengine 'get running sap gui set sapcon = sapapp.children(0) 'get first system connected set session = sapcon.children(0) 'get first session (window) on connection you getting error message because missing object sapcon in istead of connection, chance object , execute code, facing same issue , solved

r - passing correct environment to nested function -

in code, use function simple thing: takes records selected given condition , adds give text "errors" column: dterr <- function (dtin, condition, errtext) { if (!is.element('errors', names(dtin))) {dtin[,errors:=""];} dtin[eval(substitute(condition)), errors:={paste0(errors, errtext)}]; invisible(dtin); } (i thankful people helped previous question eval(substitute) ) so, in simple cases function works expected: dt1 <- fread( "id,cola,colb id1,3,xxx id2,0,zzz id3,na,yyy id4,0,aaa ") mynum=0 dterr(dt1, cola>mynum, "positive"); dt1 # id cola colb errors # 1: id1 3 xxx positive # 2: id2 0 zzz # 3: id3 na yyy # 4: id4 0 aaa but when try call function, in combination variable defined inside, error: myfun <- function(){ mynum2=1; dterr(dt1, cola>mynum2, "big!"); } myfun() # error in eval(expr, envir, enclos) : object 'my

javascript - Excluding characters in group (regular expressions) -

i have issue regular expressions in javascript (i'm not pro in regular expressions matters). for reasons don't explain, have match text in way , cannot change code deals result. for example, want match text: mon.2014/01/01 in way obtain result: ["mon.", "20140101"] , regex , no post processing. i tried lookaheads, excluding groups, noticed there not lookbehinds , lookarounds , didn't manage solve it. edit: put code sample easier understand i'm doing. function match(regexes, text) { for(var in regexes) { var match = text.match(regexes[i]); if(match !== null) { return match; } } } // expected result of match(regexes, "mon.2014/01/01"): ["mon.","20140101"] how told you, cannot change code, has done solely regex. have hint? thank much! short answer: you can't. if code uses string.match method, returns parts of strings matched regexp. can't e

zend framework2 - How do i set my composer.json on github to allow inclusion as a library? -

all of documentation , tutorials , forums i've looked @ setting client composer.json downloading other people's packages, i'm trying set own packages, zf2 modules, can include them in multiple projects. hello-world attempt. have shiny-rest repository depends on shiny-lib repository, , want specify dependency numeric(al?) version numbers. shiny-rest's composer.json: { "name": "shinymayhem/shiny-rest", "description": "rest json, xml , api-problem style errors", "license": "apache 2.0", "authors": [ { "name": "reese wilson", "email": "email" } ], "extra": { "branch-alias": { "dev-master": "0.0.x-dev" } }, "require": { "shinymayhem/shiny-lib": "0.0.*", "zendframework/zendf

.htaccess - RewriteCond blank domain to the domain with the correct path -

how set redirects following conditions: url http://domainname.be becomes http://www.domainname.be/nl/ url http://www.domainname.be becomes http://www.domainname.be/nl/ url http://domainname.be/nl/custompage/ becomes http://www.domainname.be/nl/custompage/ ? rewrite conditions rewritecond %{http_host} ^domainname.be [nc] redirectrule ^(.*)$ http://www.domainname.be$1 [r=301,l] rewritecond %{http_host} ^domainname.be [nc] rewritecond %{request_uri} ^/$ redirectrule ^(.*)$ http://www.domainname.be/nl$1 [r=301,l] rewritecond %{http_host} ^www.domainname.be [nc] rewritecond %{request_uri} ^/$ redirectrule ^(.*)$ http://www.domainname.be/nl$1 [r=301,l] rewritecond %{request_filename} !-f rewritecond %{request_filename} !-d rewriterule ^/nl/custompage /custompage.aspx?lang=nl [l,nc] rewritecond %{request_filename} !-f rewritecond %{request_filename} !-d rewriterule ^/nl/custompage/ /custompage.aspx?lang=nl [l,nc] but doesn't work. also, need clear browsercache in

php - NLP creating a model out of POS tags -

i trying create knowledgebase based on text mining. using genia corpus tag words parts of speech. given 2 terms text, how create model finds out relation? eg text: hif1a gene involved in hypoxic regulation. hypoxia regulates brca1 gene expression associated in breast cancer. i have pos tagged out. word base form part-of-speech hif1a hif1a nn gene gene nn vbz involved involve vbn in in in hypoxic hypoxic jj regulation regulation nn . . . hypoxia hypoxia nn rb regulates regulate vbz brca1 brca1 nn gene gene nn wdt vbz rb associated associate vbn in in in breast breast nn cancer cancer nn i writing web interface when queried brca1 , hypoxia should tell there positive regulation between them. when queried hif1a

mysql - Php PDO connection to database -

i have database 2 table. students , profesors. create 1 more login table , there email , passwords students , profesors. want create student try login send him on student.php , when profesor try login send him on profesor.php i try code, return me 1. not options.. if(isset($_post['submit'])){ $sql= "select count (*) `students` , 'profesors' `username` = :username , `password` = :password "; $result = $connection->prepare($sql); $result->bindparam(":username" ,$_post['username']); $result->bindparam(":password" ,$_post['password']); $result->execute(); $num=$result->rowcount(); if($num > 0){ header("location:index.php"); }else{ header("location:login.php"); } i need idea, how change datebase or login code. i not let professors , student use same login. answer question change query following: select user_type `login_table` `username` = :username , `password`

vba - Object variable not set error? -

i'm c++/c# programmer , unfamiliar vba, i'm not problem code. it's throwing following error: "run-time error '91': object variable or block variable not set." that error being thrown on line in loop. right side of statement seems throwing error. problem line, , how go fixing it? here's code snippet: option explicit private gemployees() employee const glastnamestartingcell = "a4" const gnamescountcell = "a1" const gnamestab = "namestab" function buildemployeenamearray() ' declare variables dim inamecount integer dim wksactive object ' counter dim integer ' select sheet names set wksactive = sheets(gnamestab) ' number of names on sheet inamecount = wksactive.range(gnamescountcell) ' resize array appropriate redim gemployees(0 inamecount - 1) ' fill out employee list = 0 inamecount - 1 gemployees(i).mlastname = wks

user interface - iOS: UITableView in popover and seeing "double vision" effect -

i'm working on ipad app , @ points, need show popover options user pick from. this, use uitableview in uipopovercontroller. problem that, on ipad (not on simulator), when scrolling tableview, sort of "double vision" effect, appears 2 sets of of list exist. 1 stationary, , 1 scrolls , down. i construct popover this: self.fclasstypelist = [[nsmutablearray alloc] init]; [self.fclasstypelist removeallobjects]; nsuinteger stringlength = 0; (populate self.fclasstypelist, , set stringlength size of longest entry) [self setcontentsizeforviewinpopover:cgsizemake(stringlength * 15.0f, [self.fclasstypelist count] * 30)]; cgfloat tableborderleft = 5; cgfloat tableborderright = 5; cgrect viewframe = self.view.frame; viewframe.size.width -= tableborderleft + tableborderright; // reduce width of table self.flistofitems = [[uitableview alloc] initwithframe:viewframe style:uitableviewstyleplain]; self.flistofitems.delegate = self; self.flistofitems.datasource = self; [self.v

Rails fields_for ordering -

i have form has nested fields - ie. user accepts_nested_attributes_for class. class has end_date datetime field. i'd order classes end_date in editing form. form has this: <%= f.fields_for :classes |builder| %> <%= render "class_fields", {:f => builder} %> <% end %> obviously, come out in order of created_at field. how can modify order them arbitrary field? if want classes sorted way, can add :order option association. if not, fields_for takes second argument that's record(s) display, can pass in list in whatever order want.

How to edit multi-person objects in R -

i find following behaviour of r person object rather unexpected: let's create multi-person object: a = c(person("huck", "finn"), person("tom", "sawyer")) imagine want update given name of 1 person in object: a[[1]]$given <- 'huckleberry' then if inspect our object, surprise have: > [1] " <> [] ()" "tom sawyer" where'd huckleberry finn go?! (note if try single person object, works fine.) why happen? how can above more logical behavior of correcting first name? the syntax want here a <- c(person("huck", "finn"), person("tom", "sawyer")) a[1]$given<-"huckleberry" #[1] "huckleberry finn" "tom sawyer" a group of people still "person" , has it's own special indexing function [.person , concat function c.person has perhaps different behavior expecting. problem [[ ]] messing un

What is value of OpenCart customer_id on oc_oder for guest account -

we using opencart. in case of guest checkout, value of customer_id on oc_order? assume zero? yeap right. you can find specified in catalog/controller/checkout/confirm.php elseif (isset($this->session->data['guest'])) { $data['customer_id'] = 0;

sql - cannot delete parent with children existing Laravel CRUD -

this error thrown when try delete categories entry products under parent category: illuminate \ database \ queryexception sqlstate[23000]: integrity constraint violation: 1451 cannot delete or update parent row: foreign key constraint fails (`store`.`products`, constraint `products_category_id_foreign` foreign key (`category_id`) references `categories` (`id`)) (sql: delete `categories` `id` = 1) after did research know cannot delete parent existing children i not sure how join products category id when delete category id. way can delete products associated category id. here function deleting: public function postdestroy() { $category = category::find(input::get('id')); if ($category) { $category->delete(); return redirect::to('admin/categories/index') ->with('message', 'category deleted'); } return redirect::to('admin/categories/index') ->with('message