Posts

Showing posts from April, 2010

Have to find the longest word possible out of a list of given letters PROLOG -

:-consult(words.pl). % words big database of % 30.000 used words in english language topsolution([], _, p) :- %basecase, in case given list of letters %empty, output no word , give amount of letters %and call p word(x), %sees if x word p = 0. topsolution(wordlist, x, p) :- %makes longest word can out of list %of letters , outputs said word x, , %amount of letters has p y = 0, solution(wordlist, x, y), %determines words can make given %list of letters , given length of said word y1 y + 1, solution(wordlist, x, y1), %determines longest word of y + 1 wordlength(p, x). %defines how many letters word x has , calls amount p so piece of code made find word. problem i'm struggling can't find way make recursion stop. if input: ?-

Typescript type inference, spread operator and multiple type return -

interface skillproperty { [name: string] : number }; let skills: skillproperty; skills = {}; // ok skills = { fire: 123 }; // ok skills = { ...skills, // ok ...{}, // ok ...extraskills() // {} | { ice: number } not assignable type 'skillproperty'. } function extraskills() { if (whatever) { return {}; } return { ice: 321 }; } how can change skillproperty interface make compliant both empty object , actual skillproperty type ? your skillproperty interface is compatible {} | {ice: number} : let noskills = {} let iceskills = { ice: 321 }; let randomskills: {} | {ice: number} = (math.random() < 0.5) ? noskills : iceskills let maybeskills: skillproperty = randomskills; // no error so, looks bug in typescript me. similar issue fixed , this case seems persist. might worthwhile opening new issue links existing ones. in mean time there workarounds, l

javascript - why this regex "^(0[1-9]|1[0-9]|2[0-9]|3[01])/(0[1-9]|1[012])/(19[0-9]{2}|20[0-1][0-7])$" fails for dates like 16/06/2008, 21/02/2008..? -

i trying match dates starting year 1900 2017 in dd/mm/yyyy format using ^(0[1-9]|1[0-9]|2[0-9]|3[01])/(0[1-9]|1[012])/(19[0-9]{2}|20[0-1][0-7])$ regular expression observing regular expression fails dates 16/06/2008 , 21/02/2008. make sure parts of regular expression working or not tried 3 parts ^(0[1-9]|1[0-9]|2[0-9]|3[01])$ , ^(0[1-9]|1[012])$ , ^(19[0-9]{2}|20[0-1][0-7])$ on different sets of days months , years found these working fine when ran combined got same unexpected result date 16/06/2008 . additionally want inform using regex in javascript : var patt = new regexp("^(0[1-9]|1[0-9]|2[0-9]|3[01])/(0[1-9]|1[012])/(19[0-9]{2}|20[0-1][0-7])$"); var res = patt.exec(datestring); for dates 16/06/2008 res evaluates null. please let me know going wrong i? solve have gone through regular expression tutorials , asked questions did not find relavent answer can tell me why regex fails specific dates. please help. along with 20[0-1][0-7] not mat

C# ASP.NET Application ComboBox binded to GridView Display Issue -

i creating asp.net web application display specific data sql database. have created 3 datasources each specific data want view chosen dropdownlist. my dropdownlist coding c# side followed: protected void dropdownlist1_selectedindexchanged(object sender, eventargs e) { string sourcename = dropdownlist1.selectedvalue; gridview1.datasourceid = sourcename; gridview1.databind(); } dropdownlist coding on asp.net side: <asp:dropdownlist id="dropdownlist1" runat="server" autopostback="true" onselectedindexchanged="dropdownlist1_selectedindexchanged"> <asp:listitem value="datasource_gerneral">general overview</asp:listitem> <asp:listitem value="datasource_portfolio">portfolio</asp:listitem> <asp:listitem value="datasource_errorlog">error log</asp:listitem> </asp:dropdownlist&

scala - How do you manage database connections using Akka actors? -

i've been studying akka time , building app utilizes actor model , requires maintain connection database, have dilemma: put connection , how can manage it? this reasoning far: the connection should initialized once. since connection represents state, should reside inside actor. let's call actor databaseconnection (just creative). since don't want share actor's state, querying should happen inside actor. the database driver using reactive-mongo each query returns future can piped sender. even though querying done through futures, can't thinking model cannot scale. 1 thread managing database access messages? sounds unreasonable utilizing futures. have thought of making child workers manage database querying have share connection children. last idea because if databaseconnection actor dies, children die in theory. don't know if there better way solve problem without sharing state. there? based on example code reactive mongo doesn't acto

javascript - How to sort a D3 bar chart (based on an array of objects) by value or key? -

