Posts

Showing posts from January, 2013

sql - From a certain number of rows with the same primary key, how do I select the ones with the highest value in a certain column? -

i have students table , grades table. students has columns student_id(primary key), name, date_of_birth, address, email, , level . grades has columns student_id(primary/foreign key), course_id(primary/foreign key), , grade . "grades" looks this: student_id|course_id|grade =========================== 1 | 1 | 1 | 2 | b 1 | 3 | 3 | 1 | f 3 | 3 | c . . . . this isn't whole table, gist. i'm trying write query selects name of student , student's highest grade. i'm new sql 1 little confusing me. attempt far this: select "students".name, "grades".grade "students" inner join "grades" on "students".student_id = "grades".student_id group name, grade having min(grade) <= 'f'; it's wrong, , know why, i'm not sure go here. select students.name, min(enroll.grade) stu...

php - Getting NULL in template - OpenCart 2.0 -

i trying render product_list.tpl file in home.tpl it's giving me null controller file: /controller/product/product_list.php code: class controllerproductproductlist extends controller { public function index() { $this->load->model('catalog/category'); $this->load->model('catalog/product'); $this->load->model('tool/image'); $filter_data = array( 'filter_tag' => 'featured', 'limit' => 9 ); $data['results'] = $this->model_catalog_product->getproducts($filter_data); if (file_exists(dir_template . $this->config->get('config_template') . '/template/common/productlist.tpl')) { $this->response->setoutput($this->load->view($this->config->get('config_template') . '/template/common/productlist.tpl', $d...

C# ITextSharp Copy existing PDF to new PDF -

i working series of pdf files. many of them have fields, able populate using itextsharp. my issue there 1 static pdf seems reporting odd size, 9.5 x 12. page size should 8.5 x 11 , if opened using acrobat reader, prints fine. to around this, want create new pdf document, using correct page size, read static file new document, save , print it. i have read number of posts here on , done number of searches solution, of seem skirt particular issue. is there way copy existing pdf new document using correct page size? thank you update taking bruno's advice, did double check crop box , media box. pdf working has both. crop box array is [28.008, 38.016, 640.008, 830.016] and media box array [0, 0, 668.016, 848.016] i can alter upper right corner points making crop box , media box same crop box [28.008, 38.016, 612, 792] and media box [0, 0, 612, 792] but doing shifts "text" right , top much, leaving uneven margin. i found changing lower lef...

java - How to figure out the process/Task associated with unix process LWP -

environment : jira application running on linux suse/tomcat server ps -lo pcpu,pid,lwp $procnumber | sort | tail -3 %cpu pid lwp 24.6 21133 21152 24.7 21133 21151 24.7 21133 21153 now after converting lwp hexadecimal , when trying search in java threads, not finding thread dumps(java) or process associated it. is there way figure out thread taking away of our cpu ? search thread dumps hex in both uppercase , lowercase format.

Magento: Exception printing is disabled by default for security reasons -

i error in 1 category on webshop. see site: http://support.hostgator.com/articles/specialized-help/technical/magento-install-error-exception-printing-is-disabled "has solution" problem. however, dont have local.xml.sample or local.xml file. here 1 of error logs: http://pastebin.com/w65zil5y seems error record number change every refresh. can help? go magento root/errors/ folder , rename/copy vanilla installation local.xml.sample local.xml this show exceptions on frontend ( not recommended in production ). alternatively view your root/var/logs/exception.log and root/var/logs/system.log if enabled in under /admin/system_config/edit/section/dev/ -> log settings to see exceptions , system notices. note apache uncaught magento errors stored in apache log folder specified in httpd.conf

How to count the number of different items in a range without use a pivot table excel vba -

i have large range various repeating id's. want know how many unique id's in range, don't want use pivot table. this question related, not have answer. there simple way using vba? i saw this , doesn't work me. use dictionary object load unique values, such below: sub countunique() dim odictionary object dim rngdata range dim ncounter integer set odictionary = createobject("scripting.dictionary") set rngdata = range("a1:a10") 'change range suit ncounter = 0 each cel in rngdata if not odictionary.exists(cel.value) odictionary.add cel.value, 0 ncounter = ncounter + 1 end if next cel msgbox ncounter end sub

Can I export my Azure subscription's entire configuration? -

is possible, using azure portal or other means, export subscriptions configuration, example xml file? i mean things details of web sites / roles, virtual machines, size of machines etc? then export every day , use diff tool check nothing has changed mistake.... just thought i'd ask before write giant powershell script. i agree nice feature have. it's easier build out environment via portal, copying 1 tenant (dev) (prod) faster , easier if exported json or xml , processed via powershell.

android - GridView malfunction classCastException -

