Posts

Showing posts from February, 2014

python - Can't add legend in figure -

Image
i want add legend figure, doesn't show. in code below "forecast_canvas" instance of class canvas created in qt designer. ax = self.forecast_canvas.figure.add_subplot(111) ax.plot(self.new,'--',label='observed') ax.plot(data,color='green',label='forecast') self.forecast_canvas.draw() here's code of canvas : from matplotlib.backends.backend_qt4agg import figurecanvasqtagg figurecanvas import matplotlib.pyplot plt pyqt4 import qtgui class canvas(figurecanvas): def __init__(self, parent=none): self.figure = plt.figure() #plt.tight_layout(pad=4) figurecanvas.__init__(self, self.figure) self.setparent(parent) figurecanvas.setsizepolicy(self, qtgui.qsizepolicy.expanding, qtgui.qsizepolicy.expanding) figurecanvas.updategeometry(self) #plt.legend() i tried adding plt.legend() ...

ios - How to zoom out UIImageView content(image) on scroll of UITableView? -

Image
i trying achieve effect: https://cdn.dribbble.com/users/124059/screenshots/3727352/400.gif for i'm doing: override func tableview(_ tableview: uitableview, willdisplay cell: uitableviewcell, forrowat indexpath: indexpath) { let cell = tableview.dequeuereusablecell(withidentifier: "cardcell", for: indexpath) as! cardtableviewcell uiview.animate(withduration: 0.5, delay: 0.3, usingspringwithdamping: 0.1, initialspringvelocity: 0.5, options: .curveeaseinout, animations: { cell.coverimageview.transform = cgaffinetransform(scalex: 0.7, y: 0.7) }, completion: nil) } but code resizes uiimageview frame, not image inside of uiimageview. how can improve code? the trick mess frame of imageview make redraw , content mode changing. can manipulating frame or constraints , have masked inside view. run example , let me know. import uikit class viewcontroller: uiviewcontroller { var imageview = uiimageview() var maskview = uiview()...

python - batch data prefetching uisng queue on sharded data files -

i generated 500 sharded numpy data files, each of them contains 10000 data samples (e.g., image , label), example: file-000001.npy file-000002.npy file-000003.npy ... file-000500.npy each of .npy contains numpy dictionary keys , size {'image':10000x3x512x64 (dtype=np.float32),'label':10000x100 (dtype=np.float32)} . please note of these numpy files contain less 10000 samples, 8111 etc. during training, each epoch, need iterate 500x10000 samples. these data cannot loaded memory due capacity limits. common solution data prefetching queue. my thought follows: (1) first record filenames , count of data samples in each file, (2) each batch, compute batch indices, corresponding data files needed loaded memory read data samples compose batch data. during step (2), if set batch size 256 , possible need read 256 files , read 1 sample in each of them compose batch data. might slow , unpractical. based on queue, data loading might running ...

php - QTranslate Wordpress Pages Error 500 -

i have installed qtranslate on testing server on wordpress install. have transferred install live server (different web host) , when try , edit page, it's white (error 500 think). it's fine when trying edit posts, it's on pages editor goes white. i've tried reinstalling plugin, flushing database, changing .htaccess, increasing memory limit.... any ideas? help appreciated. thanks!

mongoose - Posting to a MongooseDB with .create -

so trying simple list work , update mongoosedb. using own variables determined. here code: app.post("/forumdetailsheader", function (req, res){ forumdetail.create({ text: req.body.text, done: false }, function(err, detail){ if (err) res.send(err); }); }); everything working , getting called correctly, except never show in mongoosedb has posted there correctly.

sdn - RYU: Simple switch test is giving OFPBAC_BAD_OUT_PORT error -

