Posts

Showing posts from July, 2012

How do I delete a list within a list in Python? -

my program involves drawing card deck, adding value of hand , deleting card deck (since don't want draw same card twice). example of card: card = ["4 of clubs", 4] the code doesn't work: card_number = random.randrange(len(deck_cards)) card = deck_cards[card_number][0] print(card) hand_value += deck_cards[card_number][1] deck_cards.remove(card_number) i have no idea doing wrong, , if change code to card_number = random.chioce(deck_cards) it won't accept card = deck_cards[card_number][0] part. what do? list.remove takes object, not index, parameter. so should modify code retrieve card , use directly: >>> card = random.choice(deck_cards) # retrieve object, not index >>> print (card) # card card list, i.e.: ["4 of clubs", 4] >>> print (card[0]) 4 of clubs >>> hand_value += card[1] >>> deck_cards.remove (card) note can delete object @ specified index using del built-in: >&

c# - 'The target account name is incorrect'-IOException with DirectoryInfo.GetFiles -

i doing , working before: var di = new directoryinfo("folderonshareddrive"); var files = di.getfiles("*"); i have exception , difference can see have windows 10. exception thrown: 'system.io.ioexception' in mscorlib.dll additional information: target account name incorrect. try use ip address instead of computer name.

xml - Python Scrapy Xpath? -

for non-profit college assignment i'm trying scrape data website www.rateyourmusic.com using scrapy framework in python, have had small amount of success have been able scrape name of artist artist page xpath other info (birth date, nationality) proving difficult me scrape. of know correct xpath these objects be? here parsing method has @ least worked artist name. def parse_dir_contents(self, response): item = rateyourmusicartist() sel in response.xpath('//div/div/div/div/table/tbody/tr/td'): item['dateofbirth'] = sel.xpath('td/text()').extract() #these 2 selectors aren't working item['nationality'] = sel.xpath('td/a/text()').extract() sel in response.xpath('//div/div/div/div/div/h1'): item['name'] = sel.xpath('text()').extract() #this 1 works yield item here sample url of artist page i'm scraping http://rateyourmusic.com/artist/kanye_west here real

ios - How to add UITapGestureRecognizer inside a UIView with the target set ```self``` -

i created customized uiview , added uitapgesturerecognizer inside this: @interface customizedview : uiview @property(nonatomic,strong) uilabel* label; @end @implementation customizedview -(void) targetactionforthisview:(id)sender{ nslog(@"clicked!"); } -(void) commoninit{ _label = [[uilabel alloc] initwithframe:cgrectmake(0,0,200,100)]; _label.text = @"test string 1234"; uitapgesturerecognizer* g = [[uitapgesturerecognizer alloc] initwithtarget:self action:@selector(targetactionforthisview:)]; g.enabled = yes; [self setexclusivetouch:yes]; [self setuserinteractionenabled:yes]; [self setmultipletouchenabled:yes]; [_label addgesturerecognizer:g]; [self addsubview:_label]; } -(instancetype)init{ self = [super init]; [self commoninit]; return self; } -(instancetype)initwithframe:(cgrect)frame{ self = [super initwithframe:frame]; [self commoninit]; return self; } @end then add view control

database - SQL Server update statement won't update table -

i have server running enterprise version of sql server 2012. took backup of production database 2 days ago test migration script. worked beautifully the same database 2 days newer failed today because first step of process update records. update troopgirls set gsusaid = '00000000000'+gsusaid len(gsusaid) = 1 is 1 such statement. running statement updated(61) records every time i've run inside transaction frame commit, used go statements, messed transaction isolation levels, no avail. there no locks anywhere in database , process running against database query window. right clicking table , saying 'edit top 200 rows' work. problem have update in range of 750k records across many tables , schemas. if "gsusaid" varchar/nvarchar column, concat function work updating it. update troopgirls set gsusaid = concat('00000000000', gsusaid) len(gsusaid) = 1

How to call Rest webservice in Spring Security -

i have @restcontroller in web application, want make use of service in authentication provider security purpose .could please advise how achieve this? ( fyi : using spring boot) for example rest service url : http://localhost:8080/authentication.json login page url : http://localhost:8080/login my question similar following question, difference is, rest service available in same application . hope rest template or httpurl connection not required ? please advise. spring security login rest web service . given below sample code snippet. @restcontroller @requestmapping("authorize") public authorizecontroller{ @requestmapping(method = requestmethod.put, produces = "application/json") public employee authorize(@requestparam string username) { return employee; } } @configuration @enablewebmvcsecurity public class websecurityconfig extends websecurityconfigureradapter { @autowired customauthenticationprovider provider; @ov

gradle - Provided scope not working in eclipse -

gradle 2.2.1 i trying include dependencies jar file ship other users. want them provide own versions of dependencies , trying emulate provided scope maven. i have followed tutorial here . able build project command line (while still getting classes not found errors in eclipse) until eclipse integration part. post says add eclipse.classpath.plusconfigurations += configurations.provided getting could not find property 'provided' on configuration container apply plugin: 'java' apply plugin: 'eclipse' // causes error //eclipse.classpath.plusconfigurations += configurations.provided sourcecompatibility = 1.8 version = '1.0' jar { manifest { attributes 'implementation-title': '...', 'implementation-version': version } } repositories { mavencentral() } configurations { provided } sourcesets { main.compileclasspath += configurations.provided test.compileclasspath += co

swift - Store first few elements in array in another array if they exist -

given array contains number of objects, how cleanly , safely first 3 elements out of store in new array? if array not contain @ least 3 elements, should not trigger runtime exception, instead should add number of elements in array new array. i thought might work, won't compile in xcode 7, , if did don't imagine behave safely desire: let arr1 = [1, 2, 3, 4, 5] let arr2 = arr1[0..<3] //expected: arr == [1, 2, 3] let arr1 = [1, 2] let arr2 = arr1[0..<3] //expected: arr2 == [1, 2] let arr1 = [int]() let arr2 = arr1[0..<3] //expected: arr2 == [] of course 1 this, or use loop, neither clean , concise. want find swiftier way. let arr1 = [1, 2] var arr2 = [int]() if photos.count > 0 { arr2.append(arr1[0]) } if photos.count > 1 { arr2.append(arr1[1]) } if photos.count > 2 { arr2.append(arr1[2]) } i think simplest way be let arr2 = arr1.prefix(3)

scala - What is type declartion for in definition of Nat in shapeless? -

this definition of nat in package shapeless : trait nat { type n <: nat } case class succ[p <: nat]() extends nat { type n = succ[p] } class _0 extends nat serializable { type n = _0 } what type declarations ? once removed seems me definition works equally well. they're used nat target type of implicit conversion literal int ... see here , example, in definition of int indexing method hlist , def at(n : nat)(implicit @ : at[l, n.n]) : at.out = ... here intention method invoked literal int argument, (23 :: "foo" :: true :: hnil).at(1) the argument converted nat implicit macro able inspect compile time argument tree , construct corresponding nat value. can refer type member n of n , use index at type class extracts desired element hlist .

javascript - Angular JS TypeScript IHttpService inject custom header value -

i have project make successful http request from typescript (angular http service) code to web api controller , display list in grid. project using angular js 1.4.x , typescript successfully. full project's github url . , typescript code calls server below. module app { export class studentlistservice { private qservice: ng.iqservice; private httpservice: ng.ihttpservice; constructor($q: ng.iqservice, $http: ng.ihttpservice) { this.qservice = $q; this.httpservice = $http; } get(): ng.ipromise<object[]> { var self = this; var deffered = self.qservice.defer(); self.httpservice.get('/api/values').then((result: any): void => { if (result.status === 200) { deffered.resolve(result.data); } else { deffered.reject(result); } }, error =>

javascript - Jquery Div Changes Not Affected With in the Script -

i have div multiple dropdowns. dropdowns doesn't have id. working other logic remove , add dropdowns within div. if remove dropdown means changes doesn't affect in same script. $(document).ready(function () { $(function () { alert($('#show_lable_categories').find('select').length)); // return 5 //now remove dropdowns $('#show_value_categories').find("select").slice(2).remove(); alert($('#show_lable_categories').find('select').length)); //always return 5 //i need 3 instead of 5 in script }); }); $('#show_value_categories').find("select").slice(2).remove(); i think issue might made typo on element selecting, changes $('#show_value_categories') $('#show_lable_categories'). also tip, want have variable such as: var dropdown = $('#show_value_categories') to avoid bugs such these not have find same element twice.

django - In Wagtail, how can I add a form to the bottom of another model's form in the WagtailAdmin, for a OneToOneField relationship? -

in wagtail, let's have page this: class mypage(page): field_1 = richtextfield() field_2 = models.datefield() content_panels = page.content_panels + [ fieldpanel('field_1'), fieldpanel('field_2'), ] and have model has one-to-one relationship first model: class pagesettings(models.model): page = models.onetoonefield(mypage) extra_setting_1 = models.booleanfield() extra_setting_2 = models.charfield(max_length=50) how can add form pagesettings model bottom of wagtail admin form mypage model? bonus points way generic relationships. class mypage(page): field_1 = richtextfield() field_2 = models.datefield() content_panels = page.content_panels + [ fieldpanel('field_1'), fieldpanel('field_2'), inlinepanel('settings', label='settings', min_num=1, max_num=1), ] class pagesettings(models.model): page = parentkey(mypage, related_n

yii components - Yii error load css when using manage url -

i have folder resource containing css file. using registercssfile , registerscriptfile load them in components/controller. have trouble when using manage urlmanager in config/main . page can't load file css , javascript because link change follow controller id. this error: controller site : http://localhost/admin/site/resources/css/profile.css ........ controller user : http://localhost/admin/user/resources/css/theme-blue.css ........ please me. thank much.

c++ - Is a double not big enough to hold my data? -

i writing program simulate gps system. hard-coded in data debug in visual studio. running program in terminal can pipe in data. problem in do-while loop. trying iterate time until condition "check>0.01c" satisfied, c speed of light. position , time of satellite, xs , ts, respectively, intertwined. continually recalculating xs new, more accurate value of t. second time through, tnew not change. first time, reason can come doesn't change small it's insignificant. great, i've been debugging hours on end. included code surrounding do-while loop think problem: #include<iostream> #include<fstream> #include<sstream> #include<string> #include<iomanip> #include<math.h> #include<cmath> using namespace std; int main() { // go through each satellite , calculate ts , xs (int = 0; is<24; is++) { // compute ts , xs double initialxs[3]; (int kk = 0; kk<3; kk++)

php - Circular Reference on preFlush -

i'm having trouble dependency injection. i'm trying save record db in preflush listener. i'm saving record db via own service ( custom logging service ). i've tried few ways none working, i've tried every google / stackover flow result i've found no luck yet i'm afraid. here's setup logger class, private variables have been ommitted set ( use request stack , translator else in class, wasn't sure if should ommit question ): config: core.logger: class: xxx\corebundle\logger arguments: [@request_stack, @doctrine.orm.entity_manager, @translator] class: public function __construct(requeststack $requeststack, entitymanager $em, translatorinterface $t) { $this->requeststack = $requeststack; $this->em = $em $this->t = $t; } public function addlogentitychange($uow, $entity) { $changeset = $uow->getentitychangeset($entity); foreach($changeset $key => $value) { $log

smt - How to display specific unsat constraint, not whole core (Z3, Python) -

how can list specific constraint result unsat core? have lot of conditions , printing whole core doesn't print all. read can done assert_and_track , unsat_core commands. found examples don't works. experience this? s.assert_and_track(a > b, 'p1') s.assert_and_track(b > c, 'p2') if s.check() == sat: print('ok') else: c = s.unsat_core print(c) <- print core so how print p1 or p2 (just true/false result) ? e.g. p2 = false, or can displayed in way displayed in print(c) mode - p1. the easiest way achieve save map of labels constraints, examples can m = {} m['p1'] = (a > b) m['p2'] = (b > c) m['p3'] = (c > a) so later can print core in terms of constraints, instance follows core = s.unsat_core() e in core: print(m[str(e)]) of course work if want print entries instead of of them.

ios - launchd doesn't get triggered -

i've written mailcopy. plist file, supposed echo "gottriggered" log file, when mail arrives. <?xml version=1.0" encoding="utf-8"?> <!doctype plist public "-//apple computer//dtd plist 1.0//en" "http://www.apple.com/dtds/propertylist-1.0.dtd"> <plist version="1.0"> <dict> <key>label</key> <string>mail</string> <key>programarguments</key> <array> <string>echo</string> <string>gottriggered</string> </array> <key>watchfiles</key> <array> <string>/var/mobile/library/mail/protected\ index-wal</string> </array> <key>standardoutpath</key> <string>/var/log/mailcopy.log</string> <key>standarderrorpath</key> <string>/var/log/mailcopy_err.log</string> </dict> </plist> the file protected index-wal is (verified) changed whenever ipad (

javascript - jquery - check to see if files are the same -

i inherited webapp allows users submit 7 files @ time. there code works in checking see if there 2 of same file, bulky , not flexible. if (elementid == "file2") { if ((form.file2.value == form.file1.value) || (form.file2.value == form.file3.value) || (form.file2.value == form.file5.value) || (form.file2.value == form.file6.value) || (form.file2.value == form.file7.value)) { alert("error! file - " + form.file2.value + "\nselected more once. select file."); validfile = "false"; } } if want add file or remove file, have alter javascript/jquery work new code. want make flexible. in other places in code have been able cut on code check file name against date submitted see if match $("[id^=file]").filter(function() { if ($(this).val().length > 0){ if($(this).val().search(reportingperiod) < 0 ) { alert("error! " + $(this).ge

sql server - Query that worked for months now timesout -

i have query run delphi application started timing out last week after running months. further more when runs slows server crawl leaving other users believe system has crash running management studio stop query after on 5 minutes of spinning server id sqlexpress 2008 r2 the offending query select * signeloutilslistejobs_view4 (createddate > (getdate() - 365)) to make interesting here time required & rows return when change number of days back. activity monitor not seem show more query running select * signeloutilslistejobs_view4 -- 00.00.02 38882 rows select * signeloutilslistejobs_view4 (createddate > (getdate() - 600)) -- 00.00.02 16217 rows select * signeloutilslistejobs_view4 (createddate > (getdate() - 500)) -- 00.00.02 13013 rows select * signeloutilslistejobs_view4 (createddate > (getdate() - 200)) -- 00.00.12 4118 rows so left wondering happening here? ideas? thanks

android - Setting Facebook SDK does not work -

i trying set facebook sdk using maven, repositories { jcenter() // intellij main repo. } dependencies { compile 'com.facebook.android:facebook-android-sdk:+' } now, doubt should keep extracted facebook sdk files?

r - Genetic Algorithm or Simulated Annealing for Work Project Scheduling & Optimization -

i have been tasked improving company's rudimentary scheduling process , making more data driven, efficient, , streamlined. stands, sum per month, total hours needed projects & compare value possible work hours * number of employees. compare these results , determine if need bring on more or not. i lot more precise in process , began looking optimization resources such stable marriage problem. eventually, stumbled onto genetic algorithms , simulated annealing job-shop problem, because believe problem ends being little more complex multi-match marriage problem, wrong. my basic problem set optimization task many limiting criteria. workers : john, jane, dale, etc. can have multiple roles (john can manager or laborer) projects : project a, project b, project c, etc. projects have start , end dates. ideally, have sub-start , end dates different phases of projects limit with, overall start/end date do. these sub-dates include hours required each role type (manager 8 hou

c# - Import values from Excel -

Image
i have excel file: (you can see cell names (or codes) signed red color). i search way read data on excel template that, in future, in these cells. think of use cell code, don't know how. had tried in way: public partial class caricadocumento : system.web.ui.page { protected void page_load(object sender, eventargs e) { upload(); } protected void upload() { filestream stream = file.open("c:\\template_p6.xlsx", filemode.open, fileaccess.read); // reading openxml excel file (2007 format; *.xlsx) iexceldatareader excelreader = excelreaderfactory.createopenxmlreader(stream); // data reader methods while (excelreader.read()) { int = excelreader.getordinal("ao10"); // doesn't works: throw system.notsupportedexception var s = excelreader.getvalue(i); system.console.writeline(s.tostring()); } //free resources excelread

f# - Is there a way to not have to repeat this function invocation in pattern matching? -

i have string want use active pattern match against. i've noticed have repeat same function invocation when value input function. there way not have keep calling function? let (|a|b|c|x|) stringvalue = match stringvalue | value when comparecaseinsensitive stringvalue "a" -> | value when comparecaseinsensitive stringvalue "b" -> b | value when comparecaseinsensitive stringvalue "c" -> c | _ -> x stringvalue you define yet active pattern black-box function: let (|cci|_|) (v: string) c = if v.equals(c, system.stringcomparison.invariantcultureignorecase) some() else none let (|a|b|c|x|) stringvalue = match stringvalue | cci "a" -> | cci "b" -> b | cci "c" -> c | _ -> x stringvalue

ios - How does the IBM MobileFirst server know if it is in "production" or "sandbox" mode for APNS notifications? -

i'm looking @ mobilefirst platform 7.1 push notification setup instructions , , trying debug issue mfp server seems connected wrong apple backend server (sandbox should production). to clarify: how mfp server know if in "sandbox" or "production" mode? purely based on of 2 .p12 files ( apns-certificate-sandbox.p12 , apns-certificate-production.p12 ) exist in .wlapp file? happens if both of them present? i believe based on name of certificate. either ends "sandbox" or "production".

javascript - How to upload file using ajax/jQuery with Symfony2 -

could me? i'm trying write script when user clicks image, triggers image in database updated. for wrote code temporarily makes caller line of method in controller, when send form not validated because of cross-site-request-forgery. $("#upload_picture").on('click', function (e) { e.preventdefault(); $("#bundle_user_file").trigger('click'); }); $("#bundle_user_file").change(function () { if (this.files && this.files[0]) { var reader = new filereader(); reader.onload = function (e) { $('.active-img').attr('src', e.target.result); }; reader.readasdataurl(this.files[0]); ajax_formdata() } }); this caller line ajax, treatment in form formdata post, caught routes , token. calls route, not sure if image going or not, inspector firefox. function ajax_formdata() { var @ = $("form[name=bundle_user]"); var formdata = new f

javascript - Google Maps Api :set the center of map to different coordinates after rendering -

i want change center of google map after time interval can focus on areas of whole continent having markers showing restaurants branches. have rendered map markers. having problem changing center looping through list of latitude , longitude. trying this. var lat[]; var lang[]; function movetolocation(){ var center = new google.maps.latlng(lat, lng); map.panto(center); } setinterval(movetolocation, 3000); from related question: google maps dynamically zooming in different locations proof of concept fiddle code snippet: var map; function initialize() { map = new google.maps.map( document.getelementbyid("map_canvas"), { center: new google.maps.latlng(37.4419, -122.1419), zoom: 8, maptypeid: google.maps.maptypeid.roadmap }); var places = [ [52, -1], [52, -2], [53, -3], [53, -5], [54, -4], [54, -6] ];

Download MP3 file from server in sd card in Android -

i want download mp3 files server 1 one , save sd card folder. have no errors or exception mp3 not downloaded , not show in sd card. can how solve issue.here code. if (imagename.endswith(mp3_pattern)) { str_downloadurl = namespace + "/downloadfile/filename/" + imagename; log.e("######### ", "str_downloadurl = " + str_downloadurl); download_mp3file(str_downloadurl); strdownloadstatus = "1"; dbhelper.update_downloadstatus(imagename, strdownloadstatus); } void download_mp3file(final string fileurl) { new asynctask<string, integer, string>() { @override protected string doinbackground(string... arg0) { int count; file file = new file(newfolder, system.currenttimemillis() + imagename);

android - Database with repeating records -

i have sqlite database in app.when have internet connection,data saved , when haven't internet connection,i loaded data database , show in listview.but in listview have many records,i think when have internet created records how many times,how start app.but how can delete records,create new,and dont create same records every time when start app? mainlist: public class mainlist extends listfragment{ sqlhelper dbhelper; listview mainlist; progressbar progbar; private static string url = "https://fierce-citadel-4259.herokuapp.com/hamsters"; private static final string title = "title"; private static final string description = "description"; private static final string image = "image"; arraylist<hashmap<string,string>> jsonlist1 = new arraylist<hashmap<string, string>>(); arraylist<hashmap<string,string>> bdlist = new arraylist<hashmap<string, string>>();

java - Saving big amount of data (words): Serialization or DB -

i need save permanently big vocabulary , associate each word information (and use search words efficiently). better store in db (in table , let dbms make work of structuring data based on key) or better create trie data structure , serialize file , deserialize once program started, or maybe instead of serialization use xml file? edit : vocabulary in order of 5 thousend 10 thousend words in size, , each word metadata structured in array of 10 integer. access word frequent (this why thought trie data structure have search time ~o(1) instead of db use b-tree or search ~o(logn)). p.s. using java. thanks! using db better. many companies merged db, erp divalto using serializations , merged db performance you have many choices between dbms, if want see data in 1 file simple way use sqlite . advantage not need server dbms running.

Rhino ETL C# DelimitedRecord -

i know if there way ignore delimitedrecord if found in file string "70,000 - 99,999" file sample: 1, "70,000 - 99,999" 6, "20,000 - 99,999" 8, "50,000 - 99,999" [delimitedrecord(",")] public class myclass { public string id; public string size; } i got solution. i need use [fieldquoted()] annotation on field.

ios - Checking if text fields are empty cause error in Swift 2 -

Image
i trying check if textbox has no value. when this: if(useremail?.isempty || userpassword?.isempty || userpasswordrepeat?.isempty) i following error i tried adding "?" before ".isempty" error won't go away any ideas? try this.... if txtemail.text?.isempty == true || txtpassword.text?.isempty == true || txtrepassword.text?.isempty == true{ print("true") }

java - Redis throw exceptioon about "Read time out" -

i'm new redis, start server tutorial . , work. use write code using java connect redis, it's ok, this: jedis jedis = new jedis("localhost"); system.out.println("connection server sucessfully"); //store data in redis list jedis.lpush("tutorial-list", "redis"); jedis.lpush("tutorial-list", "mongodb"); jedis.lpush("tutorial-list", "mysql"); but, when use multithread push redis, throw exception "read time out": exception in thread "main" java.lang.reflect.invocationtargetexception @ sun.reflect.nativemethodaccessorimpl.invoke0(native method) @ sun.reflect.nativemethodaccessorimpl.invoke(nativemethodaccessorimpl.java:57) @ sun.reflect.delegatingmethodaccessorimpl.invoke(delegatingmethodaccessorimpl.java:43) @ java.lang.reflect.method.invoke(method.java:601) @ org.eclipse.jdt.internal.jarinjarloader.jarrsrcloader.m

vhdl - how to understand (clk'event and clk='1') -

since (clk'event , clk='1') commonly used describe rising edge event of clk signal, have following questions: (1) how understand "and"? mean "then"? (2) how (clk='1' , clk'event)? same above? thanks! "and" means logical "and", in "both of these things should true expression return true". yes, logically equivalent. having said this, should use in scenario rising_edge function, example if (rising_edge(clk)) then . , accompanying falling_edge function work correctly in more scenarios, , more readable.

ios - Core Data Lazy Loading with NSPrivateQueueConcurrencyType and custom setter not working -

problem: fetching managed object using background thread not lazy load nsmanaged object relationship correctly when nsmanaged object related has custom setter. doing fetch on main thread main concurrency type works without problem. why this? work around: if create custom getter on relationship object , check nil, can force nsmanaged object load calling other variables don't have custom setter methods. background core data layout pretty simple. have game managed object , turn managed object. turn object 1 one relationship game object. fetch game object in order access turn object. turnimp , gameimp implementation classes inherit game , turn object don't put getter/setter methods in auto generated code. code the fetch // //stick command on background // dispatch_async(dispatch_get_global_queue(dispatch_queue_priority_default, 0), ^ { // //load game // appdelegate *appdelegate = [[uiapplication sharedapplication] delegate]; coredatahelper *cor

tuples - python list reverse and merge -

i have these 2 lists a = [(0,1), (1,2), (3,4)] b = [[(0,1), (6,7), (8,9)], [(4,5), (7,15), (20,25)], [(18,17), (3,4)]] what need check if first tuple in exists in b merge reverse expected output is ab = [[(3,4),(1,2),(0,1),(6,7), (8,9)], [(4,5), (7,15), (20,25)], [(18,17),(3,4)]] my sample code is: import copy ab = copy.deepcopy(b) coord in b: if a[0] in coord: #print "yes", coord.index(a[0]) ab.insert(coord.index(a[0]), a[::-1]) print ab but doesn't give me output want. out there can help? thanks use list comprehension rebuild b : ab = [a[:0:-1] + sub if a[0] in sub else sub sub in b] the a[:0:-1] slice not reverses a , excludes first element of a prevent duplicates in output: >>> = [(0,1), (1,2), (3,4)] >>> b = [[(0,1), (6,7), (8,9)], [(4,5), (7,15), (20,25)], [(18,17), (3,4)]] >>> [a[:0:-1] + sub if a[0] in sub else sub sub in b] [[(3, 4), (1, 2), (0, 1), (6, 7), (8, 9)], [(4, 5), (7, 15)

r - Unscale and uncenter glmer standard errors -

as follow question unscale , uncenter glmer parameters , how can unscale , uncenter glmer standard errors? could provide function similar rescale.coefs standard errors? if needed, question referred above includes example.

algorithm - Big O or Big theta? -

suppose have function f(n)= log n , function g(n)=log n^2. question f(n)=o(g(n)) or f(n)=big_theta(g(n)). since log n^2 = 2 log n way put question can use fraction constant k? big_theta option, have k1=1/4 lower bound , k2=1 upper bound. okay? obviously, k cannot 0 or negative not sure fraction , did not see clear answer on web or in books looked in. thanks in advance help. both f(n)= Θ(g(n)) , f(n)= Θ(g(n)). please note @ same time true f(n)=o(g(n)). intuitively big-oh means f bounded above g(n)(i.e. grows no faster g). big theta on other hand means f bounded both above , below g(i.e. grows precisely fast g). please note last 2 sentences not absolutely precise purpose of being easier understand , focus on intuitive meaning of rather theory.

How can I override a function of type member in Scala? -

suppose have code: class c extends a#b { override def fun(): int = 100 } trait { type b = { def fun(): int } } the compiler says: class type required object{def fun(): int} found class c extends a#b { ^ how can understand error? you cannot extend structural type in scala. structural types denote bunch of methods type has define in order used @ places structural type expected. thus, sufficient write class c { def fun(): int = 100 } to pass objects of type c variables of b .

android - DialogFragment is not using my desired theme -

i have problem themes , styles in android when using different android versions. so main problem have dialogfragment popping @ point in application , contains edittext . alertdialog created this: alertdialog dialog = new alertdialog.builder(getactivity()) .setpositivebutton ... and edittext created , added this: editor = new edittext(getactivity()); dialog.setview(editor); on lollipop device, edittext has bottom line desired color. (c1 in list below). but on android 4.3 device, has standard ugly blue bottom line. my application has apptheme defines (among others) these items: <item name="colorprimary">@color/c1</item> <item name="colorprimarydark">@color/c2</item> <item name="coloraccent">@color/c3</item> <item name="colorcontrolnormal">@color/c1</item> <item name="colorcontrolactivated">@color/c2</item> <item name=

c# - Extension methods not showing even on implementing IEnumerable -

Image
this code: class myclass : ienumerable { public dictionary<int, string> dctidname = new dictionary<int, string>(); public myclass() { (int idx = 0; idx < 100; idx++) { dctidname.add(idx, string.format("item{0}", idx)); } } // ienumerable member public ienumerator getenumerator() { foreach (object o in dctidname) { yield return o; } } } where create object of class , use in manner not linq extension methods where , count , etc. myclass obj = new myclass(); var d = obj.where( x => x.key == 10); //<-- error here the namespaces have included are: using system; using system.collections; using system.collections.generic; using system.componentmodel; using system.data; using system.diagnostics; using system.drawing; using system.linq; using system.text; using system.th

javascript - Strange AngularJS behavior, values not updating in DOM -

i'm having issues in application i'm using setinterval poll server every x seconds check new messages, when finds them adds them sqlite database on application , updates object containing data displacement on screen. the issue values don't update automatically, can see in example provided through snippet below. click button , you'll notice t hat nothing happening in either ng-repeat or standard {{variable}} display. click button again , of sudden have results, they're inconsistent , explosive. var app = angular.module('app', []) .controller('ctrl', function($scope) { $scope.console = ""; $scope.arr = []; $scope.init = function() { setinterval(function() { $scope.arr.push("value"); }, 1000); }; $scope.start = function() { alert("started"); $scope.init(); }; }); <script src="https://ajax.googleapis.com/ajax/libs/angula

mysql - How to pass URL param from Angular to NodeJS(Express) to use it in SQL query? -

i have table , click on record(row) opens new view new url rowid clicked record (localhost/ 1 ). want pass rowid param url express , use in sql query. can making request server this $http.post('/load/:rowid',{'row_id': rowid}) .success(function(response){ //handle ok response }) .error(function(response){ //habndle error }) and use rowid in express search in database: app.get('/load', function(req, res) { var querystring = 'select * table row_id = rowid'; connection.query(querystring, function (error, results) { if(error) { throw error; } else { // got result: render res.end(json.stringify(results)); console.log(res); } }); }); and @ end data rowid show on frontend? $http.get('http://localhost/load').success(function (data) { data.foreach( function( row, index ) { $scope.push(data); });

regex - Error after updating to xcode 7 : Cannot invoke initializer for type 'NSRegularExpression' with an argument list of type -

get following error after updating xcode: "cannot invoke initializer type 'nsregularexpression' argument list of type '(pattern: string, options: nilliteralconvertible, error: nilliteralconvertible)'" following code cause error: func applystylestorange(searchrange: nsrange) { let normalattrs = [nsfontattributename : uifont.preferredfontfortextstyle(uifonttextstylebody)] // iterate on each replacement (pattern, attributes) in replacements { let regex = nsregularexpression(pattern: pattern, options: nil, error: nil)! regex.enumeratematchesinstring(backingstore.string, options: nil, range: searchrange) { match, flags, stop in // apply style let matchrange = match.rangeatindex(1) self.addattributes(attributes, range: matchrange) // reset style original let maxrange = matchrange.location + matchrange.length if maxrange + 1 < self.lengt

c - Random Array with no repeated numbers -

so trying create random array of 5 elements, elements should filled numbers 1 6 , shall not repeat, can't tell logic wrong. void gennumber(int vet[]){ int max, i, j, atual; srand(time(null)); max = 7; (i=0;i<5;i++){ vet[i] = rand() % max; while(vet[i] == 0){ vet[i] = rand() % max; } for(j=0;j<i;j++){ atual = vet[j]; while((vet[i] == atual)||(vet[i] == 0)){ vet[i] = rand() % max; atual = vet[j]; } } } } update: fixed void gennumber(int vet[]){ int max, i, j; srand(time(null)); max = 7; (i=0;i<5;i++){ vet[i] = rand() % (max-1) + 1; for(j=0;j<i;j++){ while(vet[j] == vet[i]){ vet[i] = rand() % (max-1) + 1; j = 0; } } } } the logical flaw in way produce new random number when duplicate found. imagine have vel = {1,2,0,0,0,...} , trying find number vel[2] . if randomly draw 2 , you'll find it

angularjs - Is it possible to have ui-views for non-nested states? -

say i've got state1 has children state1.child1 , state2.child2 . there's state2 has state2.child1 , state2.child2 . there way can put ui-view in state1.child1 view state2.child1 ? the answer no (as expected) . states hierarchical, , same applies views. so, cannot display child of 1 hierarchy in another's hierarchy parent. in case, wanted reduce amount of code (declaring same views , substates in different hierarchies) can use e.g. decorators: angularjs: how set 1 state global parent in ui-router (to use modal common parts) setting view's name decorator - angular ui router

objective c - Unity Plugin for iOS with UIViews like UICollectionView -

i building unity ios plugin other developers can integrate in unity projects. possible build unity plugin loads uiviewcontroller can contain uiviews uicollectionview show data web service. can uiviewcontroller come xib file? how handling of ios auto layouts, work within unity ios plugin? i new unity , seems me supports .h , .m files indicating i'll have programmatically create uiviews? after long time spent research, reading manage figure out steps develop unity plugin work existing objective-c cocoa touch framework binary. you need build regular unity plugin access objective-c code. the lazy coder has great tutorials on how that. recommend going through initial few videos before reading further. within .mm file can access unitygetglviewcontroller() gives access root view controller , can load view controllers in framework binary like: [unitygetglviewcontroller() presentviewcontroller: animated: completion:nil]; of type uiviewcontroller the cocoa touch framew

javascript - Request failing with "No 'Access-Control-Allow-Origin' header" -

i've created form using response (the email client) , trying use ajax on form create custom success/fail message. code works fine. when link ajax form stops working , receive below error message. appreciate help. error: xmlhttprequest cannot load https://app.getresponse.com/add_subscriber.html . no 'access-control-allow-origin' header present on requested resource. origin ' http://localhost:8888 ' therefore not allowed access. <form id="email-form-2" name="email-form-2" accept-charset="utf-8" action="https://app.getresponse.com/add_subscriber.html" method="post"> <input type="text" placeholder="your name" name="name"> <input type="text" placeholder="your email" name="email"> <textarea placeholder="your message..." name="custom_comment"></textarea> <input type=&quo

android - conditions satisfied by the APK to upload in play store? -

what conditions satisfied apk upload in play store? debug release,signed apk,keystore generation.and please explain them how do? a release build. should ensure not polluting logcat debugging statements. automatically flagged off may (as did) use different forms of debug logging (eg ndk) need explicit deactivation. you need sign apk also. can generate key , keystore offline development tools (i.e. android studio, can't remember eclipse ( how generate "keystore" google play? ) should work in instance). when register account on playstore need upload public key. can associate 20 (iirc) keys app's gms profile, although not strictly required upload app in general 1 of great benefits of play store account. see https://developers.google.com/android/guides/setup more on that. then if seeking financial reward, either via advertisemnet or direct sales need provide address. for service , also, suspect, purposes of identity verification, google require 1 of

java - How do I convert an object array into a map array? -

i have following code snippet: //create map array , fill 3 dummy maps map[] maparr= new map[3]; for(int = 0; < maparr.length; i++) { map map = new hashmap(); maparr[i] = map; } //now remove second element (index == 1) map array maparr = arrayutils.removeelement(maparr, 1); my problem witht final line of code, because no matter try error type mismatch: cannot convert object[] map[] how convert object[] returned removeelement() map[]? did try cast "map[]" ? maparr = (map[]) arrayutils.removeelement(maparr, 1);

mysql - Insert from same table with certain value -

i have table store meta data: id|meta_key|meta_value ======================== 1|gender |male 2|gender |female 3|gender |female 4|gender |male 5|gender |female now add salutation based on meta_value becomes id|meta_key |meta_value ======================== 1|gender |male 1|salutation|hello mr. 2|gender |female 2|salutation|hello mrs. 3|gender |female 3|salutation|hello msr. 4|gender |male 4|salutation|hello mr. 5|gender |female 5|salutation|hello mrs. while work foreach loop i'm searching single statement mysql can magic. you can use insert select : sqlfiddledemo insert table_name(id, meta_key, meta_value) select id, 'salutation' meta_key, case when meta_value = 'male' 'hello mr.' else 'hello mrs.' end meta_value table_name meta_key = 'gender';

c# - DataBinding is very slow -

i using windows application c#. when bind data table datagridview gets slow , getting sql connection timeout error. at same time data table has bulk records. how can solve problem? code: private void window_loaded(object sender, routedeventargs e) { con.statisticsenabled = true; con.open(); datatable dt = new datatable(); sqlcommand cmd = new sqlcommand("select * stktrn_table", con); sqldataadapter adp = new sqldataadapter(cmd); adp.fill(dt); griddisplay.itemssource = dt.defaultview; } sqlcommand cmdvoid = new sqlcommand("select party_no, smas_rtno,convert(numeric(18,2),sum(smas_netamount)) amount salmas_table ctr_no=@tcounter , smas_cancel<>1 , smas_rtno<>0 , smas_billdate=@tdate group smas_rtno, party_no", con); cmdvoid.parameters.addwithvalue("@tdate", dpbilldate.selecteddate.value); cmdvoid.parameters.addwithvalue("@tcounter", tcounternonew); sqldataadapter adpvoid = new sqldataa

mysql - update tables data from updated table - using merge-sql server and my sql -

i have 2 tables @ least 25 columns. customers updated_customers the columns names same. every day have changes in columns added, deleted , changed want use merge update customers (target table) updated_customers (source table). merge code is: merge customers trg using ( select [customerid] ,[type] ,[first_name] ,[last_name] ,[email] ,[phone] ,[sale_status] ,[verification] ,[campname] updated_customers ) src on src.[ customerid] =trg.[ customerid] when matched update set trg.[ customerid]=src.[ customerid] ,trg.[ type]=src.[ type] ,trg.[ first_name]=src.[ first_name] ,trg.[ last_name]=src.[ last_name] ,trg.[ email]]=src.[ email]] ,trg.[ phone]=src.[ phone] ,trg.[ sale_status]=src.[ sale_status] ,trg.[ verification]=src.[ verification] ,trg.[ campname]=src.[ campname] when not matched insert(trg.[customerid],trg.[ type]…) values(src.[ customerid],src.[type]…); end merge customers trg usin

r - Rsymphony OSX Installation failed -

i'm trying install rsymphony package on r on mac osx. following error: install.packages("rsymphony") package available in source form, , may need compilation of c/c++/fortran: 'rsymphony' want attempt install these sources? y/n: y installing source package 'rsymphony' trying url 'https://mirrors.ebi.ac.uk/cran/src/contrib/rsymphony_0.1-21.tar.gz' content type 'application/x-gzip' length 7429 bytes ================================================== downloaded 7429 bytes during startup - warning messages: 1: setting lc_ctype failed, using "c" 2: setting lc_time failed, using "c" 3: setting lc_messages failed, using "c" 4: setting lc_monetary failed, using "c" * installing *source* package 'rsymphony' ... ** package 'rsymphony' unpacked , md5 sums checked cannot find symphony libraries , headers. see <https://projects.coin-or.org/symphony>. error: configuration failed