Posts

Showing posts from February, 2012

how to divide image into three equal parts in php imagemagick and combine with some padding and output as single image -

Image
i want display image 3 parts triptych of imagemagick php library. saw same example here http://www.rubbleimages.com/canvas.php . can me on issue please i hopeless @ php seems work me: #!/usr/local/bin/php -f <?php $padding=10; $info = getimagesize("input.jpg"); $width=$info[0]; $height=$info[1]; // calculate dimensions of output image $canvaswidth=$width+4*$padding; $canvasheight=$height+2*$padding; // create white canvas $output = imagecreatetruecolor($canvaswidth, $canvasheight); $background = imagecolorallocate($output, 255, 255, 255); imagefill($output, 0, 0, $background); // read in original image $orig = imagecreatefromjpeg("input.jpg"); // copy left third output image imagecopy($output, $orig,$padding, $padding, 0, 0, $width/3, $height); // copy central third output image imagecopy($output, $orig,2*$padding+$width/3, $padding, $width/3, 0, $width/3, $he

python - Restrict records of a model [Odoo] -

i need list partners in 1 views used model 'res.partner'. <record id="view_res_partner_tree" model="ir.ui.view"> <field name="name">res.partner.tree</field> <field name="model">res.partner</field> <field name="arch" type="xml"> <tree string="contacts" edit="false" create="false" delete="false"> <field name="display_name"/> <button name="generate" type="object" string="générer" icon="oe_highlight"/> </tree> </field> </record> this works every partners listed. list partners got services. (custom module services) i have done in xml like: domain="[('display_name', 'in', 'select display_name module_services')]&q

android - Start call with speaker via intent -

i have service start call when happened, works prefect question how can start speaker on?(and remove speaker after 2 min?) according anwsers, this code should work - intent intent = new intent(intent.action_call); intent.setdata(uri.parse("tel:" + num)); intent.addflags(intent.flag_activity_new_task); intent.addflags(intent.flag_from_background);// (i'm starting call service..) startactivity(intent); //the call start here, work perfect audiomanager audiomanager = (audiomanager) getsystemservice(context.audio_service); audiomanager.setmode(audiomanager.mode_in_call); audiomanager.setspeakerphoneon(true); well, doesnt work.. why? audiomanager audiomanager = (audiomanager) getsystemservice(context.audio_service); audiomanager.setmode(audiomanager.mode_in_call); audiomanager.setspeakerphoneon(true); use turn speaker on once c

tableview - Action for button in cell - Objective C -

i'm beginner in objective-c. have problem. have tableview 20 cells, has "name" , "button" each cell. want when click button in cell, button changed background image. don't know why, when click button in cell #1 change background button in cell #8 auto change background. have idea? please me. -(void)clicklike:(uibutton*)sender { uiimage *curimg = sender.currentimage; uiimage *like = [uiimage imagenamed:@"like.png"]; uiimage *dislike = [uiimage imagenamed:@"dislike.png"]; if(curimg==like){ [sender setimage:[uiimage imagenamed:@"dislike.png"] forstate:uicontrolstatenormal]; sender.selected = true; //insert dislike song songobject *list = [self.arrsong objectatindex:sender.tag]; iduser=@"1"; idsong=list.idsong; [self dislikesong:idsong and:iduser]; } else if(curimg==dislike){ [sender setimage:[uiimage imagenamed:@"

The result is random when group by some column that set collation in SQL Server -

i have query: select dmt_informationbiz.name collate japanese_ci_ai name dmt_informationbiz group name collate japanese_ci_ai i run query 2 times result of column [name](this column use collate) difference run 1st: [アウ] => full-size run 2nd: [アウ] => half-size please me: why result diffence when run same query. how fix result(same result when run many times) p/s: english not good, sorry inconvenience

MySQL SUM(GROUP BY) -

i trying add columns id same. i'm new mysql appears group by need. here attempt gives me syntax error |siteid|staffid|holiday|total update sitestaff set total = sum(h.holiday) group h.staffid i suspect have holiday table. if so, want query uses join update , , looks this: update sitestaff ss left join (select h.staffid, sum(h.holiday) total holidays h group h.staffid ) h on ss.staffid = h.staffid set ss.total = coalesce(t.total, 0);

