Posts

Showing posts from January, 2011

php - what means if ($con->connect_errno)? -

i'm learning php , have file connects mysql database, i'd know condition inside brackets of following "if structure" in file, $con instance of class mysqli: if ($con->connect_errno) { echo "fail connect mysql"; } i know $con invoking connect_errno conditioning if(what?){...}? that's status flag mysqli handles. see http://php.net/manual/en/mysqli.connect-errno.php it's not function, property (or "variable" if will). it's 0 when connection correctly established. contains other values (e.g. 1043 ) connection problems (such wrong password, inavailable database server). so if ($con->connect_errno) check asserts $con instance usable. when ->connect_errno == 0 if block skipped. if ->connect_errno > 0 (any other value) error message printed out. (you'd more commonly see die() , trigger_error() or new exception() echo there.) alternatively mysqli can configured throw error/exception itsel

android activity - how to open different activities when receiving notification from parse -

i have different categories in app such news,weather,sports and technology ,i use parse receive notification ,but want notification customized in once notification regarding news received should open news activity,if notification regarding technology received should open technology activity. don't want custom push receiver,i tried lots of examples can't it.any ideas in advance first need create custom class extends parsepushbroadcastreceiver. , in class override onpushopen method: public class parsepushcustomreceiver extends parsepushbroadcastreceiver { protected static string pushtitle=""; @override protected void onpushopen(context context, intent intent) { super.onpushopen(context, intent); pushtitle=""; try { bundle extras = intent.getextras(); if (extras != null) { string jsondata = extras.getstring("com.parse.data"); jsonobject json; json = new jsonobject(

android - DatePicker and TimePicker code not working together ("protected Dialog onCreateDialog(int id)" is already defined) -

i have created app, in have datepicker , timepicker. first made datepicker , displayed when selected date textview, worked fine. wanted same time edittext instead of displaying datepicker supposed display timepicker when selected. after implemented code timepicker: error "protected dialog oncreatedialog(int id)" defined , cannot use method twice. any appreciated, thanks in advance i assume have 1 dialogfragment both date , time pickers... create conflict have implemented oncreatedialog. what create class each component have different implementation of oncreatedialog. public class datepickerdialog extends dialogfragment implements datepickerdialog.ondatesetlistener{ @override public dialog oncreatedialog(bundle savedinstancestate) { ... } public class timepickerdialog extends dialogfragment implements timepickerdialog.ontimesetlistener{ @override public dialog oncreatedialog(bu

Login Failure while send message using WhatsApp api c# -

when i'm trying send message using c# api whatsapp # , handle onloginfailed event and show me message of loginfailed here's code wa.onconnectsuccess += () => { messagebox.show("connected whatsapp..."); wa.onloginsuccess += (phonenumber, data) => { wa.sendmessage(to, mes); messagebox.show("message sent..."); }; wa.onloginfailed += (data) => { messagebox.show("login failed : {0}", data); }; wa.login(); }; wa.onconnectfailed += (ex) => { messagebox.show("connection failed..."); }; wa.connect();

html - JQuery Sortable bootstrap table -

i'm trying implement jquery sortable bootstrap 3 table. works fine, when drag row position want it's not under cursor stays pixels @ top, makes hard see dragging. i'm not sure whether has stylesheet or version of jquery. html <table class="table table-bordered table-striped" id="sortable"> <thead> <tr> <th> title </th> <th> description </th> </tr> </thead> <tbody> <tr data-item-id=3 class="item"> <td> voynich manuscript </td> <td> <a class="btn btn-default pull-right" href="/things/3">show</a> </td> </tr> <tr data-item-id=1 class="item"> <td>

Not able to get email address from picked contact in android -

i trying pick contact using intent in android. information need name, phone no , email address of contact. following have tried far. @override public void onactivityresult(int requestcode, int resultcode, intent data) { super.onactivityresult(requestcode, resultcode, data); if (resultcode == activity.result_ok) { // check request code, might usign multiple startactivityforreslut switch (requestcode) { case result_pick_contact: contactpicked(data); break; } } } private void contactpicked(intent data) { cursor cursor = null; try { // getdata() method have content uri of selected contact uri uri = data.getdata(); //query content uri cursor = getactivity().getcontentresolver().query(uri, null, null, null, null); cursor.movetofirst(); int phoneindex = cursor.getcolumnindex(contactscontract.commondatakinds.phone.number); int nameindex =

My client sees grossly defective image, not what I uploaded -

obligatory research done without result. client (in state) sees pixelated image. way can replicate view zooming in ctrl + repeatedly. in brief moment, before zoom complete, see defective image. becomes clear again. asked him use computer. far, no response him. must resolve issue. i'll appreciate help. first link shows see (and see). the second link shows sees. client sent me screen capture. http://63pounders.com/faculty-biographies.php#core http://codestruggle.com/bad-image.html that's moiré pattern formed due subsampling dotted (halftone) image without blurring first. low-power viewers implement scaling way, because blurring slow. seems viewer scales way first approximation, in order react quickly, makes scaled version well. you should able fix scaling image yourself. can use responsive images retain ability scale , support high dpi.

How to make Select2 infitine scroll pagination on server side and client side -

on documentation page there no server side explanation. im confused, want solve problem , maybe make reference server side , client side code. i'm trying make select2 (using v.4.0) infinite scroll pagination searchbox, confused params.page . how can parameter query request , return page number infinite scroll. how infinite scroll triggers? below codes can 10 results. html part of code is; <select id="search_products" name="q"></select> js part is; jquery('#search_products').select2({ ajax: { url: "search_results.php", datatype: 'json', delay: 250, data: function (params) { return { q: params.term, // search term page_limit: 10, page:params.page }; }, processresults: function (data, params) { params.page = params.page || 1; return { results: data.items, pagina

java - In javafx how can I change between features with different fxml files? -

here program looks now. https://github.com/thelearningcurve/revampnutritionapi/issues/48 eventually have icons navigate between features. problem having not sure how change fxml files show different features without loading them @ once making them visible , not visible. here frame.fxml code has our first feature in it. can see have frametopcontroller, , frameleftcontroller , framerightcontroller makes search feature. have few more features have no clue begin. of features placed in frame.fxml if possible. ` <?xml version="1.0" encoding="utf-8"?> <?import javafx.scene.text.*?> <?import javafx.geometry.*?> <?import javafx.scene.*?> <?import javafx.scene.effect.*?> <?import javafx.scene.web.*?> <?import javafx.scene.image.*?> <?import javafx.scene.control.*?> <?import java.lang.*?> <?import javafx.scene.layout.*?> <?import javafx.scene.layout.anchorpane?> <?import javafx.scene.control.textf

c++ - How to pass multi string with "<<" operator without using Macro preprocessor -

in order support logging string << operator, used macro handle it. my_log_fun("hello"<<"world") //in real case, people can pass variables and macro like #define my_log_fun(out) \ ostringstream os; \ os << out; \ play_with(os) \ while macros give limitation continues task, there way make my_log_fun in real function can receive parameter "hello"<<msg<<"world" ? "is there way make my_log_fun in real function can receive parameter << "hello"<<msg<<"world" ?" yes there is. instead of using macro, i'd recommend use class , overloaded global operator specialized this: class mylogger { public: mylogger(std::ostream& logstream) : logstream_(logstream) {} template<typename t> friend mylogger& operator<<(mylogger&, const t&); private: std::ostream& logstream_; }; template<

java - how to clear file before putting data there? -

i need save data text file. i'm using class files method write() . if such file doesn't exist - alright. problem if such file exists appends new data end of file. , need clear first. code is: public static void main(string[] args) { depolist test0 = new depolist(); test0.init(); arraylist<depo> list0 = test0.getlist(); collections.sort(list0); (depo depo : list0) { string str = string.format("sum = %1$8.2f interest = %2$7.2f\n", depo.getsum(), depo.getincome()); system.out.format(str); try { files.write(paths.get("depo.txt"), str.getbytes(), standardopenoption.create, standardopenoption.append); } catch (ioexception e) { e.printstacktrace(); } } system.out.println(); i think need add standardopenoperation . how clear file before putting data there? remove standardopenoption.create,standardoption.append appends new data existing one use f

javascript - Object doesn't support property or method 'slice' -

i'm newbie javascript/jquery world. have div several links , want collect url's . then want extract href's last 9 characters (actually wish optimize , collect digits independently length @ end of each string).i tried extract them slice() method not work. in console error object doesn't support property or method 'slice' can convert object string ? appreciated ! code following $(document).ready(function(){ var $posts= $('a.entry_title').each(function(){ $(this).attr('href'); }); var posts1 = $posts[0].slice(-9); var posts2 = $posts[1].slice(-9); var posts = ["myurl"+ posts1,"myurl"+posts2] $('#div1').load(posts[0] + " .shadow3"); $('#div2').load(posts[1] + " .shadow3"); }); </script> you see object doesn't support because $.each returns jquery object. use .map() instead because returns array on slice work var $posts= $('

android - What Java Collection to use in this case? -

i java novice , trying figure out java collection use flatten values json java collection don't know collection use. here getting json: user: tim product: beer user: tim product: bread user: tim product: milk user: tim product: soap user: michael product: soap user: michael product: coffee user: michael product: car user: wayne product: bread user: wayne product: soap as can see users have following products: tim: beer, bread, milk, soap michael: soap, coffee, car wayne: bread, soap what best collection use store these can determine products held 1 user? for example, providing key=michael, soap, coffee, car. much appreciated, depends on usecase data. seems map choice.

javascript - Blueimp multiple input elements with their own urls -

so have multiple input elements use blueimp upload files , folders, each having own link path on server. each element intended upload files respective urls, do; however, want them upload independently upon drop of file/folder. instance, if drop folder onto first input element, element solely uploads files url , no other input element triggers/uploads; however, behavior i'm getting if drop folder on one, upload folder. here's example of current form , inputs like: <form name = "self" action = "http://localhost/proj/index.html" method = "post"> <input class="fileupload" id="fileupload0" type="file" name="files[]" multiple> <input class="fileupload" id="fileupload1" type="file" name="files[]" multiple> <input class="fileupload" id="fileupload2" type="file" name="files[]" multiple> </for

Using a UniformGrid inside of a Button control in WPF -

i want content of button control contain uniform grid. however, button control doesn't seem allow child content control stretch. uniformgrid squeezed down fit own contents. allows me set width, won't auto stretch if set horizontalalignment explicitly. missing? <button margin="0,4,0,4"> <itemscontrol itemssource="{binding zones}" focusable="false"> <itemscontrol.itemspanel> <itemspaneltemplate> <uniformgrid columns="{binding zones.count}" /> </itemspaneltemplate> </itemscontrol.itemspanel> <itemscontrol.itemtemplate> <datatemplate> <wpfapplication2:controllerzonecontrol datacontext="{binding}" /> </datatemplate> </itemscontrol.itemtemplate>

Cannot set column names to numbers or symbols in postgresql / rails -

i need add columns in table tournament. columns correspond specific ranking , of boolean type. rankings name in real life : 40, 30/5, 30/4, 30/3 ect ect dont think can writte migration in rails : class addrankingstotournaments < activerecord::migration def change add_column :tournaments, :40, :boolean add_column :tournaments, :30/5, :boolean add_column :tournaments, :30/3, :boolean end end this not valid column names in rails , postgresql right ? best shot rename column names correct , still easy indentify ?

c++ - Can't access variable in template base class -

this question has answer here: accessing inherited variable templated parent class 2 answers i want access protected variable in parent class, have following code , compiles fine: class base { protected: int a; }; class child : protected base { public: int b; void foo(){ b = a; } }; int main() { child c; c.foo(); } ok, want make templated. changed code following template<typename t> class base { protected: int a; }; template <typename t> class child : protected base<t> { public: int b; void foo(){ b = a; } }; int main() { child<int> c; c.foo(); } and got error: test.cpp: in member function ‘void child<t>::foo()’: test.cpp:14:17: error: ‘a’ not declared in scope b = a; ^ is correct behavior? what's difference? i use g++ 4.9.

javascript - Accessing DOM elements inside a variable -

i have tr element have extracted variable in javascript. want further dig element extract specific content there. example there input of type=text inside td. want below. var trelem = $("#idoftrelem").get();//this gives me array of content of tr element. now want further dig above variable , extract values out of that. shall do? is there reason why you're calling .get() early? jquery makes extracting data pretty straightforward. example, find of inputs in row , log values this: $('#idoftrelem input[type=text]').each(function() { console.log(this.value); }); i wrote post doing you're describing, should helpful: http://encosia.com/use-jquery-to-extract-data-from-html-lists-and-tables/

c# - FFplay successfully moved inside my Winform, how to set it borderless? -

with code: show tcp video stream (from ffplay / ffmpeg) in c# application i grabbed ffmpeg output inside c# winform. changing args possible play video directly (without streaming)... here complete (short) code: using system; using system.collections.generic; using system.componentmodel; using system.data; using system.drawing; using system.linq; using system.text; using system.threading.tasks; using system.windows.forms; using system.diagnostics; using system.threading; using system.io; using system.reflection; using system.runtime.interopservices; using system.drawing.text; using system.text.regularexpressions; using system.configuration; using microsoft.win32; using system.windows.forms.visualstyles; namespace xffplay { public partial class form1 : form { [dllimport("user32.dll", setlasterror = true)] private static extern bool movewindow(intptr hwnd, int x, int y, int nwidth, int nheight, bool brepaint);

Fast, accurate timing for both widget AND app in Android? -

i have widget/app performs display [draw...()] operations 20 times second (e.g. animation), depending upon user-selected criteria. when running widget, "full" app invoked when widget touched. (the full app performs similar display operations has more bells , whistles widget.) want use same timing mechanism both widget , "full" app haven't figured out how manage this. widgets seem rely on alarmmanager, not provide sufficiently accurate timing purposes, though it's @ least tolerable when running widget. before turning app widget, used combination of timer , handler , seemed work ok. timerhandler = new handler(); timer = new timer(timerhandler, drawaction); any thoughts on how might accomplish goal (assuming it's possible) appreciated. i'm going agree commonsware here- widget should not updating frequently, widgets should infrequently updating summaries. once second ok if you're clock. else should every few seconds or few m

python - str has no attribute write -

i getting error: self.write = file.write attributeerror: 'str' object has no attribute 'write' what want dump m file-name user has entered in entry...and not whole code please import tkinter etc. def send(self): fl=(t1.get()) m=(t2.get()) x=open("database.dat",'rb') l=pickle.load(x) x.close() if fl in l: box.showinfo("send","message send") x=open(fl+".dat","wb") pickle.dump(x,m) x.close() else: box.showerror("error","user not exist") error is: the code posted doesn't cause error does. regardless, error telling problem is: you're referencing "write" method on string. maybe think you're referencing via open file object actually referencing on string. without seeing code can't debug further, it's highly you're reusing variable both filename , open file.

java - Why does this Observable.timer() cause a memory leak? -

leakcanary reports leak articleactivity via rxcomputationthreadpool-1 . so, identified articlecontainerfragment.starttimer() method 1 that's causing it. after removing creation of observable.timer() call, no more memory leak reported. still need use timer though, can me identify why leak occurring? unsubscribing in right places believe - not sure why getting leak in first place. public class articlecontainerfragment extends basefragment<articlecontainercomponent, articlecontainerpresenter> implements articlecontainerview { @bind(r.id.article_viewpager) viewpager viewpager; @inject articlecontainerpresenter presenter; articleadapter adapter; @icicle @nullable genericarticlecategory genericarticlecategory; @icicle articlestyle articlestyle; subscription subscription; private toolbar toolbar; @nullable private integer initialarticleposition; public articlecontainerfragment() { } public static a

Has this C code a defined behavior? -

this thought experiment, not production code nor coding style. suppose have function int find_process_pid_by_name(char* name, int* threads_in_process); that return pid of named process , store threads_in_process number of threads running in said process. a lazy programmer, interested on pid , writes code int pid = find_process_pid_by_name("a process name", &pid); does trigger undefined behavior? no — don't think undefined behaviour. there's sequence point before function called (after arguments , expression denotes called function have been evaluated), , there's before called function returns. side-effects on pid performed called function have been completed before function finishes returning. result of function assigned pid . there's no question of location assigned being changed function. see nothing invokes undefined behaviour. i assuming called function treats int * argument write-only pointer single value. if rea

apache spark - How to get size (metadata) of a message without fetch request in Kafka through SimpleConsumer? -

i using simpleconsumer , trying pull message size wise (bytes) using spark. i able earliest , latest offset using metadata request, dont know how number of bytes in kafka (0.8.0). i dont want use fetch request because want check sufficient data run spark job (not streaming) perform action. from metadata response cant size, size need download message meaningless.

sql server - return a string of comma delimited numbers from a sql query -

this question has answer here: simulating group_concat mysql function in microsoft sql server 2005? 9 answers how create sql server function “join” multiple rows subquery single delimited field? [duplicate] 13 answers how can return comma delimited string using sql server? select id, (<<somequery tableb b (b.id = a.tablebid)>>) tablea and have return results like: 1, '11, 12' 2, '22, 33' you can use stuff(), see demo here select id ,stuff((select ', ' + cast(data varchar(10)) [text()] b tablebid = a.id xml path(''), type) .value('.','nvarchar(max)'),1,2,' ') comma_output group id

javascript - how to extract tuples string into data structure? -

this question has answer here: parse tuple string? 3 answers i new here. trying change following tuple multi-dimensional array in javascript . tuple string: str: "(4,7,1),(8,9,6),(3,5,7)" . can think of doing loop. looking sufficient way this. 1 way use regex in javascript. not in regular expression. me please? in advance! you can parse yourself. here's 1 way in working snippet: function parsetuple(t) { var items = t.replace(/^\(|\)$/g, "").split("),("); items.foreach(function(val, index, array) { array[index] = val.split(",").map(number); }); return items; } var data = "(4,7,1),(8,9,6),(3,5,7)"; var result = parsetuple(data); document.write(json.stringify(result)); you use json.parse() parsing converting tuple string legal json this: function par

java - Apache-spark dataframe column names are inconsistent, why does this happen? -

doing similar sql-programming-guid on apache-spark site, columns produced java bean class don't match in case sensitivity. start first letter capitalized , others don't no consistency or pattern. there things have done different guide is: private members named "mname", rather "name" , getter/setter getname setname. datatypes use integer, string , timestamp. so, by reflection, how getting names? use get/set function names , truncate off , set parts? is there way disable case sensitivity? as why i'm not showing of code. it's work, want avoid showing shouldn't. --update------------------------- so looks name based on , set functions. changing set/getstarttime set/getstarttimee resulted in starttime becoming starttimee. still case have column itrn get/setitrn keeps it's upper case first letter column starttime doesn't. --update #2------------------------- after playing around names, looks deciding factor if spark

android - Boolean not keeping most recent value of Sharedpreference result -

my boolean variable not keeping current value of sharedprefs. in functions returns true of success: // method async. call public boolean downloadmatchesasync(string date) { brawtaapiadapter.rungetmatches(date, new callback<jsonkeys>() { @override public void success(jsonkeys jsonkeys, response response) { success = jsonkeys.issuccess(); message = jsonkeys.geterrormessage(); if (!message.isempty()) { toast.maketext(myapplication.getappcontext(), message, toast.length_short).show(); } gson gson = new gson(); string jsonobject = gson.tojson(jsonkeys); //converts java object json string' downloaded = preferences.savetopreferences(activity, applicationconstants.match_data, jsonobject); log.d(applicationconstants.tag,"in networkoperation " + downloaded); //is true @ point } @override public void failure(re

java - List of Class<? extends Foo> incompatible types -

i'm working on piece of code: list<class<? extends foo>> models = new arraylist<>(); if (bar == 0) models = getrandomblas(); // returns list<bla> else models = getrandomblubs(); // returns list<blub> with: public class bla extends foo { ... } public class blub extneds foo { ... } but i'm getting incompatible types: found: 'java.util.list<bla>', required: 'java.util.list<java.lang.class<? extends foo>' has got idea? knowledge, how ? extends should work... you're right. how ? extends works, list wants class objects. list<class<? extends foo>> can contain class objects represent subtypes of foo ( foo.class , bla.class , blub.class ). list<? extends foo> can contain objects subtypes of foo . you want second version.

javascript - innerHTML with NodeJS and Jade -

i'm trying change value of number displayed jade javascript. have paragraph id number, in javascript , try change using innerhtml, nothing happens. p#number 0 above how paragraph defined in jade. then element in javascript , attempt change value so. var number = document.getelementbyid("number"); number.innerhtml("1"); the object returned document.getelementbyid not null, .value() of object undefined. innerhtml isn't function. number.innerhtml = "1";

c++ - Passing a variadic function as argument -

consider working code: #include <iostream> #include <utility> #include <array> template <typename... args> void foo (args&&... args) { const auto v = {args...}; (auto x : v) std::cout << x << ' '; std::cout << '\n'; } template <typename> struct foo; template <std::size_t... is> struct foo<std::index_sequence<is...>> { template <typename container> static void execute (const container& v) { foo(v[is]...); } }; template <std::size_t n> void fooarray (const std::array<int, n>& a) { foo<std::make_index_sequence<n>>::execute(a); } int main() { fooarray<6>({0,1,2,3,4,5}); // 0 1 2 3 4 5 } i want generalize foo struct so: #include <iostream> #include <utility> #include <array> template <typename... args> void foo (args&&... args) { const auto v = {args...}; (auto x

c++ - ORing of statements -

where difference lies between these 2 style of writing. compiler showing correct answer in first case , wrong in second case. 1. string s[6]; for(int i=0;i<6;i++) cin>>s[i]; if(s[0]==s[2] && s[0]==s[4]) { cout<<"yes"<<endl; } else if(s[0]==s[2] && s[0]==s[5]) { cout<<"yes"<<endl; } else if((s[0]==s[3] && s[0]==s[5])) { cout<<"yes"<<endl; } else if((s[0]==s[3] && s[0]==s[4])) { cout<<"yes"<<endl; } else if((s[1]==s[2] && s[1]==s[4])) { cout<<"yes"<<endl; } else if((s[1]==s[2] && s[1]==s[5])) { cout<<"yes"<<endl; } else if((s[1]==s[3] && s[1]==s[4])) { cout<<"yes"<<endl; } else if((s[1]==s[3] && s[1]==s[5])) { cout<<"yes"<<endl; } else cout<<"no"<<endl; and 2.

python - Django static files not working on Heroku -

my django application working on local server. but, when deploy on heroku, static files not being served (getting 404 error). please help! from django.conf.urls import patterns, include, url django.contrib import admin django.conf.urls.static import static django.conf import settings urlpatterns = patterns('', url(r'^$', 'product.views.home', name='home'), url(r'^admin/', include(admin.site.urls)), ) if settings.debug: urlpatterns += static(settings.static_url,document_root=settings.static_root) urlpatterns += static(settings.media_url, document_root=settings.media_root) static files settings: template_dirs = ( os.path.join(base_dir, 'templates'), ) static_url = '/static/' media_url = '/media/' media_root = os.path.join(base_dir, "static", "media") static_root = os.path.join(base_dir, "static", "static_root") staticf

Run-Time Type Comparisons Within a Generic Hierarchy in java -

i unable understand text the complete reference code this, public class generic { public static void main(string[] args) { superclass<integer> s1=new superclass<>(135); subclass<double> s2=new subclass<>(1.35); if(s1 instanceof superclass<integer>) { system.out.println("i instance of superclass"); } } } class superclass<t> { t y; superclass(t ob) { y=ob; } t ret() { return(y); } } class subclass<t> extends superclass<t> { t x; subclass(t y) { super(y); x=y; } } according text, if(s1 instanceof superclass<integer>) line can’t compiled because attempts compare s1 specific type of superclass ,in case, superclass<integer> . remember, there no generic type information available @ run time. therefore, there no way instanceof know if s1 instance of superclass<integ

Pass parameter to app config file during MSI installation - Advanced Installer -

i have created msi package using advanced installer. contains app config have pass siteurl varies depending on location. need pass siteurl app config when msi installed . please me it. new advanced installer you can check online user guide advanced installer, has lot of useful info. example article on importing , editing xml config files . or how add custom dialog , write in system values captured end users. edit: additional answer regarding command line you can run installation silently command line still see message box saying package built trial. not see standard msi dialogs. , trial messages gone once purchase license advanced installer. please note command prompt window (cmd.exe) must launched administrator, if installation installing per-machine ( i.e. write in program files or hklm registry hive ). otherwise installation fail silently , not know why, because on silent installation os not show error message. here command line example: msiexec.exe /

java - How to use an if function to call elements of an array -

basically, have variable 'prime'. can take values between 0 , 6. based on value, want string 'result' sunday if prime 0, monday if 1, etc. currently, it's coded way: string result = new string(); if (prime == 0) { result = "sunday"; } if (prime == 1) { result = "monday"; } if (prime == 2) { result = "tuesday"; } if (prime == 3) { result = "wednesday"; } if (prime == 4) { result = "thursday"; } if (prime == 5) { result = "friday"; } if (prime == 6) { result = "saturday"; } else { result = "check code."; } i'm wondering if there's faster way this? i've created array days of week: string[] days = new string[7]; days [0] = "sunday"; days [1] = "monday"; days [2] = "tu

xcode - TextView cutting off large amount of text? -

i'm placing textview onto storyboard when place text inside field cuts off portion of text. looks this. now i've made sure there plenty of space in storyboard text seems silly happening. why happening , can it? thought adding textview solve issue seems rather silly add object display portion of uneditable text. can share hierarchy of main storyboard -> view controller -> ui elements structure constraints? helpful give answer question.

python - Memory efficient way to split large numpy array into train and test -

i have large numpy array , when run scikit learn's train_test_split split array training , test data, run memory errors. more memory efficient method of splitting train , test, , why train_test_split cause this? the follow code results in memory error , causes crash import numpy np sklearn.cross_validation import train_test_split x = np.random.random((10000,70000)) y = np.random.random((10000,)) x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.33, random_state=42) one method i've tried works store x in pandas dataframe , shuffle x = x.reindex(np.random.permutation(x.index)) since arrive @ same memory error when try np.random.shuffle(x) then, convert pandas dataframe numpy array , using function, can obtain train test split #test_proportion of 3 means 1/3 33% test , 67% train def shuffle(matrix, target, test_proportion): ratio = matrix.shape[0]/test_proportion x_train = matrix[ratio:,:] x_test = matrix[:ratio,:]

Does R have function startswith or endswith like python? -

was looking predictors name starts substring, not find similar function. i'm not sure when added base (at least 3.3.0), startswith (and endswith ) this. > startswith("what", "wha") [1] true > startswith("what", "ha") [1] false https://stat.ethz.ch/r-manual/r-devel/library/base/html/startswith.html

Concatenating variable into a regex php -

i have these arrays (array , array2) $urls = array("http://piggington.com/pb_cash_flow_positive") i have regular expression (preg_match("/\/{2}.*?\./", $array[$i], $matches)) it checks comes after 2nd slash , before 1st dot. find /piggington. now want concatenate variable inside following regular expression, search specific string. i tried: $matches_imploded = implode($matches); $matches_imploded = preg_quote($matches_imploded, '/'); $match_with_other_array = preg_grep("/\/{2}".$matches_imploded."\./", $array2); but it's not finding matches.. doing wrong? should looking inside array2 , making positive match $matches_imploded between second slash , first dot found $matches_imploded to match comes after // , before first dot, need use \k or positive lookbehind. preg_match("~/{2}\k[^.]*(?=.)~", $array[$i], $matches) $matches_imploded = implode($matches); $matches_imploded = preg_quote($match

AngularJS: IE Access Denied displaying PDF -

while trying display pdf blob on ie, receive access denied error. html file <object ng-show="{{content}}" data="{{content}}" type="application/pdf"></object> js file $http.post('/api',{}, { responsetype: 'arraybuffer' }) .success(function (response) { var file = new blob([response], { type: 'application/pdf' }); var fileurl = window.url.createobjecturl(file); $scope.content = $sce.trustasresourceurl(fileurl); }); when using embed instead, acrobat pdf viewer unable view temporary file.

ios - Programmatically created back button has no arrow -

in xcode swift project, have view controller has programatically created button left bar button item. text shows up, arrow missing. how add arrow matches other view controllers in project? i'd prefer not have use custom image, if way i'd know how it. var backbutton = uibarbuttonitem(title: "my list", style: uibarbuttonitemstyle.plain, target: self, action: "goback") self.navigationitem.leftbarbuttonitem = backbutton i don't think can. as seen here , here you'll have create image. let backbutton = uibarbuttonitem(customview: "yourview") self.navigationitem.leftbarbuttonitem = backbutton

java - canvas.drawText() is not showing up in Android -

i'm trying write text screen using new method taking in of arguments needed draw text. text showing text being centered , showing directly in middle. example: //create texts writetext(canvas, "money: $" + player.getmoney(), paint.align.center, color.black, 25, (screenwidth / 2), 50); writetext(canvas, "mps: " + player.getmps(), paint.align.center, color.black, 25, (screenwidth / 2), 75); writetext(canvas, "mpc: " + player.getmpc(), paint.align.center, color.black, 25, (screenwidth / 2), 100); writetext(canvas, "cost: $" + player.gethouseupgradecost(), paint.align.right, color.black, 15, 0, (screenheight - buttonheight)); writetext(canvas, "cost: $" + player.getconstructionworkercost(), paint.align.center, color.black, 15, (screenwidth / 2), (screenheight - buttonheight)); writetext(canvas, "cost: $" + player.getbobcost(), paint.align.left, color.black, 15, screenwidth, (screenheight - button

cocoa - NSSlider labels -

all, i couldn't find in cocoa documentation making labels nsslider values. functionality not exist or missing something? if not exist how place labels vertically placed nsslider control ticks placed on left side of control? normally slider linked text field indicates current numerical value. have position labels best can.

spring - authentication filter was called repeatedly -

i setup spring security rest apis. here sample of rest call, get: http://localhost:8081/dashboard/epic/data . when executing, filter, provider , eventual onauthenticationsuccess triggered. here problem, instead of executing rest url after authentication, go filter many times. second time, request.getrequesturl http://localhost:8081/dashboard . here security-context.xml: <http auto-config='false' authentication-manager-ref="authenticationmanager" entry-point-ref="authenticationentrypoint"> <intercept-url pattern="dashboard/**" access="role_user" /> <csrf disabled="true"/> <custom-filter position="remember_me_filter" ref="dashboardfilter"></custom-filter> </http> <authentication-manager alias="authenticationmanager"> <authentication-provider ref="dashboardauthprovider"></authentication-provider> <