Posts

Showing posts from June, 2014

.net core - How to unit test ActionFilterAttribute -

i'm looking test actionfilterattribute in .net core 2.0 api project , wondering best way go it. note, i'm not trying test through controller action, merely test actionfilterattribute itself. how might go testing this: public class validatemodelattribute : actionfilterattribute { public override void onactionexecuting(actionexecutingcontext context) { if (!context.modelstate.isvalid) { context.result = new badrequestobjectresult(context.modelstate); } } } create instance of context pass filter , assert expected behavior for example [testclass] public class validatemodelattributetest { [testmethod] public void invalid_modelstate_should_return_badrequestobjectresult() { //arrange var httpcontext = new defaulthttpcontext(); var context = new actionexecutingcontext( new actioncontext { httpcontext = httpc

npm - gulp error: "SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode" -

running gulp on checked-out js project resulted in syntax error. previous "npm install" had completed successfully, , looks dependencies met. running gulp correct project folder , gulpfile resident. solution = upgrade node.js @ least lts version.

asp.net - The controller for path '/default.aspx' was not found or does not implement icontroller after upgrading from MVC1 to MVC2 -

i upgraded asp.net project mvc1 mvc2 in visual studio 8 , .net3.5 following instruction https://docs.microsoft.com/en-us/aspnet/whitepapers/aspnet-mvc2-upgrade-notes . there no compile errors when ran application, got "the controller path '/default.aspx' not found or not implement icontroller" exception. before upgrading mvc2 working well. this default.aspx: <script runat="server"> protected override void oninit(eventargs args) { var httpcontext = httpcontext.current; httpcontextbase contextwrapper = new httpcontextwrapper(httpcontext); var routedata = getroutedata(contextwrapper); var httphandler = routedata.routehandler.gethttphandler(new requestcontext(contextwrapper, routedata)); httphandler.processrequest(httpcontext); } private static routedata getroutedata(httpcontextbase context) { return routetable.routes .select(route => route.getroutedata(context)) .firsto

php - update sum of columns in a sql table -

i have table named resources following columns: ress1 ress2 prod1 prod2 i've tried code indicated in following links, i'm still stuck... how find sum of multiple columns in table in sql server 2005? auto update sum of rows & columns in table sql how update sum of column on group in same table i want run script update ress1 = ress1 + prod1 , same ress2 . want update column sum of column , corresponding column, doing every rows table. here code seems easy me, not working... $sql = "select * ro_map"; $result = mysqli_query($conn,$sql); while($row = mysqli_fetch_assoc($result)){ $new_a = $row['a'] + $row['c']; $new_b = $row['b'] + $row['d']; "update ro_map set = '$new_a',b = '$new_b'"; } ah...really sorry, guys :d use mysql (with wampp server , heidisql). , running code don t give me error ( if($conn->$sql == true) give me true... solved! cool, all, i've learned :)

ubuntu 16.04 - opendkim-testkey: [path]/dkim.key: open(): permission denied -

i installed postfix on ubuntu 16.04 lts server , tested default settings. able send test email successfully. wanted add dkim, started running problem. emails don't seem getting signed. when run opendkim-testkey -d mydomain.com -s mail -vvv i get opendkim-testkey: /etc/postfix/dkim.key: open(): permission denied ownership , permissions /etc/postfix/dkim.key -rw------- 1 opendkim opendkim 887 sep 7 16:07 dkim.key postfix part of opendkim group postfix : postfix opendkim i hope has idea, because i'm here scratching head on one. so, problem in /etc/opendkim.conf i forgot uncomment , edit lines: # sign example.com key in /etc/dkimkeys/dkim.key using # selector '2007' (e.g. 2007._domainkey.example.com) domain mydomain.com keyfile /etc/dkimkeys/dkim.key selector mail these commented out. had purged , reinstalled opendkim , forgot step. hopefully give else when have brain fart me! ;-)

android - Show data in RecyclerView from firebase -

i want show firebase database in recyclerview when open activity app stopped. this xml : <android.support.v7.widget.recyclerview android:id="@+id/rec" android:layout_width="match_parent" android:layout_height="match_parent"> </android.support.v7.widget.recyclerview> and adapter class : class adapter( private val cartlist: arraylist<card>,val context: context): recyclerview.adapter<adapter.myviewholder>() { override fun oncreateviewholder(viewgroup: viewgroup, viewtype: int): myviewholder { val view = layoutinflater.from(viewgroup.context).inflate(r.layout.tkt_all_station, viewgroup, false) return myviewholder(view) } override fun onbindviewholder(holder: myviewholder, position: int) { val cart:card = cartlist[position] holder.title.text = cart.station holder.msg.text = cart.x.tostring() holder.date.text = cart.y.tostring() } override fun getitemcoun

javascript - Posting values from dynamically created table rows to ActionResult in a Controller -

Image
i'm struggling piece of code, i'm beginner in mvc , web technologies in general , received project friend practice it, , saw 1 confusing part! he adding rows bootstrap table dynamically. idea post list objects rows, many rows objects. here example of how rows looks: here example of entity : public class parameters : basedateentity { public decimal value1{ get; set; } public decimal value1{ get; set; } public decimal value1{ get; set; } public decimal value1{ get; set; } } and idea post list of object "parameters" actionresult method, , famous code looks strange me, , can't values textboxes cause don't know how handle cuz don't understand it: var modellistitem = function (item) { $('<input/>', { id: "hiddenselectedtableitemindex_" + item.id, name: "parameters.index", type: "hidden", value:

python - ValueError: Shapes (69, 44, 2) and (69, 2, 2) are incompatible -

using tensorflow version 1.3.0 in python 3.5.2. i'm trying build convolution neural network takes in data 69 rows , 44 independent values perform binary classification (that is, either jump or fall), keep getting error: valueerror: shapes (69, 44, 2) , (69, 2, 2) incompatible i'm not sure code changes size 44 columns down 2. code network i've constructed tensorflow tutorial mnist database has been modified address data/problem. main differences being, i'm using conv1d() instead of conv2d(), , i'm not using pooling layers. code follows: def cnn_model_fn(features, labels, mode): """model function cnn.""" # input layer #-1 filled 69 later on #44 used independent vars, 1 must used input in tf.layers.conv1d() input_layer = tf.reshape(features["x"], [-1, 44, 1]) # convolutional layer #1 conv1 = tf.layers.conv1d( inputs=input_layer, filters=32, kernel_size=1, padding="same&quo

javascript - Will this custom element work? I've taken it off Material Design lite -

class cardelement extends htmlelement { constructor() { super(); let shadow = this.attachshadow({mode: open}); let div = document.createelement('div'); let div_main = div; div_main.classname = "demo-card-square mdl-card mdl-shadow--2dp"; shadow.appendchild(div_main); let div_sec = div; div_sec.classname = "mdl-card__title mdl-card--expand"; div_sec.style.background = this.getattribute('src'); shadow.appendchild(div_sec); let h2 = document.createelement('h2'); h2.classname = "mdl-card__title-text"; h2.innerhtml = this.getattribute('text'); shadow.appendchild(h2); let div_three = div; div_three.classname = "mdl-card__supporting-text"; div_three.innerhtml = this.getattribute('support-text'); shadow.appendchild(div_three); let div_border = div;

css - Media Queries for Ratio not triggering -

i trying test ratio media queries: for example: @media screen , (min-aspect-ratio: 8/5) { ... } see full code: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> .mq { border: 2px solid; padding: 20px; width: 300px; resize: both; overflow: auto; } @media screen , (min-aspect-ratio: 8/5) { .mq { background-color: red; } } </style> </head> <body> <div class="mq"> text here. div can resized. </div> </body> </html> the problem code above supposed go red when ratio 18/5 it's red. what wrong code? your code fine, css says need ratio of @ least 8/5, if drag screen size around should see change when window taller wide. if want have effect div, not window, you'll need handle javascript instead of media query. var $div = $

python - How to count the number of the same instances in a column of a data frame in a rolling window -

i trying count number of same id inside of each sliding window data: id date 2017-05-17 15:49:51 s_2 2017-05-17 15:49:52 s_5 2017-05-17 15:49:55 s_2 2017-05-17 15:49:56 s_3 2017-05-17 15:49:58 s_5 2017-05-17 15:49:59 s_5 i trying count number of same id inside rolling window of size 3 overlap each other. answer should this: date id s_2_count s_3_count s_5_count 2017-05-17 15:49:51 s_2 2 0 1 2017-05-17 15:49:52 s_5 1 1 1 2017-05-17 15:49:55 s_2 1 1 1 2017-05-17 15:49:56 s_3 0 1 2 2017-05-17 15:49:58 s_5 nan nan nan 2017-05-17 15:49:59 s_5 nan nan nan use str.get_dummies , rolling , sum , shift , , add_prefix : df.id.str.get_dummies().rolling(3).su

java - Parsing Odata Filter From String Using OLingo V4 -

i building service receive "query parameters" using odata syntax, instead of more familiar ?make=honda&model=pilot the requirement accept single odata filter $filter being passed. ?$filter='make' eq 'honda' , 'model' eq 'pilot' i wondering if there way filteroption object via explicit query string parsing, can run filterexpressionvisitor . any appreciated. thanks.

configuration - "HTTP listener not registered" using OrientDB Docker image -

i'm using latest docker image of orientdb ( 3.0.0m2 happening 2.2.26 image) , when try run using 3 volume mappings ( config , databases , backup ) + orientdb_root_password environment variable, have following error , can't access orientdb studio: 2017-09-11 20:28:44:304 info installing dynamic plugin 'orientdb-studio-3.0.0m2.zip'... [oserverpluginmanager]error on installing dynamic plugin 'studio' com.orientechnologies.orient.core.exception.oconfigurationexception: http listener not registered while installing static content command @ com.orientechnologies.orient.server.plugin.oserverpluginmanager.registerstaticdirectory(oserverpluginmanager.java:224) @ com.orientechnologies.orient.server.plugin.oserverpluginmanager.installdynamicplugin(oserverpluginmanager.java:383) @ com.orientechnologies.orient.server.plugin.oserverpluginmanager.updateplugin(oserverpluginmanager.java:211) @ com.orientechnologies.orient.server.plugin.oserverpluginma

parsing - Ordering lexer rules in a grammar using ANTLR4 -

Image
i'm using antlr4 generate parser. new parser grammars. i've read helpful antlr mega tutorial still stuck on how order (and/or write) lexer , parser rules. i want parser able handle this: hello << name >>, how you? at runtime replace "<< name >>" user's name. so parsing text words (and punctuation, symbols, etc), except occasional "<< >>" tag, calling "func" in lexer rules. here grammar: doc: item* eof ; item: (func | word) punct? ; func: '<<' id '>>' ; ws : [ \t\n\r] -> skip ; fragment letter : [a-za-z] ; fragment digit : [0-9] ; fragment char : (letter | digit | symb ) ; word : char+ ; id: letter ( letter | digit)* ; punct : [.,?!] ; fragment symb : ~[a-za-z0-9.,?! |{}<>] ; side note: added "punct?" @ end of "item" rule because possible, such in example sentence gave above, have comma appear right after "func". since c

python 2.7 - tempfile object skips lines in for loop -

i read data csv file, perform normalization on each row , write temp file. temp file object created in main() function code in 1 file writes , code in file reads it. avoid importing large files memory. however, following script writes subset of rows file. when replace temp_file.write(row) print statement rows printed stdout. can me understand why print returns rows subset written temp file. update: added normalize() method main() method , results correct. suspect issue passing tempfile object name python file , writing file. main method def main(): [argparse code here - removed brevity] temp_file = namedtemporaryfile() if os.path.isfile(args.input_file): normalize.normalize_file(args.input_file, temp_file) else: print 'please supply valid source file' if __name__ == '__main__': main() method imported file def normalize_file(csv_file, temp_file): open(csv_file) file: reader = csv.reade

C++ can I have a vector of struct in a struct -

i have struct node . need have vector of node member of node . error: error c2065 undeclared identifier possible solve in c++? update although think question clear, because insist see code, add code too: typedef struct node_struct{ string id; mwtypes mwtype; bool geometricdecomposition; node_struct() { mwtype = fork; geometricdecomposition = false; } ... vector<vector<node>> barrierworkers; } node;

python - Viewing Pandas df in Eclipse on a Separate Window -

i trying see how pandas dataframes without needing use print. can eclipse? relatively older post has solution, thought eclipse there should exist more convinient way of checking variable values (including dataframes).

recursion - c++ calling a recursive function that returns an object -

i'm writing .cpp file linked list class, , helper function insert returns pointer node. here i've written far: void linkedlist::insert(course* newcourse) { course *temp = newcourse; temp = insertafter(head_ptr, newcourse); } //insert's helper function course linkedlist::*insertafter(course *current_ptr, course *newcourse) { if (current_ptr == nullptr) { current_ptr = newcourse; return nullptr; } else if (newcourse->coursenumber < current_ptr->next->coursenumber) { newcourse->next = current_ptr->next; current_ptr = newcourse; return nullptr; } else return insertafter(current_ptr->next, newcourse); } i have 2 questions, how call helper function, , suppose return after hit end of list, , after insert node

php - Ajax request returns POST <<url>> 500 (Internal Server Error) -

i've been doing module website using wamp server , works, when upladed website server returns error 500. error 500 1 error 500 2 when main page index.php loads (using javascript .ready function) send ajax request 'obtenermunicipio.php'. <script type="text/javascript"> $( document ).ready(function() { $.ajax({ type: 'post', url: '../obtenermunicipio.php', data : {'valor':'paz'}, datatype: 'json', success: function(data) { if(data.length <= 0) { return; } for(var i=0; < data.length; i++) { var opcion = document.createelement('option'); opcion.innerhtml+=data[i]; document.getelementbyid('unidadmedica').appendchild(opcion); } }, error: function(e) { console.log(e.message); }

javascript - Using jquery slidetoggle on visibility hidden elements? -

i trying figure out way use slidetoggle on elements set visibility: hidden, rather display: none. the reason because text slidetoggling causing div within stretch out. there method can use keep element want slidetoggle slide within place without div expanding? html: <section id="image-gallery"> <div class="container"> <div id="imageboxing" class="disciplines"> <img src="images/martial-arts-banner/boxing.png"> <h3>boxing</h3> </div> <div id="imagekb" class="disciplines"> <img src="images/martial-arts-banner/kickboxing.png"> <h3>kickboxing</h3> </div> <div id="muaythai" class="disciplines"> <img src="images/martial-arts-banner/muaythai.png"> &l

html - How do I align my logo using CSS in my Navigation Bar? -

i creating company website, , have logo, wanting put inside navigation bar, align @ far right, halfway down through height of navigation bar. wanting using css. here index.html. <!doctype html> <html> <head> <title>responsive navigation bar</title> <link rel="stylesheet" type="text/css" href="main.css"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <img src="images/logo.png" alt="logo" id="logo" onclick="location.replace('index.html', '_top')"> <div class="nav"> <label for="toggle">&#9776;</label> <input type="checkbox" id="toggle"/> <div class="menu"> <a href="index.html">home<

Grails package access file outside of war package -

grails3 package war. is possible modify server.xml file of embedded tomcat in war generated "grails package" command? indeed i'd run war using "java -jar app.war" , web page access files in directory outside of app.war ? does know how ? i not sure whether possible (security breach) ? thanks feedback.

rabbitmq - Camel Rabbit doesn't allow to set empty routing key when declaring DLX -

i have spring boot application uses camel rabbit consume messages queue. use uri declare queue dead letter exchange, i'm not supplying option deadletterroutingkey want messages going dlx keep original routing key. when application starts throws following error: caused by: com.rabbitmq.client.shutdownsignalexception: channel error; protocol method: #method<channel.close>(reply-code=406, reply-text=precondition_failed - invalid arg 'x-dead-letter-routing-key' queue 'entry.paid.erp' in vhost '/': {unacceptable_type,void}, class-id=50, method-id=10) is possible configure camel have behavior? some additional information: camel version: 2.19.1 spring boot version: 1.5.4.release example of uri i'm using: rabbitmq://server:port/my-exchange ?connectionfactory=#connectionfactory &exchangetype=topic &queue=my-queue &autoack=true &durable=true &autodelete=false &exclusive=false &

Describe the polymorphic relationship of Django -

Image
tell me how describe connection: there table in there can different types of records (type1, type2 or type3). models.py from django.db import models django.contrib.contenttypes.fields import genericforeignkey, genericrelation django.contrib.contenttypes.models import contenttype class general(models.model): field1 = models.charfield(max_length=512, blank=true, null=true) field2 = models.charfield(max_length=512, blank=true, null=true) content_type = models.foreignkey(contenttype) object_id = models.positiveintegerfield() content_object = genericforeignkey('content_type', 'object_id') class meta: db_table = 'general' class type1(models.model): name = genericrelation(product) address = models.charfield(max_length=512, blank=true, null=true) number = models.charfield(max_length=256, blank=true, null=true) class meta: db_table = 'type1' how make connection , choose want type in type, e

selenium - Stopping phantomjs gives memory allocation error -

i using drive.quit() . but after executions get: [errno 12] cannot allocate memory exception attributeerror: "'service' object has no attribute 'process'" in <bound method service.__del__ of <selenium.webdriver.phantomjs.service.service object @ 0x7fb299dc0bd0>> ignored in list of started processes see appear again , again: "/usr/local/lib/node_modules/phantomjs-prebuilt/lib/phantom/bin/phantomjs --ign"

typescript - RXJS and Angular: Take a number of elements in an array -

i'm trying wrap head around rxjs. i'm getting array of things via http request. but i'm having trouble taking number of objects. here's method. getthingsbyid(id: number): observable<ithing[]> { return this._http.get(this.url + id + '/things) .map((response: response) => <ithing[]>response.json()) .take(20); } when try take 20 of things of them. what doing wrong? thanks! try array.slice() method: getthingsbyid(id: number): observable<ithing[]> { return this._http.get(`${this.url}${id}/things`) .map((response: response) => <ithing[]>response.json().slice(0, 20)); }

node.js - NPM Install is not working. Getting Reference Errors -

i in process of learning node.js , web dev together, coming mobile dev background , haven't coded in few years. i cloned project github , planning on building on top of learning project. i running npm install add dependencies project , seem installing properly. succesfully being added node_modules directory being added dependancy package.json however when running app these errors referenceerror: multer not defined @ object.<anonymous> (/users/willjamieson/airdrive/app.js:26:21) @ module._compile (module.js:556:32) @ object.module._extensions..js (module.js:565:10) @ module.load (module.js:473:32) @ trymoduleload (module.js:432:12) @ function.module._load (module.js:424:3) @ module.runmain (module.js:590:10) @ run (bootstrap_node.js:394:7) @ startup (bootstrap_node.js:149:9) @ bootstrap_node.js:509:3 there other dependancies working within app ones project when forked it. var express = require('express'); var app

java - School assignment: Generating 7 random numbers, putting them into an array, and making sure each number is unique -

so, have make program have 7 random numbers , have put them array. each number in array cannot same number in array. wrote program this, works of time. when work, works perfectly, , when doesn't work, program runs forever , have force stop it. i can't seem find mistake. please help! here code: package arraysex2; import java.util.random; import java.util.scanner; public class arraysex2 { public static void main(string[] args) { scanner input=new scanner(system.in); random r=new random(); int random,count=0,count2; boolean isrepeat=false; integer[]randoms=new integer[7]; while(count<=randoms.length-1){ random=r.nextint(30)+1; for(count2=0;count2<count;count2++){ if(random==randoms[count2]){ isrepeat=true; break; } } if(!isrepeat){ randoms[count]=random; count++;

symfony 2.1 - Logging into form with cURL/PHP -

i'm trying login external site php's curl protocol. this form in question <form accept-charset="utf-8" action="/support/login" method="post"> <input name="utf8" type="hidden" value="&#x2713;" /> <input name="authenticity_token" type="hidden" value="phefln4n1clb/l8hnl1bbd6mk6tz1s5vfcexllam48o="/> <input class="required special" id="user_session_email" name="user_session[email]" type="email" value="" /> <input class="special" id="user_session_password" name="user_session[password]" type="password"> <input name="user_session[remember_me]" type="hidden" value="0" /> <input checked="checked" id="user_session_remember_me" name="user_session[remember_me]" type="checkbox&

iis - Does a browser need access to the Internet to browse an internal secured site with SSL? -

Image
i have secured website using network solutions ssl cert. website can accessed computers in environments in company have access internet. (iis redirects http calls https). have browser in locked down environment trying access same website using https. locked down environment doesn't have access internet ports 80 , 443 open website's server , verified responses telneting ports 80 & 443. (not related error anyways). iis server has access internet. the response in ie shown below. ie problem in doesn't have internet access , can't connect network solutions (ns) verification or because of maybe missing root cert ns? ns known authority unlikely. (i troubleshooting webapi calls using https in case decides not programming question. have make ie work correctly on same machine before @ webapi stuff) tl;tr: no internet access needed check certificate on internal sites, there edge cases. there no internet needed access internal site has certificate signed

python - IndexError: list index out of range: I can uderstand why this error happens -

i got error indexerror: list index out of range. wanna put dictionary data model(user) . wrote book2 = xlrd.open_workbook('./data/excel1.xlsx') sheet2 = book2.sheet_by_index(0) row_index in range(1,sheet2.nrows): rows = sheet2.row_values(row_index) print(rows) user3 = user.objects.filter(user_id=rows[0]) if user3: user3.update(talk1=rows[2],characteristic1=rows[3],talk2=rows[4],characteristic2=rows[5], talk3=rows[6], characteristic3=rows[7],talk4=rows[8], characteristic4=rows[9], talk5=rows[10], characteristic5=rows[11],talk6=rows[12], characteristic6=rows[13], talk7=rows[14], characteristic7=rows[15], talk8=rows[16], characteristic8=rows[17]) however,the number of rows's index different each list.rows like ['001200cd3ef', 'tom', 'hi', 'greeting', 'goodmorning', 'greeting', 'bye' 'say good‐bye', '', '

Podio - Multidimensional Arrays json -

can please tell me how access config:unique value in below json? can't seem multidimensional array. i'm using php "fields": [ { "status": "active", "type": "text", "field_id": 148218251, "label": "artist name", "values": [ { "value": "schema_artist" } ], "config": { "default_value": null, "unique": false, "description": null, "hidden_create_view_edit": false, "required": false, "mapping": null, "label": "artist name", "visible": true, "delta": 0, "hidden": false, "settings": { "format": "plain", "size": "small" }

process a text file with xml column in apache spark scala -

i have file : 1,<note><from>messi</from><body>don't forget me weekend!</body></note> 2,<note><from>ronaldo</from><body>don't forget laliga</body></note> 3,<note><from>neymar</from><body>i best </body></note> 4,<note><from>suarez</from><body>don't forget me weekend!</body></note> where first field id , second field data. need load rdd, parse xml string , extract fields, , create rdd this: 1,messi,don't forget me weekend! 2,ronaldo,don't forget laliga 3,neymar,i best 4,suarez,don't forget me weekend! since xml in actual scenario complex, use xml parser. how can this? you can use scala's own xml library. but, need parse string elem object before can : import scala.xml._ val str = "<note><from>messi</from><body>don't forget me weekend!</body></note>&q

primeng pie chart text label and data connector line outside the pie slice -

https://www.primefaces.org/primeng/#/chart/doughnut i want implement labels outside pie chart in primeng can me on these. link posted down here how need. chart.js: show labels outside pie chart

Cannot download file ios_setup.js for fbsdk -

i'm trying build react-native ios app. , i'm trying download file ios_setup.js curl -o https://raw.githubusercontent.com/facebook/react-native-fbsdk/master/ios_setup.js . error 404: not found. i'm using instructions verbatim facebook developer site. ideas? seems removed in master. can still latest copy 0.6.1 tag

Laravel Barryvdh PDF render html with javascript -

i can render view blade using html , when comes using laravel barryvdh pdf printing javascript not loading. i use absolute path bootstrap loading, not javascript how can make out of this? this is seems not loading... and js(vue js) @{{ }} not displaying data

python - Tensorflow DNNRegressor predict_score output -

i trying run dnnregressor on simple data can test accuracy, model should take bank transaction , try predict price, getting weird results think result of wrong code. my code here: from __future__ import print_function __future__ import division __future__ import absolute_import import itertools import pandas pd import numpy np import tensorflow tf print('running version of tensorflow') print(tf.__version__) tf.logging.set_verbosity(tf.logging.debug) names = [ 'trans', 'price', ] predict_names = [ 'trans' ] dtypes = { 'trans': str, 'price': np.float32, } df = pd.read_csv('simple.csv', names=names, dtype=dtypes, na_values='?') # split data training set , eval set. training_data = df[:50] eval_data = df[50:] print("training :\n") print(training_data) # separate input features labels training_label = training_data.pop('price') eval_label = eval_data.pop('price') #

numerical analysis - Spacing between two floating point values in a normalized system? -

let x given nonzero floating-point number in normalized system, , let y adjacent floating-point number, non-zero. a) what's minimum possible spacing between x , y? b) what's maximum possible spacing between x , y? i know floating-point number system characterized 4 integers, x = +/- (d_0 + d1/b + d2/b + ... + d_(p-1)/b^(p-1)*b^e, where 0 <= d_i, <= b - 1, = 0,...,p-1 , l <= e <= u i can't seem correlate relationship between equation have , minimum/maximum possible spacing possible between 2 adjacent fp numbers. please! numerical-methods

javascript - Fire event when route is unchanged angularjs -

i want perform reload of route when there's not route change, in other words reload controller when button takes route clicked. in view in ng-click directive call following method: this.reload = function() { $scope.$on('$routechangestart', function(event, next, current) { if($route.current == $route.next) { $route.reload(); } }) } the code inside condition never triggered because there's not change in route. i'm beginner in angularjs, appreciated :) i handle 2 things mentioned above separately. on each route change whatever want do. register event listener listens routechangestart. $rootscope.$on('$routechangestart', function (event, next, prev) { //if logic given want next/prev objects }); if user clicks button reload route. html <button ng-click="reload_route()">reload</button> controller app.controller('myctrl', function($scope, $route){ $scope.reload_route = f

ios - How to deal with CoreData save errors? -

avoiding data loss critical issue in application. need save , ensure minimal loss , immediate notification if goes wrong. unfortunately results in lot of if (![context save:&error]) { handling on place. clean in more centralised way thought implement nsmanagedobjectcontext category method such this: - (bool)savenotify:(nserror **)error { nserror *saveerror; if (![self save:&saveerror]) { nsdictionary *userinfo = @{@"error" : saveerror}; [nsnotificationcenter.defaultcenter postnotificationname:nsmanagedobjectcontextsaveerrornotification object:self userinfo:userinfo]; if (error != null) *error = saveerror; return no; } return yes; } now can listen notification in more general way , throw alert user if save has failed reason. is approach or there better way deal this? a secondary issue when occur. asking user exit app , restart bit convoluted these days need close app through task switcher. that

java - Deployment issue in Glassfish 3.1.2.2 -

i'm facing deployment issue while trying deploy main war file initiates task. totally there 3 war files among i'm able deploy 2 war file successfully, deployment fails 1 specific war. i'm facing issue couple of days before works fine. no changes made in server settings . i thought compilation issue tried redeploy backup file took in aug,july throws me same exception. error- error occurred during deployment: exception while preparing app : java.net.connectexception: connection refused: connect -- connection refused: connect. please see server.log more details. server logs: [#|2017-09-11t00:46:35.536-0700|info|glassfish3.1.2|org.glassfish.admingui|_threadid=65;_threadname=thread-2;|redirecting /index.jsf|#] [#|2017-09-11t00:46:35.974-0700|info|glassfish3.1.2|org.glassfish.admingui|_threadid=67;_threadname=thread-2;|admin console: initializing session attributes...|#] [#|2017-09-11t00:47:13.642-0700|warning|glassfish3.1.2|org.apache.catalina.connector.reque

javascript - How to assign a value of an element created with ajax to a hidden form field? -

there's div button. when click button form appears. div's id gets assigned hidden field of form. works divs on page when page loaded. doesn't work divs created ajax after page loaded. <div class=\"maincircle\"> <div class=\"textcircle\" data-id=\"$name\" onclick=\"displaylevel3('$name');\">". $row['name'] ."</div> <button class=\"add1\" id=\"$name\" onclick=\"toggle_visibility('addleaf');\"></button> <button class=\"add2\" data-id=\"$name\" onclick=\"toggle_visibility('addsibling');\"></button> <button class = \"delete\" data-id= \"$name\"></button> </div> after clicking 'textcircle', ajax displays more divs same layout: $.ajax( { type : 'post', data : {"node" : val}, url : 'displayle

mysql - Why does MariaDB-10.2.8 UNHEX() return NULL? -

i have sql script works on mysql (up current versions). built copy of mariadb-10.2.8 source on linux machine , got database , running. however, sql script fails, because mariadb returning null unhex() call, shouldn't. the call producing 20-byte random binary string in particular format (it's bittorrent node id). concatenate required bytes random bytes, bytes being limited particular range of values. these constructed 40-character hex string, run through unhex(). the sql is: unhex( concat( '414c2', hex( 8 + round( rand() * 7 ) ), substr( sha( uuid( ) ), 6, 33 ), hex( 2 + round( rand( ) ) * 8 ) ) ) if take off unhex() function, 40-character hex string: mariadb [bt]> select concat('414c2', hex(8+round(rand()*7)),substr(sha(uuid()),6,33),hex(2+round(rand())*8)); +-----------------------------------------------------------------------------------------+ | concat('414c2', hex(8+round(rand()*7))

python - How can I get a empty list when I use the enumerate before the loop? -

salary_data list in python.when used enumerate function in loop below,everything went well. ##salary_data = enumerate(salary_data) max_label = [i i,x in enumerate(salary_data) if x==max(salary_data)] print max_label but when use enumerate function below,i got salary_data empty list,and valueerror: max() arg empty sequence.i don't know why. salary_data = enumerate(salary_data) max_label = [i i,x in salary_data if x==max(salary_data)] print max_label enumerate(salary_data) iterator because wrapped in enumerate . means exhausted (empty) when call max on (besides giving wrong maximum). you should calculate max front (avoiding recalculation) , iterate on enumerate d data: max_ = max(salary_data) # avoids repeated maximum calculation in loop salary_data_enumerated = enumerate(salary_data) # other variable name, readability max_label = [i i, x in salary_data_enumerated if x==max_]

javascript - Bootstrap carousels freezing up -

i had asked previous question regarding multiple bootstrap carousels , had received absolutely fine code stack overflow user. you can see code here: how place 2 bootstrap carousels in same page? under last edit i using same code provided user. problem carousels freezing when page stays open long. by freezing mean first slider, stops sliding after specified interval. if manually click on navigation button, slides. for second carousel , thumbnails, problem when clicking on thumbnail, respective image not showing in second carousel. no amount of refreshing or copy pasting code page helps. there other elements on page too, none have jquery or similar class names. overlapping of class names or id names ruled out. where problem? any kind of appreciated. thanks. here you're missing }); in code, review jsfiddle, terminator jquery(document).ready(function($) { . check jsfiddle here .

sql server - Convert two columns into key-value json object? -

Image
using for json auto or for json path on following record set (which representing product's attributes): attribute | value ----------------- color | red size | small will produce: [{"attribute":"color","value":"red"},{"attribute":"size","value":"small"}] is there way produce following instead: {"color":"red","size":"small"} note every product attribute different others; record set different every product. pivoting not option needs dynamic sql! seems need function able cross products table produce example product catalog . instead of json functions of sql server 2016, used string concatenation function string_agg in sql server 2017 seen in following script /*create table productattributes ( product int, attribute varchar(40), value varchar(40) ) insert productattributes select 1, 'color', 'red' ins

java - iText7 : com.itextpdf.kernel.PdfException: Document was closed. It is impossible to execute action -

i got com.itextpdf.kernel.pdfexception: document closed. impossible execute action. error on itext7. 1 // update here 2 pdffont font; 3 { 4 gcsfilename gcsfilename = new gcsfilename("fonts", "msgothic001.ttf"); 5 try (gcsinputchannel inputchannel = 6 gcsservice.openprefetchingreadchannel(gcsfilename, 0, buffer_size)) { 7 font = 8 pdffontfactory.createfont( 9 getbytes(channels.newinputstream(inputchannel)), 10 pdfencodings.identity_h, 11 true); 12 } 13 } 14 // update until here 15 16 writerproperties wp = new writerproperties(); 17 wp.usesmartmode(); 18 try (pdfdocument writedoc = new pdfdocument(new pdfwriter(outputstream, wp))) { 19 20 list<inte