pingfederate - I am using Http Form Adapter in Ping Federate. How to get user attributes from SAML Response? -

http form adapter serves authentication service in application. have not implemented application on identity provider user inputs. therefore, on successful authentication, sp verifies user's signature , redirects application. @ target resource, receive open token. still possible utilize open token jar read user attributes otk? **note: ** in service provider, use open token adapter. also, please let me know if there other possible way of getting user attributes other using open token adapter/http form adapter. thanks. there numerous sp adapters can choose use last mile integration application. opentoken adapter 1 of them. if application in java , using sp opentoken adapter, use java opentoken agent implementation within application read otk ( documented in java integration kit ). if @ add ons list, there 3 flavors of otk agents (.net, java , php pingid. ruby on rails , perl available via respective open source repositories). however, not limited opentoken ada

bufferedreader - Java wrapper for ROOT. OutputStreamReader is blocking -

tldr; there friendly way java read root stdout? , vice versa? i have java function launches root process. java , root communicate via stdin , stdout. well, that's plan anyway. reason can't info output cin (root) accessible via java process. i'm sure i've stumbled upon several simultanious gotchas here, sorry long question, code included simple possible root code: void test_io(){ while (true){ string in_str; cout << "root:: loop iteration"; //cout.flush(); flushing has no effect cin >> in_str; cout << "root:: received string " << in_str; } } i run code following command: root -b -q external/test_io.c the output looks like: ------------------------------------------------------------ | welcome root 6.02/05 http://root.cern.ch | | (c) 1995-2014, root team | | built linuxx8664gcc

python - 1049, "Unknown database 'database' " django mysql can't connect -

exception type: operationalerror @ / exception value: (1049, "unknown database 'database'") at moment tried this: databases = { 'default': { 'engine': 'django.db.backends.mysql', # add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'name': 'database', # or path database file if using sqlite3. 'user': 'root', # not used sqlite3. 'password': '****', # not used sqlite3. 'host': '/var/lib/mysql/database/', # set empty string localhost. not used sqlite3. 'port': '80', # set empty string default. not used sqlite3. } } if don't specify host error: operationalerror @ / (2002, "can't connect local mysql server through socket '/var/lib/mysql/database'

clojure - Boot: serve non-root directory from classpath in handler + cljs reload -

i have tried convert leiningen project boot: https://github.com/borkdude/lein2boot . it uses serve task serve handler. handler offers api , serves files. using reload task, want able reload javascript. i needed place html , javascript @ root of resources directory (in example "assets"), because reload task sends changed javascript browser using full resource path ( /main.js ). means have serve root of classpath: (resources "/" {:root ""}) in compojure. problem can request file entire classpath: no good. when relocate javascript assets/public/main.js , serve public directory: (resources "/" {:root "public"}) , file can requested @ "/main.js", reload task notifies browser reload file "/public/main.js" causes 404. how can solve problem? it looks being worked on in https://github.com/adzerk-oss/boot-reload/issues/18 , allow :asset-path option provide relative roots.

design patterns - Non-OS Specific FD(File Descriptor) for C/C++ -

linux treated file, network socket. but, windows not. , common files , network sockets treated "fd". if code should not rely on operating system, how should write? i think below.. #ifndef invalid_socket #define invalid_socket (-1) #endif class descriptor { private: int m_fd; public: descriptor() : m_fd(invalid_socket) { } virtual ~descriptor() { this->close(); } virtual bool isvalid(); virtual bool close() = 0; virtual int getno() { return m_fd; } }; enum elistenflags { e_listen_read = 1, e_listen_write = 2, e_listen_error = 4, e_listen_nonblock = 8 }; class asyncdescriptor : public descriptor { // epoll (for linux) or iocp (for windows) or select, poll... public: virtual bool listen(descriptor* pdesc, int listenflags) = 0; virtual bool dizzy(descriptor* pdesc, int dizzyflags) = 0; virtual bool wait(std::list<descriptor*>& listout) = 0; virtual bool list(std::list<descriptor*>& listout) = 0; virtu

Android Design Library AppBar Scrolling behavior -

Image
i have own implementation of scrolling toolbar in app. in new design library google http://android-developers.blogspot.de/2015/05/android-design-support-library.html there new implementation scrolling toolbar. thats nice , easy implement problem there limitation. have toolbar , behind there image , tabstrip @ bottom. if use new implementation cant toolbar image scroll off , tabstrip dont disappear. can tabstrip under toolbar image thats not goal. in left thats way works correctly tabstrip isnt on top of image. on right correct tabstrip disappear if scrolls i hope clear mean , can me, thank you. i forget xml declarations. left screenshot: <android.support.design.widget.coordinatorlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" > <android.support.v4.widget.nestedscrollview androi

php/mysql insert into query returns null -

i struggling project want read sql file formatted in specific way , execute queries in it. need check if first query has been executed in order continue. first query returns null value. can me please ? tried mysql error returns nothing too. here code. <?php $inserts = file_get_contents($nom_definitif); $inserts = preg_replace('/--+\s.*/i', "", $inserts); $inserts = preg_split("/;/si", $inserts); $insert = str_replace('insert into', '', $inserts[0] . " ;"); $res_insert_etab = phpadm_dbquery('insert ' . $insert); //this returns name of database echo "db ".$phpadm_config['dbname_etablissements']."<br>"; //but returns null echo "res_insert: ".$res_insert_etab."<br>"; if($res_insert_etab){ //get last inserted id $last_etab_id = phpadm_dbinsertid(); //execute create database query $create

database design - Relational data modeling for sub types -

Image
i learning relational model , data modeling. , have confusion in mind regarding sub types. i know data modeling iterative process , there many different ways model things. don't know how choose between different options. example suppose want model particles (molecule, atom, proton, neutron, electron, ...). let's ignore quark , other particles simplicity. since particles of same type behave same, not going model individual particles. put in way, not going store every hydrogen atom. instead, store hydrogen, oxygen , other atom types. going model particle types , relationships between them. i using word " type " carelessly. hydrogen atom instance. hydrogen type. hydrogen type of atom. yes, there hierarchy of types involved. , ignoring lowest level (individual particles). approaches i can think of several approaches model them. 1. 1 table (relation, entity) each type of things (particle types). 1.1 first approach comes mind. proton (proto

c# - Breaking the DateTimePicker by typing in wrong dates -

i'm using datetimepicker customformat (yyyy / mm) , showupdown set true. after few attempts @ typing in dates , clicking on down datetimepicker threw indexoutofrange exception. so far haven't been able reproduce willingly, typing numbers 1-0 line , ß , ´ in fast progression while being in month part happened few times again (but not every time when did this). as both events valuechanging validating would trigger late (validating if leave field don't during typing, , valuechanging gets datetime variable e.newvalue) i'm not sure how approach problem, or if approachable @ all. question here is: there way tackle problem? check datetimepicker's mindate , maxdate properties . datetimepicker won't let set date isn't between mindate , maxdate. maybe help!

php - Limit e-mail flow in Laravel -

i'm working on app built laravel 4.2. my app send pretty large amount of individual emails. problem smtp server has limit of max 300 mails/30 minutes , 5000 mails/day that enough me. want control flow of sen email queuing them sent @ rate of max 300 mails/30 mins. is there simple way of doing that, using laravels libraries? you're on right track queue. had db table 1 row each email sent, , column tracking if email has been sent. create laravel command executed cronjob every 30 minutes send next 300 emails have not yet been sent. a better, cleaner , around more scaleable option implement 1 of many queue engines supported laravel's queues . require modification of server environment installing mysql support database.

python - Django 1.8 AttributeError: 'dict' object has no attribute 'push' -

here traceback: environment: request method: request url: http://127.0.0.1:8000/myapp/addinterest/ django version: 1.8.2 python version: 2.7.8 installed applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp') installed middleware: ('django.contrib.sessions.middleware.sessionmiddleware', 'django.middleware.common.commonmiddleware', 'django.middleware.csrf.csrfviewmiddleware', 'django.contrib.auth.middleware.authenticationmiddleware', 'django.contrib.auth.middleware.sessionauthenticationmiddleware', 'django.contrib.messages.middleware.messagemiddleware', 'django.middleware.clickjacking.xframeoptionsmiddleware', 'django.middleware.security.securitymiddleware') traceback: file "/library/python/2.7/site-packages/djan

javascript - jQuery Slider value undefined -

i'm trying learn how use jquery sliders. can't value slider on change/slide. how value? $(function() { $('.slider').slider({ value: 0, min: 0, max: 100, step: 1, change: function() { updateval(this); } }); }); function updateval(bar) { //this returns object var selection = $('.ampsli').slider('value'); alert(selection); //this returns 'undefined' alert(bar.value); } pass ui object in updateval: change: function (event, ui) { updateval(ui); } demo: http://jsfiddle.net/lotusgodkk/gcu2d/723/

sql - Add substring_index upto 3 and add comma - MySQL Query -

i have query select 1st 3 words field , add column in table: update `site`,`clients` set `site`.`words` = substring_index(`clients`.`name` , ' ', 3) `clients`.`client_id`=`site`.`client_id`; 1st 3 words added successfully, need make them comma separated. how can ? thanks help. a simple replace fix it. update `site`,`clients` set `site`.`words` = replace(substring_index(`clients`.`name` , ' ', 3)," ",",") `clients`.`client_id`=`site`.`client_id`;

ios - navigate to the second vc at the end of the animated view without using a button -

how can navigate second vc @ end of animated view without using button? i have watched tutorials in each videos solving problem using button... can me? just add performseguewithidentifier in completion block below uiview.animatewithduration(0.25, delay: 0, options: uiviewanimationoptions.curveeaseinout, animations: { //your animations }, completion: { // segue, example //self.performseguewithidentifier("signinview", sender: self) })

Select value from single value from multiplie vlaue column in mysql -

for example table: datauser plans -------- 109,1009,178 select rows datauser plans = 109 . used query. please try query:- select * datauser plans "109" or plans "109,%" or plans "%,109" or plans "%,109,%" which means there can 4 conditions in column: plans column has '109' in it, or ',109,' in or '109,' in it, or ',109' in it.

java - How to generate some identically distributed pseudo-random vectors with a fixed length r in a programming language? -

for example, dimension d=2 , means generate random angle 0<=a<2*pi , , use (x_1,x_2)=(r*cos(a),r*sin(a)) random vector. however, dimension d>=3 , not generate angle , use represent vector. how generate such vector (x_1,...,x_d) , identically distributed on x_1^2+x_2^2+...+x_d^2=r^2 ? i have come new idea, generate vector (x_1,...,x_d) such -r<=x_i<r i , normalize if x_1^2+x_2^2+...+x_d^2<=r^2 , abondon if x_1^2+x_2^2+...+x_d^2>r^2 . however, there drawback probability x_1^2+x_2^2+...+x_d^2<=r^2 become small if d large. there exist better solutions? generate random variables (x_1, x_2, ... x_d) independent , have standard normal distributions, , normalize dividing sqrt(x_1^2+...+x_d^2)/r. that joint distribution of independent normal distributions rotationally symmetric not true, characterizes normal distributions. you can generate pairs of independent variables standard normal distribution efficiently uniform random variables us

linux - Getting the device address by device tree file in C -

i working on linux; when linux starts dts (device tree), file loaded linux kernel. my question is, there have way device address dts file using c lanugage? for example: some part of dts file like: soc@ffe00000{ ....... i2c@112000{ ....... } } i want device name(soc,i2c) ,and address(ffe00000,112000) ... hi ck vir, your question isn't clear. i'm assuming looking sort of function takes argument contents of dts file , returns bunch of (device, address) pairs. correct? also, useful if told sort of device using. raspberry pi? beaglebone black? or full desktop computer? distro , version of linux using? this might not looking for, while ago, used nice library posted here on github . instance, address device named "ethernet", following. int err = dtree_open("/proc/device-tree"); if(err != 0) { printf("failed open device tree\n"); exit(1); } struct dtree_dev_t *eth = dtree_byname("etherne

ruby array iteration and cheking for nil value -

i have @banners object. want iterate through each element of array , want pluck :picture_file_name. want check whether each picture_file_name nil or not. doing this if @banners.present? , @banners.pluck(:picture_file_name) == [nil] but not getting proper result assuming it's "if ':picture_file_name's nil" : if @banners.present? , @banners.pluck(:picture_file_name).all?(&:nil?) in case checking "if ':picture_file_name's not nil" : if @banners.present? , @banners.pluck(:picture_file_name).all?

Bing maps for Windows phone app -

i'm trying build app wp8.1 in c#. want add bing maps feature windows phone app. the maps windows phone 8.1 built wp8.1 sdk. no need add nuget wp. can find them under windows.ui.xaml.controls.maps namespace. below links ref: http://www.c-sharpcorner.com/uploadfile/020f8f/windows-phone-8-1-map-control/ http://www.jayway.com/2014/04/18/windows-phone-8-1-for-developers-maps/ you can add map in xaml using "using:windows.ui.xaml.controls.maps" namespace , code behind can set location, icon, or other children.

Javascript or Jquery to detect page refresh and redirect to error page - avoid duplicate data submission -

tried jquery redirect error page when jsp page refreshed using f5 or browser refresh button following : function confirmexit() { alert("exiting"); window.location.href='index.html'; return true; } window.onbeforeunload = confirmexit; the above code gives alert when page refreshed, window.onbeforeunload alerts when save button pressed , page not redirected , duplicate data submitted. im doing avoid duplicate data submission on refresh. please help. you can't relocate onbeforeunload event. browser won't allow it, because of security reasons. (eg, keep on page forever.) the thing can onbeforeupload ask user if he's sure if wants exit. you need accept there little can in preventing user make http request, refreshing or whatever means. instead need solve on server side, redirecting browser if same request made twice. to answer question save button (even though isn't relevant more). var saved = false; function confi

asp.net mvc - how to upload multiple images with progress bar in asp .net mvc 4 with razor? -

i need upload selected multiple images @ time showing progress bar each in asp .net mvc 4 razor.please 1 help this basic: this example self-explanatory.. hope helps! create form uploading multiple files: <form action="" method="post" enctype="multipart/form-data"> <label for="lblfile1">filename:</label> <input type="file" name="files" id="file0" /> <label for="file2">filename:</label> <input type="file" name="files" id="file1" /> <input type="submit" value="upload"/> </form> now in controller post action: [httppost] public actionresult upload(ienumerable<httppostedfilebase> files) { foreach (var file in files) { if (file.contentlength > 0) { var filename = path.getfilename(file.filename); var path = path.combine(server.mappath("~/app_data

php - Access control - coding to the activity -

consider (from https://www.owasp.org/index.php/access_control_cheat_sheet ): if (ac.hasaccess(article_edit)) { //execute activity } this correctly implies access control ... policy persisted/centralized in way my question around how best centralise this. one obvious way can think of include activities needing access control in class - hardcoding. can call method hasaccess(article_edit) on class. implies whenever activity added application need add class. another way centralise access control might include controlled activities in database. each time need check access call hasaccess(article_edit) , trigger call database. include method in access control model. firstly, right track please? there other solutions people favour? might benefits/issues of solutions please? you hitting "externalized access control" issue. it's great you've thought of decoupling business logic auhthorization logic. need way express authorization logic.

ios - Unit testing app extensions iOS8 via framework -

so referring answer here recommended apple put code in framework can test it. so questions have embedded framework or can create separate project , put extension code in there? my concern because upon creating extension comes info.plist file , entitlements file , unsure should putting in relation framework , such. also once have made separate or embedded framework project, how set host test? mine interested in host app being photos, saying need actual storyboard load derives slcomposeserviceviewcontroller . create app delegate target can set host, , have load maininterface.storyboard of extension start testing? update so have discovered difference between application testing , logic testing. update question slightly, there way application test extension ui? assumption have app host target , load first view extension storyboard view.

bluetooth lowenergy - How the onCharacteristicWrite know the status is success in Android ? -

i developing in ble android , have question oncharacteristicwrite . i know oncharacteristicwrite call , return status when write value remote ble device. when oncharacteristicwrite return status 0 after gatt.writecharacteristic , means write success. question: how oncharacteristicwrite know return status 0 ?? remote ble device send ack android ?? yes, ble device send successful write acknowledgement. part of low level bluetooth low energy specification.

algorithm - Sum of digits in C# -

what's fastest , easiest read implementation of calculating sum of digits? i.e. given number: 17463 = 1 + 7 + 4 + 6 + 3 = 21 you arithmetically, without using string: sum = 0; while (n != 0) { sum += n % 10; n /= 10; }

android - how to assign textview value into string -

i want dynamically assign value of textview name "tvdistanceduration" string pass string activity textview tvdistanceduration; public string f= ""; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.publicplaceactivity); tvdistanceduration = (textview) findviewbyid(r.id.tv_distance_time); // initializing f = tvdistanceduration.gettext().tostring(); this code when view f shown nothing how can assign textview value f varaible ? first activity contain textview package com.example.project; import java.io.bufferedreader; import java.io.ioexception; import java.io.inputstream; import java.io.inputstreamreader; import java.net.httpurlconnection; import java.net.url; import java.util.arraylist; import java.util.hashmap; import java.util.list; import org.json.jsonobject; import android.content.intent; import android.graphics.color; import android.os.asynctask; impor

Estimation using mlogit in R -

i have paper author proposes d-optimal design nested multinomial logit model no-choice. design follows: cs 1: alt a: 1 2 2 1 2 2 alt b: 2 2 1 2 1 2 alt c: 0 0 0 0 0 0 cs 2: alt 1: 2 1 1 2 2 2 alt 2: 2 2 2 2 1 1 alt 3: 0 0 0 0 0 0 cs 3: alt 1: 2 2 1 1 1 2 alt 2: 1 1 2 2 2 1 alt 3: 0 0 0 0 0 0 cs 4: alt 1: 2 2 1 1 2 1 alt 2: 1 1 2 2 1 2 alt 3: 0 0 0 0 0 0 cs 5: alt 1: 1 2 1 2 2 1 alt 2: 2 1 2 1 1 2 alt 3: 0 0 0 0 0 0 cs 6: alt 1: 1 2 1 2 1 2 alt 2: 2 1 2 1 2 1 alt 3: 0 0 0 0 0 0 cs 7: alt 1: 2 1 1 2 2 1 alt 2: 1 2 2 1 2 2 alt 3: 0 0 0 0 0 0 cs 8: alt 1: 2 1 2 2 2 1 alt 2: 1 2 2 1 1 2 alt 3: 0 0 0 0 0 0 the design d-optimal design 8 choice sets , every choice set has 2 alternatives (6

powershell - Install role services using command line -

i taking windows server class , supposed install/uninstall role services using cli , powershell. now easy figure out using powershell since there install-windowsfeature , uninstall-windowsfeature cmdlets. but lab assignment asking me provide commands cli. is there way install/uninstall role services cli? just note: using microsoft's moac lab set. install-windowsfeature –name feature_name -computername computer_name -restart

java - Setting the width of a JList in a JScrollPane with GridBagLayout -

Image
i have example java swing code below produces following screenshot (screenshot has been edited make smaller): here code: import java.awt.gridbagconstraints; import java.awt.gridbaglayout; import java.awt.insets; import javax.swing.jframe; import javax.swing.jlabel; import javax.swing.jlist; import javax.swing.jpanel; import javax.swing.jscrollpane; import javax.swing.jtextarea; import javax.swing.swingutilities; public class main extends jframe { public main() { jlisttest thegui = new jlisttest(); setdefaultcloseoperation(jframe.exit_on_close); setresizable(false); add(thegui); pack(); setvisible(true); } public static void main(string[] args) { swingutilities.invokelater(new runnable() { public void run() { new main(); } }); } private class jlisttest extends jpanel { private static final int padding = 3; private jlabel label;