Posts

Showing posts from August, 2010

python - IndexError : index out of bounds -

i have implemented multinomialnb message. please me solve it. here code : kf = kfold(len(x), n_folds=2, shuffle=true, random_state=9999) model_train_index = [] model_test_index = [] model = 0 k, (index_train, index_test) in enumerate(kf): x_train, x_test, y_train, y_test = x.ix[index_train,:], x.ix[index_test,:],y[index_train], y[index_test] clf = multinomialnb(alpha=0.1).fit(x_train, y_train) score = clf.score(x_test, y_test) f1score = f1_score(y_test, clf.predict(x_test)) precision = precision_score(y_test, clf.predict(x_test)) recall = recall_score(y_test, clf.predict(x_test)) print('model %d has accuracy %f | f1score: %f | precision: %f | recall : %f'%(k,score, f1score, precision, recall)) model_train_index.append(index_train) model_test_index.append(index_test) model+=1 and result : indexerror traceback (most recent call last) <ipython-input-3-df0b24edb687>...

immutability - RxJS with immutable datastructures? -

i'm working through rxjskoans , i'm seeing recurring pattern of feeding in array of results, subscriber pushes new values onto: var rx = require('rx'), subject = rx.subject var result = []; var s1 = new subject(); s1.subscribe(result.push.bind(result)); s1.onnext('foo'); result; // ['foo'] this impure function; result array mutated subscribe. i've seen small-scale projects on github make stab @ using immutable.js, none actively maintained. im wondering if there's widely-adopted immutable implementation pattern, , if not, why? i wouldn't call pattern, since can pass through stream can pass in immutable data structure: const stream$ = rx.subject.create(); stream$ .map(data => data.set('a', data.get('a') + 1)) .subscribe(data => console.log(data)); stream$.next(immutable.map({ a:1 })); stream$.next(immutable.map({ a:2 })); <script src="https://npmcdn.com/@reactivex/...

javascript - AngularJS + ng file upload + Sails JS -

i need send information each file upload. documentation says can achieve data parameter cant access action in sails controller. frontend: upload.upload({ url: '/file/upload', arraykey: '', data: { file: $scope.files, otherinfo: {user: user, person: 12 }}})..... sails js: req.file('file').upload({ dirname: '../../websrc/uploads' }, function(err, files) { if (err) return res.servererror(err); return res.json({ message: files.length + ' file(s) uploaded successfully!', files: files }); }); if log files, see x objects this: uploadedfilemetadata[0] extra: undefined fd: "/xxxxxxxxxxxxxx/uploads/24fd1f66-36df-40ec-bed3-45e18df77469.jpg" field: "file" filename: "xxxxxxxxxxxxxxxxxxxxxx.jpg" size: 199247 status: "bufferingorwriting" stream: passthrough type: "image/jpeg" how can send information each 1 of files , access server? $scope.uploadf...

ruby on rails - RoR: curl "upload completely sent off" -

