Posts

Showing posts from February, 2010

python - Why does a class need __iter__() to return an iterator? -

why class need define __iter__() returning self, iterator of class? class myclass: def __init__(self): self.state = 0 def __next__(self): self.state += 1 if self.state > 4: raise stopiteration return self.state myobj = myclass() in myobj: print(i) console log: traceback (most recent call last): in myobj: typeerror: 'myclass' object not iterable the answer https://stackoverflow.com/a/9884259/4515198 , says an iterator object next (python 2) or __next__ (python 3) method. the task of adding following: def __iter__(self): return self is return iterator , or object of class, defines __next__() method. but, isn't task of returning object of myclass (which defines __next__() method) done __new__() method, when myclass instantiated in line myobj = myclass() ? won't objects of class defining __next__() method, iterators themselves? i have studied questions what use of returnin...

performance - How to safely and/or quickly make up an int from n bytes in memory in C? -

assuming little endian architecture , having large (unsigned char *) memory area, want able interpret n <= sizeof(size_t) bytes anywhere in area integer ( size_t ) value. want fast possible assuming gcc , x64 architecture, able offer safer code other possible scenarios. possible solutions? is possible faster following? static inline size_t bytes2num(const unsigned char * const addr, size_t const len) { switch(len) { /* sizeof(size_t) bytes after addr has allocated */ case 5: return *(size_t *) addr & 0x0ffffffffffu; case 4: return *(size_t *) addr & 0x0ffffffffu; case 3: return *(size_t *) addr & 0x0ffffffu; case 2: return *(size_t *) addr & 0x0ffffu; case 1: return *(size_t *) addr & 0x0ffu; case 6: return *(size_t *) addr & 0x0ffffffffffffu; case 7: return *(size_t *) addr & 0x0ffffffffffffffu; case 8: return *(size_t *) addr & 0x0ffffffffffffffffu; } return 0; } (the order of branches reflects actua...

matrix - Finding transition probabilities from N-state probabilities (Where N is 'a long time') -

i'm confused theory , need advice 789 456 123 this grid represents basic house 9 rooms. a mouse, m, in room i, , after time interval, "t", moves adjacent room, j. example, mouse can in room 1, , after t, either not move, or move either room 2, or 4. let's moved room 2. after "t" interval, either move 1/3/5 or stay in 2. , on. it's markov chain. what method use calculate transition probabilities between each state rules above valid , resulting probability of, after long time, being in bottom row (1/2/3) 1/6, being in middle 3 row (4/5/6) 2/6 (1/3), , top row (7/8/9) 3/6 (1/2)?

r - What is the right way to reference part of a dataframe after piping? -

this question has answer here: aggregate / summarize multiple variables per group (i.e. sum, mean, etc) 4 answers what correct way this? trying colsums of each group specific columns. . syntax seems incorrect type of subsetting. csv<-data.frame(id_num=c(1,1,1,2,2),c(1,2,3,4,5),c(1,2,3,3,3)) temp<-csv%>%group_by(id_num)%>%colsums(.[,2:3],na.rm=t) this can done summarise_each or in recent version additional functions summarise_at , summarise_if introduced convenient use. csv %>% group_by(id_num) %>% summarise_each(funs(sum)) csv %>% group_by(id_num) %>% summarise_at(2:3, sum) if using column names, wrap vars in summarise_at csv %>% group_by(id_num) %>% summarise_at(names(csv)[-1], sum) note: in op's dataset, column names 2nd , 3rd columns not specified resulting in c.1..2..3..4..5. ...

c# - ReadOnly Property that Entity Framework can set -

very basic, yet google-fu failing me. i have domain object, user, want active property read on. yet, property needs set via ef(6) when loaded database. table: create table users ( id int not null primary key clustered, active bit not null default 1 -- other stuff ); class: public class user { public int id { get; set; } public bool active { get; set; } // should ro public void activate() { active = true; this.addchangelog(changetype.activation, "activated"); } public void deactivate() { active = false; this.addchangelog(changetype.activation, "deactivated"); } // changelogging, etc. } developers should not change active directly, instead should use activate() , deactivate() methods. yet, ef6 needs set active directly can instantiate object. architecture (if matters): user class exists in domain project ef6 class configuration done via data project ef6 uses f...

oracle - SQL Trigger on field update to insert new record in another table -

i trying keep record of changes data in table. i've read there various ways of doing sound lot more convenient, in situation want implement functionality using trigger. have 2 tables: create table applications ( application_id int not null, student_id int not null, job_id int not null, applicationchange_type varchar(64) not null, primary key (application_id), foreign key (student_id) references students(student_id), foreign key (job_id) references jobs(job_id), constraint ck_type check (applicationchange_type in ('submitted', 'withdrawn', 'invited interview', 'invited assessment centre', 'rejected', 'accepted')) ); and: create table applicationchanges ( applicationchange_id int not null, application_id int not null, applicationchange_type varchar(64), applicationchange_datetime date not null, primary key (applicationchange_id), foreign key (application_id) references applications(application_id...

parsing - simple html dom parser and pagination -

i use simple html dom parser parse website, , have encountered problem handling pagination on website. actual code parse 1 page, , i'd parse pages: <?php include ('simple_html_dom.php'); $url = file_get_html('http://www.ecran-portable.net/268-ecrans-pc-portable'); foreach($url->find('.product-name') $produit) echo $produit->plaintext . '<br />'; ?>

use javascript/jquery/PHP to call automatically img link 1.jpg, 1.1.jpg, 1.2.jpg, 2.jpg, 3.jpg ... instead call them in each links -

i'm using fancybox , display gallery call images <a class="fancyboxgallerybook1" data-fancybox-group="book1" href="http://www.domaine.com/wp-content/uploads/books/1-latest/1.jpg" title=""> <img class="fancyboxthumbnailsgallerybook1" src="http://www.domaine.com/wp-content/uploads/books/1-latest/01.jpg" alt=""/> </a> <a class="fancyboxgallerybook1" data-fancybox-group="book1" href="http://www.domaine.com/wp-content/uploads/books/1-latest/2.jpg" title=""> <img class="fancyboxthumbnailsgallerybook1" src="http://www.domaine.com/wp-content/uploads/books/1-latest/02.jpg" alt=""/> </a> ... can use javascript, jquery, php ... in page call images present in folder in ascending order, mean: 1.jpg, 1.1.jpg, 2.jpg, 3.jpg, 4.1.jpg, 4.2.jpg, ... automatically without set numbers in each links <a class=...

Why doesn't my Imagemagick convert consider the loop parameter? -

i'm using command: convert -delay 10 -loop 1 -density 300 myfile.pdf myfile.gif on windows 10 , works except loop parameter: if set 1 , infinite loop. what doing wrong? i did experiments varying -loop parameter 0 through 3 , using simple red frame followed blue frame follows: for in 0 1 2 3; echo i=$i ((d=80+i)) convert -delay $d -loop $i -size 256x256 xc:red xc:blue a.gif identify -verbose a.gif | grep -e "iter|delay" done results i=0 delay: 80x100 iterations: 0 delay: 80x100 iterations: 0 i=1 delay: 81x100 delay: 81x100 i=2 delay: 82x100 iterations: 2 delay: 82x100 iterations: 2 i=3 delay: 83x100 iterations: 3 delay: 83x100 iterations: 3 so, seems -delay parameter , -loop parameter are correctly set in gif file, although -loop omitted if 1 default anyway. i looked @ animated gif in osx using quicklook feature tap ␣ (spacebar) in finder , not respect -loop setting, however, if open gif in saf...

javascript - React / Redux component props from `connect` out of sync with store in click handler -

i ran interesting error in react/redux app unfortunately haven't been able reproduce. stack, looks props in redux-connected component somehow getting out of sync global store. the basic idea connected component has click handler dispatches action if prop set. somehow action got dispatched, in middleware action, global store shows state prop null . should possible in react/redux? reason can imagine else changes global store while click event handling enqueued or delayed. don't know enough react internals know if that's reasonable. below simplified version of app. there other parts of app dispatching setexample in response other events, i.e. routing. import react 'react' import { render } 'react-dom' import { createstore, applymiddleware } 'redux' import { provider, connect } 'react-redux' // reducer const defaultstate = { example: null } const setexample = example => ({ type: 'set_example', example }) const reducer ...

python - Using fillna() selectively in pandas -

i fill n/a values in dataframe in selective manner. in particular, if there sequence of consequetive nans within column, want them filled preceeding non-nan value, if length of nan sequence below specified threshold. example, if threshold 3 within-column sequence of 3 or less filled preceeding non-nan value, whereas sequence of 4 or more nans left is. that is, if input dataframe is 2 5 4 nan nan nan nan nan nan 5 nan nan 9 3 nan 7 9 1 i want output be: 2 5 4 2 5 nan 2 5 nan 5 5 nan 9 3 nan 7 9 1 the fillna function, when applied dataframe, has method , limit options. these unfortunately not sufficient acheive task. tried specify method='ffill' , limit=3 , fills in first 3 nans of sequence, not selectively described above. i suppose can coded going column column conditional statements, suspect there must more pythonic. suggestinos on efficient way acheive this? workin...

php - Wordpress Pulling in multiple posts that share the same category -

i'm trying pull in thumbnails posts come category id "theme 01" aka id 117 , category called "ingredients" aka id 46. far got work want pull in posts match "theme 01" , "recipes". posts match "theme 01" , "chef" etc. idea. tried adding category id array no luck. <?php $my_query_args = array('posts_per_page' => 6, 'tax_query' => array( array( 'taxonomy' => 'category', 'field' => 'id', 'terms' => array( 117, 46, 65 ), 'operator' => 'and' ) ) ); $my_query = new wp_query( $my_query_args ); if( $my_query->have_posts() ) : while( $my_query->have_posts() ) : $my_query->the_post(); ?> <li> <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(array(46,65)); ?></a> </li> <?php endwhi...

c++ - What is array decaying? -

what decaying of array? there relation array pointers? it's said arrays "decay" pointers. c++ array declared int numbers [5] cannot re-pointed, i.e. can't numbers = 0x5a5aff23 . more importantly term decay signifies loss of type , dimension; numbers decay int* losing dimension information (count 5) , type not int [5] more. here cases decay doesn't happen . if you're passing array value, you're doing copying pointer - pointer array's first element copied parameter (whose type should pointer array element's type). works due array's decaying nature; once decayed, sizeof no longer gives complete array's size, because becomes pointer. why it's preferred (among other reasons) pass reference or pointer. three ways pass in array 1 : void by_value(const t* array) // const t array[] means same void by_pointer(const t (*array)[u]) void by_reference(const t (&array)[u]) the last 2 give proper sizeof info, while fi...

html - show div in the center of current viewport on mobile devices -

Image
how show div in center of current viewport? asking mobile devices, because problematic. for example, have 2 buttons show same div. 1 @ top of page, , 1 @ bottom. page's height 2 viewport heights in total. if padding-top of presented div 40px, div not visible when bottom button being pressed. solution isn't flexible enough mobile devices. solution recommend? diagram: if set padding-top 40px, green div appear @ top of page (as shown) if bottom red button pressed, green div appear @ top, 40px it. isn't visible user. should appear 40px top of second viewport (the screen users sees.) hope helps. use position: fixed . function togglediv() { var div = document.getelementbyid('togglable'); if (div.style.display !== 'none') { div.style.display = 'none'; } else { div.style.display = 'block'; } }; #container-parent { position: absolute; background-color: #eee; height: 95%;...

node.js - Bitnami Meanstack Mongoose Connection -

i created simple service in ubuntu 16.04 mongo db node , express return data angular 2 app. i have file called server.js connects local mongodb instance database called game , collection called players. works fine installed on local machine. trying deploy bitnami's mean stack image on amazon ec2. (bleh mouth full). have set ports correctly according this guide , , can connect remotely. however, can't mongoose connect database. here code works on local machine. mongoose.connect('mongodb://localhost:27017/game'); router.route('/player') .get(function(req, res) { console.log(mongoose.connection.readystate); player.find({"player":user,"password":password},function(err, test) { if (err) res.send(err); res.json(test); }); }); and here adjusted code mean stack image mongoose.connect('mongodb://root:"my-root-password@127.0.0.1:27017/game'); router.route('/player') .get(fun...

python - Cannot get pixelDelta from QWheelEvent in Qt5 -

i upgraded qt4 qt5 (pyqt, specific) , qwheelevent broke me - returns empty pixeldelta(), phase @ 2 (default). on win 7, warning phases shouldn't apply me. when run code: from pyqt5 import qtwidgets class q(qtwidgets.qlabel): def wheelevent(self, event): print(event.pixeldelta()) app = qtwidgets.qapplication([]) w = q() w.show() app.exec_() scrolling prints 'pyqt5.qtcore.qpoint()' without coordinates. can do? from qt5 docs qwheelevent : there 2 ways read wheel event delta: angledelta() returns delta in wheel degrees. value provided. pixeldelta() returns delta in screen pixels , available on platforms have high-resolution trackpads, such os x. there no pixeldata in qt4. has delta , , equivalent qt5 method angledelta .

python - Displaying an image using a class on pygame -

i new using pygame , trying make class display image on pygame. want make can put multiple images onto screen , move them around screen. @ moment want display image on screen using format. can show me code , explain why? import pygame import time import random pygame.init() display_width = 1000 display_height = 750 gameplay = false gamedisplay = pygame.display.set_mode((display_width,display_height)) clock = pygame.time.clock() #starts auto clock updater background_image = pygame.image.load("image/background.jpg").convert() gamedisplay.blit(background_image, [0, 0]) enimg = pygame.image.load('image\enemy.gif') class enemy(pygame.sprite.sprite): def __init__(self,dx,dy,image): pygame.sprite.sprite.__init__(self) self.rect = pygame.image.load('image\enemy.gif') self.image = image self.rect.x = dx self.rect.y = dy def update(self): pass while not gameplay: event in pygame.eve...

Haskell accessors for non-existing records -

i learning haskell , discovering 'accessors' data members. let's assume have dummy 2d vertex information, 1 type has color, other has texture coordinate (tc): data svertex = vertexc (float, float) int | vertextc (float, float) (float, float) deriving(show) one tedious way create accessors records write functions patterns: position (vertexc (x,y) c ) = (x,y) position (vertextc (x,y) c ) = (x,y) tc (vertextc _ tc) = tc color :: svertex -> int color (vertexc _ c) = c now, positive feature add accessors ('color' , 'tc') ones don't have 'color' or 'tc' : position (vertexc (x,y) c ) = (x,y) position (vertextc (x,y) c ) = (x,y) -- no header, here... still works tc (vertextc _ tc) = tc tc (vertexc _ _) = (0,0) -- returns if field doesn't exist color :: svertex -> int color (vertexc _ c) = c color (vertextc _ _) = 0 -- return if field doesn't exist it allows me give default 0 values vertices don'...

php - Converting json data do google chart -

Image
so i'm using curl in php , access json object , data it. getting data, not understand how can draw chart information. here php script: <?php // generated curl-to-php: http://incarnate.github.io/curl-to-php/ $ch = curl_init(); curl_setopt($ch, curlopt_url, " https://xxx.xxx.pt/api/objgroupinfo/16jcr05g37kplklz"); curl_setopt($ch, curlopt_returntransfer, 1); curl_setopt($ch, curlopt_customrequest, "get"); $headers = array(); $headers[] = "x-apikey: xxxxxxxxxxxxxxxxxxxxxxxx"; curl_setopt($ch, curlopt_httpheader, $headers); curl_setopt($ch, curlopt_ssl_verifypeer, false); $result = curl_exec($ch); if (curl_errno($ch)) { echo 'error:' . curl_error($ch); } curl_close($ch); // generated curl-to-php: http://incarnate.github.io/curl-to-php/ $ch = curl_init(); curl_setopt($ch, curlopt_url, " https://xxx.xxxxx.pt/api/dataout/iafhaftiuzrcje5q.json"); curl_setopt($ch, curlopt_returntransfer, 1); curl_setopt($ch, curlopt_customreq...

casting - Type 'Any' has no subscript members AND Value of type 'Any' has no member 'Count' -

i receiving following 2 errors below when creating array of strings in swift 3.0 on xcode8: value of type 'any' has no member 'count' original code: return tododata.count "fixed" with: return (tododata anyobject).count type 'any' has no subscript members original code: if let text = tododata[indexpath.row] { see full code below: let tododata = userdefaults.standard.value(forkey: "todosarray") override func tableview(_ tableview: uitableview, numberofrowsinsection section: int) -> int { if let tododata = tododata { return tododata.count //error 1. } else { return 0 } } override func tableview(_ tableview: uitableview, cellforrowat indexpath: indexpath) -> uitableviewcell { let cell = tableview.dequeuereusablecell(withidentifier: "reuseidentifier", for: indexpath) as! tableviewcell if let tododata = tododata { if let text = tododata[indexpath.row] { //error 2...

python - Addition of data in queue -

i think of queue line person came @ first served first. other people join him @ back. wrote following implementation in python achieve that: class queue: def __init__(self): self.item = [] def enqueue(self,value): self.item.append(value) def dequeue(self): return self.item.pop(0) def size(self): return len(self.item) def isempty(self): return self.item == [] but when checked online tutorials, found following implementation queue: class queue: def __init__(self): self.items = [] def isempty(self): return self.items == [] def enqueue(self, item): self.items.insert(0,item) def dequeue(self): return self.items.pop() def size(self): return len(self.items) according online implementation, item added first. intuition says item should added of list (appended) , removed front (remove first item). want know form correct, , if incorrect thing not understanding ? ...

ruby - Rails 5, Simple Fields For with Cocoon gem for nested resources -

i trying learn how use namespaced routes. i have model called proposal , called innovation. associations are: proposal has_many :innovations accepts_nested_attributes_for :innovations, reject_if: :all_blank, allow_destroy: true innovation belongs_to :proposal in routes.rb, have: resources :proposals resources :innovations in proposals controller, have: def new @proposal = proposal.new @proposal.innovations.build # authorize @proposal end def edit @proposal.innovations_build unless @proposal.innovations end in proposal form, trying nest form fields innovation model. <%= f.simple_fields_for [@proposal, @innovation] |f| %> <%= f.error_notification %> <%= render 'innovations/innovation_fields', f: f %> <% end %> <%= link_to_add_association 'add novel aspect', f, :innovations, partial: 'innovations/innovation_fields' %> </div> whe...

r - Document Term Matrix throwing error: Error in simple_triplet_matrix -

i creating word cloud based on tweets various different sports teams. code executes 1 in 10 times: library(tm) library(snowballc) twt.mumbai <- searchtwitter('mumbai',n=50, lang = "en") twt.london <- searchtwitter('london',n=50, lang = "en") save(list="twt.mumbai", file="mumbai.rdata") save(list="twt.london", file="london.rdata") load(file = "mumbai.rdata") load(file = "london.rdata") tweets.mumbai <- lapply(twt.mumbai, function(t) {t$gettext()}) tweets.london <- lapply(twt.london, function(t) {t$gettext()}) data.sourcem <- vectorsource(tweets.mumbai) data.sourcel <- vectorsource(tweets.london) data.corpusm <- corpus(data.sourcem) data.corpusl <- corpus(data.sourcel) #preprocessing #removepunctuation data.corpusm <- tm_map(data.corpusm, content_transformer(removepunctuation), lazy = true) data.corpusl <- tm_map(data.corpusl, content_transformer(remo...

linux - count the number of attempts from an output -

this question in regard output of script, because need know how many attempts made.. ## guess right number ## #!/bin/bash clear while : echo "enter guessing number:" read num if [ $num -eq 47 ]; echo "that right number" break elif [ $num -le 47 ]; echo "print higher number" elif [ $num -ge 47 ]; echo "print lower number" fi done and following output be: enter guessing number: 23 print higher number enter guessing number: 34 print higher number enter guessing number: 45 print higher number enter guessing number: 47 that right number how write code display line stating how many attempts made reach correct answer? you aren't far off. this on bash incrementing variable called $attempts (which starts @ 1), each time wrong answer attempted. the loop message uses $lastmsg variable make simple display relevant prompt each time. #!/bin/bash guessno=47 ...

php - Query Checklist and post multiple results to table in mysql -

hello guys im trying post several checklist values single table in database takes 1 single value table... im doing this: the form: <?php foreach($users $user): ?> <input type="checkbox" name="tipoinsertos" value="<?= $user['tipoinsertom']; ?>"> <?= $user['tipoinsertom']; ?> <?php endforeach; ?> and post form: $data = array('tipoinsertos' => $_post['tipoinsertos']); try { $dbh = new pdo("mysql:host=$servername;dbname=$dbname", $username, $password); $dbh->setattribute(pdo::attr_errmode, pdo::errmode_exception); $query = "insert barrasinternas ( tipoinsertos ) values (:tipoinsertos )"; $sth = $dbh->prepare($query); $sth->execute($data); echo "&iexcl;a&ntilde;adida exitosamente!"; } catch(pdoexception $e) { echo $sql . "<br>" . ...

javascript - how "document.createElement" works to "display" property -

i found interesting phenomenon , performs different in firefox chrome. open browser devtool f12 , type this. var span=document.createelement("span"); document.defaultview.getcomputedstyle(span).display; it returns "block" in firefox , "" in chrome . first time met case in firefox , amazed me result "block"! however, when document.body.appendchid(span) ,it ok. i searched in mdn withot harvest in end.i guess document.defaultview.getcomputedstyle influenced browser's rendering engine.the "display" property set after element has rendered rendering engine dom tree.and gecko(firefox) gives default value "block" while webkit(chrome) sets "". can give more detailed explaination? that's because spec not specify whether elements outside dom have computed styles or not. firefox thinks do. , affected stylesheets in document. console.log(getcomputedstyle(document.createelement('span...

linux - Reading and comparing column in .txt file in bash -

i got .txt file content is 5742060626,ms.pimpan tantivaravong,female 5742065826,ms.kaotip tanti,female - create interface script add list in file first, have compare input id exitsting id in list. use cut command read 1st column of .txt file. but,i got problem when trying compare it. here code. - !/bin/bash # datafile='student-2603385.txt' while read p; if [ "$id" == (echo $p | cut -d, -f1) ] echo 'duplicate id' fi done <$datafile - could suggest me, how should do? thank you your script has numerous quoting bugs, quote variable expansion when variable contains file name, expected when want avoid word splitting , pathname expansion shell. letting aside, in if [ "$id" == (echo $p | cut -d, -f1) ] : you need command substitution, $() around echo ... | cut ... , not subshell () you need quotes around $() prevent word splitting (and pathname expansion) == bash-ism, not defined posix, reminder try use [[ as p...

spring mvc - How to configure thymeleaf-extras-springsecurity4 without xml? -

i'm trying use code snippet in view, content shown regardless of user's role. <div sec:authorize="hasrole('role_admin')"> <!-- admin content --> </div> add build.gradle following dependency: compile("org.springframework.boot:spring-boot-starter-security") you must add spring security configuration in example: @configuration public class springsecurityconfig extends websecurityconfigureradapter { @autowired public void configureglobal(authenticationmanagerbuilder auth) throws exception { auth .inmemoryauthentication() .withuser("admin").password("admin").roles("admin", "user") .and().withuser("user").password("user").roles("user"); } @override protected void configure(httpsecurity http) throws exception { http.authorizerequests().antmatchers(...

Jsfiddle in Key Map: Vim Mode. Is there a shortcut to switch between editor textarea -

Image
i love jsfiddle much. found out allow using in vim mode. all favorite short-cut keyboards there except switching between editor textarea. in vim use ctrl + w switch. when use in jsfiddle, terminate browser tab. i have search in google cannot find solution. if there any, please me. thanks.

java - in a class cant make input array equal to another array -

so have code going convert strings integers, quicksort it, , turns integers strings. code works no problem want try put integers strings same input array instead of making whole other array, did not work, didnt change input. instead made int string array method return me in new array, when debugged how wanted be. , made input array equal new array put in, , return whole bunch of jumbled letters? public class runner { static void singleletterarrayalphabeticalorganizer(string[] a) { int[] number = stoianditos.singlestoi(a);//makes string integer quicksort.sort(number,0,a.length-1);//quicksorts integers string[] a1 = stoianditos.singleitos(number);//makes integers strings // tried put intead of a1 gave me same result = a1; //problem area: suppoused make input given same a1 dont have make new array in main class(if thats im running it) instead of using exsisting array } } you cannot change parameters passed in method. if want pass sorted arr...

c# - error - "attempt to write a readonly database\r\nattempt to write a readonly database" -

i using sqlite database in wpf windows application. after installing windows application database inside folder this: static sqliteconnection dbconnection = new sqliteconnection(@"data source=c:\program files (x86)\hedronix\qscan\test.s3db;"); but when trying access database location of windows application showing error. how can solve that? in situation, how can set default connection string accessing sqlite database after install application on local computer?

How do upload an Image to django from angularjs client using django rest framework? -

i can't figure out how should post image angularjs. i'm newbie in django , django-rest-framework. in advance. models.py class userimages(models.model): owner = models.foreignkey('auth.user', related_name='userimages') user=models.foreignkey(profile) # highlighted = models.textfield(default=none,blank=true,null=true) likes=jsonfield(null=true,blank=true) image=models.imagefield() pub_date=models.datetimefield(default=now) def __str__(self): return str(self.owner) serializers.py class imageserializer(serializers.modelserializer): owner = serializers.readonlyfield(source='user.username') image_url = serializers.serializermethodfield('gett_image_url') class meta: model=userimages fields=('id','owner','image','likes','image','image_url','owner') def gett_image_url(self,obj): return obj.image.url views.py(what i've tried) class profile_li...

java - Error when adding "spring-boot-starter-data-jpa" dependency to Spring project -

i'm practising spring spring tool suite. i've been trying connect project database. however, whenever add "spring-boot-starter-data-jpa" dependency pom.xml project won't start , following errors. error doesn't occur once remove dependency. have no idea why happening. here following errors: org.springframework.context.applicationcontextexception: unable start embedded container; nested exception org.springframework.beans.factory.beancreationexception: error creating bean name 'tomcatembeddedservletcontainerfactory' defined in class path resource [org/springframework/boot/autoconfigure/web/embeddedservletcontainerautoconfiguration$embeddedtomcat.class]: initialization of bean failed; nested exception org.springframework.beans.factory.beancreationexception: error creating bean name 'serverproperties' defined in class path resource [org/springframework/boot/autoconfigure/web/serverpropertiesautoconfiguration.class]: initialization of bean f...

ios - subViews only displayed when bezierPath is created using origin =0,0 and size = size of subView -

i trying improve uikit skills working on simple block breaking game. i.e view have 9 sub-views on top (each corresponding block) , have paddle , ball ball breaking blocks. i have blockview class sub-class of uiview following init , drawrect: methods. noticing first block sub-view displayed when drawrect contains first statement (i.e bezierpath created framerect property) blockviews displayed when drawrect called when bezierpath created cgrect origin = 0,0 , appropriate size. i have confirmed self.framerect has origin = column blocksize, row blockheight , appropriate size. could please explain why bezierpath should created wth origin = 0,0 , not @ right offset 0,0? is because of how drawrect called? i.e co-ordinate system has been translated when drawrect called on sub-view corresponding blockview -(instancetype) initwithframe:(cgrect)frame andcolor:(int) color { self = [super initwithframe:frame]; if (self) { self.color = color; self.fram...

Visual Studio 2015 Enterprise Update 3 missing UWP and UAP projects -

Image
i installed visual studio 2015 enterprise update 3 windows 10 sdk. all sdk installed fine can't create uwp or uap project because visual studio has not these templates. i reinstalled , restored visuals studio many times. installed windows 10 sdk , emulator seperately setup file. can't see uwp or uap templates in visual studio. visual studio doesn't see windows 10 sdk in window. help me please. you should install visual studio 2017, because in vs 2015 cannot target on creator update of windows 10 sdk or higher, source of problem.

java - use jstl with spring security -

i totally new java ee (spring, jstl, ...). managing make login page spring 4 , jstl denied page 403 failed show due parsing error. don't know reason why unable parse jstl tag, remove , works properly, of course, can not object model , show value. thanh nhut error : whitelabel error page application has no explicit mapping /error, seeing fallback. sun nov 06 14:23:20 ict 2016 there unexpected error (type=internal server error, status=500). exception parsing document: template="403", line 1 - column 18 controller : public class logincontroller { @getmapping("/") public string index() { return "welcome home page!"; } @requestmapping(value = "/403", method = requestmethod.get) public modelandview accesssdenied() { modelandview model = new modelandview(); //check if user login authentication auth = securitycontextholder.getcontext().getauthentication(); if (!(...

amazon - Riak "Node is not reachable" -

i using riak 2.1.4 series in amazon. totally new , have couple of questions : i deployed instance of riak. deployed in ec2 instance ? do need app.config , vm.args files riak configuration. think if nodename available in riak.conf thats enough isnt ? i see ip address of instance different once configured in riak.conf fine ? i.e nodename example instance name ec2-35-160-xxx-xx.us-west-2.compute.amazonaws.com , riak.conf has riak@172.31.xx.xx only change in riak.conf ring_size = 64 erlang.distribution.port_range.minimum = 6000 erlang.distribution.port_range.maximum = 7999 transfer_limit = 2 search = on this configuration exists in each instance. missing here ? can give sample configuration 5 node cluster ? kindly me resolve issue. i deployed instance of riak. deployed in ec2 instance ? not sure asking here do need app.config , vm.args files riak configuration. think if nodename available in riak.conf thats enough isnt ? the 'ap...

ios - UIScrollView starts out halfway down content -

Image
this question has answer here: why uiscrollview leaving space on top , not scroll bottom 6 answers i trying implement uiscrollview in similar fashion featured banner @ top of app store. adding 3 views , paging through them using code below. when controller loads however, started content down bit. if tap on view content goes should be. how can fix this? i've trying setting content offset 0, i've tried manually scrolling origin rect, , i've tried putting views in content view, nothing has worked. featuredscrollview.alwaysbouncevertical = false featuredscrollview.contentsize = cgsize(width: 3 * featuredscrollview.frame.size.width, height: featuredscrollview.frame.size.height) let contentview = uiview(frame: cgrect(x: 0, y: 0, width: 3 * featuredscrollview.frame.size.width, height: featuredscrollview.frame.size.height)) featuredscrollview.ad...

dcos - DC/OS Vagrant VMs cannot access the GUI after vagrant halt and vagrant up -

i have installed dcos-vagrant 1 master , 1 slave node using: vagrant m1 a1 boot . however, after stoping cluster vagrant halt m1 a1 boot , restarting vagrant m1 a1 boot cannot access gui @ https://m1.dcos . how stop cluster without having destroy ( vagrant destroy -f ) , create scratch? that functionality not supported: https://dcosjira.atlassian.net/browse/vagrant-7

c# - What is a NullReferenceException, and how do I fix it? -

i have code , when executes, throws nullreferenceexception , saying: object reference not set instance of object. what mean, , can fix error? what cause? bottom line you trying use null (or nothing in vb.net). means either set null , or never set @ all. like else, null gets passed around. if null in method "a", method "b" passed null to method "a". the rest of article goes more detail , shows mistakes many programmers make can lead nullreferenceexception . more specifically the runtime throwing nullreferenceexception always means same thing: trying use reference, , reference not initialized (or once initialized, no longer initialized). this means reference null , , cannot access members (such methods) through null reference. simplest case: string foo = null; foo.toupper(); this throw nullreferenceexception @ second line because can't call instance method toupper() on string reference pointing null ....