Posts

Showing posts from August, 2011

validate mathematical variables expression in java -

which way validate mathematical variables expression. whether can use stack or regex expression. i have gone http://www.sanfoundry.com/java-program-implement-evaluate-expression-using-stacks/ note: expression not contain parenthesis. example: valid: x+3-y/2 x+y 2+4+e invalid: x++4+8 e-3r e+r34- how validate above expressions?i need validate mathematic expression input provided user in java if no parentheses (i.e. nesting expressions) allowed, validation done simple regex: final pattern pattern = pattern.compile("([0-9]+|[a-z]+)([-+*/]([0-9]+|[a-zaz]+))*"); (string s : arrays.aslist("123", "x+3-y/2", "x+y", "2+4+e", "x++4+8", "e-3r", "e+r34-", "---x+3-y/2")) { system.out.format("%5s %s\n", pattern.matcher(s).matches(), s); } the output is true 123 true x+3-y/2 true x+y true 2+4+e false x++4+8 false e-3r false e+r34- false ---x+3-y/2

css - Can I make a file always load from server? -

this question has answer here: how force browser reload cached css/js files? 42 answers in website have changed css of page , these changes not reflecting instantly when open page in browser. showing old css styles because browser has saved copy of css file , not reflecting new changes. the new changes loading in page when load page pressing (ctrl+f5) changes have done reflected in page. can make css file loaded server , changes done page can reflect on page. try adding head tag <meta http-equiv="expires" content="0">

slick - Scala Play Forms: using HLists to get around the 22 fields limitation -