i new d3 , javascript in general , i'm trying wrap head around possible interactions rather simple bar charts. what trying achieve: i have option sort bar chart value when click on 1 of bars , alphabetically keys if click once more. my progress far: my bar chart based on array of objects keys names of companies , values indicate mean satisfaction each company on scale 0 100. var data = [ {key: "test 1", value: 21}, {key: "test 2", value: 34}, ... {key: "test 12", value: 22}, {key: "test 13", value: 97} ]; you can see progress , whole code here: bl.ocks.org i attempted create function sort array. i'm pretty lost on how reposition bars since bars positioned based on key , don't know how else on ordinal scale. var x = d3.scaleband() .domain(data.map(function(d){ return d.key; })) .range([margin.left, width]) .padding(0.1); var y = d3.scalelinear() .domain([0, d3.max(

looking for an http-in node to handle ssl inbound web services -

does know of replacement node http-in ssl? thinking alternative start nodejs https-server? any suggestions great. thanks, den you don't need replacement node (and don't believe there need instantiate it's own https server independent node-red), configure node-red listen https connections. how configure node-red listen on https in settings.js (found in node-red user directory, ~/.node-red , included in first few lines of node-red log) // `https` setting requires `fs` module. uncomment following // make available: //var fs = require("fs"); ... // following property can used enable https // see http://nodejs.org/api/https.html#https_https_createserver_options_requestlistener // details on contents. // see comment @ top of file on how load `fs` module used // setting. // //https: { // key: fs.readfilesync('privatekey.pem'), // cert: fs.readfilesync('certificate.pem') //}, ... more details can found in blog post here

pandas - Unbound local error: ("local variable referenced before assignment") -

import pandas pd, numpy np d = [{'cabin': 'f g13'},{'cabin': 'a32 a45'},{'cabin': 'f23 f36'},{'cabin': 'b24'},{'cabin': nan}] df = pd.dataframe(d) def deck_list(row): if row['cabin']!=row['cabin']: cabinid = 'none' else: cabinsubstr = row['cabin'].split(' ') in cabinsubstr: if i.find('f ') != -1: cabinid = i[0][0] break if i.find('f ') == 0: cabinid = i[1][0] break return cabinid df['deck_id'] = df.apply(deck_list, axis=1) am missing something? i've written akin plenty of times , i've never gotten error maybe it's stupid? another way write this, using vectorized string methods is: import pandas pd import numpy np nan = np.nan df = pd.dataframe([{'cabin': 'f g13'},

arduino - WEMOS WebSocket for app and WEMOS communication -

i working on project involves wemos d1 mini wifi module automation , phone app. using http server on local giving delay in data transfer , inefficient. there no available using websocket server, lightweight , fast. please me code wemos websocket , phone app communication.

java - Get Android Installed App Icon in Unity -

i'm writing quite difficult (for me) issue. quickly, want installed apps in device (icon , label). i'm using simple code works getting name of app. use android java class these informations. problem android optains app icon "drawable". unity cannot read , display sprite. wondering if there way sort issue out. have tried encode drawable base64 string unity "replies" me "invalid string length" error, maybe "infinite" length of base64 string. trying convert drawable byte array , use create texture texture.loadimage(byte[]) doesn't work. here code: androidjavaclass jc = new androidjavaclass("com.unity3d.player.unityplayer"); androidjavaobject currentactivity = jc.getstatic<androidjavaobject>("currentactivity"); int flag = new androidjavaclass("android.content.pm.packagemanager").getstatic<int>("get_meta_data"); androidjavaobject pm = currentactivity.call<androidja

Heroku Procfile with web process type -

i deploying create-react-app uses express server server-side rendering. i using cra buildpack: https://github.com/mars/create-react-app-buildpack , procfile web process type. i'm not sure when web processes run. procfile executed once when deployed? by default, heroku runs 1 dyno web process, , receives inbound http traffic. happen after first deployment. can choose scale up/down number of dynos each process type if required, including not running web process @ all. here's link heroku article explains this: https://devcenter.heroku.com/articles/procfile excerpt: the web process type special it’s process type receive http traffic heroku’s routers. other process types can named arbitrarily.

ajax - Redirect to another URL after FacetWP loads -

i'm using facetwp genesis. when using facet say, 'location' taxonomy, facetwp uses ajax , loads pages url's like: http://website.com/hotels?fwp_location=worldwide and http://website.com/hotels?fwp_locations=europe normal 301 redirects won't work, i'm trying find out how make these redirects, if have make them 1 one. want url match of taxonomy terms. in above examples, should redirected to: http://website.com/hotels/worldwide and http://website.com/hotels/europe when making 301 redirects yoast seo, redirects work if reload page manually f5. if recreated, should fine. does know solution this? thanks in advance.