i running simple switch test simple switch test i running on real sdn switch , openvswitch installed on server. port numbers correct. mapping of port numbers correct. port number 30 on real sdn switch , connected port 1 on openvswitch conncected together. 3 links connected between server(openvswitch) , switch(real) my json file [ "action: 00_output", { "description": "ethernet/ipv4/tcp-->'actions=output:30'", "prerequisite":[ { "ofpflowmod":{ "table_id":0, "instructions":[ { "ofpinstructionactions":{ "actions":[ { "ofpactionoutput":{ "port":30 } } ...

c - What are the differences between constant expressions and nonmodifiable lvalues? -

from c in nutshell: constant expressions the compiler recognizes constant expressions in source code , replaces them values. resulting constant value must representable in expression’s type. may use constant expression wherever simple constant permitted. operators in constant expressions subject same rules in other expressions. because constant expressions evaluated @ translation time, though, cannot contain function calls or operations modify variables, such assignments. what constant expressions? doesn't define constant expressions what differences between constant expressions , non-modifiable lvalues (e.g. array names, lvalues have been declared const ) are constant expressions non-lvalues? are non-modifiable lvalues constant expressions? what constant expressions? §6.6- constant expression: a constant expression can evaluated during translation rather runtime, , accordingly may used in place constant may ...

python - Checking for new messages -

i'm trying make simple autoreply script. i've made infinite loop request client.get_message_history(entity, limit=10) every second. (hopefully there no more 10 new messages second) check if there new messages , send reply client.send_message but don't think idea spam telegram servers each second. may there more efficient ways without unnecessary spamming?

ruby on rails - ElasticSearch - Search Nested Associations with Multi Match -

i having issues searching nested fields multi_match. following represents database structure: normalbrands has_many => normalmodels has_many => products i've run index on products , included parent , grandparent associations nested document types. here mapping: curl -xget 'localhost:9200/products/_mapping/product?pretty' { "products" : { "mappings" : { "product" : { "dynamic" : "false", "properties" : { "name" : { "type" : "text", "analyzer" : "synonym" }, "normal_model" : { "type" : "nested", "properties" : { "machine_type" : { "type" : "text", "analyzer" : "english" }, "name...

postgresql - Postgre SQL parametrized query for C# -

i'm trying create parametrized commad postgre in c#. goal write list of strings db table. list<string> list = new list<string> { "listitem1", "listitem2", "listitem3" }; command.commandtext = "insert table (item) values (@listitem);"; foreach (var item in list) { command.parameters.addwithvalue("listitem", item); command.executenonquery(); } this code finish listitem1 written in db table 3 times. guess need separate paramater name value, don't know how. help? thanks. addwithvalue adds new parapeter on each iteration. should declare parameter once : list<string> list = new list<string> { "listitem1", "listitem2", "listitem3" }; command.commandtext = "insert table (item) values (@listitem);"; // declare parameter once ... //todo: specify parameter's value type second argument command.parameters.add("@listitem");...

intellij idea - Log4J Attempting to Access Non-existent Path -

i decided become better acquainted code style verification tools, installed eslint in intellij following instructions in following link: eslint installation some time after installing attempted deploy webapp working on, had following error: 2017-08-14 10:21:58,807 info [org.jboss.web.tomcat.service.deployers.tomcatdeployment] (rmi tcp connection(2425)-10.130.171.44) deploy, ctxpath=/campuspunch log4j:error not create appender. reported error follows. java.security.accesscontrolexception: access denied (java.io.filepermission \users\idok\projects\eslint-plugin\temp\log.txt write) @ java.security.accesscontrolcontext.checkpermission(unknown source) @ java.security.accesscontroller.checkpermission(unknown source) @ java.lang.securitymanager.checkpermission(unknown source) @ java.lang.securitymanager.checkwrite(unknown source) @ java.io.fileoutputstream.<init>(unknown source) @ java.io.fileoutputstream.<init>(unknown source) @ org.apache.log4j.fileappender.setfile(filea...

python - How can I use list comprehension in following scenario? -

for key in enron_data.keys(): if(enron_data[key]['email_address'] != 'nan'): count += 1 print count enron_data 2d dictionary, containing names & value,key pairs can use len(..) len( [v v in enron_data.values() if v['email_address'] != 'nan'] )

Melt and Merge on Substring - Python & Pandas -

i have data has data id name model_# ms bp1 cd1 sf1 sa1 rq1 bp2 cd2 sf2 sa2 rq2 ... 1 john 23984 1 23 234 124 25 252 252 62 194 234 234 ... 2 john 23984 2 234 234 242 62 262 622 262 622 26 262 ... for hundreds of models 10 ms , variables counting 21. i have used pd.melt doing analysis @ bp1:bp21 or whatever. have need create melt @ bp1 values along rq 1 values. i looking create this: id model_# ms variable_x value_x variable_y value_y 0 113 77515 1 bp1 23 rq1 252 1 113 77515 1 bp2 252 rq2 262 2 113 77515 1 bp3 26 rq3 311 right best have been able is: id model_# ms variable_x value_x variable_y value_y 0 113 77515 1 bp1 23 rq1 252 1 113 77515 1 b...

deep learning - ResNet RGB means in tensorflow-slim -

i using tensorflow slim load pre-trained models vgg , resnet-50. vgg , tf-slim provides way load rgb mean values like: from preprocessing.vgg_preprocessing import (_mean_image_subtraction, _r_mean, _g_mean, _b_mean) i couldn't find similar resnets. not implemented yet? know libraries py-torch provide global mean values every model. case tf-slim too?

java - org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing -

i'm using spring boot , and spring data in project , have 2 classes: class mission implements serializable { private static final long serialversionuid = 1l; @id @generatedvalue( strategy = generationtype.identity ) private long id; private string departure; private string arrival; private boolean isfreewayenabled; @onetomany( mappedby = "mission" ) private list<station> stations; // getters , setters } and second class : @entity public class station implements serializable { private static final long serialversionuid = 1l; @id @generatedvalue( strategy = generationtype.identity ) private long id; private string station; @manytoone( fetch = fetchtype.lazy ) @jsonbackreference private mission mission; //getters , setters } methode add mission: public mission addmision( mission mission ) { // todo auto-generated method stub // mission mission = getmissionbyid...

FabricJs: creating a grid of lines; getting the width and height of each region -

i want create grid of draggable lines. once create grid, i'd able width , height of each region. example: 1 vertical line , 1 horizontal create 4 regions. using fabricjs, i'm able create lines, i'm able drag left , right, , down, i'm not sure how width , height each region. i trying see how code worked on link, can't quite grasp it: detecting regions described lines on html5 canvas

javascript - Uncaught Error: Module name "antlr4/index" has not been loaded yet for context on require.js -

i try use antlr4 on javascript, read https://tomassetti.me/antlr-and-the-web/ , make error has occurred. index.html <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>title</title> <script type="text/javascript" src="lib/require.js"></script> <script type="text/javascript"> var antlr4 = require('antlr4/index'); var querylexer = require('gram/querylexer'); var queryparser = require('gram/queryparser'); document.getelementbyid("parse").addeventlistener("click", function() { var input = document.getelementbyid("code").value; var chars = new antlr4.inputstream(input); var lexer = new querylexer.querylexer(chars); var tokens = new antlr4.commontokenstream(lexer); var parser = new queryparser.queryparse...

Scenario in BDD(behave) can have without 'Given'? -

can write 'scenario' in behave without 'given' , directly start 'when' ? more description: 'background' section in state requires test scenario. hence, wanted start directly 'when' , perform actions. simply, yes. seen in example: feature: testing feature without given scenario: no given step when have no given step our test should still work # coding: utf-8 behave import * @when("we have no given step") def step_impl(context): pass @then("our test should still work") def step_impl(context): pass feature: testing feature without given # test.feature:1 scenario: no given step # test.feature:3 when have no given step # steps\step.py:5 our test should still work # steps\step.py:10 1 feature passed, 0 failed, 0 skipped 1 scenario passed, 0 failed, 0 skipped 2 steps passed, 0 failed, 0 skipped, 0 undefined took 0m0.002s however, may not best p...

regex - How to match a pattern with unrelated charaters/blank-space between two fixed strings? -

i'm trying match string in files begins imports: [ , not contain sharedmodule . can have number or spaces, line-breaks, or other characters (words) in between 2 strings. i've been trying find with: grep 'imports: \[[.*\s*]*sharedmodule' */*.module.ts but cannot find files have 'sharedmodule' in it. thought process .* find words , \s find blank space characters, , character class * selector allow show in order. can use character classes skip variable number of unrelated lines/characters? how negate statement returns lines without 'sharedmodule'? the goal append 'sharedmodule' import array wherever not exist. thanks! (i'm new , 1 thing i've learned far is: regular expressions hard) sample match: imports: [ ionicpagemodule.forchild(formpage), dynamicformcomponentmodule, sharedmodule ], should not match but imports: [ ionicpagemodule.forchild(leadershippage), ], should. grep doesn't process mul...

php - Official PayPal IPN Issue -

after bit of googling noticed paypal using new ipn class got github: https://github.com/paypal/ipn-code-samples i installed it, , started passing post variables it: paypalipn.php <?php class paypalipn { /** * @var bool $use_sandbox indicates if sandbox endpoint used. */ private $use_sandbox = true; /** * @var bool $use_local_certs indicates if local certificates used. */ private $use_local_certs = true; /** production postback url */ const verify_uri = 'https://ipnpb.paypal.com/cgi-bin/webscr'; /** sandbox postback url */ const sandbox_verify_uri = 'https://ipnpb.sandbox.paypal.com/cgi-bin/webscr'; /** response paypal indicating validation successful */ const valid = 'verified'; /** response paypal indicating validation failed */ const invalid = 'invalid'; /** * sets ipn verification sandbox mode (for use when testing, * should not enabled in production)....

Android VPN connection java.net.UnknownHostException: Unable to resolve host "<url>" No address associated with hostname -

i trying connect server using vpn connection. connected pc using cisco anyconnect. when trying connect android code, find exception: java.net.unknownhostexception: unable resolve host "<url>" no address associated hostname here code: try { url endpoint = new url(sauthenticateurl); httpurlconnection connection = (httpurlconnection) endpoint.openconnection(); if (connection.getresponsecode() == 200) { // success } else { // error handling code goes here } } catch (ioexception e) { e.printstacktrace(); } the sauthenticateurl same used pc , works on it. note have connected android device pc internet connection, both use same network now. , pc connected vpn server. is there specific configuration should add able access vpn android? first of all, of cases may occur issue. check permission , sure have following permissions in manifest...

java - Project 'mymodule' not found in root project 'mymodule' -

i configured gradle project builds submodules when run ./gradlew build , goes flawless. when move subdirectory , run submodule ./gradlew :mymodule:build error project 'mymodule' not found in root project 'mymodule'. my grade root config: group 'com.example.core' version '1.0-snapshot' allprojects { apply plugin: 'java' version = '1.0' } subprojects { repositories { mavenlocal() } dependencymanagement { imports { mavenbom "org.springframework.boot:spring-boot-dependencies:${spring_boot_version}" } } dependencies { compile 'org.springframework.boot:spring-boot-starter-web' } } project(':mymodule1') { apply plugin: 'application' bootrepackage { mainclass = 'com.example.app' } springboot { mainclass = 'com.example.app' executable = true buildinfo() ...

Calculate Bounding Box Overlaps in Tensorflow -

let's have 2 tensors of bounding box coordinates: n , dimension [n, 4], , k , dimension [k, 4]. each row of each tensor represents x1, y1, x2, , y2 of bounding box. is there efficient method in tensorflow produce [n, k] matrix m m[i, j] = overlap(n[i, :], k[j, :]) ? ideally, overlap intersection-over-union, if it's simpler use method work. the source code of official object detection model has function calculating iou, see function intersection , iou reference

rvest - Saving Multiple Html Sources in R -

i have created following code library('xml') library('rvest') links <- c('https://www.google.com/', 'https://www.youtube.com/?gl=us', 'https://news.google.com/news/u/0/headlines?hl=en&ned=us') (i in 1:3){ html_object <- read_html(links[i]) write_xml(html_object, file="test.html") } i want save of these files html files, current code saving one. guessing keeps rewriting same file 3 times example. how make not rewrite same file? ideally, file name these html files url link, unable figure out how multiple links. example, end result should 3 html files titled ' https://google.com/ ', ' https://www.youtube.com/?gl=us ', , ' https://news.google.come/news/u/0/headlines?h1-en&ned=us '. what using paste0() create filename in for-loop? for(i in 1:length(links)){ html_object <- read_html(links[i]) somefilename <- paste0("filename_", i, ...

What are some good practices for managing free functions in a C++ project? -

i'm writing code implement sift feature detector , there free functions used throughout project e.g. int ialignup( int a, int b ){return (a%b != 0) ? (a + b - a%b) : (a);} int idivup( int a, int b ){return (a%b != 0) ? (a/b + 1) : (a/b);} should encapsulate these functions in unnamed namespace? wish manage code can later scale without problems. you have 2 options depending on whether used in single file or in multiple files. put them in unnamed namespace. if functions used within single source code file, can put them in unnamed namespace within file. namespace { int ialignup( int a, int b ){return (a%b != 0) ? (a + b - a%b) : a;} int idivup( int a, int b ){return (a%b != 0) ? (a/b + 1) : (a/b);} } put them in header file , internal namespace. if functions used in multiple source code files, not outside project, can put them in header file included within project, , put them in internal namespace. namespace project { namespace impl { inline i...

angular - Using component from imported module inside of child modules -

i have module export component expose other modules, want use component in modules children of module, importing first module in parent module enable use inside of child modules but, not convinced best way it. this shared module in root folder component want use: app/shared/shared.module.ts import {dtcomponent} './dt.component'; @ngmodule({ imports: [ commonmodule ], exports: [ dtcomponent ], declarations: [ dtcomponent ] }) export class datepmodule{ } i have module in app folder import datepmodule this: app/contacts/contacts.module.ts import {datepmodule} '../shared/shared.module.ts'; @ngmodule({ imports: [ commonmodule, datepmodule ] }) export class ctmodule{ } i need use dtcomponent directly in components of ctmodule , need component in other component in child modules of ctmodule . i can importing again datepmodule inside of child modules of ctmodule not convinced best approach. app/contacts/other/other...

svelte - Object destructuring for components -

i want able destructure object when pass svelte component. this? var o = { item: "bread", count: 12 } <component ...object> within component <b>{{item}}:</b> {{count}} currently seems have manually this <thing item={{thing.item}} count={{thing.count}} /> there discussion this while back, , decided hold off implementing spread attributes @ time because of concerns on how impact static analysis svelte does. it's still open debate though. something might if added destructing in each blocks, mean use compact :foo (equivalent foo='{{foo}}' ) so: {{#each things {item, count} }} <thing :item :count/> {{/each}} there isn't open issue that, should feel welcome create one! see doing @ point.

javascript - Setting title attribute for each summary tag if its parent details tag is open? -

i want add 'show' or 'hide' title each summary tag depends if parent details tag open: <details open> <summary>summary 1</summary> <p>text 1</p> </details> <details open> <summary>summary 2</summary> <p>text 2</p> </details> i tried shows 'hide' though details not set open: var detailselem = document.getelementsbytagname('details'); var summaryelem = document.getelementsbytagname('summary'); (i = 0; < summaryelem.length; i++) { if (detailselem[i].display === '') { summaryelem[i].title = 'show'; } else { summaryelem[i].title = 'hide'; } } i assume trying access element css property. if so, line wrong detailselem[i].display === '' . it should detailselem[i].style.display . also display cannot empty , values can either display , inline , inline-display , none ... here's b...

python - ImportError: When Trying to Import Custom File - Django JWT -

i'm using django-rest-framework-jwt generate token security, need user information token when logs in. way have seen create custom function override default functionality. i'm new django i'm still trying figure out how things work, have tried after reading this article. have tried many ways working, seems best approach. problem have when use current setup get: importerror: not import 'custom_jwt.jwt_response_payload_handler' api setting 'jwt_payload_handler'. importerror: no module named custom_jwt. 1 - after creating custom_jwt.py best practices on put it? if there none, suggestions on where? 2- how gain access functions in custom_jwt.py in settings.py ? settings.py jwt_auth = { 'jwt_payload_handler': 'custom_jwt.jwt_response_payload_handler', 'jwt_response_payload_handler': 'custom_jwt.jwt_payload_handler', } custom_jwt.py from datetime import datetime calendar import timegm rest_fram...

c# - Get maximum HSV values from image in emguCV -

i'm trying maximum values of hue, saturation , value image converted hsv in c# using emgucv. in opencv can use vec3b how can same effect in c#? i not sure there direct equivalent. if want max of each channel can split hsv mat 3 channels , getrangevalue should return max , min each channel. mat orig = new mat(@"c:\users\public\pictures\sample pictures\koala.jpg", imreadmodes.color); using (mat hsv = new mat()) { cvinvoke.cvtcolor(orig, hsv, colorconversion.bgr2hsv); mat[] channels = hsv.split(); rangef h = channels[0].getvaluerange(); rangef s = channels[1].getvaluerange(); rangef v = channels[2].getvaluerange(); console.writeline(string.format("max h {0} min h {1}", h.max, h.min)); console.writeline(string.format("max s {0} min s {1}", s.max, s.min)); console.writeline(string.format("max v {0} min v {1}", v.max, v.min)); mcvscalar mean = cvi...

ruby on rails - How to write this query using active record query interface? -

i have products table jsonb type specs column. 1 of keys in json brand . i can run query this: select specs ->> 'brand' brand, count(*) products group brand; brand | count -------------+------- acer | 9 dell | 4 xps 15 | 1 apple | 1 lenovo | 2 gigabyte | 1 eluktronics | 5 asus | 2 hp | 1 how can run query using active record query interface? i tried like: product.select("specs ->> 'brand' brand").group('brand').count not work , get: activerecord::statementinvalid: pg::syntaxerror: error: syntax error @ or near "as" line 1: select count(specs ->> 'brand' brand) count_specs_bran... ^ : select count(specs ->> 'brand' brand) count_specs_brand_as_brand, brand brand "products" group brand (irb):1 the following should work , ...

cypher - Make neo4j query last long for testing purposes? -

we want create slow query test in our application. there way make neo4j query last specific amount of seconds? i believe can use apoc procedure apoc.util.sleep . according docs: apoc.util.sleep({duration}) : sleeps millis, transaction termination honored for example: call apoc.util.sleep(1000) // wait 1 second match (node) // match 'node'... return node // ... return 'node' please remember install apoc procedures according version of neo4j using. take in version compatibility matrix .

c# - Does "Async" keyword is the only requirement in making NLog logging asynchronous? -

i writing target database. in targets section, have marked async true. still need write code web service make logging async or framework takes care of it? <targets async="true"> yes, async attribute needed (in config) the async keyword in c# isn't needed. ps: aware async attribute discard default if write more 10000 events in short time. if need more control, use asyncwrapper instead of async attribute. see docs

.net - c# UserControl property - setting list of string for custom property - List<string> -

after spending log of time not able solve problem. i have list in usercontrol not able bind custom property @ design time. here design screenshot error public partial class taglistcontrol : usercontrol { private hashset<string> _tags; private list<string> _tags; //[browsable(false)] // hiding because it's not working in //[editor("system.windows.forms.design.stringcollectioneditor, system.design, version=2.0.0.0, culture=neutral, publickeytoken=b03f5f7f11d50a3a", typeof(uitypeeditor))] [designerserializationvisibility(designerserializationvisibility.content)] public list<string> tags { { _tags = _tags.tolist(); return _tags; } set { value = value ?? new list<string>(); _tags = value; value.foreach(x => { string[] tags = x.split(','); foreach (string tag in tags) ...

How to connect file inbound/outbound adapter and http inbound/outbound adapter or gateway in spring integration? -

i developing service adapter poll directory/subdirectories files , , parse file using spring batch , not understanding flow of file adapter +spring batch parser + http adapter connectivity , please suggest me better approach . in advance. there examples of using file inbound channel adapters, channels connect components , integration spring batch here .

php - jquery ajax dynamic form with dynamic inputs only submiting the first form -

i in development phase of freelancer market dashboard.the main idea of sending offer fiverr. seller view buyer request displaying through while loop on view request it showing model box of details of specific request on sending offer new model box appears containing seller gigs ..now here created dynamic form respect gigid .. following js code view , submiting form function showform(seller) { var a=seller; alert(a); $("."+a).toggle(); } function submitproposal(buyerid,gigsellerid) { var buyerid=buyerid; var gigsellerid=gigsellerid; var sellerrole = $("#sellerrole_"+gigsellerid).val(); var sellerid = $("#sellerid_"+gigsellerid).val(); var detail = $("#details_"+gigsellerid).val(); var price = $("#price_"+gigsellerid).val(); var duration = $("#duration_"+gigsellerid).val(); var revision = $("#r...

java - Iterating Through Treemap Ordered By Comparator -

i created treemap sorted value through comparator passed constructor. how iterate through treemap in order created comparator? (not ascending value of keys/values) you cannot treemap . a workarround using linkedhashmap keep insertion order. , want map sorted comparator , create an instance of treemap comparator , put elements in contained in linkedhashmap . map<myobject> linkedhashmap = new linkedhashmap<>(); .... treemap<myobject> treemap = new treemap<>(new mycomparator()); treemap.putall(linkedhashmap);

Splitting xml tag in python -

i need split below xml tag using split function in python <item name="caption" type="string">python</item> the split function have used: output = data.split("<item name=title type=string>")[1].split("</item>")[0] for simple tag, can this: def get_xml_tag_content(tag: str) -> str: return tag.split('>')[1].split('<')[0] tag = '<item name="caption" type="string">python</item>' tag_content = get_xml_tag_content(tag) print(tag_content) # python at first, split our tag the closing > of opening tag , take second element of result, python</item> , , split the opening < of closing tag , take first element, tag's content. ( python )

for loop - Summation of max function with vector input in R? -

i want build function: f(a,b)=sum_{i=1 n}(max(a-b_i,0)) b=(b_1,b_2,...b_n). have done: vec<-function(a,b){ z<-0 for(i in b){ ifelse(a > i,z <- z + (a-i), 0) } return(data.frame(z)) } this code gives correct output scalar input of a. while using vector output answers not correct. example > vec(c(-6,5),c(3,1,3)) gives -25 a=-6 , 8 a=5 respectively. > vec(-6,c(3,1,3)) gives 0. , correct answer. please throw give idea how correct it. when let a = c(-6,5) , argument a > i becomes (false, true) . since contains true, vector passed z <- z + (a-i) . note if use a=-6 in formula, output of -25 . suggest doing this: vec<-function(a,b){ z<-0 for(i in b){ p <- ifelse(a > i,z <- z + (a-i), 0) } return(data.frame(p)) }

javascript - How to change a call for a WordPress user id to a call for a users display name -

i working on modifying plugin in attempt make better fit needs. have been having tremendous amounts of trouble switching using users id users display name. have included original , edits below. or recommendations appreciated! original code: <?php class chatroom { function __construct() { register_activation_hook( __file__, array( $this, 'activation_hook' ) ); register_deactivation_hook( __file__, array( $this, 'deactivation_hook' ) ); add_action( 'init', array( $this, 'register_post_types' ) ); add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) ); add_action( 'save_post', array( $this, 'maybe_create_chatroom_log_file' ), 10, 2 ); add_action( 'wp_head', array( $this, 'define_javascript_variables' ) ); add_action( 'wp_ajax_check_updates', array( $this, 'ajax_check_updates_handler' ) ); add_action( 'wp_ajax_send_message', arr...