Posts

Showing posts from July, 2015

url - How to handle links containing space between them in Python -

i trying extract links webpage , open them in web browser. python program able extract links, links have spaces between them cannot open using request module . for example example.com/a, b c not open using request module. if convert example.com/a,%20b%20c open. there simple way in python fill spaces %20 ? `http://example.com/a, b c` ---> `http://example.com/a,%20b%20c` i want convert links have spaces between them above format. urlencode takes dictionary, example: >>> urllib.urlencode({'test':'param'}) 'test=param'` you need this: import urllib import urlparse def url_fix(s, charset='utf-8'): if isinstance(s, unicode): s = s.encode(charset, 'ignore') scheme, netloc, path, qs, anchor = urlparse.urlsplit(s) path = urllib.quote(path, '/%') qs = urllib.quote_plus(qs, ':&=') return urlparse.urlunsplit((scheme, netloc, path, qs, anchor)) then: >>>url_

Rewrite does not work in nginx -

i using nginx1.8.0 in windows10, core configuration tried rewrite request server { listen 80; server_name localhost; rewrite ^/qt/(\w+)/(\d+)/(\d+)/(\d+)_(\d+).(\w+)$ /qtfile/$1/$4/$5.$6 last; # /qt/zoom/x_plus/y_plus/x_y.type ==> /qtfile/zoom/x/y.type location /qtfile { access_log logs/images.log; alias d:/tiles/; } location / { root d:/www; } } the link http://localhost/qtfile/s/214/7645/102.jpg return right image, link http://localhost/qt/s/214/323/34254/7645_102.jpg throw error: 2015/10/10 10:40:09 [error] 1420#11676: *1 createfile() "d:/www/qt/s/214/323/34254/7645_102.jpg" failed (3: system cannot find path specified), client: 127.0.0.1, server: localhost, request: "get /qt/s/214/323/34254/7645_102.jpg http/1.1", host: "localhost" it seems request catched loation / segment. anything wrong? it looks regex isn't correct input. gave example http://loc

java - Retrofit + GSON + OkHttp + Okio libraries, no build errors, program doesn't work -

my program doesn't have build error, works in android studio, in eclipse results error. have included libraries needs retrofit , gson , okhttp , okio .jars. tried searching errors in logcat though, no luck.. maybe of knows answer.. xml layout <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/linearlayout1" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" tools:context="com.checkaidev1.mainactivity" > <edittext android:id="@+id/email" android:layout_width="match_parent"

content management system - Magnolia Publication status column -

Image
i'm working magnolia 5.3 , want add status column in apps. status column shows if page o resource has been published. i've tried this hasn't worked. in next picture can see how see page app: you can see status column should in picture: any ideas? in pages app not see status column if logged in public instance. because content must published if visible on public instance. are looking @ public instance when see view above? examples: author instance https://demo.magnolia-cms.com/.magnolia/admincentral#app:pages :; public instance https://demopublic.magnolia-cms.com/.magnolia/admincentral#app:pages :;

algorithm - using 10 MB of memory for four billion integers (about finding the optimized block size) -

this question has answer here: find integer not among 4 billion given ones 38 answers the problem is, given input file 4 billion integers, provide algorithm generate integer not contained in file, assume have 10 mb of memory. searched solutions, 1 of store integers bit-vector blocks (each block representing specific range of integers among 4 billion range, each bit in block represent integer), , using counter each block, count number of integers in each block. if number of integers less block capacity integers, scan bit-vector of block find missing integers. my confusion solution is, mentioned optimal smallest footprint is, when array of block counters occupies same memory bit vector. confused why in such situation optimal smallest footprint? here calculation details referred, let n = 2^32. counters (bytes): blocks * 4 bit vector (bytes): (n / blocks) / 8 blo

python - Difference between the interaction : and * term for formulas in StatsModels OLS regression -

hi i'm learning statsmodel , can't figure out difference between : , * (interaction terms) formulas in statsmodels ols regression. please give me hint figure out? thank you! the documentation: http://statsmodels.sourceforge.net/devel/example_formulas.html ":" give regression without level itself. interaction have mentioned. "*" give regression with level + interaction have mentioned. for example a. glmmodel = glm("y ~ a: b" , data = df) you'll have 1 independent variable results of "a" multiply "b" b. glmmodel = glm("y ~ * b" , data = df) you'll have 3 independent variables results of "a" multiply "b" + "a" + "b" itself

android - play-services-base 8.1.0 Could not find element /manifest/application -

i trying package android project of libgdx game in implemented ads. works fine when run on device when try package gradle task assemblerelease throws this: :android:processreleasemanifest [f:\java\elementninja\build\exploded-aar\com.google.android.gms\play-services-base\8.1.0\androidmanifest.xml:1] not find element /manifest/application. execution failed task ':android:processreleasemanifest'. > manifest merging failed. see console more info. the library play-services-base in direction above indeed missing application tag , therefore fails merging manifests. library created upon build , adding in application tag not help, expected. recreated when try assemble. checked , play-services-base library misses application tag. missing in version 8.1.0 though. 7.8.0 has tag. when try compile version 7.8.0 throws: [f:\java\elementninja\build\exploded-aar\com.google.android.gms\play-services-location\7.8.0\androidmanifest.xml:1, c:\users\silvio\appdata\local\temp\manife

php - Fastest way to update product qty and price in Magento? -

hey guys triying save products in magento getting xml.but couldnt find way update prices , qty fast.tried : public function productupdate($productskus = array(), $data = array(), $storeid = 1) { $ids = mage::getmodel('catalog/product') ->getcollection() ->addattributetofilter('sku', $productskus) ->getallids(); mage::getsingleton('catalog/product_action')->updateattributes( $ids, $data, $storeid ); } but not enough , gives me error while updatting qty.it not differen $product->save(); need fast way upgrade 2 attribute.guys pls help.i bad situation in company posiition. thank you. did have @ extension? extension enables map fields accordingly , ease able import required information update existing ones. not cheapest worth long term. auto product import xml , webservice

arrays - Reading txt file from working directory in Java (not working) -

i have read couple of posts of how read txt file int[] , through multiple ways possible haven't succeeded in any. import java.io.*; import java.util.scanner; public class sequencesquare { private int[] arr; public sequencesquare() { int count = 0; file filename = new file("sequence.txt"); // filename opening try { scanner input = new scanner(filename); while (input.hasnextline()) //while there line read { if(input.hasnextint()) //if line has int { count++; // increment count input.nextint(); //move next integer } } arr = new int[count]; // create arr sufficient size input.close(); // close scanning file scanner newinput = new scanner(filename); for(int = 0; < arr.length; i++) { while (newinput.hasnextline()) // same above { if(newinput.hasnextint()) // same above

Read JSON response in Python -

i trying read json response link . not working! following error: valueerror: no json object decoded. here code i've tried: import urllib2, json = urllib2.urlopen('https://www.googleapis.com/pagespeedonline/v3beta1/mobileready?key=aizasydkex-f1jnlqlc164szaobalqfv4phv-ka&screenshot=true&snapshots=true&locale=en_us&url=https://www.economicalinsurance.com/en/&strategy=mobile&filter_third_party_resources=false&callback=_callbacks_._delanzu7xh1k') data = json.loads(a) i made these changes: import requests, json r=requests.get('https://www.googleapis.com/pagespeedonline/v3beta1/mobileready?key=aizasydkex-f1jnlqlc164szaobalqfv4phv-ka&screenshot=true&snapshots=true&locale=en_us&url=https://www.economicalinsurance.com/en/&strategy=mobile&filter_third_party_resources=false') json_data = json.loads(r.text) print json_data['rulegroups']['usability']['score'] a quick question - constru

regex - partial matching in r- multiple matches -

i leveraging code below partial match 1 match have follow question: supposed had additional criteria fish, , wanted "dog fish" categorized both fish , canine. possible? d<-data.frame(name=c("brown cat", "blue cat", "big lion", "tall tiger", "black panther", "short cat", "red bird", "short bird stuffed", "big eagle", "bad sparrow", "dog fish", "head dog", "brown yorkie", "lab short bulldog"), label=1:14) define regexes @ beginning of code regexes <- list(c("(cat|lion|tiger|panther)","feline"), c("(bird|eagle|sparrow)","avian"), c("(dog|yorkie|bulldog)","canine")) create vector, same length df output_vector <- character(nrow(d)) for each regex.. for(i in seq_along

swift2 - Creating a custom dialog box like this in iOS? -

Image
i'm trying create dialog box this, have failed in every attempt. box overrides rest of content, has 2 textfield , choice box. me? use dynamic programming create dialog box? or use new viewcontroller , call via code? start? if understand correctly, , blur effect necessary, standard uialertcontroller won't let that. achieve affect 1.) creating separate view controller in storyboard, 2.) add uiblureffect it, 3.) add uiview make 'form' , add text fields etc that. then, wherever want view launched (button, etc) create segue view controller , set 'modal'. help?

mysql - Alter table throw error #1005 -

Image
i have 2 different table follows apis users here users table has api_id forien key. now executing following query thorwing error (stating api_id column references id column on apis table.) alter table `users` add constraint users_api_id_foreign foreign key (`api_id`) references `apis` (`id`) on delete cascade on update cascade error : #1005 - can't create table 'xxxxx.#sql-54ef_229ff39' (errno: 150) (<a href="server_engines.php?engine=innodb&amp;page=status&amp;token=50174b3c687a6edcb259e10dd65ca6d7">details...</a>) mysql version (development server) server version: 5.5.42-37.1-log the same query working in localhost server version: 5.5.44-0ubuntu0.14.04.1 - (ubuntu) how can fix error? in advance. apis table users table sometimes problem caused if have data in table. in case if have data in users table first truncate users table , try again.

java - Simple one way suspend for thread -

please bare me still new threads... i have small project have 2 threads listenerthread , heartbeatthread both nested classes inside heartbeatserver . what have listener thread adds clients registerclients when sends request (the rest out of scope of question). i looking simple way suspend heartbeatthread when there no clients in registerclients hashmap. originally thinking easy using if statement @ top of while loop in listenerthread checks how many clients there , if client count less 0 listenerthread call heartbeatserver.heartbeatthread.wait() , heartbeatserver.heartbeatthread.notify() when client count zero. when java throws illegalmonitorexception . after doing digging found out exception because did not call wait() inside of synchronized block. since looking go 1 way listenerthread -> heartbeatthread , never other way how accomplish this? still better off using synchronized block in each thread. if that's case need clarification synchronizing. i

python - Issue with showing and updating image in Tkinter -

i'm able display image if grab 1 location, need image update along related article website. if open application tomorrow, different image appear. needless say, i'm using regular expressions image won't show on label. here's code far: from tkinter import * import tkinter tk import re re import findall urllib import urlopen import datetime pil import image pil import image, imagetk cstringio import stringio root = tk() root.title("science , technology") root.geometry("600x600") main_label = label(root, text = "science , technology") main_label.pack() all_image_height = 400 all_image_width = 400 dash = "-" = datetime.datetime.now() text_area = labelframe(root, borderwidth = 2) text_area.pack(padx = 10, pady = 10, expand = 1, fill= both) date = label(text_area) date.pack() content_t = label(text_area) content_t.pack() imag = label(text_area) imag.pack() def science_all(): sw_img = 300 sh_img = 300 webscience = u

html - Using CSS to change a class background but only if it is not after a h4 -

i trying change background colour of paragraph 4 only. want leave paragraph 2 alone (because after h4). have tried not selector can't seem logic working right. not wanting use javascript, php or jquery. pure css please. .widget-wrap > .widget-title { background-color: yellow; } .widget-title + .textwidget { background-color: red; } <div class="widget-wrap"> <h4 class="widget-title">paragraph 1 in div.</h4> <p class="textwidget">paragraph 2 in div.</p> <p>paragraph 3 in div.</p> </div> <div class="widget-wrap"> <p class="textwidget">paragraph 4 inside 2nd div.</p> <p>paragraph 5 inside 2nd div.</p> </div> if first child of .widget-wrap either h4.widget-title , or p.textwidget (i.e. when h4 not present), use :first-child : .widget-wrap > .widget-title { background-color: yellow;

operating system - What are the problems in 3-way Message passing Reliable IPC protocol? -

Image
here, @ end of page. last paragraph , mentioned problems occurs in protocol. unable understand these problems. ? example. told. "if request processing long time" unable understand statement. request processing taking long time, on client ? or on server ? or unable understand clock(time) ? on client side or server side? because here mentioned in end of 2 point. "if reply not received within time period , kernel of client machine re-transmits request message." consider this: the client sends message. if doesn't reply server within - - 1 minute transmit message again. when server receives message, sends reply after having generated full response message client sent. no suppose you, client, send message server. server receives message, , starts processing it. @ time, you, client, have no idea of whether server got message or not. assume send complicated task server, takes 1 minute , 5 seconds complete. after 1 minute (ignoring transmissio

php - Check if URL protocol exists on PC -

i building pos system, link verifone device. talk verifone, using custom built url protocol. need way check if protocol exists on local computer that's using pos. what best way of doing such thing? pos programmed in basic web languages (php, jquery, javascript), connection verifone device programmed in php, too. suggestions (if php has it, or other language) welcome.

php - wordpress custom page post query -

i have problem because database have table stores post data. need data table , show on register_post_type. function duonampost() { $labels = array( 'name' => _x( 'nam', 'post type general name', 'duonampost' ), 'singular_name' => _x( 'nam', 'post type singular name', 'duonampost' ), 'menu_name' => __( 'nam', 'duonampost' ), 'name_admin_bar' => __( 'nam', 'duonampost' ), 'parent_item_colon' => __( 'parent item:', 'duonampost' ), 'all_items' => __( 'all items', 'duonampost' ), 'add_new_item' => __( 'add new item', 'duonampost' ), 'add_new' => __( 'add new', 'duonampost' ), 'new_item' => __(

jquery - How to pass html values in Ruby within a Javascript function -

i have view page, user inputs number , clicks on generate form in same page based on input. i'm using javascript in main view: <div class="label-field-pair"><%= "#{t('total')} #{t('amount')}" %>: <%= form.text_field :total, :value =>precision_label(@total_pay.to_f) , :disabled=> true , :id=>'total' %></div> <div class="label-field-pair"> <label for="student_grade"><%= t('no_payments') %><span class="necessary-field">*</span> </label> <input type="number" min="1" max="12" step="1" value="1" name="no_payments" id="no_payments"> </div> <%= form.hidden_field :no_payments, :id=>'payments' %> <%= form.hidden_field :total_pay, :id=>'total_pay' %> <%#= submit_tag

Node.js - webrtc peer? -

since node uses javascript, can act webrtc peer? can encode vp8 stream , broadcast other peers? webrtc browser api rather being part of javascript, it'd need implemented node module. there projects build though. check out: http://blog.appfog.com/new-horizons-in-node-js-app-js-and-webrtc/

node.js - Reuse Threads - C++ -

i making , addon (to nodejs). 1 of functions have responsible of doing fast algorithms audio arrives. objective algorithms in thread. resume of function: void buffering(const functioncallbackinfo<v8::value>& args) { isolate* isolate = isolate::getcurrent(); handlescope scope(isolate); int size = args[1]->numbervalue(); int final_read = args[2]->numbervalue(); int inicio_read = args[3]->numbervalue(); int client_id = args[4]->numbervalue(); local<object> bufferobj = args[0]->toobject(); buf = node::buffer::data(bufferobj); char mini_buf[80000];//char mini_buf[4096]; memcpy(mini_buf, buf, size); //to implement thread int teste_buf = julius[client_id].audio_buffering(mini_buf, size, final_read, inicio_read, client_id); //(....returns nodejs...) } if audio_buffering executed 1 time, in way: std::thread t[num__threads]; t[client_id] = std::thread(&srenginejulius::audio_buffering, &juliu

javascript - Solution to jquery get() url as variable -

ok, problem having jquery get() using not use variable want to. here code , go deeper explanation. jquery(document).ready(function() { $.ajax({ type: "get", url: "xtest.xml", datatype: "xml", success: function(xml) { console.log(xml); $(xml).find('chart').each(function(){ chtype = $(this).find('chtype').text(); chtitle = $(this).find('chtitle').text(); chsubtitle = $(this).find('chsubtitle').text(); yaxistitle = $(this).find('yaxistitle').text(); csv = $(this).find('csv').text(); }); $(xml).find('columns').each(function(){ countarray[i] = 0; cnum = parseint($(this).find('cnum').text());

rest - webhdfs two steps upload a file -

i build hadoop cluster 4 machines: {hostname}: {ip-address} master: 192.168.1.60 slave1: 192.168.1.61 slave2: 192.168.1.62 slave3: 192.168.1.63 i use httpfs upload file hdfs restful way, there contains 2 steps finish task. step 1: submit http post request without automatically following redirects , without sending file data. curl -i -x post " http://192.168.1.60:50070/webhdfs/v1/user/haduser/myfile.txt?op=append " the server return result like: location: http://slave1:50075/webhdfs/v1/user/haduser/myfile.txt?op=create&user.name=haduser&namenoderpcaddress=master:8020&overwrite=false step 2: use response address upload file. in step 1, how datanode's ip address(192.168.1.61) rather hostname (slave1)? if hadoop version>=2.5, @ every datanode config ${hadoop_home}/etc/hadoop/hdfs-site.xml file. add: property dfs.datanode.hostname , value datanodes's ip address .

javascript - some pop-up text while hover in svg path -

i want sample text while hover in svg path, can tell me easiest way please here css code: <style> path:hover{ fill:yellow;stroke:blue; } .available { fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1 } </style> here html svg code: <svg width="210mm" height="297mm" viewbox="0 0 744.09448819 1052.3622047"> <a href=""><path name="path1" class="available" d="m 97.42857,852.3622 c 0,72.14286 0.71429,72.14286 0.71429,72.14286 l 55,23.57143 -0.71429,-95 z"/></path></a> <path name="path2" class="available" d="m 97.42857,809.50506 c 0,42.85714 0,43.57143 0,43.57143 l 55,-0.71429 0,-43.57142 z"/> <path name="path3" class="available" d="m 97.21429,766.3622 c 0,42.85714 0,43.57143 0,43.57143 l 55,-0.71429 0,-43.57142 z&qu

linux - "Find" command: highlight matching literal parts -

i use find lot, using -name or -iname parameters. i highlight matching part in files finds (like grep does). for example: find . -iname "*foo*" highlight instances foo i know pipe grep i'd rather not write 2 commands each time. is there simple way it? eg. this: find /home/ -type f | grep -i --color=always *.cpp

javascript - Error caused when set checkboxes as checked using angularjs -

this html: <span ng-repeat="category in categories"> <label class="checkbox-inline" for="{{category.id}}"> <input type="checkbox" ng-checked="check(category.id)" ng-click="saverolemenu($event,category.id)" name="group" id="{{category.id}}" /> {{category.name}} </label> </span> this controller: //get menus authorityservice.getmenus().then(function(response) { $scope.categories = response.data.data; //get menus success }) //get user's menus var roleid = sessionstorage.getitem("roleid"); authorityservice.getmenusbyroleid(roleid).then(function(response) { $scope.usermenu = response.data.data; //get user's menu success }) $scope.saverolemenu = function($event, id) { var checkbox = $event.target; if (checkbox.checked) { var roleid = $location.search().id; authorityservice.saverolemenu(roleid, id)

angularjs - ui-router ignoring state params -

i'm trying implement forgot password flow in application collects information user , passes through states. after user submits employee id , want reset code sent (email or phone), send both of token state: $state.go("^.token", { employeeid: forgot.employeeid, resettype: forgot.resettype }); my router pretty straightforward: $stateprovider.state("authentication.forgot", { url: "/login/forgot", templateurl: "partials/authentication/forgot.html", controller: "forgotcontroller forgot", onenter: function () { $(document).foundation(); } }); $stateprovider.state("authentication.token", { url: "/login/token", templateurl: "partials/authentication/token.html", controller: "tokencontroller token", onenter: function () { $(document).foundation(); } }); and here token controller: app.controller("tokencontroller", function ($state, $stateparams, $timeout, authent

Android ViewPager can not load 3rd Fragment -

i have encourage problem when load 3 fragments viewpager each time started activity, there 2 fragments (fragment 1 & fragment 2) loaded. dont know why fragment 3 not been load. below code activity protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_register_testing); // load pager data viewpager = (viewpager) findviewbyid(r.id.pagertestingregister); list<fragment> fragments = new arraylist<>(); fragments.add(new fragment1()); fragments.add(new fragment2()); fragments.add(new fragment3()); viewpager.setadapter(new registertestingfragmentpageradapter(getsupportfragmentmanager(), fragments)); } activity ui <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/expense1" android:layout_width="fill_pa

c# - Use factory pattern when using different properties based on a property value -

in web api 2 project have model orderline (nested object of order model). client can post data , via ivalidatableobject validate model. simplyfied, models looks this: public class order { public int id { get; set; } public string description { get; set; } public icollection<orderline> orderlines { get; set; } } public class orderline : ivalidatableobject { public int id { get; set; } public string type { get; set; } [required] public string itemcode { get; set; } [required] public string description { get; set; } [requiredif("type == 'a'")] public string deliverytype { get; set; } public ienumerable<validationresult> validate(validationcontext validationcontext) { if(type.toupper() == "a") { var item = itemcode + deliverytype; using(mydbcontext db = new mydbcontext)) { var items = db.items.where(q => q.item

Python socket not accepting port as variable from api -

i running socket script wait connection using port number api response seleniumport = cont["ports"][0]["publicport"] i converting int using function i'm passing socket errors client.connect(('192.168.33.10',seleniumport)) socket.error: [errno 111] connection refused econnrefused (111) connection refused. error can occur during attempt connect tcp socket. reported when reset or unexpected sync message received. i pretty sure going have put in try loop , wait other end listening. edit: comments going have print out seleniumport @ same time have port number program supposedly listening check identical each time. arguably, testing adding let's 10 port number should give identical error, ie nothing listening on other end. short of that, create script listen on given port , test against i.e. import os, socket, time address = ('localhost',32840) s = socket.socket(socket.af_inet, socket.sock_stream) s.bind(address) s.

MYSQL Trigger Update column with same column based on other column -

i have following table. order_id code value 1 sub_total 5.00 1 shipping 5.00 1 total 10.00 2 sub_total 3.00 2 shipping 6.00 2 total 9.00 on occasion sub_total need update (products added instance), , total needs updated. have created trigger update sub_total. how update total based on sub_total , shipping? i have attempted following: create trigger after_order_product_update after update on order_product each row begin update `order_total` set `value` = new.`total` `order_id` = new.`order_id` , `code` = 'sub_total'; update `order_total` set `value` = (select `value` `order_total` `code` = 'shipping' , `order_id` = new.`order_id`) + (select `value` `order_total` `code` = 'sub_total' , `order_id` = new.`order_id`) `code` = 'total' , `order_id` = new.`order_id`

Adjusting / place a larger image size imageView Android -

Image
what want open option adjust image touch inside hollow (imageview size). for example, if add profile picture, picture not come out whole, through touch move image adjust settings want. the effect after choosing photo gallery, appears this: thanks. regards.

Python 8 puzzle BFS infinite loop -

i trying solve 8 puzzle problem using bfs search, however, code seems stuck in infinite loop moves 0 tile , forth until memory of queue ends program in error. import collections import queue class node: def __init__(self, puzzle, last=none): self.puzzle = puzzle self.last = last @property def seq(self): # keep track of sequence used goal node, seq = self, [] while node: seq.append(node) node = node.last yield reversed(seq) @property def state(self): return str(self) # hashable can compared in sets @property def issolved(self): return self.puzzle.issolved @property def getmoves(self): return self.puzzle.getmoves class puzzle: def __init__(self, startboard): self.board = startboard @property def getmoves(self): possiblenewboards = [] zeropos = self.board.index(0) # find 0 tile determine possible moves if zero