Posts

Showing posts from August, 2010

Erlang - Is it possible to limit the ram consumption when using disc copies in Mnesia? -

i have 4gb ram in system , used 2gb of ram before insertion completed wen using disc_copies. wondering happen if 100 percent of ram consumed? there option limit ram consumed during disc_copies, limiting ram usage 2gb? if looking how limit erlang vm memory usage should use control groups it. if monitor memory usage should use memory monitor memsup os_mon application . $ erl -boot start_sasl erlang/otp 18 [erts-7.0] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false] ... =progress report==== 22-oct-2015::22:39:46 === application: sasl started_at: nonode@nohost eshell v7.0 (abort ^g) 1> application:start(os_mon). ... =progress report==== 22-oct-2015::22:40:03 === application: os_mon started_at: nonode@nohost ok 2> ... 2> memsup:get_memory_data(). {8162500608,6514708480,{<0.7.0>,426616}} 3> memsup:get_system_memory_data(). [{system_total_memory,8162500608}, {free_swap,5996748800}, {

javascript - AngularJS: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode -

so had directive: app.directive('customdropdown', function() { return { restrict: 'e', templateurl: '/static/templates/directive_templates/customdropdown.html', link: function(scope, element, attrs) { console.log(attrs.custom-class); } } }) markup: <custom-dropdown custom-class="custom-select-menu"> </custom-dropdown> but, due console.log(attrs.custom-class) error mentioned in question. goes away when change custom-class custom . idea why error popping up? can't use hyphens? attrs.custom-class custom-class not valid identifier in javascript. have 2 choices : rename custom-class else without hypen. use bracket syntax : attrs['custom-class']

html - Click function on element returned from the jquery load func -

i need know how call click jquery function on element returned load func (again jquery). cant elements class name , thinking not existing in dom when try them. here main page: <div id="content"> <div id="main"></div> <div style="clear: both;"></div> </div> i loading additional html content inside #main load() jquery function , works fine. inside #main content this: <div id="home_container"> <div id="left_column" class="home_columns"> <img src="images/code.jpg" alt="code" class="pics home_pics" /> <p class="home_text">code snippets</p> </div> <div id="center_column" class="home_columns"> <img src="images/me_home.jpg" alt="me" class="pics home_pics" /> <p class="home_text">

solr - java.io.IOException: Running in secure mode, but config doesn't have a keytab -

i config lily using cdh5 commandline. follow document @ search_config_hbase_indexer_for_search . my config file : cat /etc/default/solr solr_port=8983 solr_admin_port=8984 solr_log=/var/log/solr solr_zk_ensemble=host-172-17-110-81:2181/solr solr_hdfs_home=hdfs://hadoop-jkzl:8020/solr solr_hdfs_config=/etc/hadoop/conf solr_kerberos_enabled=true solr_kerberos_keytab=/etc/solr/conf/solr.keytab solr_kerberos_principal=solr/host-172-17-110-81@jkzl #solr_authentication_type=simple solr_authentication_type=kerberos solr_authentication_simple_allow_anon=true solr_authentication_kerberos_keytab=/etc/solr/conf/solr.keytab solr_authentication_kerberos_principal=http/host-172-17-110-81@jkzl solr_authentication_kerberos_name_rules=default solr_authentication_jaas_conf=/etc/solr/conf/jaas.conf cat /etc/solr/conf/jaas.conf client { com.sun.security.auth.module.krb5loginmodule required usekeytab=true useticketcache=false keytab="/etc/solr/conf/solr.keytab" principal="

c# - find numbers that can be formed from sum of numbers from array in ascending order -

i trying find possible values result of sum of values of given array. example if given array a = [50,100,120,260,360] result [0,50,100,120,150,170,200,220,240,250,260,....] . how implement ? i found 1 article realted find value can't formed using given array. find smallest number can't formed values of given array i found 1 more discussion related mathematics , still unable understand how implement it. can have @ find possible values can formed using values any algorithm or code in c# help. edit we can use single value many times. more results 270 (50*1 + 100*1 + 120) , 300 (100*3), 310 (50 * 1 + 260 *1) etc. this use: func<ienumerable<int>, ienumerable<ienumerable<int>>> getallsubsets = null; getallsubsets = xs => (xs == null || !xs.any()) ? enumerable.empty<ienumerable<int>>() : xs.skip(1).any() ? getallsubsets(xs.skip(1)) .selectmany(ys => new[] { ys, xs.t

Docker ubuntu image - bash: man: command not found -

am getting started docker , pulled basic ubuntu image. on windows 7 box running docker via docker-machine. do not know why, not able find man command on bash. tried exporting path of man $path still no joy. docker@default:~$ docker run -it ubuntu bash root@2dd12b770666:/# man ls bash: man: command not found root@2dd12b770666:/# whereis man man: /usr/local/man /usr/share/man root@2dd12b770666:/# export path=/usr/local/man:/usr/share/man:$path root@2dd12b770666:/# echo $path /usr/local/man:/usr/share/man:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin root@2dd12b770666:/# man bash: man: command not found root@2dd12b770666:/# if export command not work, not sure if editing bashrc have effect. did not try yet. there else need able run man on docker image? you have install man command in container: sudo apt-get install man

I want to take a photo when app in the background? ios -

i want take photo once every 2 minutes essential app in background. legitimate reasons. possible? no, not. way can take photo through uiimagepickercontroller(or custom through avfoundationframework) requires user action.

Azure Management API - 429 Too many requests -

i built web app queries azure rest api , creates resources (webapp, 2 mysql databases, adds hostname, add ssl cert...) all queries go to: https://management.azure.com/subscriptions/ {subscriptionid}/resourcegroups/{resourcegroup}/.... after few queries, "429 - many requests". which limit management api have? account not in free trial. seems can make around 10... thank you found way here via google after running same problem. there limits, aren't low default. the following page describes azure subscription limits: https://azure.microsoft.com/en-us/documentation/articles/azure-subscription-service-limits the relevant limits (in case page taken down): resource default limit maximum limit resource manager api reads 15000 per hour 15000 per hour resource manager api writes 1200 per hour 1200 per hour resource manager api request size 4194304 bytes 4194304 bytes if error 10 requests, might want

python - Pythonic way to iterate through a range starting at 1 -

currently if want iterate 1 through n use following method: for _ in range(1, n+1): print(_) is there cleaner way accomplish without having reference n + 1 ? it seems odd if want iterate range ordinally starting @ 1, not uncommon, have specify increase 1 twice: with 1 @ start of range. with + 1 @ end of range. range(1, n+1) not considered duplication, can see might become hassle if going change 1 number. this removes duplication using generator: for _ in (number+1 number in range(5)): print(_)

Magento remove items from cart at loggin out -

i want clear or remove items cart after logout user. found don't know have put exactly foreach( mage::getsingleton('checkout/session')->getquote()->getitemscollection() $item ){ mage::getsingleton('checkout/cart')->removeitem( $item->getid() )->save(); } you need create observer "customer_logout" event. answer here describe how create observer you need use "customer_logout" instead of "catalog_product_save_before".

sed - linux extract string between tags and paste between others tags -

i have files xml text like: <tag1>unknown string1</tag1>blablabla....<tag2></tag2> i want use sed (or command) extract string between tag's 1 , paste between tag's 2, result: <tag1>unknown string1</tag1>blablabla....<tag2>unknown string1</tag2> thanks. i found solution!. sed 's/\(.*<tag1>\)\(.*\)\(<\/tag1>.*<tag2>\)\(**\)\(<\/tag2>.*\)/\1\2\3\2\5/' file divide entire file in references, , after reorder in convenience. try sed command command : sed 'n;s/\(<tag1>\(.*\)<\/tag1>\n<tag2>\).*\(<\/tag2>\)/\1\2\3/' filename output: <tag1>unknown string1</tag1> <tag2>unknown string1</tag2>

java - Deny log in with already authenticated session -

how can deny second log in (with same or different user) authenticated http session? for form-login found following work-arounds: redirect in controller redirect in view restrict login page but these work-arounds not perfect, because can still access login-processing-url , execute second log in. problem authentication mechanisms without login page, http basic authentication , kerberos . my java configuration: @configuration @enablewebsecurity public static class mywebsecurityconfigurationadapter extends websecurityconfigureradapter { protected void configure(httpsecurity http) throws exception { http .authorizerequests() .antmatchers("/**").hasauthority("role_user") .and() .formlogin() .loginprocessingurl("/login").permitall() .loginpage("/index.jsp").permitall() .defaultsuccessurl("start.jsp")

javascript - ui-bootstrap modal html created and loaded, but isn't shown -

Image
i'm trying display simple modal using ui-bootstrap. as can see in photo, html modal loaded not displayed. i saw similar questions on forum: angularjs bootstrap.ui modal not showing ui.bootstrap modal loading html not showing anything i did suggested there, still none improvement. i updated libraries , now, i'm using: angular: 1.4.9 angular-animate: 1.4.9 ui-bootstrap: 1.1.1 bootstrap.css: 3.6.6 but didn't helped me. also modified bootstrap.css proposed in post: modal { display: none; display: block; } but didn't helped me! i solved problem, changing modal jade from div.modal.fade div.modal-dialog div.modal-content div.modal-header button.close(type = 'button', data-dismiss = 'modal', aria-hidden = 'true') &times; h4.modal-title test div.modal-body h4 test div.modal-footer h1 test to div.modal-content div.modal-header button.clo

android - Using Gradle Spoon Plugin to launch tests in specific location -

i having problem find documentation how solve case. i capable of launching small/medium/large tests with: ./gradlew spoonsmall ./gradlew spoonmedium ./gradlew spoonlarge or launching specific tests usage of setup: spoon { (...) if (project.hasproperty('spoonclassname')) { classname = project.spoonclassname if (project.hasproperty('spoonmethodname')) { methodname = project.spoonmethodname } } } i can launch specific file: ./gradlew spoon -pspoonclassname=com.package.tests.mytest; what interested in possibility launch tests located in: ./gradlew spoon -pspoonclassname=com.package.tests package. either method fine. parameter bash console or maybe way create own annotation , launch ./gradlew spoonmytests. i grateful suggestions/help. from official docs: there numerous ways run specific test, or set of tests. can use spoon --size, --class-name or --method-name options, or can use --e

number rounding - I'm not sure how to round this properly in my Java code -

i'm new java, , i've written code calculates how change need x amount of money payed y priced item. works well; issue whenever there not change owed in hundredths place (ex: $4.60), round down tenths place ($4.6). if knows how fix this, grateful. have code posted below. class main { public static void main(string[] args) throws ioexception { scanner scan = new scanner(system.in); double x; double y; double z; system.out.print("enter price of product: $"); x = scan.nextdouble(); system.out.print("enter payed with: $"); y = scan.nextdouble(); z = (int)math.round(100*(y-x)); system.out.print("change owed: $"); system.out.println((z)/100); int q = (int)(z/25); int d = (int)((z%25/10)); int n = (int)((z%25%10/5)); int p = (int)(z%25%10%5); system.out.println("quarters: " + q); system.out.println("dimes: " + d);

json - Obfuscation for Asp MVC using SmartAssembly or CryptoObfuscator -

i have question in using cryptoobfuscator or redgate smartassembly obfuscate asp mvc assemblies : it seems when use 1 of these tools obfuscate assemblies, rename properties of classes, right? so think because of operation lose access of values in json format comes server during serialization ( mean because of renaming properties cant parse json object in js correctly) if true, how can prevent loosing parsejson operation in js? let me include more details : consider class structure public class myclass { public string fname{get;set;} . . . } //samplecontroller : public jsonresult getjson() { return json(new myclass{fname = "alex"}); } now in clientside : $.ajax({ url: "/sample/getjson", context: document.body }).success(function(data) { //this problem : can access fname or not? var fname = jquery.parsejson(data).fname; }); basically obfuscators do not change return value's property's names . if obfuscator so... c

android - java.lang.IllegalStateException: No tab known for tag null for FragmentTabHost -

i getting error while rendering xml file. has fragmenttabhost, tabwidget vertical scrollview , framelayout displaying tab's content. , ya using vertical tabs on horizontal. below layout file <?xml version="1.0" encoding="utf-8"?> <linearlayout 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:background="@color/background2" android:orientation="vertical"> <include android:id="@+id/toolbar" layout="@layout/toolbar" /> <android.support.v4.app.fragmenttabhost android:id="@android:id/tabhost" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"> <linear

Handling images in a proxy server written in C -

to receive requested web server , transmit client, doing following, while(1) { bzero(buffer,65536); //character buffer of 64kb ret_val = recv(sockfd, buffer, 65535,0); //sockfd socket between web server , proxy server if(ret_val < 0) error("error reading data requested server"); send_ret_val = send_all(sock, buffer, strlen(buffer), 0);//sockfd socket between proxy server , client if(send_ret_val < 0) error("error returning data client"); if(ret_val == 0) break; } the function send() transmits data there in buffer , returns 0 else returns negative value error. the problem server seems working fine text data cannot handle images , other binary data. when using firefox, error, incompatible compression technique. is there problem in code or there problem somewhere else? strlen(buffer) truncates when found null character in buffer. image data binary data. bina

Android NDK, error: undefined reference to function of .h file -

this android.mk file when compile error error while creating my android.mk file local_path := $(call my-dir) include $(clear_vars) local_module := libndk local_cflags := -dandroid_ndk \ -ddisable_importgl local_src_files := serialport.c local_cflags := -std=c99 local_ldlibs := -lglesv1_cm -ldl -llog include $(build_shared_library)

xamarin - Update data in Kinvey Database -

Image
i want update data in kinvey database. used rest api (put method). not working . same authorization token in , post method working fine. here error : { "error": "insufficientcredentials", "description": "the credentials used authenticate request not authorized run operation. please retry request appropriate credentials", "debug": "" } please correct me. i found solution after wasting 2 days. kinvey applys permission on collection level. have change permission. here reference link. http://devcenter.kinvey.com/rest/guides/security#collectionpermissions please see snap, can better understand.

java - Calender.getTime() not showing the date time of given timeZone -

i in timezone +05:30 hrs , want time zone of europe, trying this:- timezone tmz=timezone.gettimezone("europe/zurich"); calendar calender=new gregoriancalendar(tmz); date date=calender.gettime(); string datestr=new simpledateformat("yyyy-mm-dd hh:mm:ss").format(date); system.out.println(datestr+" cst"); but getting timezone's time instead you need set time zone in simpledateformat . date value doesn't have time zone, initial code pointless - call new date() . note format string incorrect - you're using minutes instead of months, , you're using 12-hour clock isn't want. i suspect code should be: timezone tmz = timezone.gettimezone("europe/zurich"); simpledateformat format = new simpledateformat("yyyy-mm-dd hh:mm:ss", locale.us); format.settimezone(tmz); string datestr = format.format(new date()); as aside, if possibly can, avoid using these classes - use joda time if you&

c# - Trying to get a working web.config section for this programmatic AD FS configuration -

i have following programmatic code know works when try validate ad fs tokens: var configuration = new securitytokenhandlerconfiguration(); configuration.audiencerestriction.audiencemode = audienceurimode.always; configuration.audiencerestriction.allowedaudienceuris.add(new uri("https://application.local/")); configuration.certificatevalidationmode = x509certificatevalidationmode.chaintrust; configuration.revocationmode = x509revocationmode.online; configuration.certificatevalidator = x509certificatevalidator.chaintrust; var registry = new configurationbasedissuernameregistry(); registry.addtrustedissuer("<certificate thumbprint>", "adfs signing - adfs.example.local"); configuration.issuernameregistry = registry; securitytokenhandlers = securitytokenhandlercollection.createdefaultsecuritytokenhandlercollection(configuration); however, trying convert working configuration can mark in web.config . have tried this: <system.identitymodel>

ios - Objective-C: Getting PNG Thumbnail from Movie with NSData -

i have following code attempt screenshot of video file nsdata. can confirm nsdata valid , not nil, both datastring , movieurl returning nil. - (uiimage *)imagefrommovie:(nsdata *)moviedata { // set movie player nsstring *datastring = [[nsstring alloc] initwithdata:moviedata encoding:nsutf8stringencoding]; nsurl *movieurl = [nsurl urlwithstring:datastring]; // thumbnail avurlasset *asset1 = [[avurlasset alloc] initwithurl:movieurl options:nil]; avassetimagegenerator *generate1 = [[avassetimagegenerator alloc] initwithasset:asset1]; generate1.appliespreferredtracktransform = yes; nserror *err = null; cmtime time = cmtimemake(1, 2); cgimageref oneref = [generate1 copycgimageattime:time actualtime:null error:&err]; uiimage *one = [[uiimage alloc] initwithcgimage:oneref]; return(one); } edit: here's @ where/how i'm getting nsdata uiimagepicker if ([mediatype isequaltostring:@"alassettypevideo"]) { alas

html - Is there a way to render two partial views in C# MVC such that they appear side by side in a single view? -

i new c# mvc , have been utilizing partial views in solution. when render 2 or more partial views in single view, see rendered top bottom (when rendered, appear on page 1 on top of next), expect. is there way specify partial views rendered instead in side side or grid fashion? ask because there lot of white space , ideal place content of partial views in white space. example 1 you could wrap partial views in div elements , set them display: inline-block , make them appear side side. css styling: div.sidebyside { display: inline-block; vertical-align: top; } view: <div class="sidebyside">@render.partial(...)</div> <div class="sidebyside">@render.partial(...)</div> example 2 you could arrange div s table layout: css styling: div.table { display: table; } div.row { display: table-row; } div.cell { display: table-cell; } view: <div class="table"> <div class="row">

c++ - Understanding the OpenCV fitEllipse approach -

i trying figure out documented approach opencv fitellipse usage. it can found here: http://docs.opencv.org/ref/master/de/dc7/fitellipse_8cpp-example.html the problem applies threshold onto image, based on slider position, line relating slider value, original image is: mat bimage = image >= sliderpos; yet >= there makes no sense me, , using imshow on bimage/image shows them equal. can please explain happening there? i'm sorry if obvious. i'm not great c++ programmer (yet). as described in documentation binarization (0 or 255): comparison: cmpop b, cmpop alpha, alpha cmpop a, cmpop 1 of >, >=, ==, !=, <=, <. result of comparison 8-bit single channel mask elements set 255 (if particular element or pair of elements satisfy condition) or 0. try explain more technical part of functions called. following example gave first should know types of variables: image , bimage cv::mat sliderpos of type int . the function

javascript - Mapbox: How to filter markers by category? -

i creating first map using mapbox , want able filter markers category. following example on mapbox doc page: https://www.mapbox.com/mapbox.js/example/v1.0.0/multiple-marker-filters/ i have property each marker following key: cat_code. can't seem legend appear can toggle markers off , on. anyone have clues? jsfiddle l.mapbox.accesstoken = 'pk.eyj1ijoizg9zcyisimeioii1nfituws4in0.-9qpbofe3jc68wduqa1akg'; var map = l.mapbox.map('map', 'mapbox.light'); var featurelayer = { "type": "featurecollection", "features": [ { "type": "feature", "properties": { "marker-color": "#7e7e7e", "marker-size": "medium", "marker-symbol": "heliport", "cat_code": "12311" }, "geometry": { "type": "point", "coordinates": [ 46.40625, 53.5403073915

javascript - Angular Directive addEventListener with ng-repeat -

i have directive adds few event listeners element in link function. e.g.: ... link: function(scope, element) { // gives native js object var el = element[0]; el.draggable = true; el.addeventlistener('dragstart', ...); } ... now use directive inside of ng-repeat . question is, make new eventlistener each element inside of ng-repeat ? if so, have 100 items within ng-repeat, cause performance problems ? if so, changes make attach elements same event listener ? yes, add event each element in ng-repeat. directives executed 1 time per element have attached.the listener not cause major performance issues. (no more ng-repeat, not performant)

javascript - Image doesn't get hidden -

i developing pacman since lab assignment. , try hide food(image) when pacman reaches it. code used working : if((parseint(image1.style.left)>=(parseint(s1.style.left))) && (parseint(image1.style.left)<=(parseint(s1.style.left)+100)) && (parseint(image1.style.top)+30>=(parseint(s1.style.left) && parseint(image1.style.top)+30<=(parseint(s1.style.left)+100)))) {var e= document.getelementbyid('s1'); e.style.visibility='hidden'; } <img id="s1" src="s.gif" style="position: fixed; top:50; left:100" /> now problem i'm using exact same code food not working. here : <img id="s5" src="s.gif" style="position: fixed; top:150; right:700" /> if((parseint(image1.style.left)>=(parseint(s5.style.left))) && (parseint(image1.style.left)<=(parseint(s5.style.left)+100)) && (parseint(image1.style.top)+30>=(parseint

How to make a sprite move with keyboard in java(libgdx) -

i'm making game school motives, have made sprite , background(tiled map) problem how can make sprite move left, right, , down using keyboard, please guys me possible here code: public class level1 implements applicationlistener, screen { private music music; private spritebatch batch; private texture sprite; private vector2 position; private tiledmap map; private orthogonaltiledmaprenderer renderer; private orthographiccamera camera; @override public void render(float delta) { gdx.gl.glclearcolor(1, 0, 0, 0); gdx.gl.glclear(gl20.gl_color_buffer_bit); position.y = position.y - 5; // player controls if(position.y < 0){ position.y = 0; } //.................................................. // renderer camera , map camera.update(); renderer.setview(camera); renderer.render(); //................................................... //tells computer when start drawing textures batch.begin(); batch.draw(spr

sorting - Quicksort in Java - space is bigger than number -

i wrote code read data data.txt , quicksort them , write data2.txt input format is: 145 567 12 3456 1345 67 i need output in format: 12 3456 145 567 1345 67 but get: 12 3456 1345 67 145 567 here code: private static arraylist<string> sort(arraylist<string> ar, int lo, int hi){ if (lo < hi){ int splitpoint = partition(ar, lo, hi); sort(ar, lo, splitpoint); sort(ar, splitpoint +1, hi); } return ar; } private static int partition(arraylist<string> ar, int lo, int hi){ string pivot = ar.get(lo); lo--; hi++; while (true){ lo++; while (lo<hi && ar.get(lo).compareto(pivot) < 0){ lo++; } hi--; while (hi>lo && ar.get(hi).compareto(pivot) >= 0){ hi--; } if (lo<hi){ swap(ar, lo, hi); }else { return hi; } } } private static arraylist<string> swap(arraylist<string> ar, int a, int

Does Android Studio not offer hot deployment of apps? -

Image
whenever make smallest change code, have stop avd , restart see change. normal? android studio not offer hot deployment of apps? it in android studio 2.0, check out instant run feature.

lua - LUA_INIT environment variable not working -

i'm quite new lua language , i'm trying different things. manual said before interpreter start, looks environment variable lua_init , if has form of @filename , interpreter run file filename first. i'm using ubuntu, after tried define lua_init variable @/home/tontyoutoure/lua/lua_init.lua , in write simple function, returns factorial of natural number: function fact(n) if n == 0 return 1 else return n*fact(n-1) end end i checked variable, , seems alright: $ echo $lua_init @/home/tontyoutoure/lua/lua_init.lua i suppose interpreter should load function fact first, when start interpreter , make simple test: $ lua > = fact(5) stdin:1: attempt call global 'fact' (a nil value) stack traceback: stdin:1: in main chunk [c]: in ? it seems me interpreter did not load file. part did wrong?

Wordpress - List all pages that have children but show children than for the current page -

the tree of pages : - teeshirts * long * big * short - sweat * hot * cold - pants - skirts on active page (for example teeshirts) , want display parent pages , children of current page : - teeshirts (active page) * long * big * short - sweat - pants - skirts the children pages of sweat not display. can me ? thank youuuu try this <?php if($post->post_parent) $children = wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0"); else $children = wp_list_pages("title_li=&child_of=".$post->id."&echo=0"); if ($children) { $parent_title = get_the_title($post->post_parent);?> <li><a href="<?php echo get_permalink($post->post_parent) ?>"><?php echo $parent_title;?></a></li> <?php echo $children; ?> <?php } ?> read also, https://codex.wordpress.org/function_reference/wp_list_pa

statistics - t test in python on a frequency table -

if have 2 lists of numbers x , y , can run t-test on them using scipy.stats.ttest_ind(x,y) . far good. if instead of x , y , have frequency counts; there pythonic way run efficient t test or have "manually" calculate original vectors? edit (frequency count): if x = [1,0,3,0,1,3,2] corresponding frequency count is: +---+---+ | 0 | 2 | | 1 | 2 | | 2 | 1 | | 3 | 2 | +---+---+ where first column value , second corresponding count/frequency. you can use rv_discrete scipy.stats generate data according distribution marked frequencies. using example of frequency counts provide in edit, generate random variable this, import scipy.stats stats x = [0, 1, 2, 3] freq = [2, 2, 1, 2] total = sum(freq) p = [i/total in freq] custm = stats.rv_discrete(name='custm', values=(x, p)) where take account vector of probabilities p has sum 1. and can generate data distribution easily, in [7]: custm.rvs(size=7) out[7]: array([2, 0, 3, 1, 3, 2, 0]) hope hel

How to add padding between each item of a row in Android? -

i having table each row containing 3 buttons. now, want add padding between each buttons in single row.. how can that..? when add statement in code, tablerow.setpadding(20,20,20,20); i able observe padding between each row. want have padding between each button... note: want java programmatically, not xml.. you can in way: <button android:id="@+id/mybtn" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginleft="5dp" android:layout_marginright="5dp" android:text="click me" />

optimization - MySQL different explain plan for the same query -

i've got following query performs locally (0.4 execution time acceptable): select categories.*, parameters_values.key, l.* categories join parameters_values on parameters_values.parameter_id = 2 , parameters_values.country_id = 223 join categories_countries on categories.category_id = categories_countries.category_id , categories_countries.country_id = 223 join listings l on l.listing_id = ( select listings.listing_id listings join listings_categories on listings.listing_id = listings_categories.listing_id join categories c on listings_categories.category_id = c.category_id (c.category_id = categories.category_id or c.subcategory = categories.category_id) , case parameters_values.`key` when 1 listings.transaction_type = 1 or listings.transaction_type = 3 when 2 listings.transaction_type = 2 or listings.transaction_type = 3 when 3 true end , listings.country_id = 223 , listings.property_type = 1 , listings.active

c# - How to use regular expression with a string array -

i have string array string [] ar = { "net" , "com" , "org"}; and want label writes "true" when user enter website example ends string in array i tried this: private void timer1_tick(object sender, eventargs e) { foreach ( string ex in ar) { if (regex.ismatch(txtbox.text, @"^(www\.)([\w]+)\.(" + ex + ")$")) { lbl.text = "true"; } else { lbl.text = "false"; } } } when write example "www.google.com", label still writes false . when write "www.google.org" label writes true . you using foreach loop completing ittrations, when ittration compare condition remove control loop e.g. org @ last of array index thatswhy found @ last of lopp ittrations, edit code as. foreach ( string ex in ar) { if (regex.ismatch(txtbo

android - Refresh ListView pressing option DialogFragment -

i have listview clicking on element shows dialogfragmen several options, options take user shown in item of listview textview , following error in execution: activity app.gepv.inventario has leaked intentreceiver com.immersion.android.haptics.hapticfeedbackmanager$hapticfeedbackbroadcastreceiver@426e94b8 registered here. missing call unregisterreceiver()? enter code think important, if need else edit question :) this mi dialogfragment: final string[] items= equidisp.toarray(new string[equidisp.size()]); alertdialog.builder builder = new alertdialog.builder(getactivity()); builder.settitle("asigne equipo/equipos:") .setonkeylistener(new dialog.onkeylistener(){ public boolean onkey(dialoginterface arg0, int keycode,keyevent event) { // todo auto-generated method stub if (keycode == keyevent.keycode_back)

postgresql - Postgres array fields: find where array contains value -

currently have table schema looks this: | id | visitor_ids | name | |----|-------------|----------------| | 1 | {abc,def} | chris houghton | | 2 | {ghi} | matt quinn | the visitor_ids guids, i've shortened them simplicity. a user can have multiple visitor ids, hence array type. i have gin index created on visitor_ids field. i want able lookup users visitor id. we're doing this: select * users visitor_ids && array['abc']; the above works, it's really slow @ scale - takes around 45ms ~700x slower lookup primary key. (even gin index) surely there's got more efficient way of doing this? i've looked around , wasn't able find anything. possible solutions can think of be: the current query bad , needs improving using separate user_visitor_ids table something smart special indexes help appreciated :) i tried second solution - 700x faster. bingo. i feel unsolved problem however, what'

shell - Parser generating segfaults in C -

i've been trying work past 2 weeks no avail. have project create shell implements parsing , built-in commands. issue i'm having when pass char* parse function , returns, when try access part of it, segfault. i've tried different methods including struct holding char** same problems, i'm guessing it's issue parser. appreciate help. code parser.c: #define bufsize 1024 #define tok_bufsize 64 #define tok_delim " \t\r\n\a" char*** parse(char *line0){ char* null_ptr = 0; char*** cmd = malloc(max_size * sizeof(char**)); /* char arg[] = argument char* argv[] = argument array char** cmd[] = array of argument arrays */ int bufsize = max_size, cmdp = 0, argp = 0, com = false, redir = false; char *token; char* line = malloc(100*sizeof(char)); strcpy(line,line0); token = strtok(line, tok_delim); while (token){ if (*token == ';'){ // new command string char* tmp1 = malloc(bufsize * sizeof(char)); char** tmpa = malloc(bufsize * sizeof(

how to execute rake tasks using whenever gem, in amazon aws server in ruby on rails? -

iam using whenever gem execute rake task, in rails application. in development environment working fine following code. set :environment, "development" set :output, {:error => "log/cron_error_log.log", :standard => "log/cron_log.log"} every :day, :at => '12:10pm' runner "employee.assign_shift_policies" end and in terminal create crontab , run cron tab file using whenever gem iam running following commands. whenever whenever -w and tasks executing correctly. , output of these rake tasks appending following log files properly. log/cron_error_log.log log/cron_log.log in development everthing working fine. how run these background jobs in amazon aws beanstalk server, means how execute these whenever , whenever -w commands in amazon aws server generate crontab , execute jobs in aws server using elastic beanstalk? now, using whenever-elasticbeanstalk gem. getting following error in eb-activity.log file

Kafka distributing messages from a partition among consumers -

i have kafka topic has 3 partitions. want consumers read same partition each message should go different consumer in round-robin fashion. possible achieve this? in order that, have implement consumer group. it's provided out of box kafka. have specify same group.id tree consumer. [edit] but, each consumers read in different kafka partition. think make difference consumer mthe same group read in same partition not possible if you're using kafka api. see more in documentation : http://kafka.apache.org/documentation.html#intro_consumers

jquery - Get all kendo dropdown inside a div -

i struggling kendo dropdowns inside div. if use $(".k-list-container").each(function () { var elementid = this.id.split("-")[0]; var cb = $("#" + elementid).data("kendodropdownlist"); if(cb){ // operation on dropdown } } it gets kendo drop down of page, want div. i tried $("#mydiv .k-list-container").each(function () { and several other selectors did not work out. have tried using .find on div want search? $("#mydiv").find(".k-list-container{

jquery - Masonry multiple image width -

i implemented masonry script cannot fit layout base on mockup. layout has different width images. tried many ways , still trying. tried custom width different size image, example .hotspot { width:47.38%} .secpos { width:27.69%} .thepos { width:24.7%} do guys have idea how can fix problem? my exmple http://codepen.io/anon/pen/ngybgb there width width: 33.333%; $(document).ready( function() { // init masonry var $grid = $('.grid').masonry({ itemselector: '.grid-item', columnwidth: '.grid-sizer' }); // layout isotope after each image loads $grid.imagesloaded().progress( function() { $grid.masonry(); }); }); check mockup https://dribbble.com/shots/2307670-magazine-website-layout/attachments/437382 the setup fine, need define different grid sizes, in design, see @ least 3 different widths: 33.3333%, 30%, , 40% (the big one). detail .grid-sizer width should min width going use. hacking pen little bit, idea: http:/

Run arbitrary ruby code in a chef cookbook -

i have simple chef cookbook , sets motd on centos machine. takes content of /tmp/mymotd.txt , turns motd. i have simple ruby script (a full-fledged ruby script) reads text web-server , puts in /tmp/mymotd.txt. my questions are: how run ruby script within cookbook? how pass parameters script (e.g. address of web-server) thanks lot beforehand. ad 1. you can use libraries directory in scripts place there ruby script , declare in module. example: # includes module module_name # here code using script # example function def example_function (text) # code end end you can use include module_name in recipe import functions , use like example_function(something) what's - can use there chef functions , resources. important info: remember chef has 2 compilation phases. first of ruby code, second of chef resources. means, have remember priority of code. won't write here more info it, since haven't asked this, if want,

jquery - Inline editing with Laravel 5 and Bootstrap Editable: 405 Method Not Allowed -

i have comment form , list on each post in app, imported bootstrap editable able give users access edit comments inline without page reload. but keep getting error methodnotallowedhttpexception in routecollection.php line 219: post http://localhost/r2/public/posts/comment/update 405 (method not allowed) i'm assuming it's comment routes can't figure out what. edit: after adding type: 'post' ajaxoptions started getting different error creating default object empty value it seems input::get('commenter_comment') not returning anything. guess wrong anyway not x-editable field appearing. how can grab x-editable field? routes route::get('{post}/comment', ['as' => 'comment', 'uses' => 'commentcontroller@index']); route::post('{post}/post_this_comment', 'commentcontroller@post_this_comment'); route::get('{post}/recaptcha', 'commentcontroller@recaptcha