rails version: 2.2.4. ruby version: 5.0.0.1 curl version: 7.50.1 hello people, i new ruby on rails programmer , need programm university authentication function ruby on rails through json request , on end can use authentication-function directly on android app. after hours of work made can registrate , login ruby on rails. followed deprecated tutorial ( http://lucatironi.net/tutorial/2012/10/15/ruby_rails_android_app_authentication_devise_tutorial_part_one/ ) , see how authentication function through json request. update: think messed create sessions controller right. created this: controllers/api/v1/sessions_controller.rb data , put text in it: class api::v1::sessionscontroller < devise::sessionscontroller skip_before_filter :verify_authenticity_token, :if => proc.new { |c| c.request.format == 'application/json' } respond_to :json def create warden.authenticate!(:scope => resource_name, :recall => "#{controller_pa...

html - Radio button's appearing one over another -

i have custom radio buttons on application. issue radio buttons display fine individually. when try have 2 of them in 1 line... appear on each other instead of beside each other. can't change html , can mess css. appreciated. thinking due width of each label giving low width had same result. html: <label class="radio"> <input type="radio"> <span class="custom"><span>one</span></span> </label> css: * { box-sizing: border-box; } input[type="radio"] { display: none; cursor: pointer; } label { cursor: pointer; } .radio span.custom > span { margin-left: 22px; } .radio .custom { background-color: #fff; border: 1px solid #ccc; border-radius: 3px; display: inline-block; height: 20px; left: 0; position: absolute; top: 0; width: 20px; } .radio input:checked + .custom:after { background-color: #0574ac; border-radius: 100%; border: 3px solid #fff; conten...

string - shortest repeated substring [PYTHON] -

is there quick method find shortest repeated substring , how many times occurs? if there non need return actual string ( last case ). >>> repeated('ctctctctctctctctctctctct') ('ct', 12) >>> repeated('gatcgatcgatcgatc') ('gatc', 4) >>> repeated('gatcgatcgatcgatcg') ('gatcgatcgatcgatcg', 1) because people think it's 'homework' can show efforts: def repeated(sequentie): string = '' in sequentie: if not in string: string += items = sequentie.count(string) if items * len(string) == len(sequentie): return (string, items) else: return (sequentie, 1) your method unfortunately won't work, since assumes repeating substring have unique characters. may not case: abaabaabaabaabaaba you on right track, though. shortest way can think of try , check on , on if prefix indeed makes entire string: def f...

python - Threads not exiting and program won't exit -

using script below, cannot seem exit threads. script runs smoothly without issues never exits when done. can still see thread alive, have use htop kill them or exit command line. how can script exit , threads die? def async_dns(): s = adns.init() while true: dname = q.get() response = s.synchronous(dname,adns.rr.ns)[0] if response == 0: dot_net.append("y") print(dname + ", y") elif response == 300 or response == 30 or response == 60: dot_net.append("n") print(dname + ", n") elif q.empty() == true: q.task_done() q = queue.queue() threads = [] in range(20): t = threading.thread(target=async_dns) threads.append(t) t.start() name in names: q.put_nowait(name) remove , return item queue. if optional args block true , timeout none (the default), block if necessary until item available. if timeout positive num...

CSS stylesheet not linking to html -

so trying use stylesheet background-image of html page. , isn't linking or isn't working. (yes html , css files within same directory/folder). this code have used <html> <head> <link href="stylesheet1.css" rel="stylesheet" type="text/css"> <body> <center> <p style="border:1px solid white; padding:15px; color:blue; font-family:courier; font-size:200%;"> welcome </body> </head> </html> and stylesheet code contains this. , in link type, have tried using /png/image. body { background-image: url("image-name-here.png"); backgound-repeat: no-repeat; background-position: center top; } and yes have tried replacing tag body head. you had spelling mistake in background-repeat , spelled backgound-repeat . also, if haven't already, there needs <body></body> tag in html. update html , <!doctype html> <html...

ios - didSelectRowAtIndexPath index path with uisearchcontroller -

i have application when user clicks on cell open viewcontroller , add uisearchcontroller on tableview. when searching on tableview result correct , when click on cell after filtering , opens wrong page. my problem don't how identify indexpath when uiviewcontroller active make result open correct page func tableview(tableview: uitableview, didselectrowatindexpath indexpath: nsindexpath) { indexpathrow = indexpath.row performseguewithidentifier("toview2", sender: self) } edit i solved problem adding new variable in struct of type integer , modify didselectrowatindexpath function func tableview(tableview: uitableview, didselectrowatindexpath indexpath: nsindexpath) { if resultsearchcontroller.active && resultsearchcontroller.searchbar.text != ""{ indexpathrow = filtereddata[indexpath.row].i } else { indexpathrow = indexpath.row } performseguewithidentifier("toview2", se...

oracle - How is it possible to insert and select inserted data in one SQL query? -

i have function insert_info(num in number) clears temp table's content , rewrites in data , adds amount of columns equal num arguments list. need call function , retrieve values temp table in 1 sql query, like: select insert_info(5), t.* dual, temp t however, old values table , after table content updated. i'm using oracle 10g. you this: create or replace function show_table_data(p_info in number) return temp%rowtype cursor c_temp select * temp; p_table c_temp%rowtype; p_status varchar2(4000) := insert_info(p_info); -- not sure function returns; begin open c_temp; fetch c_temp p_table; close p_table; return p_table; end; select show_table_data(5) dual;

c - Simple buffer overflow via xinetd -

i'm trying make simple buffer overflow tutorial runs program below service on port 8000 via xinetd. code compiled using gcc -o bof bof.c -fno-stack-protector ubuntu has stack protection turned off well. exploiting locally i.e python -c ---snippet--- | ./bof is successful , hidden function executed, displaying text file contents. however, running service , performing python -c ---snippet--- | nc localhost 8000 returns nothing when exploiting. missing here? #include <stdio.h> void secret() { int c; file *file; file = fopen("congratulations.txt", "r"); if (file) { while ((c= getc(file)) !=eof) putchar(c); fclose(file); } void textdisplay() { char buffer[56]; scanf("%s", buffer); printf("you entered: %s\n", buffer); } int main() { textdisplay(); return 0; } output buffered default. disable can following @ top of main: setbuf(stdin, null); this should...

Java Spring Scheduled job not working -

i have web application supposed run scheduled code: package com.myproject.daemon.jobs; import org.slf4j.logger; import org.slf4j.loggerfactory; import org.springframework.beans.factory.annotation.autowired; import org.springframework.scheduling.annotation.scheduled; import org.springframework.stereotype.component; @component public class mydaemonjob { private static final logger log = loggerfactory.getlogger(mydaemonjob.class); @postconstruct public void init() { log.info("mydaemonjob intialized " ); } @scheduled(fixeddelay = 1000) public void startdaemon() { try { log.info("mydaemonjob running ..."); } catch (exception e) { log.error("encountered error running scheduled job: " + e.getmessage()); } } } it surely recognized spring bean , initialized, can see postconstruct log. method @scheduled annotation never runs although supposed run every 1 second. h...

AngularJS and PHP object oriented scripts and sessions -

okay. it's theory based question angularjs. so, if had php based web app, , want use angularjs instead of pure js , jquery scripts. first of all, how save sessions while logging in ? and why oop php class not work angular, because didn't specify function execute. need split classes functions echo json result ? does angular append data directly page without using jquery basics of .append() or `.after() or... ? please, new angularjs, , need know how manage each of problems. know people gonna downvote, others reply.

pyspark - How to know how many files spark created after saving data frame -

i have data frame , im saving csv file databricks.spark.csv using save function on dataframe. how can know how many files spark created (spark dividing files automatically) +1 anshul's comment, can use getnumpartitions number of partitions of rdd, , number of file number. btw,why need know saved file number?

php - Combine two files -

i have 2 files want combine 2 files name in other file. my first file (3 columns id;name;comment): 2538;api plazza - nov-16;acceuil chef de projet... nicolas pour briefing. 2538;api plazza - nov-16;exposer les produits de jive software 2538;api plazza - nov-16;objectifs de securité.... ope = secirité ? 2538;api plazza - nov-16;moa hr pas simple... 2538;api plazza - nov-16;grosse pression pour livrer vite et en charge moe obs + consultant obs pour deploiement jive... my second file (2 columns id2;name): tk-135;api plazza - nov-16 i want have in third file (4 columns id2;id;name;comment). my code: $tab1 = file('fichier1'); $tab2 = file('fichier2'); $taille = count($tab2); for($i=0;$i<$taille;$i++){ $vars = explode(';',$tab2[$i]); $taille2 = count($tab1); //echo $vars[1]; for($j=0;$j<$taille2;$j++){ $vars2=explode(';',$tab1[$j]); ...

python - Input file doesn't exist even though the file is mentioned in the correct location- pyspark -

i'm trying read log lines forming key-value pairs error. code: logline=sc.textfile("c:\testlogs\testing.log").cache() lines = logline.flatmap(lambda x: x.split('\n')) rx = "(\\s+)=(\\s+)" line_collect = lines.collect() line in line_collect : d = dict([(x,y) x,y in re.findall(rx,line)]) d = str(d) print d error: line_collect = lines.collect()......invalidinputexception: input path not exist: file:/c:/testlogs esting.log i don't know how correct this. i'm new python , spark. try replace logline=sc.textfile("c:\testlogs\testing.log").cache() logline=sc.textfile("c:\\testlogs\\testing.log").cache() the backslash character not '\' in string rather "\\"

django - Creating a shortcut - Atom -

i need use shortcut creates {% %} in html file. use emmet doesn't support kind of syntax. know other packages allows or how create shortcut this? you can create own custom snippets django. there used package zen coding (the predecessor emmet), since snippets no longer stored in xml json (and new format simpler!) yet, use reference create own snippets. alternatively, take @ non-emmet django snippets .

Google Cloud SQL: Can I change machine type with zero downtime? -

we need change our google cloud sql instance db-g1-small db-n1-standard-1. can change 0 downtime? edit 1 i think found answer. seems take few seconds of downtime. you can change instance's tier @ time, few seconds of downtime. https://cloud.google.com/sql/pricing edit 2 i tried on our dev env. downtime 10 sec. while true; date; curl https://api.xxx.com/v1/items; echo ""; sleep 1s; done 2016/8/29 16:24:50 jst {"ok"} 2016/8/29 16:24:51 jst error 2016/8/29 16:25:01 jst {"ok"} the note changing tier in few seconds under first generation section of page. for second generation instance, may take several minutes.

mysql - Rails + Heroku: A foreign key constraint fails -

i trying seed mysql database rails project on heroku server , getting error: activerecord::invalidforeignkey: mysql2::error: cannot add or update child row: foreign key constraint fails ( heroku_b08bb4ad8dfb726 . posts , constraint fk_rails_5b5ddfd518 foreign key ( user_id ) references users ( id )): insert posts ( id , title , description , user_id , category_id , created_at , updated_at ) values (1, 'title', 'desc', 1, 1, '2016-08-29 06:53:04', '2016-08-29 06:53:04') surprisingly, not error in development environment. the extract of seed file looks this: # creating users here category.create!([ { id: 1, name: "category"}, ]) post.create!([ { id: 1, title: "title", description: "desc", user_id: "1", category_id: "1" }, ]) post model: class post < applicationrecord belongs_to :user belongs_to :category has_many :comments validates :title, :description, presence: tr...

CheckMarx scan on dot net application -

checkmarx scan complains "element’s value flows through code without being sanitized or validated , displayed user in method onitemdatabound " in places drop down values passed or selected.example: strtext = dropdownlist.selectedvalue; or return dropdownlist.selectedvalue; how sanitize these values?can htmlencode , decode apt avoid such vulnerability results? note dot net application. assuming referring xss vulnerability finding, resulting string other string, , controllable attacker. yes, should call htmlencode (or perform other type of sanitization, deoending on context, e.g. antixss) on string before embedding in html - other external data.

c# - Azure Service Bus timeout exception with NancyFX -

i have nancyfx api, , when 1 of endpoints hit, need kick of longer running asynchonous task that's decoupled endpoint itself. i'm trying use azure service bus queue. i'm writing message queue when nancyfx endpoint hit. can subscribe , read queue other nancyfx (i tested linqpad). however, if try subscribe nancyfx app, timeout exception within second or 2 starting app. i'm doing in thread kicked off nancyfx bootstrapper.applicationstartup override. i'm unsure why different doing not in nancyfx app. can't see of relevance in web.config file. below code i'm using subscribe queue ... var tokenprovider = tokenprovider.createsharedaccesssignaturetokenprovider("main", accesskey); var factory = await messagingfactory.createasync("sb://myapp.servicebus.windows.net", tokenprovider); var receiver = await factory.createmessagereceiverasync("myqueue"); receiver.onmessage(bm => { // here }, new onmessageoptions {...

How to play 1080p HD DICOM video @30fps -

i have tried leadtool sdk play 1080p dicom video @30fps, have problem read images dicom file, taking long time image dicom file. if have achieve 30fps frame rate, image should read within 33 milliseconds, because 33 milliseconds time between 2 frames 30fps frame rate. lead tool taking more 50 milliseconds read single image/frame of 1080p. therefore can't achieve 30fps frame rate 1080p video. leadtool can read 720p video file, without problem, problem there 1080p hd video. i using below code image. rasterimage image = _dataset.getimage(null, count++, 0, _dicomimageinformation.isgray ? rasterbyteorder.gray : rasterbyteorder.bgr | rasterbyteorder.rgb, dicomgetimageflags.none | dicomgetimageflags.autoloadoverlays); please, can suggest me solution or knows dicom library can enable play 1080p dicom video @30fps. it looks using leadtools still imaging support rather l...

Resize the textview according to the text content (swift) -

func tableview(tableview: uitableview, cellforrowatindexpath indexpath: nsindexpath) -> uitableviewcell { let cellframe = cgrectmake(0, 0, tableview.frame.width, 100) var retcell = uitableviewcell(frame: cellframe) var textview = uitextview(frame: cgrectmake(8,30,tableview.frame.width-8-8,65)) textview.layer.bordercolor = uicolor.bluecolor().cgcolor textview.layer.borderwidth = 1 retcell.addsubview(textview) if(reqgrpindex == 0){ reqgrpindex = reqgrpindex + 1 } } func textviewdidchange(textview: uitextview){ let fixedwidth = textview.frame.size.width textview.sizethatfits(cgsize(width: fixedwidth, height: cgfloat.max)) let newsize = textview.sizethatfits(cgsize(width: fixedwidth, height: cgfloat.max)) var newframe = textview.frame newframe.size = cgsize(width: max(newsize.width, fixedwidth), height: newsize....

Detecting midi controller pads in Quartz Composer -

i'm trying use 8 pads , 8 knobs of akai lpd8 midi controller in quartz composer, can control patch parameters. i have mapped 8 knobs, via midi controller receiver patch, , learn controller button: added 1 parameter patch each knob. unfortunately, 8 pads aren't detected in learn mode, , haven't been able map them patch parameters in way. do know how this? thanks time! use must activate 1 of pad/prog chng/cc modes configure kind of message pads send. (learning note-on or program change messages not make sense.)

mysql - Does COUNT() run twice? -

i've code: "select post_id, count(post_id) number_of_votes, (sum(vote) / count(post_id)) result " . log_table . " , $wpdb->posts p post_id = p.id , p.post_status = 'publish' group post_id having count(post_id) >= 2 order result desc, count(post_id) desc limit 10 " i'd know if count used in first row run twice? edit: run twice mean if acces table twice best regards, dario unless using subqueries of below form,table accessed once(if meant count, accessed twice),so count calculated once , used everywhere select id,(select min(id) table1 t2 t1.id=t2.id)b table1 t1

Python way of doing difference of lists containing lists -

consider 2 lists , b. know list(set(a) - set(b)) give difference between , b. situation whereby elements in both , b lists. i.e. , b list of list? e.g. a = [[1,2], [3,4], [5,6]] b = [[3,4], [7,8]] i wish return difference a - b list of list i.e. [[1,2],[5,6]] list(set(a) - set(b)) typeerror: unhashable type: 'list' the idea convert list of lists lists of tuples, hashable , are, thus, candidates of making sets themselves: in [192]: c = set(map(tuple, a)) - set(map(tuple, b)) in [193]: c out[193]: {(1, 2), (5, 6)} and 1 more touch: in [196]: [*map(list, c)] out[196]: [[1, 2], [5, 6]] added in python 2.7 final touch simpler: map(list, c)

Weird behaviour about bluetooth on Android when sending high frequency data -

i doing project receiving ecg signal ecg sensor. @ first connect ecg sensor bluetooth transmitter using arduino , connect bluetooth dongle pc using usb port. i use processing write program in pc receive data arduino output ecg signal through bluetooth, , received data in pc expected. however, when tried write android app receive bluetooth data, found there data loss, , received not same received in pc. why that? there differences between android bluetooth , bluetooth dongle in pc? i have found if use android receive ecg data through bluetooth, android receive several ecg data in 1 packet, not case if use pc receive bluetooth data. my devices: arduino + ecg sensor + bluetooth transmitter. pc + bluetooth dongle (connected using usb port) android 1+2 can produce want, 1+3 cannot. since sending ecg signal, data transmission rate near 1000hz, , baud rate used 115200. therefore, wonder why android receive bluetooth differently pc bluetooth dongle.

java - Catch EJBTransactionRolledbackException before it is logged to file -

my setup: i have ejb bean (deployed in ear on jboss 6.4) method calculates values , stores in database. method started in new transaction. looks this: @transactionattribute(transactionattributetype.requires_new) public void dostuff() { myobject value = calculatesomevalues(); entitymanager.merge(value); entitiymanager.flush(); } by design, possible flush fail due constraintviolationexception . new transaction, exception wrapped in ejbtransactionrolledbackexception , thrown runtimeexception . have set logging ejb exceptions useful find them in whole system. know constraintviolationexception occur , then, catch , rollback before logging system logs error (the constraint violation not seen exception, required database's point of view). @ moment, log file clogged entries one: error [org.jboss.as.ejb3.invocation] (default-threads - 49) jbas014134: ejb invocation failed on component how can catch exception in such way logger prevented printing these errors? (no...

Mysql and php w/ html database issue -

i want data sql database table html. i have writed 1st part of code ended ?> and started html table , end html my code getting empty table without getting data database, here code, dont know how data <td> <?php echo $result['nazwiskoimie'] ?> </td> here's full code : <?php $con=mysqli_connect("localhost","root","","listap"); if (mysqli_connect_errno()) { echo "blad przy polaczeniu z baza: " . mysqli_connect_error(); } $result = mysqli_query($con,"select * 'lista'"); ?> <html> <table border='1'> <tr> </tr> <tr> <td> <?php echo $result['nazwiskoimie'] ?> </td> //in part have problem data database </html> here's screenshot of result: final after save file please try this: $result = my...

Cuda, two streams created by a NPP function -

i'm working on image processing project cuda 7.5 , geforce gtx 650 ti. decided use 2 stream, 1 apply algorithms responsible enhance image , stream apply independent algorithm rest of processing. i wrote example show problem. in example created stream , used nppsetstream. i invoked function nppithreshold_ltvalgtval_32f_c1r 2 stream used when function executed. here there's code example: #include <npp.h> #include <cuda_runtime.h> #include <cuda_profiler_api.h> int main(void) { int srcwidth = 1344; int srcheight = 1344; int paddstride = 0; float* srcarraydevice; float* srcarraydevice2; unsigned char* dstarraydevice; int status = cudamalloc((void**)&srcarraydevice, srcwidth * srcheight * 4); status = cudamalloc((void**)&srcarraydevice2, srcwidth * srcheight * 4); status = cudamalloc((void**)&dstarraydevice, srcwidth * srcheight ); cudastream_t teststream; cudastreamcreatewithflags(&teststream, cudastreamnonblocking); nppsetstream(te...

android - Facebook login in fragment -

i use facebook login in app. have registred app , added sdk project. however, tried follow tutorial documentation nothing worked (i need id , email profile , send to server). fragment public class loginfragment extends fragment { @bindview(r.id.ivlogo) imageview ivlogo; @bindview(r.id.email) edittext edemail; @bindview(r.id.password) edittext edpassword; @bindview(r.id.btnfblogin) loginbutton btnfblogin; private callbackmanager callbackmanager; private accesstokentracker accesstokentracker; private profiletracker profiletracker; string email, password, id; user user; public loginfragment() { // required empty public constructor } public static loginfragment newinstance() { loginfragment fragment = new loginfragment(); bundle args = new bundle(); fragment.setarguments(args); return fragment; } @override public void oncreate(bundle savedinstancestate) { super.oncreate...

python - Can't run crontab without excecuting the programm once -

i wrote script.py should open tkinter window on raspberry: from tkinter import * import turtle import math import time import sys import os root = tk() root.config(cursor="none") ccanvas = canvas(root, width = 800, height = 480) root.overrideredirect(1) turtle_screen = turtle.turtlescreen(ccanvas) ccanvas.pack() turtle = turtle.rawturtle(turtle_screen) turtle.hideturtle() mainloop() i able run script command line with: python /home/pi/script.py when tried run via crontab first display not found. fixed with: display=:0 python /home/pi/script.py but following error: _tkinter.tclerror: couldn't connect display ":0" until execute script.py once manual in cmd. crontab able execute script.py without error. how can fix that? finally solved problem. fine, using root crontab . root crontab not able find display, before display not mentioned/used command. transferred cronjobs "normal" crontab , works fine. point commands, ne...

ios - How to set title of navigationitem which have titleview for some conditions -

i have navigationitem titleview . in conditions want use title property navigationitem . how that? idea? here have tried, not working: self.revealviewcontroller().navigationitem.titleview = uiview.init() self.revealviewcontroller().navigationitem.title = "my item" before set title, need set titleview nil.

python - Multiple "finally" clauses/"with" statements added on the fly? -

let's writing code need fail-safe section - in case of failure - save me wasting money. example, code buys virtual servers via aws api , since paid per hour, it's preferable shut them down stop being useful. the problem is, don't know how many such instances use , create them on fly, adding them list or whatnot. "destructor" of each of instance might have unexpected exception , because of that, i'm afraid code finally clause ugly. cannot think of how use with because introducing objects on fly. other fail-safe solutions use python?

lucene - Segments in solr index gets deleted after every restart -

i have issue respect increasing space on solr servers. whenever see allocated space full particular server, perform service solr restart , clears space , things work there time. again builds , space utilization 100% warning. while debugging this, found every solr restart, couple of collections, there segments gets deleted. means, 1 segment, corresponding .nvm, .fdx, .tvx, .si etc gets deleted. eg: 1 such segment deleted after restart: _on0.nvm, _on0.si, _on0_lucene50_0.dvm,_on0.fnm,_on0.fdx,_on0.tvx, _on0_lucene50_0.tip, _on0.nvd, _on0_lucene50_0.tim, _on0.fdt, _on0_lucene50_0.dvd, _on0_lucene50_0.doc, _on0_lucene50_0.pos, _on0.tvd can please explain happening behind scenes such behavior? have solr cloud solr version being 5.2.1 , lucene version 5.2.1. can provide solrconfig.xml collections please check directoryfactory settings if set toramdirectoryfactory. ramdirectoryfactory memory based, not persistent, , doesn't work replication possible segments c...

sql server - Azure SQL Database Corruption - Tables Missing -

we have windows service provisions azure sql databases our clients. using microsoft.windowsazure.management.sql api. have database named "green" in server located in 'east asia', server version 'v12'. today found database data not found. tables, stored procedures , data missing. restoring deleted azure sql database using azure portal to restore database in azure portal following: open azure portal. on left side of screen select browse > sql servers. navigate server deleted database want restore , select server scroll down operations section of server blade , select deleted databases: restore azure sql database select deleted database want restore specify database name, , click ok:

javascript - how to convert a div values into a csv file in a specific file name and specific path -

i having div element consists of table. table values taken fron json array , have create new row of array , displayed ina table using export button have export table valus in csv file in specific filename , in specific path. export: $("#export").click(function(e) { alert('inside export method'); var = document.createelement('a'); //getting data our div contains html table var data_type = 'data:application/vnd.ms-excel'; var table_div = document.getelementbyid('exportdata'); var table_html = table_div.outerhtml.replace(/ /g, '%20'); alert(table_html); a.href = data_type + ', ' + table_html; //setting file name alert("pname"+pname); a.download = 'export.xls'; alert('after got id'); //triggering function a.click(); //just in case, prevent default behaviour e.preventdefault(); }); this code xls have store values in c...

sockets - Linux (uclinux 2.4.x) -

i have 1 doubt. using uclinux 2.4.x. in linux have own adapter code reading frames ingress port. have added debug log @ exact place reading frames word word , sure received number of frames transmitted peer. ( @ layer2 receiving frames). from here onward invoking "netif_rx" send received framer upper layer (i.e network layer , transport layer). doubt : observe there drop of packets @ (transport layer)udp protocol. how did confirm: added count check @ layer 1 , layer3(udp layer) , both counts not equal. that means if receiving framer layer 1 when reaching udp in between somewhere drop happening. so, 1 suggest problem be, how check if memory full or skb_alloc not happening more packets @ udp layer. kindly suggest opinion, of great , support. please let me know if need more information. br karn

javascript - Get params from URL using $stateParams, UI-router. Undefined Value -

i passing value 1 state using ui-router. in controller when url updated trying access second parameter of url using $stateparams , reason can access first parameter second 1 undefined . code: state 1, url: http://localhost:16009/#/5nqeapqlv21/ state 2, url: http://localhost:16009/#/5nqeapqlv21/details/pp163ku3dor candidatecontoller.js: //go state 2 (same controller parent , child views) $state.go('index.details', { "submissionidd": publicsubmissionid }); //when located in new state , new url: console.log($stateparams.submissionidd); //shows undefined console.log($stateparams.token); //shows 5nqeapqlv21 app.js: $stateprovider .state('index', { url: '/:token/', views: { '': { templateurl: 'angularjs/templates/indexview.html', controller: 'candidatecontroller candctrl' }, 's...

Simple JavaScript function returns function and not value -

i'm starting out , i'm trying build simple calculation function display result of 2 numbers on page. when submit button hit output function , not value. have gone wrong? html <div id="input"> <form id="start"> <input id="price" type="number" placeholder="what starting price?" value="10"> <input id="tax" type="number" value="0.08" step="0.005"> </form> <button type="button" form="start" value="submit" onclick="total()">submit</button> </div> <div id="test">test</div> js <script> 'use strict'; var total = function() { var price = function() { parsefloat(document.getelementbyid("price")); } var tax = function() { parsefloat(document.getelementbyid("tax")); } var final = function() { final = price * ta...

java - How to use CompositeDisposable of RxJava 2? -

examples on how use compositedisposable or disposable in rxjava2. in rxjava 1, there compositesubscription, not present in rxjava2, there compositedisposable in rxjava2. how use compositedisposable or disposable in rxjava2. private final compositedisposable disposables = new compositedisposable(); // adding observable disposable disposables.add(sampleobservable() .subscribeon(schedulers.io()) .observeon(androidschedulers.mainthread()) .subscribewith(new disposableobserver<string>() { @override public void oncomplete() { } @override public void onerror(throwable e) { } @override public void onnext(string value) { } })); static observable<string> sampleobservable() { return observable.defer(new callable<...

Drupal ubercart product import with feeds -

i use drupal 7 postgres database. created product importer feeds module import basic datas, doesn't import sku, cost, list price... in picture want import cikkszám (sku in english) first. feeds problem pic i didn't find solution. can me? thanks! try tamper module plugins https://www.drupal.org/project/feeds_tamper seek patches or go commercekickstart package, imports products without bugs ubercart has (personal experience), has many other troubles, ubercart has not...

docker-compose with multiple databases -

i'm trying figure out how implement docker using docker-compose.yml 2 databases imported sql dumps. httpd: container_name: webserver build: ./webserver/ ports: - 80:80 links: - mysql - mysql2 volumes_from: - app mysql: container_name: sqlserver image: mysql:latest ports: - 3306:3306 volumes: - ./sqlserver:/docker-entrypoint-initdb.d environment: mysql_root_password: root mysql_database: dbname1 mysql_user: dbuser mysql_password: dbpass mysql2: extends: mysql container_name: sqlserver2 environment: mysql_root_password: root mysql_database: dbname2 mysql_user: dbuser mysql_password: dbpass app: container_name: webdata image: php:latest volumes: - ../php:/var/www/html command: "true" the above returns following: kronos:mybuild avanche$ ./run.sh creating sqlserver creating webd...

http status code 404 - Drupal 8 - Nginx 1.10.1 Ubuntu - 14.04 - 404 Not found after installation is completed -

i wonder if can on please. installed drupal 8 on ubuntu 14.04 (webserver nginx 1.10.1) wiht php-fpm. issue - created test site part of installation set , once installation finished, 404 not found error. can access - http://hostname/sitename/index.php gives me home page when try access let's (content, appearance, structure etc) 404 not found. grateful if can me on this. drupal uses apache's mod_rewrite via .htaccess rewrite urls front controller (i.e. index.php). have configure nginx rewrites because nginx not have mod_rewrite . i not use nginx cannot directly, searched configurations help: http://valuebound.com/resources/blog/drupal8-nginx-default https://www.nginx.com/resources/wiki/start/topics/recipes/drupal/ hope gets on right path.

ios - IBOutlet for image button not correctly referencing button after recreating outlet -

i have custom button image. have iboutlet reference in viewcontroller.swift file. the button working hooked wrong outlet. removed of outlets , actions button , similar buttons , remade them. @ point stopped working. i first tried change image button code: star1backbuttonreference.setimage(uiimage(named: "starfull_48dp.png"), forstate: this didn't anything. after thinking problem code changing image decided check few things. so tried hide button this: star1backbuttonreference.hidden = true this did not either think there problem iboutlet reference star1backbuttonreference , found instance change/hide image , reference. the reference this: @iboutlet var star1backbuttonreference: uibutton! i checked referencing outlet on storyboard , correct (one side viewcontroller other side star1backbuttonreference). there must mistake have done in connecting outlet or deleting old one. if deleting referencing outlet must remove it's reference conn...

java - Regular expression number -

my target format next number 01122222222 011-22-22-22-22 first 3 numbers of number, dash , next numbers dash after second one. tried: private string phoneformat(string phonenumber){ string regex = "\\b(?=(\\d{3})+(?!\\d))"; string formattedphone = phonenumber.replaceall(regex, constants.characters.dash); return formattedphone; } but produce different result. a regex trick. replace sets of 2 digits "-[digit][digit]" long have 3 digits before those. public static void main(string[] args) { string s = "01122222222"; system.out.println(s.replaceall("(?<=\\d{3})(\\d{2})+?", "-$1")); } live example o/p : 011-22-22-22-22 ps : approach should not used in prod environment , has been written solely please own stubbornness problem can solved using 1 regex.

java - RequestBody + JSON -

i have problem convert json java class. controller @requestmapping(value = "/{username}/add", method = post) public void add(@requestbody notemodel note) { system.out.println(note.gettitle()); } json { title : "title", text : "text" } notemodel public class notemodel { private string title; private string text; public string gettitle() { return title; } public void settitle(string title) { this.title = title; } public string gettext() { return text; } public void settext(string text) { this.text = text; } } so, when send json controller, controller see same url, can't deserialize json java (i think). because, when try, send json - { title : "title" } , , controller wait argument - @requestbody string note , can display it. i'm try do, in https://gerrydevstory.com/2013/08/14/posting-json-to-spring-mvc-controller/ , inclu...

c# - Comparing two list using lambda expression -

i want list of string based in 2 lists lstjobs , lstpraudits. want planid common in both list. here code- list<string> result=reviewmodel.lstjobs.select(x=>x.planid.contains(reviewmodel.lstpraudits.slect(y=>y.planid).tolist())); what doing wrong here. code giving error message. use enumerable.intersect : list<string> result = reviewmodel.lstjobs.select(x=> x.planid) .intersect(reviewmodel.lstpraudits.select(y=> y.planid)) .tolist(); what doing wrong here your approach wrong because x.planid.contains search substrings , passing list method. it's wrong approach anyway because don't want compare substrings.

perl - Why does a match against regex $ return 1 when the input string contains a newline? -

why command perl -e "print qq/a\n/ =~ /$/" print 1 ? as far know, perl considers $ position both before \n position @ end of whole string in multi-line mode, default (no modifier applied). the match operator returns 1 true value because pattern matched. print outputs value. the $ anchor, specific sort of zero-width assertion. matches condition in pattern consumes no text. since have nothing else in pattern, /$/ matches target string including empty string. return true. the $ end-of-line anchor, documented in perlre . $ allows vestigial newline @ end, both of these can match: "a" =~ /a$/ "a\n" =~ /a$/ without /m regex modifier, end of line end of string. but, modifier can match before newline in string: "a\n" =~ /a$b/m you might behavior if don't see attached particular match operator since people can set default match flags: use re '/m'; # applies in lexical scope over-enthusiastic fans o...

python - Can you annotate return type when value is instance of cls? -

given class helper method initialization: class trivialclass: def __init__(self, str_arg: str): self.string_attribute = str_arg @classmethod def from_int(cls, int_arg: int) -> ?: str_arg = str(int_arg) return cls(str_arg) is possible annotate return type of from_int method? i'v tried both cls , trivialclass pycharm flags them unresolved references sounds reasonable @ point in time. use generic type indicate you'll returning instance of cls : from typing import type, typevar t = typevar('t', bound='trivialclass') class trivialclass: # ... @classmethod def from_int(cls: type[t], int_arg: int) -> t: # ... return cls(...) any subclass overriding class method returning instance of parent class ( trivialclass or subclass still ancestor) detected error, because factory method defined returning instance of type of cls . the bound argument specifies t has (subclass ...

javascript - Can ServiceWorker be notified at selected time in offline? -

say, want make alarm clock app on android progressive web app. like native alarm app, should notified @ selected time without active web page. at first, considered using push api. of course push message cannot arrived while offline. , push message arrival time cannot accurate enough alarm clock. is possible notified @ time without network connection? what you're describing functionality that's more closely tied periodic background sync , rather push notifications, in push notifications require network connection. periodic background sync has advantage of being network-independent. (periodic background sync proposal right now, , hasn't been implemented in browsers.) but , unfortunately use case, periodic background sync explicitly not designed events need triggered @ precise time, needed make alarm clock useful. that's explicitly called out in proposal: what periodic sync not periodic sync not exact alarm api. scheduling granularity in ...

r - Some Unicode characters not displayed in RMarkdown PDF output -

Image
i'm trying put course notes pdf, , having trouble getting unicode characters display properly. using xelatex latex engine necessary document rendered @ (using default engine results in error due unrecognized characters), however, first unicode character (uppercase delta) displayed properly. for example, when using rmarkdown render() function render following .rmd file: --- output: pdf_document: latex_engine: xelatex --- - works - Δ - doesn't work - ⌘ the resulting pdf shows first unicode character (uppercase delta), , not later 1 (looped square). i know there different character subsets make full utf-8 character encoding, seems perhaps more basic subsets supported. just certain, checked encoding of file using iconv -f utf-8 your_file -o /dev/null [ 1 ], , indeed appear valid utf-8 document. finally, document renders fine html using default options, issue specific pdf output. any ideas how second character render pdf? system information linu...

Matlab Help code Script -

i working matlab, have data row vector 36000. wold cut vector matrix- first column of matrix must first 300 data samples of vector, , second row must second 300 samples (301 600), , on. please need matlab script that, please body can me ?? just use reshape reshape vector matrix 300 rows. b = reshape(a, 300, []); also switch columns , rows in question. example above places data in column-major order. if want row-major instead, take transpose. b = reshape(a, 300, []).';

c# - FlowDocument page load based on the next page button click -

i loading huge document more 25mb flowdocument. , fine, it's taking more cpu or long time during initialization load entire data flowdocument. instead of there way load page dynamically based on next page click in bottom of flowdocument control. sample code of flow document. <scrollviewer horizontalalignment="stretch"> <groupbox> <groupbox.header> <textblock text="standard output"></textblock> </groupbox.header> <flowdocument name="flowdocument" columnwidth="999999" background="transparent" iscolumnwidthflexible="true" > <paragraph name="para" background="transparent" textalignment="justify" keeptogether="true"> </paragraph> </flowdocument> </groupbox> ...

c# - Passing argument to Class method -

i have problem passing argument class. want pass every iteration fill array. private string[,] links; (int = 0; < 40; i++) { links = sql.link(i); } and that's method inside class: public string[,] link(int i) { sqlcommand sqlcommand = new sqlcommand(); string[,] array = new string[40,40]; int num = 0; sqlcommand.connection = this.conn; sqlcommand.commandtext = "select top (40) link dbo.links"; sqldatareader sqldatareader = sqlcommand.executereader(); while (sqldatareader.read()) { array[i,num] = sqldatareader.getvalue(0).tostring(); num++; } sqldatareader.close(); return array; } the thing is, links array contains nulls. when change passing code to: links = sql.link(0); then every index 0,0 0,39 filled. why passing not work properly? because, in following line string[,] array = new string[40,40]; gener...