Posts

Showing posts from August, 2015

r - How to separate my output by comma? -

km<-kmeans(iris,3) scorekm<- function(km, x,...) { args<-list(x,...) result=null for(i in seq(from=1,to=nargs()-1,by=4)) { data<-matrix(c(args[[i]],args[[i+1]],args[[i+2]],args[[i+3]]),nrow=1) k <- nrow(km$centers) d <- as.matrix(dist(rbind(km$centers, data)))[-(1:k),1:k] d <- matrix(d,nrow=1) category<- apply(d,1,which.min) result<-cbind(category,result) } return(result) } now, output this: > scorekm(km,5.9,3.0,5.1,1.8,5.1,3.8,1.6,0.2) category category category >[1,] 1 2 how can change this: >[1,] 1,2 output separated comma. as roland asked, why relevant, don't know how wish use output. should return "result" character string comma. change line result<-cbind(category, result) result<-paste(category, ",", result, sep="") . hope helps. greetins, ben

New connection to send email in C# / .NET -

i facing problem in sending email. webhost/emailhost instructed me can not send more 10 emails in 1 connection. sending 30-40 emails using following code: smtpclient emailserver = new smtpclient("server"); emailserver.credentials = new system.net.networkcredential("username", "password"); (int icount = 0; icount < listemail.count; icount++) { mailmessage email = new mailmessage(); email.from = new mailaddress("from"); email.subject = "subject"; email.to.add(listemail[icount]); emailserver.send(email); } but if put code smtpclient emailserver = new smtpclient("server"); emailserver.credentials = new system.net.networkcredential("username", "password"); in for loop like: for (int icount = 0; icount < listemail.count; icount++) { smtpclient emailserver = new smtpclient("server"); emailserver.credentials = new system.net.networkcredential("username&

java - Most effective way to read from a TCP socket -

i have tcp connection server, implemented socket , streams. during session, server can send number of messages - must read , process them all. i created thread, checks , reads data in infinite cycle: in = socket.getinputstream(); bytearrayoutputstream baos = null; byte[] buf = new byte[4096]; while(!isinterrupted()) { baos = new bytearrayoutputstream(); for(int s; ( s = in.read(buf)) != -1; ) { baos.write(buf, 0, s); if(in.available() <= 0 ) { readchunk(baos.tobytearray()); } } } but actually, it's not efficient - puts cpu under heavy load, , somehow bytes stick previous answer. what effective , elegant way resolve situation? tcp not message-oriented, it's stream-oriented. means if send 2 messages aa , bb, it's quite possible read on different occasions values aabb, a b b, abb, aab b, aa bb (where spaces indicate different read attempts). you need handle either message size or message delimiters on own, no l

c# - Reset combobox selected item on set using MVVM -

i using combobox in wpf application , following mvvm. there list of strings want show in combobox. xaml: <combobox itemssource="{binding itemscollection}" selecteditem="{binding selecteditem}" /> view model: public collection<string> itemscollection; // suppose has 10 values. private string _selecteditem; public string selecteditem { { return _selecteditem; } set { _selecteditem = value; trigger notify of property changed. } } now code working absolutely fine. able select view , can changes in viewmodel , if change selecteditem viewmodel can see in view. now here trying achieve. when change selected item view need put check value good/bad (or anything) set selected item else not set it. view model changes this. public string selecteditem { { return _selecteditem; } set { if (somecondition(value)) _selecteditem = value; // update selected item. else

jsf 2 - EL Expression error on JBoss EAP 6.1 -

i've following el expression throwing error , i'm trying figure out workaround this. expression #{usr.resetpwd eq 's'} usr.resetpwd of type java.lang.character, , in glassfish expression resolves java.lang.string, but, apparently, jboss resolves java.lang.long, , fails interpret correctly expression. the error cannot convert s of type java.lang.string java.lang.long i can make expression work changing type of resetpwd, or changing expression #{usr.resetpwd.tostring() eq 's'} , wanted avoid having verify , change applications. there configuration or better approach make applications behave same way when running on jboss or glassfish? kind regards, carlos ferreira

Android Intel x86 Emulator vs Real Device (Performance) -

i'm away home , forgot bring nexus 7 me, i've been developing on emulator. i'm using haxm intel x86 system image , it's loads faster traditional arm system image. then, experience lag when comes rendering simple animations such swiping across viewpager or flipping fragment around "cover flip" sort of effect. i've googled various articles regarding performance, of them seem compare performance between arm system image , intel system image. since won't have access nexus 7 before release new app, question this: how performance on intel system image emulator correlate real device's performance? real device faster intel emulator, or can expect see same occasional stuttering see on emulator? haxm faster emulated arm , if graphics hardware acceleration doesn't cause problems quite usable. able run nexus 10 emulator without problems until "fixed" in hardware acceleration , mac(ati) started freeze every time have launched emul

php - How to resolve ORA-01036 -

i creating online system using php , oracle oci8. anyone here have encountered error: warning: oci_bind_by_name() [function.oci-bind-by-name]: error while trying retrieve text error ora-01036 in dbcontrol.php on line 50 success here dbcontrol.php: function plsql_insert($plsql, $array){ $this -> connect(); //create database connection $this -> statement = oci_parse($this -> conn, $plsql); //prepare statement call pl/sql stored procedure foreach ($array $key => $value){ oci_bind_by_name($this -> statement, $key, $array[$key]); } $this -> execute = oci_execute($this -> statement); //execute statement $this -> result = ($this -> execute) ? "success" : "failed"; return $this->result; } here code calls function: include "../dbaseconn/dbcontrol.php"; extract($_get); $personalbackground = explode(",",$personalbackground); $arrperson

Issues while deserializing exception/throwable using Jackson in Java -

i facing issues while deserializing exception , throwable instances using jackson (version 2.2.1). consider following snippet: public static void main(string[] args) throws ioexception { objectmapper objectmapper = new objectmapper(); objectmapper.configure(serializationfeature.indent_output, true); objectmapper.setvisibility(propertyaccessor.field, visibility.any); objectmapper.enabledefaulttyping(defaulttyping.non_final, as.property); try { integer.parseint("string"); } catch (numberformatexception e) { runtimeexception runtimeexception = new runtimeexception(e); string serializedexception = objectmapper.writevalueasstring(runtimeexception); system.out.println(serializedexception); throwable throwable = objectmapper.readvalue(serializedexception, throwable.class); throwable.printstacktrace(); } } the output of system.out.println in catch block is: { "@class" : "ja

java - What is meant by lexicographical byte -

i tried searching word unable proper answer... lexicographical means sorting alphabetically or if 2 or more parameters share same name, sorted value. thanks help!!!!..... lexicographical order stands way order data (sort) - in dictionary (alphabetically). that is, in java, if want sort strings order them using a.compareto(b) < 0 . if have string[n] strings lexicographically sorted if following holds: strings[0].compareto(strings[1]) < 0 strings[1].compareto(strings[2]) < 0 ... strings[n-2].compareto(strings[n-1]) < 0 read more on wikipedia

Response ajax jquery form undefined -

i have javascript code, don't use php, , when try submit form object ("data") undefined. try lot of changes, configuration form sends response undefined ... $(this).html('<div id="contactable_inner"></div><form id="contactform" class="contactform" method="post" onsubmit="return false;">' + '<p><label for="id">' + options.id + '</label><input id="id" class="contact_id" name="id" value="" disabled="disabled"/>' + '<p><label for="name">' + options.name + '</label><input id="name" class="contact" name="name"/>' + '<p><label for="select">' + options.select + '</label><select id="select" class="select&quo

silverlight - Ampersand in XAML -

when set text property of rolestextname codebehind in silverlight5 app doing: rolestextname.text = "david &amp; goliath"; <textblock textwrapping="wrap"> <span fontweight="bold">roles:</span> <span><run x:name="rolestextname" /></span> </textblock> problem: don't & symbol, actual text. xaml used create object graph represents user interface. when modify user interface setting property values in code xaml has been processed , no longer used. should not xaml specific encoding when modifying object graph code. encoding required in xaml because based on xml , need way represents characters & , < , > unambgiously. so executing rolestextname.text = "david &amp; goliath"; will set text of run to david &amp; goliath to achieve want execute code insted: rolestextname.text = "david & goliath";

.net - Caching compressed data from WCF on IIS -

i have wcf service hosted on iis. size of responses quite big require dynamic data compression enabled on iis side (service uses wshttpbinding). at point realize need caching of compressed data too. each of requests server unique return 1 of few possible values. means can't use iis caching because each request different. on other hand can't use wcf caching because doesn't know iis compressing, have re-compress cached data on , on again. is there way work iis compressed data cache wcf/.net code? other known solutions? given payload large, assume round trip add negligible latency. therefore suggest you take full advantage of fact on http. write service behavior detects on http. once determine of large objects "returning", intercept return call, , replace httpcontext.response.redirect() . then write separate service host actual results http get deterministic url. the advantages get. you can cache using iis again (potentially faster implemen

Creating subscriptions on Azure ServiceBus with QPID JMS (AMQP 1.0) -

the servicebus client 2.1 supports amqp 1.0 . on msdn there article how use qpid.amqp.jms azure servicebus. however, although can connect predefined topic , subscription, post messages , receive of them, cannot change message selector or create new topic/subscription. my goal able connect topic , dynamically create subscriptions based on different filters using org.apache.qpid.amqp_1_0.jms. questions: 1/ how can create new topic. topic newtopic = (topic) session.createtopic("newtopic"); session.createproducer(newtopic); // returns error this maybe because jms doesn't support administration of topics though... although i'm sure i've read somewhere should create topic if doesn't exist.? 2/ how can create new subscription different message selector via jms? // still gives me messages no matter put in 'class' property. topicsubscriber subscriber = session.createdurablesubscriber(topic, "sub1", "class = 'boo'&

Django NoReverseMatch Error -

Image
i'm trying develop blog script django. when want show post links, noreversematch error. my views.py # -*- coding: utf-8 -*- # create views here. .models import yazi, yorum, kategori django.http import httpresponse, http404 django.shortcuts import render_to_response django.template import requestcontext, loader django.contrib.sites.models import site def home(request): try: posts = yazi.objects.filter(yayinlanmis=true).order_by('-yayinlanma_tarihi') except yazi.doesnotexist: raise http404 site = site.objects.get_current() c = requestcontext(request,{ 'posts':posts, 'site':site }) return render_to_response('penguencik_yazilar/yazi_list.html', c) def detail(request, slug): post = yazi.objects.get(slug=slug) site = site.objects.get_current() c= requestcontext(request,{ 'posts':post, 'site':site }) return render_to_response(

gstreamer - find_library or link_directories or find_package? What is better way? Error - Link libraries using cmake -

given file /usr/lib/gstreamer-0.10/libgstffmpeg.so present making changes in cmakelists.txt approach 1 find_library() find_library(gst_ffmpeg names gstffmpeg paths /usr/lib/gstreamer-0.10/ ) ... target_link_libraries( mylibraryormyexecutable ${gst_ffmpeg} ) when run make above configuration(approach 1), following errors /bin/ld: warning: libvpx.so.1 , needed /usr/lib/i386-linux-gnu/libavcodec.so.53, not found (try using -rpath or -rpath-link) /bin/ld: warning: libschroedinger-1.0.so.0 , needed /usr/lib/i386-linux-gnu/libavcodec.so.53, not found (try using -rpath or -rpath-link) /bin/ld: warning: libgsm.so.1 , needed /usr/lib/i386-linux-gnu/libavcodec.so.53, not found (try using -rpath or -rpath-link) looks added library depends on more libraries not linked! can see above 3 .so files in /usr/lib. 1 possible solution approach 1 add 3 more find_library() functions. right ? may not- this question explores issues found in above possible solution

InCorrect XML formats are not Rejecting while Validating XML in C# -

i validating string weathere has valid xml format? while have added incorrect xml format incorrect formats need rejected accepting string parameters="abc>" string parameters="abc" coorect format need accepted rejected string parameters=<paramnumber aaa="120901" /> is rejecting my code : public bool isvalidxml(string value) { try { // check have value if (string.isnullorempty(value) == false) { // try load value document xmldocument xmldoc = new xmldocument(); xmldoc.loadxml("<root>" + parameters+ "</root>"); // if managed no exception valid xml! return true; } else { // blank value not valid xml return false; } } catch (system.xml.xmlexception) { return false; } } please let me know how can handle these

javascript - how to pop out an iframe from document? -

i included iframe in document open in window using "window.open" without changing context in iframe. is possible open existing iframe in window without changing context? try this: var w = window.open(null,'test',[800,600]); $(w.document.body).append($('iframe').contents().find('html')); basically opening new window title 'test' , specific width , height , append content iframe in new opened window. you need have permission iframe (it needs on own domain).

import - Enum can not be resolved? Java -

i have 2 classed @ different pages. the object class: public class sensor { type type; public static enum type { prox,sonar,inf,camera,temp; } public sensor(type type) { this.type=type; } public void tellit() { switch(type) { case prox: system.out.println("the type of sensor proximity"); break; case sonar: system.out.println("the type of sensor sonar"); break; case inf: system.out.println("the type of sensor infrared"); break; case camera: system.out.println("the type of sensor camera"); break; case temp: system.out.println("the type of sensor temperature"); break; } } public static void main(string[] args) { sensor sun=new sensor(type.camera); sun.tellit(); } } main class: import sensor.type; public class main

.net - Code Analysis fails when building with FinalBuilder -

update 3 have discovered appears old version of fxcop invoked when finalbuilder calling msbuild. using command line, when running vs2010 version of fxcop works fine, when use same command vs2008 error message switch /reference unknown switch . i had visual studio 2008 solution built using finalbuilder 6. i have converted solution visual studio 2010 , upgraded finalbuilder 7. solution builds fine using static code analysis within visual studio, build fails when running in finalbuilder 7, following error: running code analysis... switch '/reference' unknown switch. msbuild : error : ca0059 : invalid settings passed codeanalysis task. see output window details. what causing this, , how can resolve issue? can't find anywhere /reference switch means, or set. since works in visual studio thinking might have how finalbuilder calls upon msbuild, i'm guessing here. any ideas appreciated. update: code analysis settings located in .ruleset file pa

ios - Adding cell from one tableView to another -

Image
in relation other question , tried few things add cell 1 tableview new one. first of have little picture shows how process should work. there carsviewcontroller containing array of cars. when tap on 1 cell new view ( cardetailviewcontroller ) shows details of each car , has got favoritebutton opens. tapping on button cell of car tableview ( carsviewcontroller ) should added new tableview ( favviewcontroller ) can see in picture. i've tried didn't work. car class: #import "car.h" @implementation car @synthesize name; @synthesize speed; @end carsviewcontroller : @implementation carsviewcontroller { nsarray *cars; } @synthesize tableview = _tableview; - (void)viewdidload { car *car1 = [car new]; car1.name = @"a1"; car1.speed = @"200 km/h"; car *car2 = [car new]; car2.name = @"a2"; car2.speed = @"220 km/h"; cars = [nsarray arraywithobjects:car1, car2, nil]; } the cardetailviewcontroll

Gradle replace resource file with WAR plugin -

i'm trying replace resource file in war plugin task gradle. basically have 2 resource files: database.properties database.properties.production what want achieve replace 'database.properties' 'database.properties.production' in final war file under web-inf/classes . i tried lot of things logical me following not work: war { webinf { ('src/main/resources') { exclude 'database.properties' rename('database.properties.production', 'database.properties') 'classes' } } } but causes other resource files duplicate, including duplicate database.properties (two different files same name) , still database.properties.production in war. i need clean solution without duplicates , without database.properties.production in war. if can't make decision @ runtime (which recommended best practice dealing environment-spe

c# - Javascript error when loading a page in the winforms webbrowser control -

i have webbrowser control on windows form. call this url. http://www.oddsportal.com/soccer/argentina/primera-division-2012-2013/results/ then following javascript error: an error has occurred in script on page: url: http://r1.oddsportal.com/x/global-130724112306.js also, columns in table, next soccer matches, empty (all contain: - ) instead of decimal numbers. believe has js file in above error message. when open page in normal windows browser (ie10) works fine, no error message , information on page present. also, didn't error message month ago when used program intensively guess has changed on website i'm requesting. i had no results finding solution this. can help! thanks, jasper my code (easy reproduce, drag webbrowser on form, add documentcompleted event , copy code): private string url = "http://www.oddsportal.com/soccer/argentina/primera-division-2012-2013/results/"; public frmmain() { webbrowser.url = new uri(url); } private void d

php - ajax / json output must be an other format -

hi jquery map values on ajax. format map must var new_sample_data = {"af":"16.63","al":"11.58","dz":"158.97",...}; . i have tested var new_sample_data = {"af":16.63,...}; , works good. if take on jason. doesn't work. must change? the php testcode: $sample_data[] = array("de","$de"); echo json_encode($sample_data); the javascript code: $.ajax({ type: "post", url: '../mail/assets/includes/geodata1.php', data: {datum1: date.today().add({days: -29}).tostring('yyyy-mm-dd'), datum2: date.today().tostring('yyyy-mm-dd')}, datatype: 'json', success: function(data) { var new_sample_data = data; in firebug see response [["de","4"]] . how can change format map need? you need create associative array in php: $sample

c# - How to Get Closest Location in LINQ to Entities -

i trying closest location via linq query: var coord = new geocoordinate(loc.latitude, loc.longitude); var nearest = ctx.locations .select(x => new locationresult { location = x, coord = new geocoordinate(x.latitude.getvalueordefault(), x.longitude.getvalueordefault()) }) .orderby(x => x.coord.getdistanceto(coord)) .first(); return nearest.location.id; however, getting following error: only parameterless constructors , initializers supported in linq entities. i have tried googling still not sure how fix it. parameterless constructor? you need try instead: var coord = new geocoordinate(loc.latitude, loc.longitude); var nearest = ctx.locations .select(x => new locationresult { location = x, coord = new geocoordina

php - Advice on SQL structure and maybe JOIN? -

i made similar thread month realized didn't ask right questions. i'm gonna try again. i have database 2 tables, 1 user-table , 1 fish-table. in user-table have user_id, username, email etc etc.( user_id pk ). in fish-table have fish_id, weight, length etc etc. ( fish_id pk ). when user logged in able register fish. problem occurs. i need know user has registered fish. "$query = $this->db->prepare("insert `fish` (`fish`, `weight`, `length`, `lure`, `comment`) values (?, ?, ?, ?, ?) ");" that how query looks like. assume have make user_id column in fish-table have no idea how register user_id uploaded fish. all appreciated. thanks! you add user_id column fish table said. when user registers fish, you'd have insert user_id @ same time. suppose use sessions keep users logged in, should have session variable containing user id.

Space between html5 elements -

okay i'm trying start scratch building html5 site css, i've tried hard eliminate spaces between elements: header, nav, article, , footer they stay there. know it's basic question i've spend time on , still can't figure what's going on. any ideas how remove it? (if copy , save these files you'll see space) thank you code: <html> <head> <meta charset="utf-8" /> <title>my first website</title> <link href="style.css" rel="stylesheet" type="text/css" /> </head> <body> <div class="wraper"> <header> <h1>header</h1> </header> <nav> <ul> <li> inicio </li> <li> conceito </li> <li> fotos </li> <li>

java - String to Date conversion returning wrong value -

i trying convert string date... return value wrong. string startdate = "2013-07-24"; date date = new date(); try{ dateformat formatter = new simpledateformat("yyyy-mm-dd"); date = (date)formatter.parse(startdate); system.out.println(date); } catch(exception e){ e.printstacktrace(); } the desired output is: thu jul 25 00:00:00 cdt 2013 but actual output is: fri jan 25 00:00:00 cst 2013 how month becomes jan july? change dd dd; dateformat formatter = new simpledateformat("yyyy-mm-dd");

vb.net - How to change height of asp.net calendar control? -

i have asp.net calendar has these properties <asp:calendar id="calendar1" runat="server" height="20px" width="250px"></asp:calendar> for reason, cannot change height. have tried different values, , never changes how looks in browser. there must simple answer this, cannot find possible problems , getting overly frustrated... appreciate help! in advance. it should respect height property ideally. however, other styles on page might overriding property. could try checking computed value height of table got emitted because of calendar. in case no master page being used , if not contained in databound control, calendar1 id of table tag got emitted because of asp control. between, using chrome observing these styles. probably, quick check can lessen frustration letting know culprit.

Differences in JavaScript Static Object Creation Approaches -

i'm java developer trying learn javascript ethos. are these 2 approaches creating static object in javascript different in non-syntactical way? approach more acceptable javascript programmer's perspective? approach a: var obj = {}; obj.field1 = /* expression */; obj.field2 = /* expression */; approach b: var obj = { field1: /* expression */, field2: /* expression */ }; i believe both of objects end being created in similar manner, , difference in performance (if any) minute point shouldn't notice difference. this not universal, though. when creating arrays, more efficient use similar approach b. because (at least v8) allocating array set size more efficient because knows size of array. // here v8 can see want 4-element array containing numbers: var = [1, 2, 3, 4]; // don't this: = []; // here v8 knows nothing array for(var = 1; <= 4; i++) { a.push(i); } source: smashing magazine i suggest trying out chrome profiling tools

mongoose - How to change multiple fields from an object without doing update? (because I need to use the save method, because of pre) -

mongoose: how update multiple fields of model without using update or manually setting every field? thanks (: you can underscore : var _ = require('underscore'); _.extend(doc, new_data); doc.save(next); see api docs more info.

SQL Server 2012 Query Multiple but not all Column Counts -

i'm building query application in sql server 2012. query supposed grab sorts of statuses single table sql server. tables structured this: projecttype | team | projectstatus ---------------------------------- proj1 b rec proj1 b rec proj1 b hold proj2 b rec proj3 hold proj4 c my wanted output be: projecttype | total | team | rec| hold | | ----------------------------------------------- proj1 3 b 2 1 0 proj2 1 b 1 0 0 proj3 1 0 1 0 proj4 1 c 0 0 1 i think possible because know statuses ever be: all statuses rec, ba, dq, p, prev, pred, pcom, 90, 90rev, 90red, 90com, ss, ssred, d, c what have tried far: select projecttype, team, count(projectstatus) sites (projecttype not null , projecttype <> '') , team <> '' group

AngularJs $scope.$apply not working as expected -

i using controll: http://blueimp.github.io/jquery-file-upload/angularjs.html file uploading in angular, once file uploaded server return url , display client on success callback. plugin being used normal jquery file upload there angular directive wrapper provided i'm using. here's how define callback: $scope.options = { url: '/api/client/', type: 'put', done: function (event, data) { var scope = angular.element(this).scope(); scope.test = "doesn't work"; scope.$apply(function () { scope.test = "this doesn't work either"; }); } }; the file uploads fine, , done function called unable update view. tried changing scope, realised require $apply() function isn't working either. i have tried $scope.options = { url: '/api/client/', type: 'put', done: function (event, data) { $scope.test = "doesn't work"; $sc

c# - How to run an animated SplashScreen at the same time as a Bootstrapper on STA threads -

background: i working on wpf application uses mef framework automatically link necessary libraries , components app. people adding own components, loading takes anywhere 0-2 seconds 6-7 seconds on slower machines. this, think nice splash screen let user know application loading necessary. ideally splash screen display animated progress bar status text field describing components being loaded. problem: i designed splash screen window called right @ start of application ( onstartup ), followed loading of mef bootstrapper. problem of course, window not animate because on same thread mef bootstrapper loading. tried putting bootstrapper on separate thread complains not sta thread. on sta thread still didn't , threw errors when trying load main app window. i can't put splash screen window on separate thread because don't have access it, , has sta thread because ui component. (realized untrue, can talk thread) update i found solution kept splash screen window in sep

android - setText to TextView when using the inflater -

in android app have been using relativelayout , inflater. need set text in textview, have used inflater, cannot set text code. xml file activity_title <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:padding="10dp" android:layout_height="match_parent" android:background="#000000" > <textview android:id="@+id/text_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparentleft="true" android:layout_alignparentright="true" android:text="text" /> </relativelayout> 2 xml file <relativelayout android:id="@+id/rel_container" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_alignparentright="tr

Paypal payment method -

which method secured , best paypal payments. 1.) https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business=xxx@123.com&custom=xxxx& return=xxxxxx&cancel=xxxxxx&notify_url=xxxx 2.) <form action="https://www.paypal.com/cgi-bin/webscr" method="post"> <input type="hidden" name="cmd" value="_s-xclick"> <input type="hidden" name="hosted_button_id" value="221"> <input type="image" name="submit" border="0" src="https://www.paypal.com/en_us/i/btn/btn_buynow_lg.gif" alt="paypal - safer, easier way pay online"> <img alt="" border="0" width="1" height="1" src="https://www.paypal.com/en_us/i/scr/pixel.gif" > </form> thnx in advance 2.) post method safe method.

Regex Grouping (Retrieve subdomain) -

i'm trying write regex match url subdomain excluding "www". trying retrieve subdomain after match can't seem group correctly. first group matches whole url. allow lower case letters, numbers , "-" in subdomain. need retrieve subdomain if pattern matches ^(((?!www)[a-z0-9\\-]*))+(\\.)+?example\\.com.*$ /^(?!www)([a-z0-9\-]+)\.example\.com.*$/ group 0 have whole url, , group 1 contain subdomain

android - Actionbar fills transparent icon pixels with wrong background -

i using actionbar sherlock. have icon transparent pixels. when run app, seems "something" replacing these transparent pixels main background theme, not actionbar background. it not matter if main background specified @color or @drawable (9 patch) in latter case (which want) there additional quirk in few pixels of main background 9 patch appear @ right(!) hand edge of actionbar. go figure. i have no idea what's going on here. if remove background items main style, actionbar looks should (so seems problem). has else seen such behaviour before? taking look! i'll paste style.xml below: <?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="viewpagerindicator"> <attr name="vpisubtabpageindicatorstyle" format="reference"/> </declare-styleable> <style name="theme.standby" parent="theme.sherlock.light.darkactionbar"> <item

mysql - php unable to read characters in utf8 -

i trying simple following: <?php header("content-type: text/html;charset=utf-8"); $con=mysqli_connect("localhost","dsdsds","test1234","dsdsds"); if (mysqli_connect_errno()) { echo "failed connect mysql: " . mysqli_connect_error(); } $result = mysqli_query($con,"select * discounts"); while($row = mysqli_fetch_array($result)) { echo $row['name'] . " " . $row['rate']; echo "<br>"; } ?> when this, output shows ??????. in database table, showing arabic correctly. doing wrong? know should add code set mysqli utf8 , when do, breaks script. if (!$mysqli->set_charset("utf8")) { printf("error loading character set utf8: %s\n", $mysqli->error); } else { printf("current character set: %s\n", $mysqli->character_set_name()); } looking forward support mysqli has 2 ways call met

node.js - Serving files concurrently to multiple clients in node -

i'm building simple http server serves large file clients using streams. need serve multiple clients @ same time, , i'm wondering simplest way achieve is. my initial feeling using cluster module , forking {num cpus} processes might simplest way. var streambrake = require('streambrake'); var http = require('http'); var fs = require('fs'); var server = http.createserver(function(req, res) { var stream = fs.createreadstream('/data/somefile'); stream.pipe(new streambrake(10240)).pipe(res); }); server.listen(1234, 10); edit : clarify, issue code won't begin serve second client until has finished serving first. after thinking issue, i'm confused why believe there's issue. createreadstream asynchronous. here in example complicates code little bit in order demonstrate using createreadstream can indeed service multiple connections @ time. /*jshint node:true*/ var http = require('http'); var fs = require(&#

windows - change default search engine in major browsers (msie, chrome, firefox, safari and opera) -

goal: change default search engine, homepage , url searchbar in major browsers ff, msie (version6+), chrome, safari, opera. conditions: want create setup program through nsis installer, change settings. not looking javascript solution, or browser add solution. all helps appreciated. i have answered similar question earlier on forum, please little search before posting questions. following summary ie, ff , chrome implemented in installer. hope helps. for ie: you need edit registry hkey_current_user "software\microsoft\internet explorer\main" "start page" hkey_current_user "software\microsoft\internet explorer\main" "default_search_url" hkey_current_user "software\microsoft\internet explorer\main" "default_page_url" "http://abc.com/" hkey_current_user "software\microsoft\internet explorer\searchscopes\yoursearchenginename" "displayname" "yoursearchenginename" hkey_c

How do I convert int to std::string in C++ with MinGW? -

this question has answer here: to_string not member of std, says g++ (mingw) 10 answers it known issue std::to_string not work. std::itoa didn't work me. can convert int string? don't care performance, need work without being slow. edit: have latest mingw 32 installed, std::to_string still not work. installed here: http://sourceforge.net/projects/mingwbuilds/files/host-windows/releases/4.8.1/32-bit/threads-win32/sjlj/ have considered using stringstream? #include <sstream> std::string itos(int i){ std::stringstream ss; ss<<i; return ss.str(); }

SlickGrid filter not working after calling jquery dialog -

i calling jquery dialog tabs.( popup tabs | jquery ). when call popup slickgrid filter not working.ie., datarows.length null..before callng jquery dialog,filter works fine..let me know hve change code..here code snippet filter $(grid.getheaderrow()).delegate(":input", "change keyup", function (e) { if ($(this).data("columnid") != null) { alert($(this).data("columnid")+"---"+$.trim($(this).val())); columnfilters[$(this).data("columnid")] = $.trim($(this).val()); dataview.refresh(); }else{ alert("else in delegate");//comes here } }); function filter(item) { (var columnid in columnfilters) { if (columnid !== undefined && columnfilters[columnid] !== "") { var c = grid.getcolumns()[grid.getcolumnindex(columnid)]; if (item[c.field].tostring().tolowerca

c# - Get the module/File name, where the thread was created? -

i used below code list threads in running process. process p=process.getcurrentprocess(); var threads=p.thread; but requirement know file name or module name, thread created. please guide me achieve requirements. i punt on getting file name. can done, not worth effort. instead, set name property on thread name of class created it. you able see name value when inspected visual studio debugger. if want list of managed threads in current process via code need create own thread repository. cannot map processthread thread because there not one-to-one relationship between two. public static class threadmanager { private list<thread> threads = new list<thread>(); public static thread startnew(string name, action action) { var thread = new thread( () => { lock (threads) { threads.add(thread.currentthread); } try { action(); } { lock (th

ruby - How do I stop users from editing other user posts in Omniauth (rails) -

i have network people can write posts, , have personal feed of own posts, , network feed of everyone's. the problem is, omniauth'ed user can edit user typing in /edit or delete on url. cannot have live site! does have quick answer how can blocked? have: before_filter :authenticate_user!, :except => [:index, :show] but can't figure out without errors how lock down edit user created post. model- user.rb class user has_many :posts end model - post.rb class post belongs_to :user end let me know if want see more- help! -d if read correctly, users authenticated via omniauth, you're looking way 'authorize' them specific resources/actions based on permissions or ownership. the popular gem authorization of resources/actions users, groups, roles, , in-between cancan. can, can cancan? there railscast video helped me understand application of gem in applications. once know how write abilities in cancan, take here ability so

java - How to draw on Border of JFrame -

Image
i building ribbon frame similar 1 below don't know how draw on border/ title bar of jframe. need draw elipse on top-left corner on jframe border/ title bar, similar 1 below. there way in java, if not how go creating aero style border. this can done using the... wait it... jribbonframe . in order use however, you'll need flamingo framework. it's pretty simple use! here's working example. of course, you'll have download flamingo things working. it doesn't "real" ribbon frame, though. i'm not sure, apparently can end too. the project dead looks of (updated 3 years ago), recommend if used setundecorated(); on frame. hide title bar. then, add custom buttons replace buttons on title bar (close, minimize, maximize). you create custom jframe appearing ribbon frame advanced , rewarding option. using this, end might fit needs more accurately. hope liked answer! :)

regex - Use .htaccess to redirect files beginning with certain criteria -

i'm moving website following big redesign , lot of url structures have changed. i've managed use .htaccess sort of redirects, i've got lot of pages need redirecting begin /shop.php?, e.g.: /shop.php?search=as&x=0&y=0&sec=search&filter=price&filt_id=12&sort=asc&page=1 /shop.php?sec=cat&cat=13&filter=cat&filt_id=13 basically, need every file beginning /shop.php? redirecting /shop/ thanks in advance! enable mod_rewrite , .htaccess through httpd.conf , put code in .htaccess under document_root directory: options +followsymlinks -multiviews # turn mod_rewrite on rewriteengine on rewritebase / rewritecond %{query_string} ^.+$ rewriterule ^shop\.php$ /shop/? [l,r=301,nc]

How to Display Numbers with a specific format (Android Eclipse, Java) -

this question has answer here: how can format string number have commas , round? 10 answers double pv = 154055.054847215 how can display 1,540,055.055 ? add instance of decimalformat top of method: decimalformat 3 = new decimalformat("#,##0.000"); // display numbers separated commas every 3 digits left of decimal, , round 3 decimal places. no more, no less. // 3 zeros after decimal point above specify how many decimal places accurate to. // 0 left of decimal place above makes numbers start "0." display "0." vs "." if don't want "0.", replace 0 left of decimal point "#" then, call instance "three" , pass double value when displaying: double pv = 154055.054847215; display.settext(three.format(pv)); // displays 1,540,055.055

Android WebView - code that can display and play a podcast can't play a YouTube video -

i have code works display webview , use it: webview webview = null; @override public void oncreate(bundle savedinstancestate) { //settheme(r.style.theme_sherlock_light); super.oncreate(savedinstancestate); //setcontentview(r.layout.podcasts); webview = new webview(this); webview.getsettings().setappcacheenabled(false); webview.getsettings().setjavascriptenabled(true); webview.setinitialscale(1); webview.getsettings().setpluginstate(pluginstate.on); webview.setwebviewclient(new webviewclient() { @override public boolean shouldoverrideurlloading(webview view, string url) { view.loadurl(url); return true; } }); //websettings.setbuiltinzoomcontrols(true); websettings websettings = webview.getsettings(); websettings.setjavascriptenabled(true); websettings.setbuiltinzoomcontrols(true); //websettings.getmediaplaybackrequiresusergesture(); websettings.setallowcontentaccess(true); websettings.setenablesmoothtrans