slick uses kind of hack hlists manage tables have more 22 columns, instance (auto-generated) row model constructor: type samplesrow = hcons[int,hcons[string,hcons[option[string],hcons[int,hcons[string,hcons[int,hcons[int,hcons[option[int],hcons[option[float],hcons[option[float],hcons[option[string],hcons[option[string],hcons[boolean,hcons[option[string],hcons[option[string],hcons[option[string],hcons[option[string],hcons[option[string],hcons[option[int],hcons[option[float],hcons[option[float],hcons[option[float],hcons[option[string],hcons[option[string],hnil]]]]]]]]]]]]]]]]]]]]]]]] def samplesrow(id: int, name: string, shortname: option[string] = none, sampletypeid: int, receiveddate: string, projectid: int, taxoid: int, quantifmethodid: option[int] = none, concentration: option[float] = none, volume: option[float] = none, description: option[string] = none, comment: option[string] = none, istrashed: boolean = false, commentcustomer: option[string] = none, createdat: option[stri

angular - Angular2 service emitter subscribe fail -

referring global events in angular 2 trying implement cart service emits event when new item added cart. subscribe service event in component called navbar (which not child of cart) show number of cart items etc. my cart service: export class cartservice { public itemadded$: eventemitter<any>; ... constructor(private http: http){ this.itemadded$ = new eventemitter(); this.cart=[]; } addtocart(id: any): { this.itemadded$.emit(id); return this.http.get( this.myurl + 'add' + '/' + id + '/', { withcredentials:true}) .topromise() .then(response => response.json()) } ... ... } my navbar component: @component({ directives:[router_directives, cart], providers:[cartservice], }) export class navbar implements oninit{ ... totalcost: any; cartitemcount : any; addeditem: any; constructor(private cartservice: cartservice){ this.cartservice.

images paste in python -

can tell me how use img.paste in python, i can if once this from pil import image img = image.open("images.tiff") sub_image = img.crop(box=(0,0,250,250)).rotate(180) sub_image2 = img.crop(box=(100,0,350,250)).rotate(180) final_image = img.paste(sub_image, box=(0,0,250,250)) img.save("images2.tiff") but iam try from pil import image img = image.open("images.tiff") sub_image = img.crop(box=(0,0,250,250)).rotate(180) sub_image2 = img.crop(box=(100,0,350,250)).rotate(180) final_image = img.paste(sub_image, box=(0,0,250,250)) final_image = img.paste(sub_image2, box=(100,0,350,250)) img.save("images2.tiff") that code error in line 6 or from pil import image img = image.open("images.tiff") sub_image = img.crop(box=(0,0,250,250)).rotate(180) sub_image2 = img.crop(box=(100,0,350,250)).rotate(180) final_image = img.paste(sub_image, box=(0,0,250,250)), img.paste(sub_image2, box=(100,0,350,250)) img.save("imag

android adb take screenshot in specific resolution -

is possible take screenshot on android device using adb in specific resoltion? e.g screen resolution of device 1280x720, when run such command "adb shell /system/bin/screencap -p /sdcard/screenshot.png" screenshot saved in resolution 1280x720. how can take screenshot in 320x240 without resizing after screenshot taken?

.htaccess - How to rewrite url in htaccess without redirecting on localhost? -

trying ask question again , explain best can. i running wamp on windows 10. apache version 2.4.18. project in www folder named hoidja.ee . mod_rewrite enabled, allowoverride is set all. inside folder have .htaccess file, trying accomplish rewrite without redirect , not work @ all. know .htaccess file working, since can rewrite index.php /home/ example , working fine. i have page users listing. can click on user, , take url: http://localhost/hoidja.ee/hoidja.php?user_id=94&username=john how show is http://localhost/hoidja.ee/user/john without redirection. what have tried: #tried first user_id rewritecond %{query_string} ^user_id=([a-za-z0-9-]+)$ rewriterule ^hoidja\.php$ /user/%1? [l] this gave me 404 /user/94 doesn't exist. rewriterule ^user/([0-9]+)/([a-za-z0-9-]+)/?$ hoidja.php?user_id=$1&username=$2 [qsa] this doesn't visually. if enter http://localhost/hoidja.ee/user/94/john in url manually, goes page , shows user data, if enter or

php - Passing selected date value to a query -

this question has answer here: when use single quotes, double quotes, , backticks in mysql 10 answers i found similar questions here of solutions don't work me. have form 'jquery ui date picker' , want search results on given date. tried changing date formats doesn't return result. search form- <div class="form-group row"> <label for="duration" class="col-sm-4 col-form-label"> <input type="checkbox" name="search2" value="checkbox" id="duration" class="search2"> duration</label> <div class="col-sm-4"> <input type="date" class="form-control input-sm data2" name="data1" id="startdate" placeholder="start date" disabled="disabled"> </div> &

download - Is there a way to recover an entire website from the wayback machine? -

my website files got corrupted , lost backup files somehow. can 1 please suggest process download entire site. its simple html site. once after downloading how can host ? please help you can't use regular crawler because contents served have original links, out of first page when you're crawling if don't rewrite links: in browser rewritten client-side script point wayback machine. if it's simple html, mentioned, , small might want save pages manually or copy contents hand new website structure. if it's not small, try tools mentioned in answers similar question in superuser: https://superuser.com/questions/828907/how-to-download-a-website-from-the-archive-org-wayback-machine after downloading may have check structure of files downloaded links may have been incorrectly rewritten or missing files. links point files belong website should local links , not external ones. can host again on web hosting service of preference.

scala - DataFrames for Apache Spark MLLib online real-time single-item prediction, seriously? -

having trained mllib model, have convert every incoming item in online system dataframe call predict/transform-like method on it? looks overkill high risk of time/memory-related issues. can build/transform/predict 1 row somehow, or that? (solution in scala preferable) i've found text authors they've implemented of own this: https://www.oreilly.com/ideas/training-and-serving-nlp-models-using-spark-mllib

java - RFID ReaderTrack Loop -

hey guys i'll project call "rfid management system" i found samlpe code websites , add few codes it. my rfid can read number mifare card right now, face problem : how create loop rfid machine in order read card again , again without pushing "run" button in eclipse import java.util.list; import javax.smartcardio.*; import javax.xml.bind.datatypeconverter; public class blog { public static void main(string[] args) { try { // display list of terminals terminalfactory factory = terminalfactory.getdefault(); list<cardterminal> terminals = factory.terminals().list(); system.out.println("terminals: " + terminals); // use first terminal cardterminal terminal = terminals.get(0); // connect wit hthe card card card = terminal.connect("*"); system.out.println("card: " + card); cardchannel channel = card.getbasicchannel(); // send select applet command responseapdu answer = channel.tra

rust - `if` condition remains borrowed in body -

this question has answer here: why borrow still held in else block of if let? 4 answers i came across behaviour in rust (1.12) cannot explain. have struct implements lazy loading refcell<option<i32>> , function access data: struct foo { data: refcell<option<i32>> } impl foo { fn get_data(&self) -> i32 { if self.data.borrow().is_none() { // <--- (a) let d = 1337; self.data.borrow_mut() = some(d); // <--- (b) d } else { self.data.borrow().unwrap() } } } this compiles yields runtime error: refcell complains borrow active when attempting borrow_mut on line (b) . issue not occur, however, if change if statement following: let is_none = self.data.borrow().is_none(); if is_none { question: why borrow in if condition on line (a) still active

jquery - Javascript not following step by step instruction -

this html $(function(){ $(".button1").on("click",function(){ $(".img").css("display","block"); $(".bord").append('<div class="test1">11111111</div>'); $(".img").css("display","none"); }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <div class="parent"> <div class="button1">button1</div> <div class="button2">button2</div> </div> <div class="bord"> <img src="http://www.mtlexs.com/images/reload.gif" class="img" style="display: none;"> </div> here write code , when button1 click show image, display text, hide image . here image not showing t

osx - Core Data entity name equivalence -

i have hierarchical entities named {foo, fooa, foob, etc}. when creating new entity object method insertnewobjectforentityforname: , tried following: #define namefoo @"foo" #define namefooa @"fooa" [nsentitydescription insertnewobjectforentityforname:[namefoo stringbyappendingstring:@"a"] inmanagedobjectcontext:context]; even though [namefooa isequaltostring:[namefoo stringbyappendingstring:@"a"]] returns yes, runtime error entity not found. using namefooa work, hoping re-use code. there way make work?

swift - data lost in segue (xcode8.0) -

i beginner in swift , try develop simple program shows characterisitcs of ble. confirmed print captured uuid of target characteristics mycharacteristicuuid_1 : ( "manufacturer name string", "model number string", "serial number string", "hardware revision string", "firmware revision string", "software revision string" ) however, in override func prepare(for segue: uistoryboardsegue, sender: any?), checked again print , see data gone below; mycharacteristicuuid_2 : ( ) i can hand on other types of values (e.g.string, text,etc..) can't handle data captured ble. can point out have when use data ble in segue ? below code; func peripheral(_ peripheral: cbperipheral, diddiscovercharacteristicsfor targetservice: cbservice, error: error?) { if error != nil { print("characteristic not found : \(error)") } let foundcharacteristics = targetservice.characteristics

python - Reading CSV file in WinPython -

i want merge 2 csv files in spyder, import pandas pd data1 = pd.readcsv('c:/rdata/plant1.csv') data2 = pd.readcsv('c:/rdata/species.csv') newdata = pd.merge(data1, data2, on='speies') but got error: ………………………………, line 9, in <module> data1 = pd.readcsv('c:/rdata/plant1.csv') attributeerror: 'module' object has no attribute 'readcsv' how can fix problem? obviously there not function named 'readcsv'. read_csv. import pandas pd data1 = pd.read_csv('c:/rdata/plant1.csv') data2 = pd.read_csv('c:/rdata/species.csv') newdata = pd.merge(data1, data2, on='speies')

Use string as a property in lambda expression c# -

this question has answer here: get property value string using reflection in c# 16 answers i have method pass string , list in to. i'm trying achieve convert string lambda expression property. private somemethod(string mytypestring, list<values> typelist) { foreach(var type in typelist.where(x => x."mytypestring" > datetime.now)) { //do loop } } is there way that? you can try using reflection : using system.reflection; ... private void somemethod(string mytypestring, list<values> typelist) { propertyinfo pi = typeof(values) .getproperty(mytypestring, system.reflection.bindingflags.instance | system.reflection.bindingflags.nonpublic | // private/internal/protected system.reflection.bindingflags.public); // property exists, can read , returns datetime if

jquery - Remove element from array of objects javascript -

i have following array of objects. [{"rid":24,"gid":40,"sid":20,"disabled":false}, {"rid":24,"gid":40,"sid":19,"disabled":false}, {"rid":24,"gid":40,"sid":50,"disabled":false}, {"rid":24,"gid":40,"sid":20,"disabled":true}, {"rid":24,"gid":40,"sid":19,"disabled":true}, {"rid":24,"gid":40,"sid":50,"disabled":true}, {"rid":24,"gid":39,"sid":18,"disabled":false}] in records antithesis ex. 1st element , 4th has same rid, gid, , sid disabled flag opposite. want eliminate such records. my expected array {"rid":24,"gid":39,"sid":18,"disabled":false} (eliminate antithesis records) i tried following code giving me wrong output. arrofobj=[{"rid&qu

rhel6 - Getting 301 Moved Permanently from Apache HTTPD -

i trying create local repository on rhel 6 vm in azure using apache httpd, getting 301 when try curl on path. $ yum install httpd i 2.2.15 version default. then untar tarball in /var/www/html and when try curl: $ curl --head http://<fqdn>/hdp/hdp-utils-1.1.0.21/repos/centos6/ i result: 1.1.0.21/repos/centos6 http/1.1 301 moved permanently date: tue, 08 nov 2016 11:11:03 gmt server: apache/2.2.15 (red hat) location: http://<fqdn>/hdp/hdp-utils-1.1.0.21/repos/centos6/ connection: close content-type: text/html; charset=iso-8859-1 however, when moved original compressed file (tar.gz) within /var/www/html , , try curl on that, 200. what should configuring correct this?

x86 - Connecting C# Application to MS Access 2013 DB -

i'm using vs 2012 & office 2013 64 bits, , changed target platform x86, still got weard error the 'microsoft.ace.oledb.12.0' provider not registered on local machine". you need download 2 components: 1) microsoft access database engine 2) office system driver: data connectivity components after these installations application start work. furthermore, following link better use on access database: void test() { string connstr = "provider=microsoft.ace.oledb.12.0;data source=|datadirectory|\\database1.accdb;persist security info=false;"; oledbconnection conn = new oledbconnection(baglanticumlesi); conn.open(); conn.close(); }

Android Warning - Ignoring InnerClasses attribute (jnamed) -

i have warning when building code in android studio. few times don't show up, of times do. warning: ignoring innerclasses attribute anonymous inner class (jnamed$1) doesn't come associated enclosingmethod attribute. class produced compiler did not target modern .class file format. recommended solution recompile class source, using up-to-date compiler , without specifying "-target" type options. consequence of ignoring warning reflective operations on class incorrectly indicate *not* inner class. warning: ignoring innerclasses attribute anonymous inner class (jnamed$2) doesn't come associated enclosingmethod attribute. class produced compiler did not target modern .class file format. recommended solution recompile class source, using up-to-date compiler , without specifying "-target" type options. consequence of ignoring warning reflective operations on class incorrectly indicate *not* inner class. warning: ignoring innerclasses attribute anonymous

github - push files into git remote repo using different user account -

i want push code changes git remote repo, able pull changes not allowing me push changes. using ssh key authentication authorization, keys generated using email id. windows system doing development admin account. have kept required private public key .ssh folder since windows user different account using configured key giving pre-receive hook declined error. have tried setting user name , user email same account used key gen using git config command, not luck far. appreciated. i able eclipse. configured ssh key path in network setting , commit code using account, first add untracked files git index , able see file in git staging view. there show staged changes , enter commit message, there author , committer default having value of whichever user account have logged in in case admin account, changed account manually , commit , push. doing able push code repository successfully. author abc<abc.@mail.com> committer abc<abc.@mail.com>

html - Box border for each letter inside span -

Image
i have span below <span style="font-size:18px; font-weight:bold;">8342</span> how can put black box around each number inside span using css? i want below image please check demo <span style="font-size:18px; font-weight:bold;" class="test">8342</span> .pwn{ border: 2px solid black ; display: inline; } var text= $(".test").html(); $(".test").html(''); for(i=0;i<=text.length-1; i++) { var html = text.substr(i,1); var sp="<span style='font-size:18px; font-weight:bold;' class='pwn'>" + html sp+=" </span> &nbsp;"; $(".test").append(sp); }

elasticsearch - How to remove elastic index with special characters in name? -

on elasticsearch 2.2 node accidentally created index name '%{[index]}'. how can index removed? curl -xdelete 'http://localhost:9200/%{[index]}/' fails curl: (3) [globbing] nested brace in column 28 . you need url-encode special characters in index name, this, , index magically disappear: curl -xdelete 'http://localhost:9200/%25%7b%5bindex%5d%7d/'

asp.net - ASP URL rewrite / redirect -

i using asp.net in project suppose have page abc, if url abc/abc comes, want redirected on page abc rewrite url abc/abc same first url how can write rule in web.config achieve this? i have tried rewrite , redirect rules, did not work me

postgresql - Maximum values from SELECT SQL Query -

i have query returns results in following format: user1 typea 3 user1 typeb 29 user1 typec 100 user2 typea 221 user2 typeb 31 user2 typec 32 user3 typea 21 user3 typeb 1 user3 typec 10 .... so each user in database, lists 3 rows, each corresponding typea, typeb, typec. need return user id corresponds maximum value each type. example, data above obtain: typea user2 typeb user2 typec user1 i'm not sure how proceed in sql. a typical way of doing uses row_number() : with t ( <your query here> ) select t.* (select t.*, row_number() on (partition typecol order col3 desc) seqnum t ) t seqnum = 1; postgres offers solution typically more efficient: select distinct on (typecol) q.* (<your query here>) q order typecol, col3 desc;

reactjs - Redux Action Method doesn't return any reponse -

Image
i created following action method export function searchproducts(searchquery) { console.log('redux - searchquery: ', searchquery); return { types: [search, search_success, search_fail], promise: (client) => { console.log('client is: ', client); client.get('/products/search/:' + searchquery); } }; } but when call function, prints first console command doesn't return anything. doesn't print console.log('client is: ', client); problem? here console snapshot: redux action object's have 1 requirement, has have key value of type. object should this... return { type: "someaction", payload: somevalue };

asynchronous - C# MDI Forms mixing the code execution -

i developing tcp client server application , receiving packet clients asynchronously , have in server 2 winforms: frmmain main server form mdi parent. frmclient child form instantiated every client when connecting. i invoking frmclient below code private static void onclientconnect(iasyncresult asyn) { try { tcpclient clientsocket = default(tcpclient); clientsocket = _listener.endaccepttcpclient(asyn); clientsocket.receivebuffersize = 1024; showformforclient(clientsocket); } catch (exception se) { throw; } waitforclientconnect(); } public static void showformforclient(tcpclient clientsocket) { // check if on different thread , redirect if if (rootform.invokerequired) { rootform.begininvoke((methodinvoker)delegate { showformforclient(clientsocket); }); return; }

mysql - Codeigniter query builder using implode function in where_in -

here normal sql query using implode function: select * search_result skills in ('".implode("','",$s_id)."'); now want convert codeigniter form. tried following code fails $this->db->from('search_result'); $this->db->where_in('skills','".implode("','",$s_id)."'); $query = $this->db->get(); here $s_id array: array ( [0] => 2d design [1] => 3d design [2] => 3d modelling ) so please me this. in advance :) official doc say's $names = array('frank', 'todd', 'james'); # data array $this->db->where_in('username', $names); # passing array try below method 01 ( recommended ) $this->db->from('search_result'); $this->db->where_in('skills',$s_id); $query = $this->db->get(); method 02 $this->db->from('search_result'); $this->db->where_in('

javascript - jQuery get data from db after button clicked -

i creating button , automatically increasing value , getting current value on db. the update value worked, value didn't update automatically after button clicked (it's updated after page has refreshed). here jquery code: $(document).ready(function(){ $('#like').on('click', function(e){ var id = '{{$news->id}}'; $.get('{{ url('home/like')}}/'+id, function(data){ console.log(id); console.log(data); $('#like_data').empty(); $.each(data, function(index, element){ $('#like_data').append('<p>'+element.like+'</p>'); }); }); }); }); here html code: <form method="get"> <div id="sample-table-3"> <a id="like"><img src="/images/likes1.png" title="likes"></a> </div> </form> <

python - How to convert series to dataframe in Pandas -

i have 2 csvs need compare them based on 1 column. , need put matched rows in 1 csv , unmatched rows in other. so, created index on column in second csv , looped through first. df1 = pd.read_csv(file1,nrows=100) df2 = pd.read_csv(file2,nrows=100) df2.set_index('crc', inplace = true) matched_list = [] non_matched_list = [] _, row in df1.iterrows(): try: x = df2.loc[row['crc']] matched_list.append(x) except keyerror: non_matched_list.append(row) the x here series in following format policyid 448094 statecode fl county clay county eq_site_limit 1322376.3 hu_site_limit 1322376.3 fl_site_limit 1322376.3 fr_site_limit 1322376.3 tiv_2011 1322376.3 tiv_2012 1438163.57 eq_site_deductible 0 hu_site_deductible 0.0 fl_site_deductible 0 fr_site_deductible

gdb scripting restart continue while loop -

what equivalent of continue in gdb scripts? tried using loop_continue didn't work. gdb threw error saying undefined command. i want like while $thr if $thr->procedureid != 28 set $thr = $thr->cnext loop_continue; // doesn't work end print $thr set $thr = $thr->cnext end the problem here, surprisingly, ; . me causes gdb say: undefined command: "loop_continue". try "help". however, if leave out ; , works: (gdb) set $x = 0 (gdb) while $x < 5 >if $x < 3 >set $x = 72 >loop_continue >end >end (gdb) print $x $1 = 72

Resetting a value every month - swift & firebase -

i have 2 integer values called score , highscore . using firebase store values, users , such. wondering, if possible reset users score every month? when reach 1st of month, every users score set 0? is possible? sure hope so! ps. sorry not showing code, believe irrelevent @ point - let me know if think otherwise :-) you should better add app engine backend has simple servlet , cron task. backend going update firebase database monthly. backend: servlet; updates scores 0 except top score. cron task; calls servlet monthly. see link; adding backend logic using app engine :

c - Why is the elapsed time 0? -

i made program unrolls loops , measures time taken sort array, problem have unrolled loop program gives me answer of 0 in nano seconds , can't be. tried monotonic doesn't help. here's code: #include <stdio.h> #include <time.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <math.h> #include <unistd.h> #define billion 1000000000l int main() { char buf[500]; int numberofelements = 10; int currenttest = 1; int randomarray[numberofelements]; int minindex; int minvalue; struct timespec requeststart; struct timespec requestend; long int recordstarttime; long int recordendtime; long int elapsedtime; file *arrangedarray; file *stopwatch; sprintf(buf,"place store file/stopwatch.txt", currenttest); stopwatch = fopen(buf, "a+");

java - Is there an easy way to find out if the process is waiting in a UserTask inside Delegation Code? -

this question camunda bpm engine. i implement executionlistener can attach process events. listener should send process state messages message queue. process message should contain state "pending" process if process waiting in usertask somewhere. now wonder if there easy way find out if process waiting (somewhere) in usertask inside delegation code (by using provided delegateexecution object of delegation code method). not find 1 far. for example: import org.camunda.bpm.engine.runtimeservice; import org.camunda.bpm.engine.delegate.delegateexecution; import org.camunda.bpm.engine.delegate.executionlistener; import org.camunda.bpm.engine.runtime.activityinstance; public class exampleexecutionlistener implements executionlistener { public void notify(delegateexecution execution) throws exception { runtimeservice runtimeservice = execution.getprocessengineservices().getruntimeservice(); activityinstance activityinstance = runtimeservice.getactivity

json - Jquery datepicker - Pass date array from Controller MVC -

i have created list containing available dates , serialized json: list<string> dates = new list<string>(); foreach(bookingdates itm in model.availabledates) { dates.add(itm.expdate.tostring("dd-mm-yyyy")); } model.datesstr = new javascriptserializer().serialize(dates); i pass model data jquery , try pass dates datepicker: var availabledates = @html.raw(json.encode(@model.datesstr)); alert(availabledates); function available(date) { dmy = date.getdate() + "-" + (date.getmonth() + 1) + "-" + date.getfullyear(); if ($.inarray(dmy, availabledates) != -1) { return [true, "ui-available", "available"]; } else { return [false, "ui-unavailable", "unavailable"]; } } the datepicker not populate dates. if type dates, does: var availabledates = ["20-11-2016","17-12-2016"]; the difference have noticed result of alert when dates typed ab

php - Error with Woocommerce short description in category page -

this code i'm using , appears work correctly when log in add_action('woocommerce_after_shop_loop_item_title', 'lk_woocommerce_product_excerpt', 35, 2); if (!function_exists('lk_woocommerce_product_excerpt')) { function lk_woocommerce_product_excerpt() { $content_length = 10; global $post; $content = $post->brief_description; $wordarray = explode(' ', $content, $content_length + 1); if (count($wordarray) > $content_length) : array_pop($wordarray); array_push($wordarray, '...'); $content = implode(' ', $wordarray); $content = force_balance_tags($content); endif; echo "<span class='excerpt'><p>$content</p></span>"; } } when logout , check page, first product in each category doesn't show short description added, although appears when i'm login. is there probl

api - Python's request.get only show 200 status -

i'm trying workd cisco prime api, , seems work when using postman (the output xml file). however, when try reproduce same python: request.get(url, verify=false, auth=credentials) print(response) the response <response [200]> (and warning disabling ssl, that's not relevant)... use requests.auth.httpbasicauth generate "crdentials" variable well, of course, it's after posting found answer: first, need search json, not xml , second, when want cast json, need response.json()

Python requests code snippet from Postman -

i trying check if email exists in website. using sample python code postman. sample code works: import requests url = "https://registration.mercadolivre.com.br/registration/" payload = "-----011000010111000001101001\r\ncontent-disposition: form-data; name=\"signup.email\"\r\n\r\ntest@hotmail.com\r\n-----011000010111000001101001\r\ncontent-disposition: form-data; name=\"signup.repemail\"\r\n\r\ntest@hotmail.com\r\n-----011000010111000001101001\r\ncontent-disposition: form-data; name=\"signup.newsletter\"\r\n\r\ntrue\r\n-----011000010111000001101001\r\ncontent-disposition: form-data; name=\"source\"\r\n\r\nmercadolibre\r\n-----011000010111000001101001--" headers = { 'content-type': "multipart/form-data; boundary=---011000010111000001101001", 'cache-control': "no-cache", 'postman-token': "179cabe2-dd22-490e-8fbd-15bf2977feb5" } response = requests.request("post

sql server - Retrieving X rows from an ordered CTE, TOP vs Range -

Image
objective: want know faster/better performance when trying retrieve finite number of rows cte ordered. example: say have cte(intentionally simplified) looks this, , want top 5 rows : with cte ( select id = rank() on (order t.actionid asc) , t.name tblsample t -- tblsample indexed on id ) which faster: select top 5 * cte or select * cte id between 1 , 5 ? notes: i not db programmer, me top solution seems better once ss finds 5th row, stop executing , "return" (100% assumption) while in other method, feel unnecessarily process whole cte. my question cte, answer question same if table? the important thing note both queries not going produce same result set. consider following data: create table #tblsample (actionid int not null, name varchar(10) not null); insert #tblsample values (1,'aaa'),(2,'bbb'),(3,'ccc'); both o

ubuntu - How to send fixed data with Iperf and measure bandwith? -

Image
is there way use iperf3 tool sending 1gb of data , measure bandwidth between server , client? used tool in following way: for server: iperf3 -s for client: iperf3 -c <server ip> i obtained following data of image, want measure time takes send 1gb of information server client. there way iperf? thanks in advance. you can try using -n flag iperf3 have send number of bytes, although have noted problems test stopping before data has been received. have theory problem (basically comes down client telling server "the test's done now" before data has been transmitted , received). no idea fix should be, of writing. give try. large enough test, might not make huge difference.

c# - Access web.config appsettings from Angular js 2 Typescript -

i new angular js 2 type script programming. trying find out way access app settings keys of web.config typescript. wouldn't want hardcode data in type script vary across environments. tia typescript compiled javascript later gets executed within context of application consuming web.config file. because of this, won't able read configuration @ typescript level. what need instead make configuration available @ runtime. in other words, whatever code generated typescript needs aware of object available while page running feed configuration may need. there few ways this. you make js code aware of object should exist in global context (e.g. appconfig in js when page running). can populate object settings. example asuming razor: var appconfig = []; appconfig.adminemail = '@configurationmanager.appsettings["adminemail"]'; then typescript code can rely on variable appconfig @ runtime. alernatively, can device way page inject configuration code

mule - RAML - json schema error -

i have included json schema file in raml. in real file, i'm getting error saying "the included resource schemas/createrecord.json contains error" i have validated json file, has no errors when replaced file contents working file content, still i'm getting same error. it seems problem file format , not content. can me in identifying issue? this depends on how validated json schema. not validitors created equal , trick use 1 matches mulesoft , have found http://jsonschemalint.com/#/version/draft-05/markup/json best , when error in mule same error in jsonschemalint

android - Connection to remote postgreSQL database timed out with JDBC -

so trying connect android app postgresql database jdbc, although driver part went fine, connection timing out, i've authorized connections ip in pg_hba file, tried search on internet, noone of answer suits or problem. here's code connect : string url = "jdbc:postgresql://hostingmachineip:5432/mytestdb?user=user&password=password"; connection = drivermanager.getconnection(url); i've put line in pg_hba conf file : host 0.0.0.0/0 trust and error : i/system.out: -------- postgresql jdbc connection testing ------------ i/system.out: postgresql jdbc driver registered! e/dalvikvm: not find class 'org.postgresql.translation.messages_fr$1', referenced method org.postgresql.translation.messages_fr.getkeys w/dalvikvm: vfy: unable resolve new-instance 3930 (lorg/postgresql/translation/messages_fr$1;) in lorg/postgresql/translation/messages_fr; d/dalvikvm: vfy: replaci

Azure DocumentDB Users in a multi tenant application -

i playing around azure document db because planning create multi tenant application. for multi tenant application, idea create 1 db user per tenant. gives me advantage tenant data separated: when creating document, permission added tenant user. (read/write) means when querying, data scoped current tenant. i playing around 1 db user per end-user. gives me lot of overhead manage security on documents. when user x tenant z adds document, users tenant z need updated permissions document. seems unfeasible. is assumption correct? or suggest approach this? there downside approach? for our multi-tenant solution chose not use documentdb's controls @ , of our authorization in middle tier because wanted predicate based , different per tenant. said, approach of using documentdb's authorization capabilities @ tenant level makes sense. give tenants added assurance other tenants can't see data. my 1 thought if have cross-tenant functionality (maybe in form of tenant g

Playframework: How to add new database connections post server startup? -

how add new database connection ebean , pool support after playframework 2.5 web app initialized? playframework starts default db connection , while running need connect few other databases. i can use ebean.register(ebeanserver server, boolean defaultserver) register new datasource , use ebean.getserver("dbconfigname"). how specify hikaricp pool configuration database? play use hikaricp defaults play.db.prototype.hikaricp ?

android - How so I return multiple JSON values to multiple text views? -

i did research json . found tutorials jsonarray , not how make allow multiple text views jsonobject . should have method, add parameters or what? this json , { "name": "iss", "id": 25544, "latitude": -16.621580566205, "longitude": -22.573425077475, "altitude": 403.33965999684, "velocity": 27615.932538565, "visibility": "daylight", "footprint": 4421.7128198729, "timestamp": 1478617317, "daynum": 2457701.1263542, "solar_lat": -16.808913358406, "solar_lon": 310.46294067763, "units": "kilometers" } here code if want see it, public class isstatusactivity extends appcompatactivity { string longitst; jsonparser jsonparser = new jsonparser(); textview latitude; textview longitude; string lat; string longit; jsonobject jobj = null; @override

java - Accessing a variable from one class that is located in another class -

iv been stuck on bug, in android app, 3 weeks now. killing me... :(. can please fix code me (its small error), , can learn it. basically, have mainactivity class holds variable "dblcountvalue". want access variable in withdraw class. here code: class: mainactivity package com.mycash.borgjake.mycash; import android.content.intent; import android.support.v7.app.appcompatactivity; import android.os.bundle; import android.widget.button; import android.widget.textview; import android.view.view; import com.google.android.gms.ads.adlistener; import com.google.android.gms.ads.adrequest; import com.google.android.gms.ads.adview; import com.google.android.gms.ads.interstitialad; import static com.mycash.borgjake.mycash.r.styleable.view; public class mainactivity extends appcompatactivity { private interstitialad minterstitial; button btnclick; button btnwithdraw; textview txtbalance; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(s

php - Send email via Outlook. I want to pick my own "to" receivers -

i have small php script (shown below) "automatically" emails simple test message whichever email address in $to variable e.g. username@email.com $subject="this test message"; $message='this <font color="red">body</font> section'; $to="username@email.com"; // starting outlook com_load_typelib("outlook.application"); if (!defined("olmailitem")) {define("olmailitem",0);} $outlook_obj = new com("outlook.application") or die("unable start outlook"); $omsg = $outlook_obj->createitem(olmailitem); $omsg->recipients->add($to); $omsg->subject=$subject; $omsg->htmlbody=$message; $omsg->save(); $omsg->send(); the script works great, except don't want automatically send out email. i want load email outlook , allow me manually add email addresses. however, if leave $to variable blank (i.e. "") or remove "$omsg->recipients->add($to);

jsf 2 - Strange fatal errors with 'JavaClassScanningAnnotationScanner' on web application startup -

i strange fatal errors when start web application since upgraded java 8. here example of messages (and there lot of them): nov 08, 2016 4:11:08 pm com.sun.faces.config.javaclassscanningannotationscanner$constantpoolinfo containsannotation fatal: unknow type constant pool 0 @ position 126 the application running jetty (quite old, 8.1.14.v20131031) before. these fatal errors appeared , found question why lambda expression threw error? , changed jetty 9.2.9.v20150224. fatal errors still here, other post indicates has lambdas in faces components converters. maybe javax-faces old? updated 2.1.9 2.2.9, messages still here. have hint me? best regards, felix

python: xpath lxml to extract data -

<td> <span class="data_lbl updated-daily">p/e ratio <small class="data_meta">(including extraordinary items)</small></span> <span class="data_data"> <span class="marketdelta deltatype-negative">-69.83</span> </span> </td> how extract data pe ratio data '-69.83' in robust way? want point straight p/e ratio. from lxml import html import requests stockdata =['aasia'] page_wsj1 = requests.get('http://quotes.wsj.com/my/'+stockdata[x]+'/financials') wsj1 = html.fromstring(page_wsj1.content) pe = wsj1.xpath('//td[contains(.,"p/e ratio")]/text()') but result ['','','','',''] wsj1.xpath('//td[normalize-space(span) = "p/e ratio"]/span[@class = "data_data"]/span/text()') also result [] //td[normalize-space(span/text()) = "p/e ratio"]/span[@class =

javascript - PHP: Best way forward [serialisation, objects, Redis] -

i have been developing php application quite while. (basic) idea follows; users can build web-pages using blocks. these blocks can contain images, text etc. each of these blocks have own options. these blocks defined in domain driven design through php. i've build application use php-based controller handles requests jquery/javascript front. each time user edits option send controller unserialises collection of blocks (php-objects) redis and/or php-session , sets the attributes of blocks edited or adds/removes 1 of blocks. enforce domain logic. which fine developing myself. never kept race conditions , such in mind. while moving forward product notice people lose data. i'll explain happens; user edits option of block press save a request made controller which, unserialises collection and sets blocks based on uuid puts blocks in collection and serialises collection again. there scenario's 2 concurrent request might created override edits of 1 of both requ