i have been busting head on this... code doesn't seem working, , cannot find error. sure error occurs because malformed layout in xml. can of guys take look. <?xml version="1.0" encoding="utf-8"?> <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" tools:context="gokerakinci.lottery.sayisal" > <linearlayout android:id="@+id/llnumbers" android:layout_width="match_parent" android:layout_height="50dp" android:layout_alignparenttop="true" ...

c# - Model Validation on collection with checkbox fails when checkbox not rendered -

when index view display 2 people , none of them selected model validation works correctly due minlengthattribute in .net 4.5. now comes custom logic in ui. when 1 person displayed in index view need no checkbox check it. customer can directly press submit button. try manually fill selectedids array see @else clause. but code: model.selectedids = new int[]{ item.personid}; does not work, viewmodel.selectedids property on server side action {int[0]} how can still assign 1 person id selectedids array? view @model listtest.models.peoplelistviewmodel @{ var hasmorethanoneperson = @model.people.count > 1; } @html.beginform("save", "home") { @html.validationsummary(false) <table> @foreach (var item in model.people) { <tr> @if (hasmorethanoneperson) { <td> <input type="checkbox" name="selectedids" value="@item.personid...

css - How to persist css3 animation change -

goal keep background red @ end of animation. using chrome http://codepen.io/juliannorton/pen/rnqlzm .animation { -webkit-animation:test-animation 2s 2; // animation stops after few seconds, state doesn't stay red. } @-webkit-keyframes test-animation { 0% { background-color:#fff } 100% { background-color:red } } @keyframes test-animation { 0% { background-color:#fff } 100% { background-color:red } } animation-fill-mode: forwards; is looking for. source: css animation property stays after animating

sql server - Cannot connect to SQL database (hosting from home) -

i installed windows server 2012 , iis because wanted host website home (inside network). i able host simple static site, when want deploy asp.net site uses sql server database have problems. from tutorial "published" site visual studio http: //youtu.be/dqgboijwgbs?t=6m and here error get: http://i62.tinypic.com/j9uhjt.jpg i have installed sql server management studio , attached database it, in iis have set/up database name , server, believe ok. firewall disabled (just until working). here sql server set-up iis http://i61.tinypic.com/ao2r95.jpg i don't know problem is, maybe in permissions? (i can view static page, website folder located in inetpub folder)

outlook - Reading mail data from powershell -

i'm trying read data .pst file using powershell , can't seem extract attributes mail items, specifically: recipients, sender, cc, bcc, body for reason when try access these properties code shows blank. of other properties show file (subject, attachments etc...) i'm using following code: $objoutlook = new-object -comobject outlook.application $ns = $objoutlook.getnamespace("mapi") $ns.addstore($pst.fullname) $folders = $ns.folders $archivestore = $ns.folders[$pst.name.replace(".pst","")] from there use folders , items recursively mail items. any ideas? this returns sender me. $archivestore.items | %{$_.sendername} which property using fetch recipients,sender,cc,bcc,body?

php - Mailchimp API with Groupings -

i need add mailchimp subscriber specific grouping. have no issue getting subscriber subscribed, can't seem them specific grouping. this have: // enter mailchimp $newsletter = $_post['newsletter']; $newsletter = 'yes'; if ($newsletter = "yes") { $mailchimp = new \drewm\mailchimp('api'); $result = $mailchimp->call('lists/subscribe', array( 'id' => 'listnumber', 'email' => array('email'=> $_post['usersemail']), 'merge_vars' => array( 'fname'=>$_post['usersname'], 'lname'=>$_post['userslastname'], 'groupings' => array( 'id' => 494281, ...

cocoa - Is there better documentation on Apples UTI system? -

i have cocoa document-based application works fine. however, when create uti document , export it, application can neither read, write or create own files (or others). has menu. no logs, nothing. is cocoa nsdocument system broken? no, nsdocument system not broken. have bug. cause have corrupted info.plist . without hints you've done it's difficult certain, that's likely. can use plutil -lint <file> make sure haven't broken that. beyond that, of course, try removing uti , see if problem goes away. if so, adding uti incorrectly , details, may able help. if problem doesn't go away, broke else didn't realize touched.

design patterns - How to make a Java project 'extendable' by developers? -

i'm working on server engine, , not sure in form distribute it. quite modular , uses interfaces/abstract classes. should be: a library (no entry-point, write own main() , call new server().setsomehandler(myhandler).run() ) a binary (executable entrypoint config file can inject jar handlers) something else? basically, developer should able extend or change way server works. don't idea of making library because should platform itself, whole server system. providing programmatic way more versatile executable. , both ways aren't mutually exclusive. after all, if developer provides handler, internally still need call setter in example use handler. exposing api shouldn't difficult. still provide small launcher application loads config file , wraps in api calls, if needed. the more important question be, there predefined extension points developers can plug in own implementations or modular , exchangeable? for simple way provide implementations of p...

python - NameError: name 'subprocess' is not defined -

i'm trying make rng website: http://jamesdotcom.com/?p=417 . when run following code: captureimage = subprocess.popen( [ "fswebcam", "-r", "356x292", "-d", "/dev/video0", "static.jpg", "--skip", "10" ], stdout=devnull, stderr=devnull) captureimage.communicate() i following error message: nameerror: name 'subprocess' not defined what should do? thanks have imported first? import subprocess captureimage = subprocess.popen(["fswebcam", ...) subprocess included in python standard library since python 2.4. should not necessary install it.

jquery - Bulk Declare JavaScript Associative Array -

is there way bulk set associative array keys , values in javascript, similar php's shorthand array declaration below? $array = [ 'foo' => 'val1', 'bar' => 'val2', 'baz' => 'val3' ]; the way can think of declare associative arrays in js this: var newarray = new array(); newarray['foo'] = 'val1'; newarray['bar'] = 'val2'; newarray['baz'] = 'val3'; or this: var newarray = new array(), keys = ['foo', 'bar', 'baz'], vals = ['val1', 'val2', 'val3']; for(var = 0; < keys.length; i++) { newarray[ keys[i] ] = vals[i]; } that last 1 can cause mess in cases, wanted list since it's doable. if there isn't way top example, that's fine. would've been nice. tried using js object literal jquery this: var myobject = { foo: $('foo'), bar: $(this.foo).find('bar'), baz: $(this.bar...

c# - A worker process serving application pool 'xxx v4.0 (Classic)' has requested a recycle because it reached its private bytes memory limit -

i have shared hosting account 128mb of ram , site in own app pool. the site small , gets low traffic, keep getting following error: a worker process serving application pool 'xxx v4.0 (classic)' has requested recycle because reached private bytes memory limit. this happening frequently, restarts app pool. if app pool restarts often, stop. i'll 503 error when go site. the site written using c#, data access ef , ado.net. database connections in using statements , confident being opened , closed correctly. i have spoken host , can upgrade ram 256mb appear make site run nicely. bit concerned upgrading ram masking problem temporarily. debug set false in web config , before copy files server building release. when run solution in visual studio iis worker process hovers around 100 mb. i think questions are: is there way can replicate hosting environment on local machine? normal small website exceed 128mb of ram? i @ bit of loss of try. or guidance apprecia...

Julia: conversion between different time periods -

full disclosure: i've been using julia day, may ask questions. i'm not understanding utility of dates module's period types. let's had 2 times , wanted find number of minutes between them. seems natural thing subtract times , convert result minutes. can deal not having minute constructor (which seems natural python-addled brain), seems convert should able something. the "solution" of converting millisecond int minute seems little gross. what's better/right/idiomatic way of doing this? (i did rtfm, maybe answer there , missed it.) y, m, d = (2015, 03, 16) hr1, min1, sec1 = (8, 14, 00) hr2, min2, sec2 = (9, 23, 00) t1 = datetime(y, m, d, hr1, min1, sec1) t2 = datetime(y, m, d, hr2, min2, sec2) # println(t2 - t1) # 4140000 milliseconds # minute(t2 - t1) # error: argumenterror("can't convert millisecond minute") # minute(t2 - t1) # error: `minute` has no method matching # minute(::millisecond) # convert(minute, (t...

python 2.7 - I need to calculate the likelihood P(D|N) and also to implement my function that it allows arrays as input arguments -

i tried gives me error 'local variable 'l' referenced before assignment' def likelihood(n,n,k): """ call: l = likelihood(n,n,k) input argument: n: integer (array) n: integer (array) k: integer (array) output argument: l: float (array) example: likelihood(6,10,5) => 1.190748e-05 """ if isinstance(n,list): # n array l = zeros(len(n)) i, in enumerate(n): l[i]=exp(log_factorial(i)-log_factorial(i-k)-n*log(i)) else: # n scalar l= exp(log_factorial(n)-log_factorial(n-k)-n*log(n)) return(l) where wrong? or there way solve it? if call function n not list, not go if clause. l not defined when return reached. actual error, though, else clause indented. want: from numpy import zeros, exp, log scipy.special import gammaln log_factorial = lambda z:gammaln(z+1) def likelihood(n,n,k): ...

validation - PYTHON: While loops, comparing more than one value -

i can understand how use while loop if compare 1 thing, example: x=int(input("guess number 1-10")) while x!=7: print("wrong!") x=int(input("try again: ")) print("correct 7. ") however, if want compare 2 or more values through while loops (especially if want validate something), this: number=input("would eat 1. cake 2. chocolate 3. sweets: ") while number!= "1" or number != "2" or number != "3": number=input("please input choice [1,2,3]") #some code... when number equal 1, 2 or 3, program should proceed... doesn't, no matter value input, program stuck @ infinite loop @ line 2-3. have tried while number != "1" or "2" or "3" , same infinite loops occurs. when try replacing or and , while loop break when number equals first value compared (which in case "1" ). is there way can resolve this? :...

angularjs - Angular code from ng-book -

i'm reading ng-book , there's code i'm not quite following: <div ng-controller="mycontroller"> <input ng-model="expr" type="text" placeholder="enter expression" /> <h2>{{ parsedvalue }}</h2> </div> angular.module("myapp", []) .controller('mycontroller', function($scope, $parse) { $scope.$watch('expr', function(newval, oldval, scope) { if (newval !== oldval) { // let's set our parsefun expression var parsefun = $parse(newval); // value of parsed expression $scope.parsedvalue = parsefun(scope); } }); }); i'm guessing parsefun() evaluates scope.expr. if case how know evaluate property? parsefun $parse(newval) in case implying means parsefun new parsed expression. retrieve value of parsed expression passing scope given watch function callback parsefun(scope) note: in actual angular development find need use watch st...

objective c - Sort NSMutableArray by date and then by alphabetical order -

i have nsmutable array of objects. objects represent football (soccer) matches , have nsstring parameter called title (ed "arsenal v chelsea"), , nsdate parameter called actualdate . i sorting array date @ moment using following code: nsmutablearray* = [self getmatchlistfromurl:@"http://www.url.com"]; [a sortusingdescriptors:@[[nssortdescriptor sortdescriptorwithkey:@"actualdate" ascending:yes]]]; obviously there multiple games happen on same date. sort games happen on same date in alphabetical order. there simple way this? the method sortusingdescriptors takes array of nssortdescriptor argument. can pass multiple sort descriptors method follow: nssortdescriptor *sortalphabetical = [nssortdescriptor sortdescriptorwithkey:@"title" ascending:yes]; nssortdescriptor *sortbydate = [nssortdescriptor sortdescriptorwithkey:@"actualdate" ascending:yes]; nsarray *sortdescriptors = @[sortalphabetical, sortbydate]; //perfo...

Can command-line set Java system properties be distinguished from the defaults? -

is there way distinguish java system property has been set command line using -d option system property got same value default? e.g., program class test { public static void main(string[] args) { system.out.println(system.getproperty("user.home")); } } prints /home/uckelman for me regardless of whether run java test or java -duser.home=/home/uckelman test is there jdk provides test distinguish these 2 situations? one way command line arguments used start jvm , check returned list if given system property set or not. runtimemxbean mx = managementfactory.getruntimemxbean(); system.out.println("command line args:\n" + mx.getinputarguments());

javascript - jQuery hide buttons if they don't contain text -

i have buttons dynamically generated text inside. there no text generated want hide button jquery. cannot seem work. below code: $('.inner:empty').parent().remove(); <button><span class="inner">{{dynamic1}}</span></button> <button><span class="inner">{{dynamic2}}</span></button> <button><span class="inner">{{dynamic3}}</span></button> <button><span class="inner">{{dynamic4}}</span></button> thanks. this satifies requirements. need use quotes around selector , call hide instead of remove. works versions of jquery available on google jquery cdn (1.2.3 - 2.1.1) $(document).ready(function() { // can replace 'hide' 'remove' if want purged dom. $('.inner:empty').parent().hide(); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>...

hive - FAILED: SemanticException [Error 10008]: Line 5:16 Ambiguous table alias 'in_2051_1' -

insert overwrite table out_2051 select in_2051_0.column1,in_2051_0.column2,in_2051_1.column2,in_2051_1.column1 in_2051_0 right outer join in_2051_1 on (in_2051_0.column2 = in_2051_1.column1) left outer join in_2051_1 on (in_2051_0.column2 = in_2051_1.column1) ; failed: semanticexception [error 10008]: line 5:16 ambiguous table alias 'in_2051_1' what error mean , how fix it? i can find left , right outer join 2 tables same column means "full outer join". change sql insert overwrite table out_2051 select in_2051_0.column1,in_2051_0.column2,in_2051_1.column2,in_2051_1.column1 in_2051_0 full outer join in_2051_1 on (in_2051_0.column2 = in_2051_1.column1) and think error means last in_2051_1 table refer same 4th line. at on clause of 5th line. in_2051_1.column1 ambiguous, hive dont know in_2051_1 right join 1 or left join one. can give in_2051_1 alias 'in_2051_1_2' @ line 5. i think full outer join want.

Data type conversion from Access to SQL Server errors -

Image
i have sql server odbc access being utilized front end. created column in sql bit data type , created checkbox yes/no data type uses sql column control source. when go form , try change in there , update tables, writing error , wont let me append updates i'm trying make. delete bit data type, , check box, able again append information form. know solution or way utilize boolean check boxes report sql database track progress of order, still able append records? if knows why happening appreciate information own notes , understanding. this image shows column created in sql server this image shows looks in odbc table in access this image shows control source picked query utilizes names of form comboboxes, text boxes, , check boxes this image shows happens after try update , and close thanks haven't done long time, problem related numbers stored. yes/no in access = -1/0, in sqlsrvr = 1/0 (or similar). use int field in sqlsrvr store whatever access sends...

parallel processing - Apache Spark vs Akka -

could please tell me difference between apache spark , akka, know both frameworks meant programme distributed , parallel computations, yet don't see link or difference between them. moreover, use cases suitable each of them. apache spark built on akka. akka general purpose framework create reactive, distributed, parallel , resilient concurrent applications in scala or java. akka uses actor model hide thread-related code , gives simple , helpful interfaces implement scalable , fault-tolerant system easily. example akka real-time application consumes , process data coming mobile phones , sends them kind of storage. apache spark (not spark streaming) framework process batch data using generalized version of map-reduce algorithm. example apache spark calculation of metrics of stored data better insight of data. data gets loaded , processed on demand. apache spark streaming able perform similar actions , functions on near real-time small batches of data same way if ...

powershell - List of possible Status outputs from Get-AzureVM -

i have been unable find list of possible states can returned status get-azurevm. for example, checking: 1) $vms = get-azurevm | {$_.status -eq "readyrole"} 2) $vms = get-azurevm | {$_.status -eq "stoppeddeallocated"} 3) $vms = get-azurevm | {$_.status -eq "stopped"} are there other possible outputs? if want see possible values, can information service management api documentation page: https://msdn.microsoft.com/en-us/library/azure/ee460804.aspx . scroll down section roleinstancelist , see possible values.

How do I use chai and mocha with Grunt? -

i trying use 'grunt-mocha-test' package can't find way hookup chai configuration. need manually configure it? simply require chai in spec files: var chai = require('chai');

c - Gstreamer Playbin could not determine type of stream -

i trying create audio application in linux using gstreamer 1.0. main issue i'm having running gst-launch-1.0 playbin uri="file:///home/root/documents/mp3/songs/test.mp3" results in error, error: element /gstplaybin:playbin0/gsturidecodebin:uridecodebin0/gstdecodebin:decodebin0/gsttypefindelement:typefind: not determine type of stream. additional debug info: gsttypefindelement.c(1067): gst_type_find_element_loop (): /gstplaybin:playbin0/gsturidecodebin:uridecodebin0/gstdecodebin:decodebin0/gsttypefindelement:typefind error: pipeline doesn't want preroll. i have mad plugin installed audio decoder. plugins have installed: playback: playbin: player bin 2 playback: playsink: player sink playback: streamsynchronizer: stream synchronizer playback: decodebin: decoder bin playback: uridecodebin: uri decoder mad: mad: mad mp3 decoder if run gst-launch-1.0 filesrc location=test.mp3 ! mad ! pulsesink the audio runs flawlessly want playbin work. experie...

Google Glass compile error on Android Studio -

i'm trying create google glass app(immersion based) on android studio 1.1.0 , error throws up. error:could not normalize path file 'c:\users\admin\androidstudioprojects\sampleapp\app\build\intermediates\mockable-google inc.:glass development kit preview:19.jar'. filename, directory name, or volume label syntax incorrect i tried on eclipse , worked fine in android studio it's little weird. update project: build.gradle apply plugin: 'com.android.application' repositories { jcenter() flatdir { dirs 'prebuilt-libs' } } android { compilesdkversion "google inc.:glass development kit preview:19" buildtoolsversion "21.1.2" defaultconfig { applicationid "example.com.sampleapp" minsdkversion 19 targetsdkversion 19 versioncode 1 versionname "1.0" } compileoptions { sourcecompatibility javaversion.version_1_7 targetcompati...

javascript - How can I pass arbitrary parameters to my mocha tests with mochaPhantomJS & gulp? -

i'm using gulp & mochaphantomjs. i'd use same test html , run different tests against it. how can pass arbitrary parameters (by mean not phantom args) can retrieve within test javascript? var gulp = require('gulp'); var mochaphantomjs = require('gulp-mocha-phantomjs'); gulp.task('testmisc', function() { return gulp.src('testmisc.html') .pipe(mochaphantomjs()); }); but clear want able is gulp.task('testmisc-1', function() { return gulp.src('testmisc.html') .pipe(mochaphantomjs({whatever:1})); }); gulp.task('testmisc-2', function() { return gulp.src('testmisc.html') .pipe(mochaphantomjs({whatever:2})); });

android - Minimum Distance required to add PolyLine between two points -

polyline line = googlemap.addpolyline(new polylineoptions().add(mypos, itempos).color(color.blue)); for polyline created above, app crashes. distance between mypos , itempos 0.019 miles. there minimum distance required draw line between 2 points using polyline? @jb15613 believe correct that. you can use api v3 draw line between 2 points: var line = new google.maps.polyline({ path: [new google.maps.latlng(37.4419, -122.1419), new google.maps.latlng(37.4519, -122.1519)], strokecolor: "#000000", strokeopacity: 1.0, strokeweight: 10, geodesic: true, map: map }); the ‘geodesic’ /geometric library if wish have shortest path. need account facet earth curved. please add libraries parameter: <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry"></script>

Android: How make dynamically generated check boxes or radio buttons wrap automatically? -

Image
what trying right making radio buttons or checkbox button wrap on own. generating buttons dynamically java. how make if cannot fit on row put button on next row. looking @ image can see third check box cut off screen. how can make start line? there no way in android, rather implement logic able measure child controls of layout , calculate if reaches end of screen, , create new layout row. take @ post subject, using linearlayout: android - linearlayout horizontal wrapping children this approach discussed here: android horizontal linearlayout - wrap elements

oop - Does Java 8 provide an alternative to the visitor pattern? -

this popular answer on stack overflow has difference between functional programming , object-oriented programming: object-oriented languages when have fixed set of operations on things , , code evolves, add new things. can accomplished adding new classes implement existing methods, , existing classes left alone. functional languages when have fixed set of things , , code evolves, add new operations on existing things. can accomplished adding new functions compute existing data types, , existing functions left alone. say have animal interface: public interface animal { public void speak(); } and have dog , cat , fish , , bird implement interface. if want add new method animal named jump() , have go through of subclasses , implement jump() . the visitor pattern can alleviate problem, seems new functional features introduced in java 8 should able solve problem in different manner. in scala use pattern matching, java doesn't have yet. do...

java - How to access thread objects inside custom threadpool executor's methods? -

i want access data inside runnable objects have in custom threadpool executor. if tried access in before/after execute methods getting class cast exception. how resolve scenario. public class mythread implements runnable { string key; public void run(){ /* */} } public class myexecutor extends threadpoolexecutor { @override protected void beforeexecute(thread paramthread, runnable paramrunnable) { mythread mt = (mt)paramrunnable; } @override protected void afterexecute(runnable paramrunnable, throwable paramthrowable) { mythread mt = (mt)paramrunnable; /* need access "key" inside mythread */ } if classcastexception means pass in thread implementations not mythread or subclass of mythread myexecutor . in order fix instanceof check before casting. public class myexecutor extends threadpoolexecutor { @override protected void beforeexecute(thread paramthread, runnable paramrunnable) { if...

python - O(nlogn) Runningtime Approach -

the function consumes list of int , produces unique elements in list in increasing order. examples: singles([4,1,4,17,1]) => [1,4,17] i can in o(n^2) running time , wonder how change o(n) running time without loop. def singles(lst): if lst==[]: return [] else: rest_fn = list (filter (lambda x: x!=lst[0], lst[1:])) return [lst[0]] + singles(rest_fn) as discussed above, per https://wiki.python.org/moin/timecomplexity (which cited time complexity of python set operations? links more detailed list of operations, sorted should have time complexity o(nlogn). set should have time complexity o(n). therefore, doing sorted(set(input)) should have time complexity o(n) + o(nlogn) = o(nlogn) edit: if can't use set, should mention that, hint, assuming can use sorted, can still pull out uniques in o(n) if use deque (which has o(1) worst case insertion). like rez = deque() last = none val in sorted(input): if val != last: ...

python - Biased coin flipping? -

what simplest (does not have fastest) way biased random choice between true , false in python? "biased", mean either true or false more probable based on probability set. it's pretty easy and fast: import random def biased_flip(prob_true=0.5): return random.random() < prob_true of course if call biased_flip() you'll true , false 50% probability each, e.g biased_flip(0.8) give 8 true s each false in long run.

swift - Dynamically performing an action based on string passed in textfield -

say have textfield - inputtextfield and button on ui action performactiondynamically , in same class define 2 functions: 1. firstfunc , 2. secondfunc , want achieve behavior: if user types "firstfunc" in textfield , taps on button should invoke firstfunc function, , if types "secondfunc" in textfield , taps on button should invoke secondfunc function. in objective-c have achieved following below pseudocode: within performactiondynamically pass inputtextfield.text in nsselectorfromstring() obtain selector invoke performselector:withobject: on self perform respective function the thing can think in implementing same behavior in swift - define 2 closures name firstfunc , secondfunc store closures in dictionary values keys - 'firstfunc' , 'secondfunc' respectively obtain respective closure dictionary based on value in textfield invoke obtained closure is there better way achieve intended behavior? please guide. you ...

c# - Why does this Regular Expression not return the correct match? -

i trying return part of string, want return before fist slash: ec22941c/02/ori should give me: ec22941c i have used http://www.regexr.com/ build expression: (ec.+?)\/.+ when tested against text: ec22941c/02/ori it correctly tells me first group is ec22941c when put c#: public static string getinstructionref(string supplierreferenceid) { // instruciton ref bit before slash var match = regex.match(supplierreferenceid, @"(ec.+?)\/.+"); if (match == null || match.groups.count == 0) return ""; // return first group instruction ref return match.groups[0].value; } the result is: ec22941c/02/ori i have tried number of different patterns , seem same thing. does have idea im doing wrong? the issue you're returning wrong group index, 0 return entire match while 1 returns matched context of capturing parentheses — numbered left right. return match.groups[...

.htaccess - Apache rewrite to test directory -

i trying use apache redirects change directories between production , test folders if use subdomain test test.mywebsite.com think gets stuck in infinite loop. sure simple cannot seem figure out. <directory /> rewriteengine on rewritebase /var/www/mywebsite rewritecond %{http_host} ^test\.[^.]+\.com$ rewriterule ^(.+) %{http_host}$1 [c] rewriterule (.*) /var/www/mywebsite_dev </directory> edit getting errors in apache log this. request exceeded limit of 10 internal redirects due probable configuration error. use 'limitinternalrecursion' increase limit if necessary. use 'loglevel debug' backtrace. redirected r->uri = /mywebsite_dev/mywebsite_dev/ redirected r->uri = /mywebsite_dev/ redirected r->uri = / if you're explicitly checking test subdomain, don't use rewritebase . rewriteengine on rewritecond %{http_host} ^test\. [nc] rewritecond $1 !^/?mywebsite_dev/ [nc] rewriterule ^(....

asp.net web api - How to name api routing on a webhost sub folder -

i have thought api controllers not found physical paths. reason ask have website example.com created folder example.com/testing , uploaded project there. when ran got errors saying none of apicontrollers found. changed /api/apicustomers /testing/api/apicustomers. worked, not actual posting of new records. did locate , retrieve records database though. doesn't seem need do? have domain winhost , default publish folder example.com/myapp looking @ wrong way? to handle request not know root path, can use (as in asp.net) ~-character this: ~/api/apicustomers ~ replaced root (i.e. /api/apicustomers prod , /testing/api/apicustomers test environment)

java - Split method of String class returns a string? -

according string.split() documentation method returns array, how come following code compiles? the retval variable inside loop string , not array there no error? public class string_splitting_example { public static void main(string args[]) { string str = new string("welcome-to-tutorialspoint.com"); system.out.println(""); system.out.println("return value :" ); (string retval: str.split("-")) { system.out.println(retval); } } } as jared burrows commented, writing for (string retval: str.split("-")) iterating through each part of array retval contains current string in array of strings got doing str.split

python - Django Admin modifications -

i have app in 2 models related foreign keys. class trans(models.model): pk = uuidfield(auto=true, primary_key=true, serialize=true, hyphenate=true) en = models.textfield('english') class article(models.model): pk = uuidfield(auto=true, primary_key=true, serialize=true, hyphenate=true) title = models.onetoonefield(trans) description = models.onetoonefield(trans) now if want add values in article model via admin interface , title , description there '+' sign above field add values , on click trans model form popup shown can add values , instance attach article title field (usual process). but not want add values , want show simple text field admin there both title , description , on save values saved trans model , instance in article model . in simple words not want show '+' sign admin simple text field. is possible in django admin if yes suggestions ?

Magento site is in maintenance mode -

i installed extension in magento site through magento connect.i forgot uncheck put magento site maintenance mode check box.installation failed due unknown reason.i unable goto magento frontend.it still in maintenance mode.how change magento production mode. thanks in advance goto magento root installation .there should file named maintanence.flag .delete file , check magento frontend.

highlight.js - Where is the actual documentation for highlight js / CKeditor theme values? -

whether ckeditor themes, or codesnippet themes, actual string values pass arguments config options? i'm having trouble finding actual string values, or pointing convention/pattern value follows. the ckeditor documentation huge, , links send around in circles, referring generic documentation pages, either actual string values possible arguments not available. the 1 example plugins follows lower case, no separation between words. highlight js themes ckeditor requires seems snake case, inconsistent , not working. for instance, i'm looking find values <script> ckeditor.replace( 'editor1', { skin: 'kama', codesnippet_theme:'tomorrow_night_dark' } ); </script> http://cdn.ckeditor.com/4.4.7/full-all/plugins/codesnippet/lib/highlight/styles/ a link to in ckeditor documentation help, short liner saying copy file name excluding paths , file type suffixes. reference file name without .css suffix correct string format codesn...

oauth - DotNetOpenAuth Bad Request on ProcessUserAuthorization -

i'm implementing sso process (oauth 2.0) using dotnetopenauth example. solution has 3 projects (client web, authorization server, , resource server) got issue in step of processing user authorization response after authorization server returned authorization code client. http://localhost/oauthclient/samplewcf2.aspx?code=xxx&state=l6saxlxhlxwsbrctck3iaw exception is: [webexception: remote server returned error: (400) bad request.] system.net.httpwebrequest.getresponse() +8765848 dotnetopenauth.messaging.standardwebrequesthandler.getresponse(httpwebrequest request, directwebrequestoptions options) +271 [protocolexception: error occurred while sending direct message or getting response.] dotnetopenauth.messaging.standardwebrequesthandler.getresponse(httpwebrequest request, directwebrequestoptions options) +2261 dotnetopenauth.messaging.channel.requestcore(idirectedprotocolmessage request) +516 dotnetopenauth.messaging.channel.request(idirectedprotocolmess...

oracle - SQL Query to fetch employee Attendence -

i need write query on employee table fetch employee employee id & how many days present absent & half-day given date range. employee aid empid status date 1 10 present 17-03-2015 2 10 absent 18-03-2015 3 10 halfday 19-03-2015 4 10 present 20-03-2015 5 11 present 21-03-2015 6 11 absent 22-03-2015 7 11 halfday 23-03-2015 expected output : empid present absent halfday 10 2 1 1 11 1 1 1 can please me sql query ? here query tried select emp.empid, (case when emp.status = 'present' count(status) else 0 end) pres, (case when emp.status = 'absent' count(status) else 0 end) absent, (case when emp.status = 'halfday' count(status) else 0 end) halfday employee emp group emp.empid the count() function tests if value not null. therefore increment both sides of case statement this: count(case status when 'present...

can we classify text using SVM classifier in python-TextBlob? -

>>> train = [ ('i love sandwich.', 'pos'), ('this amazing place!', 'pos'), ('i feel these beers.', 'pos'), ('this best work.', 'pos'), ("what awesome view", 'pos'), ('i not restaurant', 'neg'), ('i tired of stuff.', 'neg'), ("i can't deal this", 'neg'), ('he sworn enemy!', 'neg'), ('my boss horrible.', 'neg') ] >>> test = [ ('the beer good.', 'pos'), ('i not enjoy job', 'neg'), ("i ain't feeling dandy today.", 'neg'), ("i feel amazing!", 'pos'), ('gary friend of mine.', 'pos'), ("i can't believe i'm doing this.", 'neg') ] >>> textblob.classifiers import naivebayesclassifier >>> cl = naivebayesclassifier(train)...

java - Can I trust methods in Files will throw NoSuchFileException when expected? -

the java.nio.file.files api nice improvement on old java.io.file class, 1 detail strikes me odd; exception of delete() no methods document may throw nosuchfileexception , , delete() says optional. i'd able differentiate between failures due missing files , other io issues, seems isn't guaranteed possible. the alternative of calling files.exists() , beforehand risks race-condition if file created in between 2 operations. can expect methods in files raise nosuchfileexception when appropriate? if so, documented? if not, how can safely determine failure due missing file? example: on windows 7 java 7.0.02 files.readalllines() method raise nosuchfileexception , though it's not explicitly documented so: files.readalllines(paths.get("foo"), standardcharsets.utf_8) java.nio.file.nosuchfileexception: foo @ sun.nio.fs.windowsexception.translatetoioexception(windowsexception.java:79) @ sun.nio.fs.windowsexception.rethrowasioexception(windowse...

php - JavaScript: Updating <select> list of days given month input -

my raw html has 3 <select> inputs side-by-side so: <select id="smonth" name="smonth" onchange="updatesdaysinput()"> <option value="month">month</option> <option value="1" <?php if ($smonth == '1') { echo 'selected'; } ?>>january</option> <option value="2" <?php if ($smonth == '2') { echo 'selected'; } ?>>february</option> <option value="3" <?php if ($smonth == '3') { echo 'selected'; } ?>>march</option> <option value="4" <?php if ($smonth == '4') { echo 'selected'; } ?>>april</option> <option value="5" <?php if ($smonth == '5') { echo 'selected'; } ?>>may</option> <option value="6" <?php if ($smonth == '6') { echo 'selected'; }...

c# - Modified Chain Of Responsibility -

i quite understand basics of chain of responsibility pattern. however, ask if possible set next receiver in sequence dynamically. the basic idea depending on sequence of approver, instantiate next object. below example: abstract base class public abstract class approvercategorizer { protected approvercategorizer nextapprover { get; private set; } public approvercategorizer registernextapprover(approvercategorizer nextapprover) { nextapprover = nextapprover; return nextapprover; } public abstract void approveamount(testentity entity); protected bool islast(queue<string> approverqueue) { return string.isnullorempty(approverqueue.peek()); } } officer approver class public class officeraapprover : approvercategorizer { public override void approveamount(testentity entity) { entity.approverqueue.dequeue(); if (entity.amount <= 300) { entity.status = "approved...