php - Unable to send emails with attachment using elastic email API in codeigniter -

i have used tcpdf generate pdf, working fine.i'm trying send email pdf generated attachment email. emails being sent without attachment. please in correcting codes below ensure attachment sent in email. payment.php $attachment = $pdf->output('example_001.pdf', 'd'); $attachment = base64_encode($attachment); $attachmentlink = 'http://localhost/cfac/resources/invoices/example_001.pdf'; $inputdata['firstname']="abc"; $inputdata['ename']="event name"; $inputdata['tno']="tno:232423"; $inputdata['amount']="10000rs"; $inputdata['edetails']="edetails"; $inputdata['startdate']="start date"; $inputdata['enddate']="end date"; $template='xyz'; $emailid="xxx@gmail.com"; // email helper send email $this->load->helper ('email'); $filename = "example_001.pdf"; $file_name_with_f

ruby on rails - Customize "create" message on a simpleform button -

i have calendar , when click on buttons, book specialist half day. redirects same page if booking correctly saved in base. while proceeds, button briefly change message "create booking". want custom message, specially because during operation explodes whole calendar table (done simple calendar). there nothing in .yml simple form. activerecord messages? .yml these gem don't have kind of message. screen shot of brief message

Python: Turn a comma-delimited string into a CSV -

i have long string in type of format [var1,var2,var3,...], [var1,var2,var3,...], ... (it's 1 giant string) what best way turn large csv each [var1,var2,var3,...] existing row in csv each component var1, var2, var3, etc delimited 1 another? using python3 solve problem. as long there's no malformed data might away this: >>>import numpy np >>>import ast >>> s = '[1, 2, 3], [4,5,6], [7,8,9]' # string >>> ll = np.vstack(ast.literal_eval(s)) # converts python >>> ll array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) writing list of lists csv can done pretty csv package.

php - Undefined value for response.message in AJAX -

i'm trying display response.message content tag id test. it's getting displayed undefined. success:function(response){ console.log("response"+response); // works var msg = response.message; if(response.status=="success"){ console.log("response1"+msg); document.getelementbyid('test').innerhtml = msg; //undefined } else { jquery('#test').contents(msg); document.getelementbyid('test').innerhtml = msg; //undefined } } the way handle parsing json response made javascript object (using json.parse ), try code below. success: function(response) { console.log("response" + response); response = json.parse(response); var msg = response.message; // works if (response.status == "success") { console.log("response1" + msg); // prints/works document.getelementbyid(&

Operations across rows of a matrix, comparing overlap -

imagine symmetric matrix follows: b c d 50 0 25 b 50 0 50 c 0 0 50 d 25 50 50 what i'm trying accomplish dyadic, comparing across 2 nodes see how overlap have other nodes in matrix. for example, following matrix product need obtain. b c d 25 25 50 b 25 50 25 c 25 50 0 d 50 25 0 the value of 25 in [a,b] cell of latter matrix obtained comparing how , b respectfully related c , d. instance: first across top row of top matrix. ignore a's relationship b. a has 0 relationship c. ignore because of 0. a has 25 relationship d. b's relationship d equal or greater number, give 25 credit a. becomes [a,b] cell. for [b,a] cell, it's similar process: similarly, across second row of matrix. ignore b's relationship a. b has 0 relationship c. ignore because of 0. b has 50 relationship d. node a's relationship d 25, give b credit of 25 in terms of overlap. conceptually, these relatively straightforward, functions pe

c# - ASP.NET Core 2.0 repository pattern with a generic base class -

i'm implementing repository pattern in asp.net core 2.0 application. i have baserepository class follows: public class baserepository<tentity> tentity : class { private applicationdbcontext _context; private dbset<tentity> _entity; public baserepository(applicationdbcontext context) { _context = context; _entity = _context.set<tentity>(); } public ilist<tentity> getall() { return _entity.tolist(); } public async task<ilist<tentity>> getallasync() { return await _entity.tolistasync(); } } then i've implemented 2 concrete repositories (i'm testing): public class coursesubjectrepository : baserepository<coursesubject> { public coursesubjectrepository(applicationdbcontext context) : base(context) { } } public class themerepository : baserepository<theme> { public themerepository (applicationdbcontext context) : base(context)

windows - how to apply findstr expressions to the first column of a string in a .csv file while returning the entire string in CMD? -

i made btach script , works well, exception of returning additional strings not exact matches source file. when run script below, return additional strings share same number structure the numbers in .txt file, additional numbers @ end of them ex. searching "^%%l" = "^12210" return strings 12210 , 122100,122101,122102 ect.. any appreciated! batch script: for /d %%a in (*) ( /f %%f in ("%%a"\*.txt) ( /f %%l in (%%f) ( findstr "^%%l" c:path\file.csv >> %%a.csv ) ) move %%a.csv "%%a" >nul ) @compo- assist!! comments got me going in right direction , problem solved. ended having modify expression bit return entire string. here worked. findstr "^%%l,*,*\>" c:\path\file.csv.

functional programming - Converting List To Maps in Java 8 -

i loading log file input stream , need aggregate processing on matching values on each line, need store duplicates while saving lines in multimap, finding trouble collecting below stream stored list multimap<string, list<string>> try (stream<string> stream = files.lines(paths.get(infilename))) { list<string> matchedvalues = stream .flatmap(s -> multipatternspliterator.matches(s, p1)) .map(r -> r.group(1)) .collect(collectors.tolist()); matchedvalues.foreach(system.out::println); } how convert same store values in map duplicate values. it's hard want, given need "log line <retimestamp, rehostname, reservicetime> " stored " map<<retimestamp>, <retimestamp, rehostname, reservicetime> " i'd go with: map<string, list<string>> matchedvalues = stream .flatmap(multipatternspliterator::matches

ZeroMQ on Windows, with Qt Creator -

i have installed zmq link given below on windows 7. http://zeromq.org/distro:microsoft-windows 1) have c++ project in qt-creator , i'm using zmq c++ binding (zhelpers.hpp etc). 2) have added .lib installed zmq folder qtcreator 3) while compiling, compiler looks _imp__zmq_verion, in .dll files present in .lib have __imp_zmq_version. 4) causing undefined reference zmq_version. anyone else faced problem , has solution ?

python - Value Error; Printing out Blank Map -

i trying grid plots on map, grid not showing , getting valueerror. it says valueerror: not enough values unpack (expected 2, got 1) import numpy np import matplotlib.pyplot plt cartopy.mpl.gridliner import longitude_formatter, latitude_formatter import cartopy.crs ccrs avglonlist=[-63.414436532479854, -63.41382404937334, -63.41320293629234, -63.4126322428388, -63.412060546875, -63.41134304470493] avglatlist=[44.5523500343606, 44.55130764100617, 44.550250391568596, 44.54927937825529, 44.54830612909229, 44.5470865885415] klist=['0.1243', '0.1304', '0.1321', '0.1281', '0.1358', '0.1105'] ax = plt.axes(projection=ccrs.platecarree()) #ax.set_extent((-65.0, -58, 40, 47.7), crs=crs_latlon) ax.set_extent((-64.0, -61, 42.5, 45.0), crs=ccrs.platecarree()) #add coastlines , meridians/parallels (cartopy-specific). plt.gca().coastlines('10m') gl=ax.gridlines(crs=ccrs.platecarree(), draw_labels=true, linewidth=1, color=

Execute a PHP function in a file of functions from a JavaScript function -

i want call php function javascript function. "why?" might ask? i have series of php functions organized in separate file custom_functions.php i learning how build javascript , jquery how bridging gap. more familiar php, finding way through window. i have list of elements constructed in index.php. list of items constructed on fly database , id attribute created based on id of record: echo "<span id="content_" . $row{'unique_id'} . "\" onclick=\"displaydetails(" . $row{'unique_id'} . ")\">"; displaydetails(record_no) javascript function in external javascript file. for tried this: function displaydetails(record){ data = {}; //data = <?php retrievecontent(content_id); ?> $('.output').html("testing function - section " + section_number); } but of course not work because php server side action , javascript client-side action . my particular problem

css - can I post images in a JavaScript array -

i asking series of questions of user. @ end of question system shows bunch of items. next each item want add picture item. can put image array? i have searched this, of results complicated me understand. i wondering if can put pictures in css , have javascript change <div> 's id can post picture , item? this thought work: var blue = ["question1button1" + "img/ads.jpg"]; you use classes: function setbgclass(arg1) { var el = document.getelementbyid("bg-container"); var clname = 'background-' + arg1; el.classname = ''; el.classlist.add(clname); } #bg-container { width: 200px; height: 200px; } .background-1 { background: url("https://avatars0.githubusercontent.com/u/82592?v=4&s=200"); } .background-2 { background: url("https://pbs.twimg.com/profile_images/794277147846340608/tmfi-dro.jpg"); } <div id="bg-container"></

Why does Android OS 8 WebVew with HTML select tag crash the app -

i've got hybrid cordova android app, , app crashes when user tap on drop-down box in webview running on android os 8. i've created simple page tag , issue reproducible. i've got workaround own pop alert select, wondering if happening else , whether os8 webview bug. below simple page tag https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_select below crash log 11:04:58.643 3208-3208/com.****.****e/androidruntime: fatal exception: main process: com.****.****, pid: 3208 android.content.res.resources$notfoundexception: resource id #0x0 @ android.content.res.resourcesimpl.getvalue(resourcesimpl.java:195) @ android.content.res.resources.loadxmlresourceparser(resources.java:2133)

python - Why is the order of dict and dict.items() different? -

>>> d = {'a':1, 'b':2, 'c':3, 'd':4} >>> d {'a': 1, 'd': 4, 'b': 2, 'c': 3} >>> d.items() [('a', 1), ('c', 3), ('b', 2), ('d', 4)] does order randomized twice when call d.items()? or randomized differently? there alternate way make d.items() return same order d? edit: seems ipython thing auto sorts dict. dict , dict.items() should in same order. you seem have tested on ipython. ipython uses own specialized pretty-printing facilities various types, , pretty-printer dicts sorts keys before printing (if possible). d.items() call doesn't sort keys, output different. in ordinary python session, order of items in dict's repr match order of items items method. dict iteration order supposed stable long dict isn't modified. (this guarantee not explicitly extended dict's repr , surprising if implicit iteration in repr broke consistenc

php - Symfony file field empty on edit -

i reading while found nothing works me. entity /** * @orm\column(type="string") * * @assert\notblank(message="molimo unesite pdf ili word fajl.") * @assert\file(mimetypes={ "application/vnd.openxmlformats-officedocument.presentationml.presentation", "application/vnd.ms-powerpoint", "application/pdf", "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"}) */ private $body; this form // problem empty field on edit persist! form expect filetype db sends string!!! ->add('body', filetype::class, [ //'data_class' => null,// <-- if change nothing happened. 'label' => 'word ili pdf dokument', 'invalid_message' =>'id posta nije validan', 'attr' => [ 'class' => 'form-group',

c++11 - Can Someone explain this C++ code to me? -

its exemple of 2d pointers in 1 of slides teacher gave us. can't seem understand code other pointer pointer. ps: still beginner @ c++ #include <iostream> using namespace std; int **ptr; int main(){ ptr=new int *[3]; (int i=0;i<3;i++){ *(ptr+i)=new int[4]; } for(int i=0;i<3;i++) for(int j=0;j<4;j++){ *(*(ptr+i)+j)=i+j; cout<<ptr[i][j]; cout<<"\n"; } return 0; } taking account comments i'll try explain unclear. let's assume there 3 integers int x = 1; int y = 2; int z = 3; and going declare array of pointers these integers. declaration like int * a[3] = { &x, &y, &z }; or int * a[3]; *( + 0 ) = &x; // same a[0] = &x; *( + 1 ) = &y; // same a[1] = &y; *( + 2 ) = &z; // same a[2] = &z; take account array designator used in expressions rare exceptions converted pointer first element. so example in expr

rest - How is the blanket recommendation to version RESTful APIs justified for web-only apps? -

the blanket recommendation restful api should accessed through version number ( /api/v1 , /api/v2 , ..) puzzling. if restful api accessed mobile app or desktop program, it's evident versioning necessary. older apps/programs installed on users' devices should continue function when breaking change introduced api. but suppose app purely web app. html5 served match current api version. there reason version api, besides potential future implementation of mobile apps or desktop programs targeting same api? it not @ blanket recommendation. in fact, lots of folks argue it's bad practice. many best practices, there's people in either camp. if control caller , callee, think can take lot more liberty in terms of best practices can ignore. keep in mind though, things, after being built, might take life on own used in unexpected contexts. can lot more expensive rebuild new use-case, rather build scratch. especially if relatively easy (planning versioning might

sql server - Restore filegroup to different database -

i have sql server database 5 filegroups want backup 2 filegroups(one contains filestream)only , restore them different existing database. what asking piecemeal restores (sql server) you can restore primary + readwrite fg + of readonly filegroups in in simple recovery model or can restore primary + other filegroup(s) if in full recovery model. as first filegroup restore primary filegroup, replace "different existing database" primary data file , log (in restore command should use with move points existing mdf + log files) , every subsequent restore overwrite other files, there remain nothing "existing" database, there no sense restore "different existing database": able bring online filegroups restored , database know nothing remaining files of "existing database". it's same restore another(non existing) database. here restore sequence example primary + readonly fg in simple recovery model example: piecemeal rest

active directory - Where to check LDAP query from Cloudera Navigator? -

i configured our cloudera navigator service authenticate via ldap. i'm able login in navigator, instantly error: you not authorized view page when log in full administrator , try search ldap groups add, nothing returned, think there wrong configuration. should able see how ldap query like? i use identical settings ldap used when configuring cloudera manager, works fine. ldap group i'm looking has "navigator" admin role assigned in cm. i use tool monitor queries performed on ad : https://docs.microsoft.com/fr-fr/sysinternals/downloads/adinsight

jquery - Yii2: What is the different between a HTML table and a GridView? -

i know gridview php it's executed in server side , html table executed in client side, jquery , bootstrap. i learning yii2 , have been using gridviews. has features buttons edit, view , delete, , can sort. now learning jquery can make html table bootstrap , results same. i needing simple table, without features gridview has. need features: a checkbox each row, user can check rows , send php server . so confused. option better? yii2 gridview yii2 php widget (alias part of code ) generate automatically html table code starting configuration value pass in gridview widget call it extremely useful if need build frequent feature representation in form of table included filtering , sorting. takes data data provider , renders each row using set of columns presenting data in form of table. you can see result of widget looking @ code generated in html page in browser can see html source usint ctrl +u (if take deep @ resulting html code can recognize how ti

javascript - Split a string based on multiple delimiters -

i trying split string based on multiple delimiters referring how split string in jquery multiple strings separator since multiple delimiters decided follow var separators = [' ', '+', '-', '(', ')', '*', '/', ':', '?']; var tokens = x.split(new regexp(separators.join('|'), 'g'));​​​​​​​​​​​​​​​​​ but i'm getting error uncaught syntaxerror: invalid regular expression: / |+|-|(|)|*|/|:|?/: nothing repeat how solve it? escape needed regex related characters +,-,(,),*,? var x = "adfds+fsdf-sdf"; var separators = [' ', '\\\+', '-', '\\\(', '\\\)', '\\*', '/', ':', '\\\?']; console.log(separators.join('|')); var tokens = x.split(new regexp(separators.join('|'), 'g')); console.log(tokens); http://jsfiddle.net/cpdjz/

angularjs - How to wait/finish multiple insert function in for each loop? -

how asynchronously, print console.log("print this, after loop done") i have foreach inside foreach. insertservice not return value, want insert here. i don't know how apply $q , $q.all. pls help. angular.foreach(main, function (value, key) { //#1 selectservice1.selectid(value.id).then(function (res) { angular.foreach(res, function (value, key) { insertservice1.insert(value).then(function (res) { console.log("new inserted service 1!"); }, function (err) { }); }); }, function (err) { }); //#2 selectservice2.selectid(value.id).then(function (res) { angular.foreach(res, function (value, key) { insertservice2.insert(value).then(function (res) { console.log("new inserted service 2!"); },

machine learning - Keras pretrained Xception model always gives the prediction 'sewing_machine' -

i'm using keras pretrained model 'xception' image recognition. however, no matter picture give xception, predictions always: predicted: [[('n04179913', 'sewing_machine', 1.0), ('n15075141, toilet_tissue', 0.0), ('n02317335', 'starfish', 0.0), ('n02389026, sorrel', 0.0), ('n02364673', 'guinea_pig', 0.0)]] is there wrong code? my code is: from tensorflow.contrib.keras import applications app tensorflow.contrib.keras import preprocessing pp import numpy np model = app.xception(weights='imagenet', include_top=true) img_path = 'test123.jpg' img = pp.image.load_img(path=img_path, target_size=(299, 299)) x = pp.image.img_to_array(img) x = np.expand_dims(x, axis=0) x = app.xception.preprocess_input(x) preds = model.predict(x) print('predicted:', app.xception.decode_predictions(preds))

javascript - Enable buttons when user read the disclaimer angular 2 -

hi have following modal, <div class="dialog-header"> <div class="col-2 warning-image"> </div> </div> <div class="dialog-content" [innerhtml]="message | translate: messagedata? messagedata : null"></div> <table>........</table> <div>{{descalimer}}</div> <div class="dialog-footer"> <button class="btn btn-dbs-solid" (click)="confirm(false)">{{confirmbtn.text | translate}}</button> </div> i can have table long , can short. button should shown time, enable once user read full table , disclaimer. how enable button on full scrolldown in angular or javascript? idea? in advance.

python - Matplotlib clipping first bar in hbar in half horizontally -

Image
i'm struggling understand why first bar in matplotlib hbar plot being chopping in half horizontally. yaxis label missing bar. idea of why happening? here script , attached output import networkx nx import matplotlib.pyplot plt matplotlib import cm import numpy np import neptcon nc import sys import pickle fp = open("c:\python27\internal_reports\\shared.pkl") shared = pickle.load(fp) con = none cur, con = nc.connect() cur = con.cursor() scriptfile = open("c:\python27\internal_reports\ann_report_sql\den diff.sql", 'r') script = scriptfile.read() scriptfile.close() cur.execute(script.format(**shared)) items = cur.fetchall() client, ship, imo, diff = zip(*items) new_list = [] item in diff: new_list.append(int(item)) n = len( new_list ) x = range( n ) n_groups = n index = np.arange(n_groups) fig = plt.figure() f, (ax1) = plt.subplots(1, 1, figsize=(8, n/2), sharex=false) bar_width = 0.95 opacity = 0.5 g = nx.complete_graph(1

javascript - How to show one div on click and hide others on click using ui-route? -

my js: var app = angular.module("dashboardapp", ["ngmaterial", "nganimate", "ngsanitize", "ui.bootstrap", "ngaria", "ui.router", "datatables", "gridshore.c3js.chart"]); app.config(function($stateprovider, $urlrouterprovider, $locationprovider){ $locationprovider.hashprefix(''); $urlrouterprovider.otherwise('/systems'); $stateprovider .state('systems',{ url:"/systems", templateurl: 'pages/systems.html' }) .state('summary', { url:"/summary", controller:"maxectrl", templateurl: 'pages/summary.html' }); }); app.run(function($rootscope, $location, $anchorscroll, $stateparams, $timeout) { $rootscope.$on('$statechangesuccess', function(newroute, oldroute) { $timeout(function() {

python - Kmeans clustering with heatmaps -

just wondering how go using k means clustering data set? restricted using packages or modules. https://raw.githubusercontent.com/gsprint23/cpts215/master/progassignments/files/simple.csv this data set training one https://raw.githubusercontent.com/gsprint23/cpts215/master/progassignments/files/cancer.csv have been trying solve while, tried couple things none of them seemed have worked. no code required if give me general thought process solve i'd grateful. this current way of thinking. i'm trying put data heatmap current thought process first randomly choose centers. create list of lists each point distance each center. find index of minimum distance each point each center. create data frame of same size data set , fill each index each element index of center point closest to. recompute center taking mean of points same center index repeat process multiple times until index data frame not change. create new data frame , add points have same center point close in fra

Accessing kissmanga.com HTML with Python -

i trying access html of pages http://kissmanga.com/manga/shokugeki-no-soma can make function lets me know when new chapters of manga added. however, attempts access code have not been successful, because of website's requirements/securities. ways can past access website's html? import requests resp = requests.get('http://kissmanga.com/manga/hajime-no-ippo') print (resp.text) you're far away being able requests can ideas kiss anime plex plugin, have working python module requests through python: https://github.com/twoure/kissnetwork.bundle

Are Session Variables in ASP.Net MVC Industry standard? -

i writing database app returns recordsets controller. reuse them because static data, (based on user, different every user), , resort/search needed using linq based on multiple requests user. in past, session variables highly frowned upon, taboo, in asp.net mvc because 1 of benefits of technology was supposed fire , forget. seeing more people suggesting using session variables hold recordsets. is standard now, or there better way handle multiple requests use same recordsets? example, should make local service hold data service asp.net mvc application? else? in general, session frowned upon because of limitations. instance, it's highly serialized , can impact performance, although using attributes make session read-only can improve that. issue session volatile, , can literally go away whenever iis wants more memory. it's not secure, nor should used secure. a better option might using asp.net cache store data, or httpcontext.items array if need on per r

apache spark - How to get this using scala -

**df1** **df2** **output_df** 120 d 120 null 120 e b 120 null b 125 f c 120 null c d 120 d d e 120 e e f 120 null f g 120 null g h 120 null h 125 null 125 null b 125 null c 125 null d 125 null e 125 f f 125 null g 125 null h from dataframe 1 , 2 need final output dataframe in spark-shell. a,b,c,d,e,f in date format(yyyy-mm-dd) & 120,125 ticket_id's column there thousands of ticket_id's. extracted 1 out of here. full join of possible values, left join original dataframe: import hivec

phoenix - Unable to get data from Default and other user define schemas in Hbase using apache phoneix -

i trying table data ("default") schema in hbase using apache phoenix. , request body follows: {"request": "gettables","connectionid":"1875901652","schemapattern":"default"} and response contains rows empty else returned internal server error. note: have changed connectionid each , every request,but still issue exists.similarly other schema also.only "system" schema able data. please let know reason , how resolve same. in advance.

ios - Invalid Toolchain - xCode 9 GM Seed -

i previous developed apps in xcode 9 beta versions downloaded gm seed yesterday. have "cleaned" projects, re-built , uploaded them processing. i still receiving following automated message apple. invalid toolchain - new apps , app updates must built public (gm) versions of xcode 6 or later, macos, , ios sdk. don't submit apps built beta software including beta macos builds. will need re-build , upload when final xcode version released. you may have still beta of macos not in gm status? wait gm of os x.

java - is this considered a bad singleton design for mongoDB? -

public class dataservice { private static dataservice dataservice; private static mongoclient mongoclient; private static mongodatabase db; static { try { mongoclient = new mongoclient( "localhost" , 27017 ); db = mongoclient.getdatabase("mydb"); } catch (exception e) {} } private dataservice() {} public static dataservice getinstance() { if (dataservice == null) { dataservice = new dataservice(); } return dataservice; } public mongodatabase getdb() { return db; } } is bad design access mongodb? , singleton? suggests me solution if bad... sorry english. thank you

python - what are most frequently used real-time examples of Django custom middleware? It would be great if a code snippet is also shared -

what used real-time examples of django custom middleware? great if code snippet shared. a common piece of middleware forcing users use https. here's snippet: from django.conf import settings django.http import httpresponsepermanentredirect class sslifymiddleware(object): """force requests use https. if http request, we'll force redirect https.""" def process_request(self, request): secure_url = url.replace('http://', 'https://') return httpresponsepermanentredirect(secure_url)

python - How to get input from QTextEdit in PyQt4 -

how solve following problem unable text qtextedit , insert database... code: import sys import mysqldb #from pyqt4.qtcore import * pyqt4.qtgui import * e1=none e2=none def window(): app=qapplication(sys.argv) win=qwidget() win.setwindowtitle("sample") vbox=qvboxlayout() e1 = qtextedit() e2 = qtextedit() vbox.addwidget(e1) vbox.addwidget(e2) vbox.addstretch() b1=qpushbutton("tap it!") vbox.addwidget(b1) b1.clicked.connect(b1_action) win.setgeometry(100,100,200,50) win.setlayout(vbox) win.show() sys.exit(app.exec_()) def b1_action(): print "button clicked" db = mysqldb.connect('localhost', 'root', 'mysql', 'tecoc354') cursor=db.cursor() x1=e1.toplaintext() x2=e2.toplaintext() print x1," ",x2," " #sql="create table sample(addr varchar(10),name varchar(10))" # cursor.execute(sql) sql2="

amazon web services - AWS cognito forgot password flow -

i've created aws cognito user pool email required attribute , checked email verification. users created java spring backend service using awscognitoclient sdk , calling admincreateuser(createuser) method. user gets email temporary password, on signing in first time set new password. when execute forgot password flow, following error, invalidparameterexception: cannot reset password user there no registered/verified email or phone_number although have received temporary password email id signed , changed password first time above error. can explain missing? below javascript code executing forgot password flow, forgotpassword(username: string, poolinfo:any){ var pooldata = { userpoolid : poolinfo.poolid, // user pool id here clientid : poolinfo.portalclientid // client id here }; var userpool = new awscognito.cognitoidentityserviceprovider.cognitouserpool(pooldata); var userdata = { username : username

ImportError: Couldn't import Django -

i've configured virtualenv in pycharm, when using python manage.py command, error shown: e:\video course\python\code\web_worker\mxonline>python manage.py runserver traceback (most recent call last): file "manage.py", line 17, in <module> "couldn't import django. sure it's installed , " importerror: couldn't import django. sure it's installed , available on pythonpath environment variable? did forget activate virtual environment? how should fix it, i've installed django. you need install django , error giving because django not installed. pip install django

model view controller - Error in IIS for failed assemblies -

i installing 1 software on windows 7 iis7.0. client pc. .net framework 4.0 , 4.5 installed. installed asp.net mvc3, vc2008,2010,2013 redistributable. after installing, web page not opening , showing error: [fileloadexception: not load file or assembly 'system.web.mvc, version=4.0.0.1, culture=neutral, publickeytoken=31bf3856ad364e35' or 1 of dependencies. my web config file is: <?xml version="1.0"?> <!-- note: alternative hand editing file can use web admin tool configure settings application. use website->asp.net configuration option in visual studio. full list of settings , comments can found in machine.config.comments located in \windows\microsoft.net\framework\v2.x\config --> <configuration> <appsettings> <add key="forcemapimage" value="false"/> <add key="mapprovider" value="leaflet"/> <!-- bing, leaflet --> <add key="