Posts

Showing posts from July, 2012

Ruby on Rails assets/images are accessible to users not logged in -

when load image link url loads images if person not logged in. for example, this link takes me login: website.net this link takes me image file (without logging in) website.net/assets/idaho/idaho_ellen_mitchell_sig.png i don't want image file load if user isn't logged in. i'm new ror , unsure start problem. is sessions issue? security issue? my gut tells me i'll need use nginx make work. any appreciated! your problem is, placed images in assets folder, public. can solve problem paperclip gem. the documentation great , surely find way around it.

python - (Pycharm mac os x) can't flush to file -

i want write file in real time(instead of waiting code finish) flushing, doesn't seem change anything. here's code: datafile =open("json",'a+') def write(data): datafile.write(data) datafile.flush() also datafile.close() didn't change anything. know problem is? edit: managed make work adding os.fsync(datafile.fileno()) right after datafile.flush() you must use standard python library json https://docs.python.org/3.3/library/json.html i think use of open file inside function global name not correct.

javascript getElementById gives error in chrome but works fine in IE -

here javascript function : function deletealert(tabstate){ var form = window.document.alertsform; var numofelements = form.elements.length; var okdelete = "false"; (i=0; < numofelements; i++) { if(form.elements[i].checked) { okdelete = "true"; break; }else{ okdelete = "false"; } } if(okdelete == "true") { //changpage("screen1b.html"); prototype form.action="/cpi/producer/myalerts/alertsgateway?jadeaction=ma06&tab="+tabstate; form.document.getelementbyid('deletealertsbutton').disabled=true; form.submit(); }else{ alert("please select 1 or more items delete."); } } i 'm calling function in 2 jsps , code snippet same both (note same id values) <input type=button value="delete" id="deletealertsbutton" title="delete&q

ios - MPRemoteCommandCenter pause/play button not toggling? -

Image
i'm having issues getting play , pause buttons toggle in mpremotecommandcenter. whatever reason audio , events work correctly, command center doesn't change play button pause button. here's code... - (void)setupmpremotecommandcenter{ mpremotecommandcenter *commandcenter = [mpremotecommandcenter sharedcommandcenter]; mpremotecommand *play = [commandcenter playcommand]; [play setenabled:yes]; [play addtarget:self action:@selector(playaudio:)]; mpremotecommand *pause = [commandcenter pausecommand]; [pause setenabled:yes]; [pause addtarget:self action:@selector(playaudio:)]; [commandcenter.skipbackwardcommand setpreferredintervals:@[@30.0]]; mpremotecommand *skipbackwards = [commandcenter skipbackwardcommand]; [skipbackwards setenabled:yes]; [skipbackwards addtarget:self action:@selector(skipbackwardevent:)]; [commandcenter.skipforwardcommand setpreferredintervals:@[@30.0]]; mpremotecommand *skipforwards = [commandc

c# - how to remove a row from an 2-D Array -

i meet problem don't know how solve it. created 2-d array contains date , price.i want delete row datetime between 2 date.the example below, want delete third row. date price 01/07 10 02/07 20 empty 30 03/07 40 here code:(i dont know why work) for (int i=0;i<row.length;i++) { (int j=0;j<col.length;j++) { if (array[row,0]=" ") { array[row,j]=array[row+1,j]; i++ } } } if hell-bound on using arrays, can use linq query filter out results , return new array: var data = new[] { new { date = "01/07", price = 10 }, new { date = "02/07", price = 20 }, new { date = "", price = 30 }, new { date = "03/07", price = 40 } }; var noblanks = (from d in data !string.isnullorwhitespace(d.date) select d).toarray(); which select data not have e

batch file - How to extract all multi-volume RAR archives from subfolders of a folder? -

i search way unpack multi-volume archives after download via batch. i download folders .r?? files in on ftp monitoring program , want winrar goes in first subfolder in source folder , start unpacking .r00, delete archive , move folder unpacked files new location. then batch script should start process again next subfolder. let's source folder c:\users\unpack contains following subfolders files: source folder subfolder1 archive1.r00 archive1.r01 archive1.r02 xxx.txt subfolder2 archive2.r00 archive2.r01 yyy.txt subfolder3 archive3.r00 archive3.r01 archive3.r02 archive3.r04 archive3.r05 zzz.txt i had start script in link below, script can't want, have started new question. how unpack rar archives in subfolders of folder , delete archives? the script in link above unrars files in subfolders , moves folder files new location. want script unrars , moves subfolder subfolder in source folder. edit.1 if winrar ready first subfolder s

pyqt4 - Identical Python files, one runs, the other throws a "file not found" error -

i trying replicate/incorporate code found in this tutorial in own pycharm project. i have 2 files, tempconv.py , mainwindow.py , contain identical code. the former file resides in users/some_user/documents/coding/qt/firstgui . latter file in /users/some_user/documents/coding/python/cv-generator . file tempconv.ui , referenced in code, present in both folders. this code in files. files identical, mainwindow.py included in pycharm project while tempconv.py not. import sys pyqt4 import qtcore, qtgui, uic form_class = uic.loaduitype("tempconv.ui")[0] # load ui class mywindowclass(qtgui.qmainwindow, form_class): def __init__(self, parent=none): qtgui.qmainwindow.__init__(self, parent) self.setupui(self) self.btn_ctof.clicked.connect(self.btn_ctof_clicked) # bind event handlers self.btn_ftoc.clicked.connect(self.btn_ftoc_clicked) # buttons def btn_ctof_clicked(self): # ctof button even

OOP responsibility assignment -

lets have 2 classes user & orders. should functionality of getuserorders (userid) implemented ? in user class or orders class ? should in user class orders being retrieved related user or should order class retrieving orders it depends on oop design. key feature consider loose coupling . it's bit difficult make determinant decision based on information have provided. however, let's take deeper @ 2 opposite scenarios. scenario no.1 : have user class , order class. using composition link between two. that's means user class has list (array, list, linked list, dictionary, associative array, or whatever) consists of order objects @ disposal. in case, prefer make function inside user class called: getorders . retrieve of orders associated current user. order not know user entity, , easier refactor things in future when user gets change. user knows order not vice versa. way kept on loosely coupled objects (at degree). scenario no.2 : have user class

MySQL Multiple Counts within Date Groups -

select calldate, from_unixtime(floor(unix_timestamp(calldate)/(60*60))*(60*60)) grouptime , count(*) cntout asterisk.cdr accountcode = '10102-131' , date (calldate) = date (now()) , calltype = 'outgoing' group grouptime; i have query groups count every hour of date outgoing calls. there way count of incoming in same query? try this: select calldate from_unixtime(floor(unix_timestamp(calldate)/(60*60))*(60*60)) grouptime, sum(calltype='incoming') cntin, sum(calltype='outgoing') cntout asterisk.cdr accountcode = '10102-131' , date (calldate) = date (now()) , calltype in ('incoming', 'outgoing' ) group grouptime; sample sql fiddle

c++ enum convertibility to int? -

according http://www.cplusplus.com/doc/tutorial/other_data_types/ : values of enumerated types declared enum implicitly convertible integer type int, , vice versa. in fact, elements of such enum assigned integer numerical equivalent internally, of become alias. if not specified otherwise, integer value equivalent first possible value 0, equivalent second 1, third 2, , on... so, following idea, wanted see if following sample work: #include <iostream> using namespace std; enum colors {white, yellow, red, green, blue, black}; int main() { colors a{3}; colors b{1}; colors c{a-b}; cout << c << '\n' << (c == red) << '\n' << c+20 << '\n'; return 0; } and works expected, if set -fpermissive flag, otherwise g++ spits out compilation errors. , flag set still presented number of warnings, this: invalid conversion ‘int’ ‘colors’ if understand documentation correctly above sample should 100% compliant

javascript - how to display binary image in html using angularjs? -

i trying diplay binary data image in angularjs html form.i geeting 2 responses.i dono how avoid have enclosed screetshot.1st 1 response again passing bad response please 1 me out.i have enclose client , server side controller client side controller 'use strict'; /** * @ngdoc object * @name test1.controllers.test1controller * @description test1controller * @requires ng.$scope */ angular .module('test1') .controller('test1controller', [ '$scope','$http' ,'$location','$window', function($scope,$http, $location,$window) { $scope.image = {}; var image="download.jpg"; $http.get('*/upload/'+image).success(function(data,status,response) { console.log(data); $scope.image=data; var testjpg = $scope.image; document.getelementbyid("myimage").src = testjpg; }); } ]); backend controller 'use strict'; var mongoose = re

spring - Request from html client: how will I know that requested user is logged in or not? -

Image
here spring login handler public class loginsuccesshandler extends savedrequestawareauthenticationsuccesshandler { @override public void onauthenticationsuccess(httpservletrequest request, httpservletresponse response, authentication authentication) { httpsession session = request.getsession(); loggedinuser logginuserobj = (loggedinuser)authentication.getprincipal(); string userid = logginuserobj.getuserid(); session.setattribute("userid", userid); session.setattribute("username", logginuserobj.getname()); session.setattribute("hasphoto", user.getproperty(uservertex.profilephotouploaded.tostring())); if(logginuserobj.getactivatelink()!=null) session.setattribute("activatelink", logginuserobj.getactivatelink()); try { object referurl = session.getattribute("referer_url"); if(referurl != null){ session.remo

curl - My Apache 2 error log contains all error message lines splitted to individual characters -

i mean, error messages splitted 1 character length, , these lines in error_log. example if error message of cgi application "error", can see 5 lines of text, 1 line every character of error message, appended referer , other time informations. error messages come forked curl process, , countains \r (carriage return) characters, because of downloading progress indicator. can error output / stderr of curl processes line-by-line? fortunately managed find solution popen3 stdlib: require "open3" cmd=%q{curl -b cookie.txt 'http://www.example.com/file/afancyfileid/yetanotherfilename.avi' -l -o -j} open3.popen3(cmd) {|stdin, stdout, stderr, wait_thr| pid = wait_thr.pid # pid of started process. line_no=0 stderr.each_char |c| if c=="\r" line_no+=1 stderr.puts if line_no % 5 == 0 else stderr.print c if line_no % 5 == 0 end end exit_status = wait_thr.value } i print every 5th lines no

ios - 24 hour time from date string -

i trying time , in 24 hour format following string : 7/2/2015 2:30:00 pm this have tried : -(nsstring*)returndate:(nsstring*)datestring { nsdateformatter *dateformatter1 = [[nsdateformatter alloc] init]; [dateformatter1 setdateformat:@"mm/dd/yyyy hh:mm:ss aaa"]; nsdate *date = [dateformatter1 datefromstring:datestring]; datestring = [date descriptionwithlocale:[nslocale systemlocale]]; nstimezone *currenttimezone = [nstimezone localtimezone]; nstimezone *utctimezone = [nstimezone timezonewithabbreviation:@"utc"]; nsinteger currentgmtoffset = [currenttimezone secondsfromgmtfordate:date]; nsinteger gmtoffset = [utctimezone secondsfromgmtfordate:date]; nstimeinterval gmtinterval = currentgmtoffset - gmtoffset; nsdate *destinationdate = [[nsdate alloc] initwithtimeinterval:gmtinterval sincedate:date]; nsdateformatter *dateformatters = [[nsdateformatter alloc] init]; [dateformatters setdateformat:@"

html - Apply CSS Filter to all but specific sub-elements -

i need css filter apply elements in container, except specific ones. quick example explain situation: <div class="container"> <img class="one" src="blah" /> <img class="two" src="blah" /> <img class="three" src="blah" /> </div> then applying filters so: .container { -webkit-filter: grayscale(100%); filter: grayscale(100%); } so container has greyscale filter applied it, , img in turned grey. however, want 1 of img not turn grey: .two { -webkit-filter: grayscale(0); filter: grayscale(0); } however, not working. filter of container seems overriding filter of contained element. ideas how can around this? there easy way, or have write jquery @ elements aren't ".two" , apply filter them, rather container? update: neglected mention important caveat: container has greyscale, due having background-image property turned grey. little snippet part of more co

javascript - After complete an registration form, how can i show an alert 'Your are done. click OK to login' and then when user click OK it will go to login page? -

after complete registration form, how can show alert 'your done. click ok login' , when user click ok go login page? if($query){ echo (" window.alert('successfully registered') window.location.href='login.php'; "); } ??? why not change ok button "login", why need alert ??

bash - Detect column separators in awk -

i'm trying separate in various files initial *.txt file using awk. got following format. inline xline x y horizon time 1 159 806313 939258 kf2 0.80 .... 81 149 805004 948030 fallriver 0.85965 .... 243 146 804252 965837 tensleepbbase 1.1862 in case separator fifth column (kf2,fallriver,tensleepbbase). idea iterate , break loop when value of fifth column change don't know how structure algorithm in awk. the expected result 3 txt files. 1 each horizon key word: file1.txt inline xline x y horizon time 1 159 806313 939258 kf2 0.80 ... end of kf2 horizon keyword file2.txt inline xline x y horizon time 81 149 805004 948030 fallriver 0.85965 ... end of fallriver horizon keyword .... thank you. using input file, inline xline x y horizon time 1 159 806313 939258 kf2 0.80 2 9 806313 939258 kf2 0.80 3 59 806313 939258 kf2

python 2.7 - Using scrapy's FormRequest no form is submitted -

Image
after trying scrapy's first tutorial excited it. wanted try form submission well. i have following script , if print out response.body page form , nothing happened. can me how results page? # spiders/holidaytaxi.py import scrapy scrapy.http import request, formrequest scrapy.selector import htmlxpathselector, selector class holidaytaxispider(scrapy.spider): name = "holidaytaxi" allowed_domains = ["holidaytaxis.com"] start_urls = ['http://holidaytaxis.com/en'] def parse(self, response): return [formrequest.from_response( response, formdata={ 'bookingtypeid':'return', 'airpotzgroupid_chosen':'turkey', 'pickup_chosen':'antalya airport', 'dropoff_chosen':'alanya', 'arrivaldata':'12-07-2015', 'arrivalhour':'12',

ios - How to deep link to OpenTable -

i'm trying add deep link opentable in ios app , can't find url scheme anywhere. opentable support deep links , if can find url scheme? thanks there's reference app url schemes online list opentable. can't speak whether information accurate, take look: http://wiki.akosma.com/iphone_url_schemes#opentable edit: site gone, here's archived version of page: https://web.archive.org/web/20160505224800/http://wiki.akosma.com/iphone_url_schemes

c# - Validation attribute depending on object instance type -

i'm facing conception problem. create , update our deals in 2 ways : using web forms (one create deals, 1 edit them) , through integration file (to allow mass creation & update). public class createdealviewmodel { public int dealid { get; set; } [validatesalesman] public int salesmanid { get; set; } } public class editdealviewmodel { public int dealid { get; set; } [validatesalesman] public int salesmanid { get; set; } } public class integrationline { public int dealid { get; set; } [validatesalesman] public int salesmanid { get; set; } public string status { get; set; } } i have validation logic implement : @ deal creation, active salesman accepted ; in update, active salesman plus previous salesman value (stored in db) accepted. i wrote : public class validatesalesman : validationattribute { protected override validationresult isvalid(object value, validationcontext validationcontext) { var container =

mysql - Foreign key relationship methods deferred and never created in RDBO -

i'm playing rosedb::object on employees test dataset , , reason, can't foreign key relationships ('department' , 'employee') work on deptemp object. (class structure below). when try $e->dept_emp->[0]->department , get: can't locate object method "department" via package "my::fakeemployees::deptemp" methods following relationships , foreign keys deferred , never created in class my::fakeemployees::deptemp. type name ---- ---- foreign key department foreign key employee i'm sure have set wrong in class structure, what? class structure (some classes omitted clarity): i created various objects using instructions in rdbo tutorial : package my::fakeemployees::employee; use strict; use base qw(my::fakeemployees::db::object); __package__->meta->setup( table => 'employees', columns => [ emp_no => { type => 'serial', not_null =&g

Swift Autolayout warnings and other warnings i do not understand -

the app allows users post images/follow others etc. so works fine following warnings: (i know has autolayout constraints how know causing problems?) 2015-07-05 17:19:37.701 pixym[1271:72192] cuicatalog: invalid asset name supplied: 2015-07-05 17:19:37.702 pixym[1271:72192] not load "" image referenced nib in bundle identifier "hp.pixym" 2015-07-05 17:19:37.705 pixym[1271:72192] unable simultaneously satisfy constraints. @ least 1 of constraints in following list 1 don't want. try this: (1) @ each constraint , try figure out don't expect; (2) find code added unwanted constraint or constraints , fix it. (note: if you're seeing nsautoresizingmasklayoutconstraints don't understand, refer documentation uiview property translatesautoresizingmaskintoconstraints) (nslayoutconstraint:0x7fa83b822a40 h:[uiimageview:0x7fa83b8529a0(300)], nslayoutconstraint:0x7fa83b85ccb0 h:[uiimageview:0x7fa83b8529a0]-(10)-| (names: '|':uitableviewcell

batch file - Pin shortcut (.lnk) to start menu -

i'm making installation script using .cmd file. here code: if exist "%userprofile%\desktop\opslag\opslag.hta" ( start "" "%userprofile%\desktop\opslag\opslag.lnk" /secondary /minimized msg "%username%" program installed. exit ) else ( xcopy %source% %destination% /d /e /c /r /i /k /y start "" "%userprofile%\desktop\opslag\opslag.lnk" /secondary /minimized msg "%username%" setup complete! exit ) the %source% , %destination% set earlier in script. when folder has been copied want file %userprofile%\desktop\opslag\opslag.lnk added start menu. i have seen earlier posts like: how pin start menu using powershell , cannot make work. i'm testing on home laptop runs windows 7 danish language. machine need runs windows 7 english language. therefore think $verb different scripts i've found, haven't tested on work station. furthermore work station has limited uac, , therefore not have admi

javascript - Separating instances of require in node -

say example have 2 files a.js , b.js both : var some_package = require('some_package'); i call a.dosomething() , b.dosomething(), in both files, same instance used - therefore altering states inside "some_package" - didn't want happen. what want create separate instance of some_package in , b. possible despite module caching of node.js? a.dosomething() , b.dosomething() affect required module's state if function dosomething accesses internal module scope variable. e.g. // some_package.js var modulescopevariable = 0; // acts global module exports.dosomething = function() { return ++modulescopevariable; // change modulescopevariable }; one way around expose constructor function instead, put state in instance object, , make sure not access module scope vars in dosomething . // some_package.js exports.doer = function() { this.objectscopevariable = 0; this.dosomething = function() { return ++this.objectscopevariable; } } /

python - Scrape XML files into RSS feed as input for IFTTT -

i've got set of xml files article content (title, subtitle, content). i've got yahoo pipe finds article xml specific date , turns rss feed. feed read ifttt publish article today on wordpress blog. now yahoo pipes going down in september, , i'm in trouble! service can use fetch content xml , feed ifttt, can published on blog. far see, ifttt takes rss input sort of things. i've tried pipe2py turn pipe python code (if work @ all), can't pipe2py working, not on gae (as need online service) , not on windows pc either. i'm experienced yql well, outputs xml, no rss, it's of no use here. so far can think of: implement on gae/python own app reads xml , turns rss (cumbersome) manually publish articles on blog due date (three months of daily articles go - more cumbersome) any ideas? according ideas - should consider using wordpress core code fetch xml data. create plugin load xml data using http api , call proper actions on blog (in case

android - setting strings equal to eachother in a popup -

i'm making type of calculator app calculates surface areas of weird shapes etc.. when measurements inputted, user clicks calculate,and result gets displayed. problem i'm having cant result string (z) equal 1 in popup... dearly appreciated because have been stuck on quite while now. public class rectangular extends activity { edittext length; edittext width; edittext edge; edittext roll; textview tt; button calculate; double w=0; double x=0; double y=0; double z=0; double v=0; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_rectangular); initcontrols(); //when calculation done, popup window inflates final button btnopenpopup = (button)findviewbyid(r.id.button8); btnopenpopup.setonclicklistener(new button.onclicklistener() { public void onclick(view arg0) { layoutinflater layoutinflater = (layoutinflater) getbasecontext()

c# - Serializing a class containing a WPF Brush using `DataContractSerializer` -

i have class serializing like: using (filestream filestreamwriter = new filestream(filename, filemode.create)) { var datacontractserializer = new datacontractserializer(typeof(classtobeserialized)); datacontractserializer.writeobject(filestreamwriter, btchartgrouplist); filestreamwriter.close(); } this works fine until add property of type brush (called areabrush ) classtobeserialized class. areabrush property solidbrush , lineargradientbrush or radialgradientbrush . during serialization, datacontractserializer throws: type 'system.windows.media.matrixtransform' data contract name 'matrixtransform: http://schemas.datacontract.org/2004/07/system.windows.media ' not expected. consider using datacontractresolver if using datacontractserializer or add types not known statically list of known types - example, using knowntypeattribute attribute or adding them list of known types passed serializer. any ideas on how can work? played around bru

Entity Framework / SQL Server Include behaviour with filtering -

i have 2 basic questions regarding ef , sql server ask along examples. say have following query: db.customers.include(c => c.orders) .include(c => c.items) .include(....).where(c => c.age > 25) in simple query retrieve customers based on condition , related data other tables. includes (joins) happen on records in database first , these filtered on condition or first engine filter records without joining , perform joins on filtered records? question concerns ef far generated query maybe , sql server query engine too. what behaviour if of properties used in includes part of filtering? again all joins performed on every record in database or perform needed joins filtering on records in database , remaining joins on filtered records? situation can described like: db.customers.include(c => c.orders) .include(c => c.items) .include(....).where(c => c.orders.any(o.name.startswith("football") also how behaviour d

xml - Android Studio: android.support.v7.widget.Toolbar can not be initiated -

Image
i developing toolbar android app , after creating tool_bar.xml file, ide showing error following classes can not initiated - android.support.v7.widget.toolbar the full error details are java.lang.noclassdeffounderror: android/support/v7/appcompat/r$attr @ android.support.v7.widget.toolbar.<init>(toolbar.java:191) @ sun.reflect.nativeconstructoraccessorimpl.newinstance0(native method) @ sun.reflect.nativeconstructoraccessorimpl.newinstance(nativeconstructoraccessorimpl.java:57) @ sun.reflect.delegatingconstructoraccessorimpl.newinstance(delegatingconstructoraccessorimpl.java:45) @ java.lang.reflect.constructor.newinstance(constructor.java:526) @ org.jetbrains.android.uipreview.viewloader.createnewinstance(viewloader.java:413) @ org.jetbrains.android.uipreview.viewloader.loadview(viewloader.java:105) @ com.android.tools.idea.rendering.layoutlibcallback.loadview(layoutlibcallback.java:177) @ android.view.bridgeinflater.loadcustomview(br

Android Picasso Fragment Pic from URL -

Image
i've got problem load pic url fragment picasso. when start app it's start without errors pic not loading. app has 1 mainactivity , 3 fragments. below paste xml of mainlayout , 1 fragment class. best me scenario: when user click button on fragment three(red on image), pic load url imageview located on fragment 2 (yellow on image) above of fragment three. please help package testowy.com.testowyfragment2; import android.app.activity; import android.app.fragment; import android.content.context; import android.os.bundle; import android.view.layoutinflater; import android.view.view; import android.view.viewgroup; import android.widget.button; import android.widget.imageview; import com.squareup.picasso.picasso; /** * created administrator on 2015-07-04. */ public class klasadown extends fragment { private klasadownlistener listener; @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { view view

npm - Permissions denied to override or delete node targets -

i've been running issue every time i've attempted run npm install command receive error: '-bash: npm: command not found' i've attempted uninstall , reinstall both node , npm using homebrew, still running few errors. after i've uninstalled both, have run command: "brew doctor" , "your system ready brew." first attempt install node: "brew install node", following: ==> downloading https://homebrew.bintray.com/bottles/node- 0.12.7.yosemite.bottle downloaded: /library/caches/homebrew/node-0.12.7.yosemite.bottle.tar.gz ==> pouring node-0.12.7.yosemite.bottle.tar.gz ==> caveats bash completion has been installed to: /usr/local/etc/bash_completion.d error: `brew link` step did not complete formula built, not symlinked /usr/local not symlink share/systemtap/tapset/node.stp target /usr/local/share/systemtap/tapset/node.stp exists. may want remove it: rm '/usr/local/share/systemtap/tapset/node.stp' force link ,

ruby on rails - What is the rationale for `reject_if`? -

i've come across reject_if in cocoon's readme , , in documentation nested attributes . rationale using reject_if when associated active record objects can determine whether they're valid or not? for nested objects, may not want attempt submit record :all_blank or other reason may want check on. point being, empty or incomplete (in way) object can, way, not built / added nested objects collection. validations serve different purpose. if empty object, say, fails validation whole form submit fail. reject_if approach allows submission succeed in such case removing object consideration before validations fire.

.net - How to make custom DataGridViewComboBox dependent only on its DataGridViewComboBoxColumn? -

popular way ( 1 , 2 ) custom painting of items in datagridviewcombobox handling of event datagridview1. editingcontrolshowing , setting drawitem event handlers there: private void datagridview1_editingcontrolshowing( object sender, datagridvieweditingcontrolshowingeventargs e) { theboxcell = (combobox) e.control; theboxcell.drawitem += theboxcell_drawitem; theboxcell.drawmode = drawmode.ownerdrawvariable; } you see wrong: uses control-level event handle work columns. if have 50+ datagridviews? painting of custom combo boxes should handled per column instance , leaving control level intact. minimal implementation of per-column handling below. problem have ondrawitem() method not getting called. missing? (you can see fuchsia background override the same class working.) (to reproduce, paste following class file , add column of type datagridviewcustompaintcomboboxcolumn datagridview1 .) public class datagridviewcustompaintcomboboxcolumn : datagrid

node.js - Mongoose: Updating some/all fields in a Mongodb collection -

a settings form example. on submit, appropriate collection needs updated; , 1, some, none or of fields need updated. assuming i'm not mistaken, mongoose: ignores fields aren't defined in schema. does low-level validation on field based on schema (i.e. reject, (ignore?) value isn't of correct type). so mean following advisable ? .put(function(req, res, next) { if (mongoose.types.objectid.isvalid(req.params._id)) { collection.update({_id: req.params._id}, { $set: req.body}, function (err, collection) { if (err) return next(err); res.send(200, {success: true}); }) }else{ res.send(400, {success: false}); } }) i.e. passing req.body directly update? it works, can't feel it's little lacking in validation/filtering? mongoose doing enough in schema approach sufficient? or should iterating on each expected field? i'm happy set tests thought i'd check community , sanity check approach - suggested alternatives gratef

How to find the minimum value from the ranges in array of hashes in ruby? -

i have below array of hashes z = {"range"=>[{"10-50"=>"5"}, {"50-100"=>"15"}, {"100-150"=>"25"}]} how can output 10 you can try following: z["range"].map(&:keys).flatten.map(&:to_i).min #=> 10 demo

objective c - How can I get CoreLocation to resume ranging when the device is restarted? -

i able monitoring , ranging work when backgrounded app. when restarted phone, i'm able diddeterminestate, ranging, , monitoring when lock screen on. when go home screen or phone screen off, corelocation functions (state change, ranging , monitoring) paused. how can make resume diddeterminestate, didrangebeacons, didmonitorbeacons when go home screen or phone screen off? because when entered app , backgrounded it, when phone screen off or lock screen on, i'm able corelocation updates. why restarting phone different?

laravel - Optional route parameter that must equal a string -

i need show exact same page/data 2 differents paths ( / , /index ). how can create route satisfies rule? i tried following, optional parameter allows any word (like /hello , /world , or /anything ), whereas want / or /index : route::get('/{trending?}', array('as' => 'index', function() { // code }); you can add regular expression route parameters, in case this: route::get('/{trending?}', array('as' => 'index', function() { // code }))->where('trending', 'index'); however if have controller anyways (and should) i'd add 2 routes: route::get('/', ['as' => 'index', 'uses' => 'somecontroller@index']); route::get('index', 'somecontroller@index');

'Launch Failed. Binary Not Found' error when trying to run program -

i'm new using c++ programming , have no idea error means or how solve it. every other forum on specific error gives different remedies, none of them have worked me. can me understand means? my code is: #include <iostream> int main() { std::cout << "game over!" << std::endl; return 0; } it should pretty straight forward 'helloworld'-esque program. that error means ide can't find compiled binary file execute. make sure building project , check if binary exists.

ios - Starting a View Controller from a "nested" View Controller -

i have uiviewcontroller has uiviewcontroller added subview: #import "listviewcontroller.h" @interface searchviewcontroller () @end @synthesize listcontroller; - (void)viewdidload { [super viewdidload]; … self.listcontroller =[[listviewcontroller alloc] init]; [self.view insertsubview:listcontroller.view belowsubview:maintabbar]; self.listcontroller.view.frame = cgrectmake(0, tabheight, screenwidth, (screenheight-tabheight)); } @end the listviewcontroller has tableview in it. on click of item in tableview, want add uiviewcontroller navigation controller: #import “placeviewcontroller.h" @interface listviewcontroller () @end - (void)tableview:(uitableview *)tableview didselectrowatindexpath:(nsindexpath *)indexpath { placeviewcontroller *vc = [[placeviewcontroller alloc] init]; [self.navigationcontroller pushviewcontroller:vc animated:yes]; [tableview deselectrowatindexpath:indexpath animated:yes]; } @end this works i

ios - Generate a Swift array of nonrepeating random numbers -

i'd generate multiple different random numbers in swift. here procedure. set empty array generate random number check if array empty a. if array empty, insert random number b. if array not empty, compare random number numbers in array i. if numbers same, repeat 2 ii. if numbers not same, insert random number , repeat 2 import uikit //the random number generator func randomint(min: int, max:int) -> int { return min + int(arc4random_uniform(uint32(max - min + 1))) } var temp = [int]() var = 0; i<4; i++ { var randomnumber = randomint(1, 5) if temp.isempty{ temp.append(randomnumber) } else { //i don't know how continue... } } if use method problem is, create new random-number each time. possibly have same random-number 4 times , array have 1 element. so, if want have array of numbers within specific range of numbers (for example 0-100), in random order, can first fill array numbers in 'normal' order. example loop etc:

python - Using Django ----If there are more than 1 record then displaying it and if there is only 1 record then i am deleting it -

what problem code displaying records whether there 1 record or many...but want delete if there 1 record.... advise code writing obliged.... here view def delete(request): form = searchform(request.post) searched_data = information.objects.filter(name="full_name").count() d_data = none if form.is_valid(): if (searched_data == 1): d_data = information.objects.filter(name= form.cleaned_data.get('full_name')).delete() else: d_data = information.objects.filter(name=form.cleaned_data.get('full_name')) context = { 'form': form, 'd_data': d_data, } return render(request, 'delete.html', context) i not unless form valid: if form.is_valid(): d_data = information.objects.filter(name=form.cleaned_data.get('full_name')) if len(d_data) == 1: d_data.delete() d_data = none else: d_data = none context = { 'form': form, 'd_data': d_

How to get Value from One textbox to another instantly on a single form c# -

i have 4 textboxes on form in windows form. named: id, session, class, section . need generate id in id_txtbox instantly session, class , sections inserted , save db. id contain (session+class+section) . problem how can data on single form these 3 txtboxes (session, class, section) , special id without clicking button ? use textbox.textchanged event , validate if input matches requirements. if so, save database. it's possible attach textboxes same event way. i'm assuming need generate id yourself, if can use guid class this.

eclipse - Upgrade Cordova 2.6.0 to newest version for Android -

Image
i developed cordova app on 2.6.0. have upgrade 3.5.1 or higher since google play store sent me mail so. now installed newest version of cordova npm install -g cordova , created new project in right (old) namespace. added plugins, copied old www-files new www folder , added android platform. back in eclipse (juno) imported project , tried build it. eclipse tells me solve errors firstly. after realized files under src marked errors. i searched web not information on going wrong... what right way find out going wrong , how solve errors probably? thanks in advance help!

Android MipMaps not working (Android Studio) -

Image
so, set mipmap folders in res/ directory (such /src/main/res/mipmap-mdpi, , on, different densities), , in manifest put android:icon=@mipmap/ic_launcher ic_launcher.png files, yet still android green guy on phone when press play button. frustrating. suggestions try? ive tried uninstalling app , cleaning project in android studio inside package manager right click on folder app , select new->image asset default launcher icon, select image , done

python 2.7 - Problems using Scrapy to scrape craigslist.org -

i'm using following set-up scrape prices http://puertorico.craigslist.org/search/sya def parse(self, response): items = selector(response).xpath("//p[@class='row']") items in items: item = stackitem() item['prices'] = items.xpath("//a[@class='i']/span[@class='price']/text()").extract() item['url'] = items.xpath("//span[@class='href']/@href").extract() yield item my problem when run script, of prices shown each item.. how can price of particular item url each available item? you can try using realtive xpath expression based in context of previous one, traversing nodes until 1 want. also, use different variable in for loop, like: import scrapy craiglist.items import stackitem class craiglistspider(scrapy.spider): name = "craiglist_spider" allowed_domains = ["puertorico.craigslist.org"] sta

html - Div height 100% of content -

Image
i have easy question css guru ruining weekend. have div image on left , text on right. need box height same of content text example in image below last line outside box while need box height content. i cannot use fixed height due text can change inside box, need min-height defined. some guru can me? <a href="#" class="myclass"> <div class="postimageurl" style="overflow:hidden; z-index: 10; max-width: 100%;"> <div class="imgurl" style="background-image:url(http://cdn8.openculture.com/wp-content/uploads/2015/03/17231820/lorem-ipsum.jpg);"> </div> </div> <div class="centered-text-area clearfix"> <div class="centered-text"> <div class="myclass-content"> <div class="ctatext" style="float:left;"> upnext </div>