Posts

Showing posts from May, 2013

Attributed text, replace a specific font by another using swift -

i'm using attributed text in uitextview. text contain many fonts. i'm looking way replace particular font one. any swift approach this? :) my code in objective-c, since use both cocoatouch, should same logic. the method use enumerateattribute:inrange:options:usingblock: nsfontattributename . there point isn't discussed: how recognize font 1 searched. looking familyname , fontname (property of uifont ? in same family, font may lot different , may want search 1 matching same name. i've discussed once font names here . may found interesting in case. note there methods (that didn't know @ time) can bold name of font if available (or italic, etc.) the main code in objective-c one: [attrstring enumerateattribute:nsfontattributename inrange:nsmakerange(0, [attrstring length]) options:0 usingblock:^(id value, nsrange range, bool *stop) { uifo

unit testing - Conditionally load ngMock into app only if running karma jasmine tests -

i having issues loading app when including ngmock, load when running tests works fine. there flag or kind of istesting() function gets set when karma runs tests? can reference when creating array of dependencies app. i ended checking existence of global variable set if test classes had loaded, suppose it's kind of obvious kind of hoping karma.isrunning property or something... anyway solution looks kind of like: var dependencies = [ 'ui.router', 'nganimate', 'ngsanitize', ]; if (typeof app_test !== "undefined") dependencies.push("ngmock"); angular.module('myapp', dependencies)... keep in mind test classes need loaded before main app files

java - Is it possible to have a session timeout specific to a single JSR-168 portlet application -

i have jsr-168 portlet deployed inside ibm portal server v6.0 , having issues portlet reaching maximum amount of in-memory sessions defined in websphere console portal server. as result need tweak session-timeout setttings. question should tweak settings. i.e. in jsr-168 portlet allowed have following , work... <session-config> <session-timeout>30</session-timeout> </session-config> i confused because i'm not sure makes sense have session-timeout on individual portlet. portlet widget on web page , if portlet has session timeout mean rest of page times out? or not possible have session-timeout 1 portlet , hence portlet inherits session timeout settings defined portal server in websphere? , making session timeout parameter applicable pages/portlets on portal server? thanks a portlet , jsr portlet more widget on page. based on j2ee spec full application on server side , websphere application server generates server side session object

android - How to make the ellipsize textview and imageview show correct -

i'm working on layout file. layout requires icons should after single line textview. if textview long,then textview ellipsize , icons should shown.such as: situation1: [[textview][icon1][icon2]      ] situation2: [[textview......][icon1][icon2]]. i have found similar case in here , doesn't work me. my current code this: <relativelayout android:id="@+id/parent" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:gravity="left"> <!-- icon show here --> <linearlayout android:id="@+id/icons" android:paddingleft="5dp" android:orientation="horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content"

swift - Correct behaviour of Mouse down inside row of NSTableView? -

i have nstableview nsview based. in each row have nsimageview subview of nsview. have subclassed nsimageview overrided mousedown method. problem tableviewselectiondidchange getting fired when user clicks on imageview. want mousedown called not tableviewselectiondidchange. if set selectionhighlightstyle of table nstableviewselectionhighlightstyle.none mousedown of image view called. , if don't give selectionhighlightstyle nstableviewselectionhighlightstyle.none both mousedown of imageview , tableviewselectiondidchange getting called. setting selectionhighlightstyle none seems solve problem correct approch? or getting behaviour because of bug in appkit? also can't find behaviour documented somewhere. i think correct approach subclass nstableview , override nsresponder method -(bool)validateproposedfirstresponder:(nsresponder *)responder forevent:(nsevent *)event you'll have finer control on view mouse event, , won't have resort "hackery&

html - How to fixed image dimension when zoom out page using css? -

how fixed image dimension when zoom out page using css ? for example in case fiverr.com when zoom page 25% http://image.free.in.th/v/2013/iy/150803122836.png and when zoom page 100% (normal) http://image.free.in.th/v/2013/ij/150803122858.png how fixed image dimension case ? i tried many time not work (image dimension not fixed). how can ? to make background image fit entire width of page there option in css. in case should try background-size cover. css .background { background-size:cover; }

coding style - Can I get Scala to infer the Option type here? -

i want call generic function f[x](...) , , in case x happens option[y] . try pass both some[...] , none function expects x , scala insists x of type some[y] . def flattenoptionmap[a, b](input : map[a, option[b]]) : option[map[a, b]] = { input.foldleft[option[map[a,b]]] (some(map.empty)) { case (_, (_, none)) => none case (none, (_, _)) => none case (some(acc), (key, some(value))) => some(acc + (key -> value)) } } in example, had explicitly specify option[map[a,b]] should used generic type foldleft . necessary type information contained in context, , typing cumbersome types option[map[a,b]] more necessary in opinion drastically reduces readability of code. is there way scala infer type after all, or otherwise avoid copy-pasting whole type? when use option(map.empty[a, b]) start value of foldleft , scala infer correct type wrote in comments (and beefyhalo in answer). i add, if open using scalaz, can use sequence funct

java - Generic method accepts different data type list -

i want make method accepts data type list . accepting same data type list. have done below @safevarargs public static <e> list<e> mergearray(list<e> ...list) { list<e> result = new arraylist<e>(); for(list<e> temp : list) { result.addall(temp); } return result; } public static void main(string[] args1) { list<string> l1 = arrays.aslist("hello", "world"); list<double> l2 = arrays.aslist(2.3, 2.2, 4.5); list<integer> l3 = arrays.aslist(1, 2,3); list<string> l4 = arrays.aslist("hello1", "world1"); system.out.println(mergearray(l1, l2)); } here method mergearray accepts mergearray(l1, l4) //same data type. if passed different data type mean mergearray(l1,l2) or mergearray(l1,l2,l3) doesn't work. possible do? it's possible , i'm not sure it's useful

python - lxml installed, but not working on Windows -

i need validate xml file against xsd. accomplish use lxml library . problem though have from lxml import etree , have installed lxml c:\python33\lib\site-packages\lxml\ , i'm getting error traceback (most recent call last): file "c:\users\asmithe\documents\dev1\testparse.py", line 3, in <module> lxml import etree et_l importerror: no module named lxml why , how fix it? tried adding c:\python33\lib\site-packages\lxml\ path variable , didn't help. had installed lxml using pip. update: when run script through interactive terminal (i.e. typing python in cmd) can import lxml here simple script from lxml import etree def main(): print('hi') if __name__ == "__main__": main() in cmd do c:\users\dev1\documents\test>python python 3.3.5 (v3.3.5:62cf4e77f785, mar 9 2014, 10:35:05) [msc v.1600 64 bit (am d64)] on win32 type "help", "copyright", "credits" or "license" more inf

html5 - HTML Table Query on thead and tfoot -

what happens when have more 1 thead , tfoot tag inside table?how browser respond it? it add header , footer existing table. you check here https://jsfiddle.net/no220phd/3/ <table style="width:100%"> <thead> <tr> <th>head1 col1</th> <th>head1 col2</th> <th>head1 col3</th> </tr> </thead> <thead> <tr> <th>head2 col1</th> <th>head2 col2</th> <th>head2 col3</th> </tr> </thead> <tr> <td>jill</td> <td>smith</td> <td>50</td> </tr> <tr> <td>eve</td> <td>jackson</td> <td>94</td> </tr> <tr> <td>john</td> <td>doe</td> <td>80</td> </tr> <tfoot> <th>foot1 col1</th> <th>foot1 col2</th> <th>foot1 c

unit testing - vstest.console.exe not generating Test Attributes (Owner, Priority, TestCategory) in .trx file -

i have test methods given attributes owner, priority, testcategory follows <testmethod()> <owner("madhu")> <priority(1)> <testcategory("mycategory")> public sub sampletest() assert.areequal("0", "0") end sub when run test using mstest.exe these arrtibutes appearing in generated trx file if run vstest.console.exe not coming. i have checked vstest comands, not find 1 this. am missing anything, or feature doesn't exist in vstest ? https://visualstudio.uservoice.com/forums/330519-team-services/suggestions/10102809-include-traits-and-other-attributes-to-vstest-cons it says update 2 visual studio 2015 fixed issue

ios - Custom Swift NSNumberFormatterStyle -

i'm using ios charts chart data in swift ios app including times. times stored in int variables seconds people don't want see 1 hour , 45 minutes on y axis 6300 need format it. ios charts lets set use nsnumberformatter so var formatter: nsnumberformatter = nsnumberformatter() formatter.numberstyle = nsnumberformatterstyle.spelloutstyle chartholder.leftaxis.valueformatter = formatter but none of styles available suitable need. need take number of seconds , turn into, example, 1h 45m. want make custom nsnumberformatterstyle... how do this? any appreciated. this won't work nsnumberformatterstyle - options limited you. should do, subclass nsnumberformatter , , override stringfromnumber: function. there can string manipulation want.

Dynamic MapPin image not scaling correctly IOS 8 Swift -

Image
hello i'm working mapkit, ios 8, , swift , i'm using custom map pins display annotation view. i'm pulling map data server etc. , have property tell me wether display custom map pin or regular map pin that's part of map kit. i added extension mkannotationview asynchronously loads image nsurl , works fine. use similar extension uiimageview tableviews , async loading. if have image asset (map pin) stored locally in image assets folder results map pin on map expected correct dimensions , no distortion etc. the problem when download exact same image server , set image, larger 1 stored in image assets , distorted. so know guys & gals know problem. again both same image same size , dimensions 50x82 72 dpi. things have tried: thought might ios thing images being 2x etc. cut dimensions in half image coming server 25x41 , didn't help. thought might have point issue , not pixel issue. changed points half resolution , doubled dpi. sadly none of helped

Using SwitchPreference's XML Attribute android:key causes my app to crash -

i have been trying use standard android switchpreference in preferencescreen of app. when define preferences.xml as: <?xml version="1.0" encoding="utf-8"?> <preferencescreen xmlns:android="http://schemas.android.com/apk/res/android" > <preference android:icon="@mipmap/ic_launcher" android:id="@+id/pref_taosettings_id" android:key="pref_taosettings_key" android:title="@string/pref_taosettings_title" /> <switchpreference android:defaultvalue="false" android:id="@+id/pref_playlevel_id" android:summary="level" android:summaryoff="@string/pref_playlevel_beginner" android:summaryon="@string/pref_playlevel_expert" android:title="@string/pref_playlevel_title" /> </preferencescreen> when bring settings activity see following screen: [ *

android - ArrayAdapter Initializing not Clear -

i trying create list containing names of available applications on phone triggering implicit intent. being beginner in android following tutorials book. have created custom adapters extending arrayadapter before syntax of simple arrayadapter not being clear me. here is: arrayadapter<resolveinfo> adapter = new arrayadapter<resolveinfo> (getactivity(),android.r.layout.activity_list_item,activities) { @override public view getview(int position, view convertview, viewgroup parent) { // todo auto-generated method stub view v = super.getview(position, convertview, parent); textview tv = (textview)v; resolveinfo ri = getitem (position); tv.settext(ri.loadlabel(pm)); return v; } }; 1- why method getview being called in within parenthesis after calling constructor of arrayadapter? 2- kind of anonymous class structure? 3- in reality custom adapter object type of resolveinfo? any appreciated. thanks g

objective c - How to set UITextField border/CALayer border ios on three sides only -

Image
i need border textfield following image.how can that? try these.. hope helps... uitextfield *txt=[[uitextfield alloc]initwithframe:cgrectmake(10, 100, 150, 30)]; [txt setbackgroundcolor:[uicolor clearcolor]]; [txt setplaceholder:@"hello friend"]; [self.view addsubview:txt]; calayer *border = [calayer layer]; cgfloat borderwidth = 2; border.bordercolor = [uicolor redcolor].cgcolor; border.frame = cgrectmake(0, -2, txt.frame.size.width, txt.frame.size.height); border.borderwidth = borderwidth; [txt.layer addsublayer:border]; txt.layer.maskstobounds = yes;

javascript - Save file automatically from IFrame in Node Webkit -

i using node-webkit automate common tasks. have iframe goes site address, clicks save , have file save dialog pop out. is there way can catch event save file witout requiring external action (like setting save folder , clicking on save)? you may not able way, have thought doing http request node's http module? that's beauty of using node-webkit, use node.js! var http = require('http'); var fs = require('fs'); var path = require('path'); var savelocation = path.join(__dirname, "/cache", "file.txt"); //the url want is: 'www.random.org/integers/file.txt' var options = { host: 'www.random.org', path: '/integers/file.txt' }; callback = function(response) { var str = ''; //another chunk of data has been recieved, append `str` response.on('data', function (chunk) { str += chunk; }); //the whole response has been recieved, print out here

swift2 - Xcode 7 beta 3 crashes creating core data ns managed subclass or entity -

having problem xcode 7 crashing when try create core data entity. can create entity , add attributes after crashes... when xcode resumes entity no longer there. error seems reflect in core foundation, not specific, exception. i've asked in apple dev forums no response. sometimes can past stage create ns managed subclass files, files appear generated same error, crash, , upon resume entity , subclass files no longer there. any suggestions appreciated. thank you.

python - To find the pixel coodinates for a given ra-dec -

Image
i'm new python, , presently working on labeling galaxy images. have set of 512x512 pix^2 images scaled 0.2 arcsec/pix. each 1 of images have 2 objects labeled - 1 @ centre (256pix,256pix) @ other @ offset (i've projected separation between objects ra-dec values both objects). task encircle objects in each of images. easy central objects, i'm stuck on how same thing done other object. following snippet encircling of central object, need figure out how other one: i have ra-dec values both objects (in degrees). have separation between objects (in kpc). for image 512x512 px @ .2 ''/px: this iterates through objids in list - each objid have file objid.png in folder called images_fin - loads correct image, , labels objid. for galaxy in range(0, len(objid)): ![enter image description here][1]im=imread('images_fin/'+objid[galaxy]+'.jpeg') imshow(im) a=gca() print a.text(20, 480, "objid:", color ='w', fontsize='10') pr

codeigniter - Cpanel My php code minified and not working -

this question has answer here: reference - error mean in php? 30 answers hi project install cpanel server not working cpanel php code minifide @ http://prntscr.com/7vd5gt left picture local php file right picture server cpanel php file. php file error parse error: syntax error, unexpected end of file in /home/cinselterapi/public_html/application/controllers/site.php on line 2 help me please. server php version http://prntscr.com/7vd7kb apllication frame work codeigniter 2.0 my php code picture http://prntscr.com/7vd5gt this on picture left page local php file right page install cpanel on php file

Visual Studio 2015: Program out of date -

i've been using vs2015 rc until july 19th, uninstalled , subsequently installed vs2015 community (the official release). able debug , run c++ programs on vs2015 rc, however, when try run simple program have debugged in past or new one, vs2015 community gives me popup says: "this project out of date. projectname - debug win32. build it?" i've been on , found this: visual studio project out of date , after deleting .tlog files, i've still been getting same issue. i've deleted .pdbs, hasn't helped either. know fix might be? thanks! you can change build output verbosity setting make visual studio 2015 tell why rebuilding: build solution change msbuild project build output verbosity setting detailed or diagnostics. it's found here: tools (menu) options project , solution build , run build solution , check output view. in case printed message this: 1>------ up-to-date check: project: xyz, configuration: xyz ------ 1>pr

ios - How to resolve this error? - Class 'ViewController' has no initializers -

Image
i have created uilabel programmatically in swift gives me following error : class 'viewcontroller' has no initializers code : class viewcontroller: uiviewcontroller { let lbl_lastname: uilabel! override func viewdidload() { super.viewdidload() lbl_lastname.frame = cgrectmake(10, 230, 300, 21) self.view.addsubview(lbl_lastname) } } change let lbl_lastname: uilabel! var lbl_lastname: uilabel!

python - Change base url in django-tastypie-swagger -

i have django site running gunicorn on port 62022 , nginx running on port 62090. port open outside world 62090 (where nginx listen). problem django-tastypie-swagger thinks base url http://localhost:62022/ , can not make documentation api because url not respond. is there way set base url whatever need instead? try insert settings.py swagger_settings = { "base_path": 'localhost:62090/', } of course instead localhost insert domain

how to convert the SQL date type to Java param -

i have field in sql table of type date value 1944-01-02. writing java function pull data database , use java method param. how should handle it? method looks this: void search(date date); i want put 1944-01-02 in method param, java complier complain not matter if import java.util.date or java.sql.date . you have convert sql date java date: java.util.date utildate = new java.util.date(sqldate.gettime()); get more info @ link

java - What is the difference between `this` and `ActivityClass.this` in android intent constructor? -

this question has answer here: what's difference between , activity.this 3 answers what difference between this , activityclass.this when pass in intent constructor for example given 2 activities: activityone , activitytwo the following doesn't work (compile error) @override public void onclick(view v) { intent intent = null; log.i(tag, this.tostring()); log.i(tag, activityone.this.tostring()); intent = new intent(this, activitytwo.class); startactivity(intent); } while works @override public void onclick(view v) { intent intent = null; log.i(tag, this.tostring()); log.i(tag, activityone.this.tostring()); intent = new intent(activityonethis, activitytwo.class); startactivity(intent);

c++ - undefined reference errors when I add boost log dependecies -

Image
i trying add boost logging functionality. but i've got lot of errors undefined reference . d:\c++\boost_1_58_0\bin.v2\libs\log\build\gcc-mingw-5.1.0\debug\link-static\threading-multi/libboost_log-mgw51-mt-d-1_58.a(core.o): in function `boost::thread_specific_ptr<boost::log::v2s_mt_nt5::core::implementation::thread_data>::~thread_specific_ptr()': d:\c++\boost_1_58_0/./boost/thread/tss.hpp:79: undefined reference `boost::detail::set_tss_data(void const*, boost::shared_ptr<boost::detail::tss_cleanup_function>, void*, bool)' d:\c++\boost_1_58_0\bin.v2\libs\log\build\gcc-mingw-5.1.0\debug\link-static\threading-multi/libboost_log-mgw51-mt-d-1_58.a(core.o): in function `boost::thread_specific_ptr<boost::log::v2s_mt_nt5::core::implementation::thread_data>::get() const': d:\c++\boost_1_58_0/./boost/thread/tss.hpp:84: undefined reference `boost::detail::get_tss_data(void const*)' d:\c++\boost_1_58_0\bin.v2\libs\log\build\gcc-mingw-5.1.0\debug\link-st

Android Studio wizard buttons hidden behind Windows TaskBar -

Image
i have problem wizard height more or equal screen height in android studio, issue buttons hidden under windows taskbar, see following image : i have latest android studio ide 1.3 build ai-141.2117773 jdk version 8 update 45, on windows 10 pro (build 10240) screen resolution 1366 x 768 (for laptop 15 inches screen) any solution issue? well not problem of yours bug in studio 1366x768 resolution discussed in forums suggestion use tab keys have control on keys beyond cursor reach or may use autohide feature of taskbar..

.jar plugin for Eclipse not being loaded -

i trying install fatjar plugin in eclipse, not showing up. doing explained in documentation , extracted .jar file in plugins directory, started command prompt inside eclipse folder "eclipse -clean", , doesn't show up... anyone know how can check if plugin being noticed @ all? this plugin old , using old style plugin format not supported default current versions of eclipse. as mentioned in documentation (probably all) of features provided plugin part of eclipse standard (see 'file > export > java > runnable jar file')

ruby - How to test if all divs with class one has also class two in Rails integration test? -

i test in rails integration test, if divs class 1 has class 2 , if not, fail. there may other classes, not relevant test. this should pass: <div class="one two">...</div> <div class="one 3 two">...</div> <div class="two one">...</div> and should fail: <div class="one two">...</div> <div class="one three">...</div> <div class="one">...</div> thx! you can using capybara. let(:items) { page.find('div.one') } "items has both classes" items.each |item| expect(item[:class]).to match(/two/) end end

javascript - How to change an image selected from another window -

i have got code change image image list of then. i'm trying show new window image list choose one. <div class="row"> <div class="service-icon"> <img style='margin:0; padding:0; border:0;' id="imggaleria" onclick="imgseleccionada='imggaleria';" src="img/modulo1.jpg" /> <img style='margin:0; padding:0; border:0;' id="imggaleria2" onclick="imgseleccionada='imggaleria2';" src="img/modulo2.jpg" /> <img style='margin:0; padding:0; border:0;' id="imggaleria3" onclick="imgseleccionada='imggaleria3';" src="img/modulo3.jpg" /> <div id="galeria_miniaturas"> <img class="miniatura" onclick="javascript:document.getelementbyid(imgseleccionada).src='img/modulo5.jpg';" src="img/modulo5.jp

windows - Threading and Thread Safety in C -

Image
when there common set of global data needs shared among several threaded processes, typically have used thread token protect shared resource: edit - 7/22/15 (to incorporate atomics viable option, per jens comments) my [first] question is , in c, if write routines in such way guarantee each thread accesses one, , 1 element of array: is there reason think asynchronous , simultaneous access different indices of same unprotected array (as shown in diagram) problem? second question: given an object can accessed atomic entity, in presence of asynchronous interrupts ( c99 - 7.14 signal handling ) using atomics effective method thread protection otherwise unprotected variable? edit (clarifications address questions in comments point): - specifics application: - target os: windows 7/8/10 - compiler : c99 compliant (cannot use c11, include _ atomic() type specifier ) - h/w : intel i7 family this (which looks c standard of sort) http://www.open-

How to call a function which is returning another function in Swift? -

will please guide me how call function returning function in swift. i think need this: func f1() -> () -> int { let = 3 func f2() -> int { return } return f2 } this function of course useless, give idea.

php - Using custom fonts hosted on AWS S3 in a Wordpress site -

i have fonts typography.com moved production , uploaded aws s3 bucket use on wordpress site. have done typography.com has told me do, fonts still not being displayed. has gone through before , can point me in right direction? added @import statement in style.css in theme url typography.com gave me. have wp_enqueue function in functions.php have uploaded s3 server. add_action( 'wp_head', 'my_fonts' ); function my_fonts(){ ?> <link rel="stylesheet" type="text/css" href="//cloud.typography.com/7783912/761788/css/fonts.css"> <?php } the fonts still not being displayed. doing wrong? the proper way include stylesheets use wp_enqueue_style . using function allow declare font dependency other stylesheets. should use 'wp_enqueue_scripts' hook, opposed 'wp_head' : /** * proper way enqueue scripts , styles */ function theme_name_scripts() { wp_enqueue_style( 'typography', '//cloud.typo

sails.js - How to code composite keys into SailsJS -

i have question sailsjs. research i've done have yet find substantial amount of examples or explanation composite keys in sailsjs. have done have learned absolutely have form of workaround in order composite keys work in sailsjs however, don't understand or follow small examples have found online. if take time out of day , explain them or explicitly give example i'd appreciative. this possibly asked here: sails.js composite unique field and issue conversation on git - best done in actual db , not live in code...if cannot done whatever use case warrants departure of best practice, code whatever works best needs...it's not "wrong" answer have needs drive edges :) if have specific question feel free edit question , perhaps better explanation of composite keys can provided.

c# - string is null when posting from Angular to Web API? -

when try post string web api, value null. have tried wrapping in quotes, still null. angularjs code: return $http.post("http://localhost:59437/api/recaptcha/post", vcrecaptchaservice.getresponse()); web api code: [enablecors("*", "*", "*")] public class recaptchacontroller : apicontroller { public string post([frombody] string response) { return response; } } i not sure how works because, don't have response in form body. vcrecaptchaservice.getresponse() returns response string , going send google's verify api verify recaptcha, [frombody] part doesn't make sense me if not part of body your post call should sending data in json format {response: 'something'} return $http.post("http://localhost:59437/api/recaptcha/post", { response: vcrecaptchaservice.getresponse() } //data );

java - How to get AsyncHttpResponseHandler response as a JSONObject? -

my java restful service login method returns jsonobject (with name, username, , on) in responsebuilder entity. i'm trying inside asynchttpresponsehandler (using loopj ) in android app. problem is: onsuccess method expecting byte[] response, not jsonobject. how jsonobject inside onsuccess method in order use it's values (user data) on app? here code: my restful api login method public response login(@context httpheaders httpheaders, @formparam("username") string username, @formparam("password") string password) { authenticator authenticator = authenticator.getinstance(); string servicekey = httpheaders .getheaderstring(httpheadernames.service_key); try { // login method returns jsonobject data of logged user jsonobject obj = authenticator .login(servicekey, username, password); return getnocacheresponsebuilder(response.status.ok

Can I develop Java Enterprise application in IntelliJ Community Edition? -

i want develop application in java enterprise , google web tool using intellij idea community edition. possible? or have buy ultimate edition. you able write j2ee/gwt code, compile , unit test in intellij community. won't able run , debug in editor. need use command line and/or third party scripts , configuration.

java - I have to count the all the possible pair from left to right in array.How I can do it effectively? -

//below implementation how improve that? int[] numbers = { 1, 5, 23, 2, 1, 6, 3, 1, 8, 12, 3 }; int count = 0; int length = numbers.length; for(int i=0; i<length; i++){ for(int j= i+1;j<length; j++ ){ if(j!=i && numbers[i]==numbers[j]){ count+=1; } } } solution in o(n): public static void main(string[] args) { int[] numbers = { 1, 5, 23, 2, 1, 6, 3, 1, 8, 12, 3 }; int count = 0; map<integer, integer> elements = new hashmap<>(); (int = 0; < numbers.length; i++) { integer e = elements.get(numbers[i]); if (e == null){ e = 0; } count += e; elements.put(numbers[i], e+1); } system.out.println("count: "+count); }

Visual Studio 2012 - Coded UI Test Builder: Assertion Formula? -

while automating testing of website shopping experience, attempting verify subtotal, total, , tax calculating properly. since price and/or tax change in future, cannot assert actual price value inside control. instead, need build calculation based upon controls , assert quantity multiplied individual price each item added equals subtotal, , on. for example, controls each named such (control names in asterisks): quantity = *uiitem2cell* (innertext has value of 2) individual price = *uiitem249pane* (displaytext has value of 2.49) individual product total (price x qty) = *uiitem498pane* (innertext has value of 4.98) instead of validating values actual numbers, can write assertion formula using identifiers variables? keep in mind, using coded ui test builder rather writing code outright. if individual product total innertext assertion comparator areequal, can comparison value like: uiitem2cell-innertext * uiitem249pane-displaytext a. sort of formula possible? b

material design - Change color of DrawerToggle in toolbar on Android -

can pinpoint why drawer toggle (the little hamburger icon animates open navigation drawer) refuses switch color on me? it's causing me lot of downtime , can't seem figure out why. here's theme - drawer toggle takes on color of disabled_default_text. <style name="theme.myapp.noactionbar" parent="theme.myapp.noactionbar"> <item name="actionbarstyle">@style/widget.myapp.actionbar</item> <item name="coloraccent">@color/cs7</item> <item name="colorcontrolnormal">@color/disabled_default_text</item> </style> and here's toolbar layout: <?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.toolbar 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="?att

ios - Prevent reloading on reusable cells in Swift -

i new swift language , facing problem... in "my profile" tableview, query (to parse) currentuser()'s posts includekey of array of pointers point tagged objects other class. for each post, have set different colors each object tagged according "type" (using attributedstrings concatenated strings) i discovered cells reloading each time scroll down thing code becoming quite heavy , slow. do have idea how fix or how prevent cells being reused ? thanks lot. this code cellforrowatindexpath() : cell.selectionstyle = uitableviewcellselectionstyle.none // pour activer la selection de cellules // cell.selectionstyle = uitableviewcellselectionstyleblue;(by default) // cell.selectionstyle = uitableviewcellselectionstylegray; var imagetoload = self.images[indexpath.row] pffile var imagecaption = self.imagecaptions[indexpath.row] string var imagedate = self.imagedates[indexpath.row] string var postkooleqts: anyobject = self.

PHP | Download the zip file in php -

i want download zip file in php. here code below. <?php ob_start(); // set example variables $filename = "test.zip"; $filepath = "/home/somewhere/file/zip"; // http headers zip downloads header("pragma: no-cache"); header("expires: on, 01 jan 1970 00:00:00 gmt"); header("cache-control: no-store, no-cache, must-revalidate"); header("cache-control: post-check=0, pre-check=0", false); header("content-description: file transfer"); header("content-type: application/zip"); header("content-disposition: attachment; filename=\"".$filename."\""); header("content-transfer-encoding: binary"); header("content-length: ".filesize($filepath.$filename)); readfile($filepath.$filename); ?> and have link in html code. <html> <head> </head> <body> <a href="myphpfile.php">download</a> </bod

css - circle overflowing the container -

Image
i trying make effect on image attached. circle overflowing container css border-radius. it's there not yet right. this code nearest can it. body { margin: 0; } .bg-border-radius { margin: 0px; width: 100%; height: 200px; overflow: hidden; border-radius: 0 0 100% 100%; background-color: #0080c1; } <div class="bg-border-radius"></div> how can closer what's on image css? wrap <div> inside another, let's call "wrapper" <div class="wrapper"> <div class="bg-border-radius"></div> </div> .wrapper { width: 100%; overflow: hidden; } now can arange circle like, bigger width 100%. make circle responsive, set border-radius: 50% , height: auto; , padding-top: 150%; <--same width . if move circle margin-top: -120%; , margin-left: -25%; you'll http://jsfiddle.net/qcfo5688/

ios - how to save one name string and two different length array of email and phone no -

as guess simple , basic question. i using #import <addressbook/addressbook.h> contact info of device , had implemented same. everythings work fine when got 1 phone no , 1 email each contact. when got multiple phone no's , multiple email getting crash on app. guess not using proper saving method. so want know how save 1 name string , 1 array of email(different length) , phone no(different length) group contact , same other. not difficult reproduce result later on detail screen cferrorref *error = null; abaddressbookref addressbook = abaddressbookcreatewithoptions(null, error); cfarrayref allpeople = abaddressbookcopyarrayofallpeople(addressbook); cfindex numberofpeople = abaddressbookgetpersoncount(addressbook); for(int = 0; < numberofpeople; i++) { abrecordref person = cfarraygetvalueatindex( allpeople, ); nsstring *firstname = (__bridge nsstring *)(abrecordcopyvalue(person, kabpersonfirstnameproperty)); nsstring *lastname = (__bridge nsstring

android - Setting widget background to programmaticaly generated gradient -

i'm struggling making widget pretty, widget fights ;( i have problem setting widget layout background generated linear gradient. for now, have found how generate linear gradient custom "weigth" of colors gradient: public static paintdrawable createlineargradient(final int left, final int top, final int right, final int bottom, final int[] colors, final float[] positions) { shapedrawable.shaderfactory shaderfactory = new shapedrawable.shaderfactory() { @override public shader resize(int width, int height) { lineargradient lg = new lineargradient(left, top, right, bottom, colors, positions, shader.tilemode.repeat); return lg; } }; paintdrawable gradient = new paintdrawable(); gradient.setshape(new rectshape()); gradient.setshaderfactory(shaderfactory); return gradient; } and here way set widget background drawable drawable folde

javascript - Lose events with ng-include -

i'm new in html/css/js , have following problem: want create list of component. i've created componenta (works perfecly) , now, in componentb want add ng-include specific number of componentsa seems loose ng-click event. can me ? later edit: this piece of componenta: html: <div id="container" class="container"> <p id="details" class="details" ng-show="!pressed" ng-click="expand();">details</p> </div> js: 'use strict'; angular.module('app', []) .directive('componenta', [function () { return { templateurl: 'componenta.html', restrict: 'a', scope: true, controller: function ($scope) { $scope.pressed = false; $scope.expand = function() { if ($scope.pressed === true) { $scope.pressed = false; d