Posts

Showing posts from January, 2015

java - StringOutofBoundsException -

when put in while loop n, out of bounds exception appears, if take out it's perfect. i'm add data array later on, it's producing error .... string day = date.substring(0, spacepos); the exception follows: exception in thread "main" java.lang.stringindexoutofboundsexception: string index out of range: -1 @ java.lang.string.substring(unknown source) @ helloworld.main(helloworld.java:21) scanner userinputscanner = new scanner(system.in); // i/o stream string months[] = {"jan","feb","mar","apr","may","jun","jul","aug","sept","oct","nov","dec"}; // months compare int n = userinputscanner.nextint(); while(n != 0) { system.out.print("enter data: "); string date = userinputscanner.nextline(); // input , store data string output; ...

ios - How can I set a UILabel to change after a certain amount of time? -

i trying make uilabel change every 24 hours , have tried using method article: changing uilabel after specific time not know how save time app knows timer has been running 24 hours. should using different approach? maybe using date , when date changes change uilabel? problem not want people able advance clocks or change dates of devices see uilabel changes to. goal trying make quote of day app. please help. what looking querying ntp (network time protocol) service. query ntp save result (user defaults simplest) set timer (you check every hour) on timer fire re query ntp , validate has passed 24 hours change label

Finding difference between strings in Javascript -

i'd compare 2 strings (a before , after) , detect , changed between them. for change, want know: starting position of change (inclusive, starting @ 0) ending position of change (inclusive, starting @ 0) relative previous text the "change" assume strings change in 1 place @ time (for example, never " b il l " -> " k il n "). additionally, need start , end positions reflect type of change: if deletion, start , end position should start , end positions of deleted text, respectively if replacement, start , end position should start , end positions of "deleted" text, respectively (the change "added" text) if insertion, start , end positions should same; entry point of text if no change, let start , end positions remain zero, empty change for example: "0123456789" -> "03456789" start: 1, end: 2, change: "" (deletion) "03456789" -> "0123456789" start...

asp.net mvc - How to call a jquery function from an ActionResult in the Controller using Mvc? -

public actionresult deletecart(int id) { cartlist = (list<product>)system.web.httpcontext.current.application["cartlist"]; product p = cartlist.singleordefault(item => item.productid == id); cartlist.remove(p); system.web.httpcontext.current.application["cartlist"] = cartlist; int cartlen = cartlist.count; system.web.httpcontext.current.application["cartlen"] = cartlen; //*** xxx *// return scriptmanager.registerstartupscript(this.page, this.gettype(), "script", "viewkart();", true); } i want view cart whenever delete items it. cart can viewed calling jquery function followed delete actionresult in controller. gettinmg error in this.page argument of script register method in controller. jquery function called follows : <script type="text/javascript"> //alert("hello"); function viewkart() { // alert(...

Unable to build project in Android Studio -

i imported project android studio eclipse. building in eclipse. @ end of importing process got error: gradle project sync failed. basic functionality not work in gradle console following error: error:failed find: com.android.support:appcompat-v7:20.+ i have installed google support repository mentioned in other places. this build.gradle: apply plugin: 'com.android.application' android { compilesdkversion 20 buildtoolsversion "21.0.0" defaultconfig { applicationid "com.entujn.demo" minsdkversion 10 targetsdkversion 19 } buildtypes { release { runproguard false proguardfiles getdefaultproguardfile('proguard-android.txt'), 'proguard- rules.txt' } } } dependencies { compile 'com.google.android.gms:play-services:+' compile 'com.android.support:appcompat-v7:20.+' compile files('libs/commons-lang3-3.3.2.jar') } local.properties: sdk.dir=/home/p...

memory management - Where does the Java store the final member and static member? -

i know static method , non-static method of class store in method area. in doubt java stores final variable(constant) members , static variable members of object. for example, class a{ private final int = 1; private static int b = 2; private static final int c = 3; //other codes... } i wonder java store a,b,c in memory. heap,stack,or method area? ======update===== hey,thanks help.and please allow me share link components of jvm: http://www.artima.com/insidejvm/ed2/jvm2.html inside java virtual machine instance, information loaded types stored in logical area of memory called method area .memory class (static) variables declared in class taken method area. all instance variables stored in heap area , including final members.

jquery - How can I submit a multipart form via Ajax into web2py? (form includes file(s)) -

i have process arbitrary file, not related model. so, let's want full control on form , data sends. have "manually built" form in controller: the_form = form(input(_type='file', _name='image'), input(_type='text', _name='sometext'), _action=url('controller', 'upload_test'), _method='post') in view, display form normally, with, let's {{=the_form}} then, using simple jquery, try submit form via ajax. however, i've encountered following problems: the file doesn't seem through server; eventually i've found there request._body.file appears contain uploaded file, "access denied" when trying read (it's temporary file); , doesn't feel right using it. why doesn't file through server side in regular request.vars or request.post_vars ? appreciated. thank you. i managed resolve myself. "trick", if may so, se...

c# - mvc5 model which is posted with html.beginform is missing some properties -

i have model i'm using in view: using (var db = new fieldsavercontext()) { aspnetuser user = (from p in db.aspnetusers p.id == id select p).include(m => m.aspnetroles) .first(); model.auser = user; list<aspnetrole> roles = (from r in db.aspnetroles select r).tolist(); model.rolelist = roles; list<listid> ids = (from l in db.listids select l).tolist(); model.listidlist = ids; list<viewerlist> viewerlists = (from v in db.viewerlist select v).tolist(); model.viewerlist = viewerlists; } this how view looks like: @using (html.beginform("edit", "users")) { <div class="container containeredit"> <div class="col-md-9"> <div class="col-md-6"> <div class="form-group"> @html.labelfo...

python - Invalid syntax for except ValueError -

when run code (python 3.3): counter=0 score=0 import random = random.randint(1,25) b = random.randint(1,25) c=a+b try: answer=int(input("what "+str(a)+" + "+str(b)+" ? ") if answer == c: score=score+1 print("well done!") print("your score "+str(score)+".") print("") counter = counter + 1 else: print("thats wrong. correct asnwer is: "+str(c)+".") print("your score "+str(score)+".") print("") counter = counter + 1 except valueerror: print("sadas") i says "invalid syntax" , highlight colon "if answer == c:" red. you missing closing parenthesis: answer=int(input("what "+str(a)+" + "+str(b)+" ? ") # ^ ^ ^? # | \----...

protractor - Are elementfinder promises resolved on declaration? -

i know elementfinder s promises i'm not sure how promise behaves if define elementfinder s in beginning of page object. looking @ example: var eventheader = function (context) { this.eventname = this.moduleroot.element(by.css('.event-name')); this.venuename = this.moduleroot.element(by.css('.venue-name')); this.eventtime = this.moduleroot.element(by.css('.event-time')); this.eventdate = this.moduleroot.element(by.css('.event-date')); this.marketname = this.moduleroot.element(by.css('.market-name')); }; will protractor try resolve promises when page objects initialised? i guess other option define locators in beginning , create methods return elementfinder itself. the element finders not execute until call function on them. have make sure elements on page when call click() , sendkyes() , etc.

xml - How to add the border on editext programmatically in android -

i working on demo app require set the border width , border color programmatically. i know can done using xml drawable want these @ run time. know have these creating xml , use requirement such dynamic have these stuff @ runtime instead of below approach. border_edittext.xml <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" > <solid android:color="#ffffff" /> <stroke android:width="1dip" android:color="#000000"/> </shape> setting drawable. edittext foo = (edittext)findviewbyid(r.id.edittext); foo.setbackgroundresource(r.drawable.border_edittext); thanks in advance. shape drawables came mind first. android guide has details on this. int x = 10; int y = 10; int width = 300; int height = 50; mdrawable = new shapedrawable(new rectshape()); // rectangle border mdrawable.getpaint().setcolor(0xff74ac23); // set colo...

c - My while loop with char doesnt work. Some help please -

so have peace of code: int choice_dig; char choice_dup; printf("welcome mystery number game.\n"); printf("how many digits want use (3 5)?"); scanf("%d", &choice_dig); while (choice_dig<3 || choice_dig>5) { printf("\nplease choose number between 3 , 5.\t"); scanf("%d",&choice_dig); } printf("\ndo want allow duplicate digits (y or n)?"); scanf(" %c", &choice_dup); while (choice_dup != 'y' || choice_dup != 'n') { printf("\ninvalid entry. please choose y yes , n no.\t"); choice_dup = getchar(); getchar(); } the choice_dup assinged char var @ start of main. when run good. when press y or n cant recognize , loop never ends. no matter type. can me , expain me wrong? the loop run forever because while (choice_dup != 'y' || choice_dup != 'n') evaluate true . you wanted: while (choice_dup != 'y' && choice_dup != ...

c# - moq callback makes linq throw exception -

i using moq , ef6. i need query table , if there less 5 dates in table need add more. so, in code: public void fillpartylist(observablecollection<party> argpartylist) { argpartylist.clear(); using (ipartytrackerdataaccess localdb = locator.resolve<ipartytrackerdataaccess>()) { initializedates(localdb); var locallist = (from templist in localdb.parties templist.partydate >= datetime.now.date select templist); foreach (party currentparty in locallist) { argpartylist.add(currentparty); } } } inside "initializedates" query database see how many dates there , add enough make 5. there rules around creating dates [e.g. on fri or sat, etc] not trivial. then, when method comes full list database , add parameter. my problem comes when try test this. here's test. public...

java - android app stop variable from resetting - lifecycle -

i have app has few screens. main screen automatically opens "new" screen if it's first time user opens app. set boolean variable (on main screen) keeping track of this. the intention if user goes main screen, code opens "new" screen can skipped. the problem variable keeps getting reset on oncreate. so, added code use sharedpreferences. this works; however, want clear variable when app exits. (i want "new" screen open every time app opens first time). so, looking @ lifecycle tried both onstop , ondestory. sharedpreferences cleared but... not when app exited; when "new" screen appears. am looking @ lifecycle wrong? there sort of global variable can declare lives while app open? this functionality requirement, cannot change it. you should use onsaveinstancestate , onrestoreinstancestate, keep boolean alive if activity calls oncreate not if exit , come later. see answer implementation: saving android activity state using ...

zeromq - Which one is preferable : zmq_send or zmq_msg_send? -

i discovering zeromq, , understand zmq_send sends buffer , zmq_msg_send sends zmq_msg_t message. seems me 2 different ways of doing same thing (both can send multi-part messages, etc). what advantages of using zmq_msg_t structs? advantage code works on bit lower-level, closer metal, , saves few cpu-cycles, .zmq_send() wrapper spends on preparing zmq_msg_t struct , passing forward zmq-internal messaging processing .zmq_msg_send() in 1 step.

java - Why do gaps appear in a List backed by @ManyToMany with @OrderColumn -

we have queues of ticket objects persisted database. our entity containing queues looks this: @entity public class storequeuecollection { @id private int storeid; @manytomany(fetch=fetchtype.lazy) @ordercolumn private list<ticket> mainqueue = new arraylist<ticket>(); @manytomany(fetch=fetchtype.lazy) @ordercolumn private list<ticket> cancelledqueue = new arraylist<ticket>(); .. etc we have 1 operation moves ticket 1 queue (call changestatus), , adds new ticket end of queue (call newticket). when 2 operations interleave on same queue, operations work, end "gap" in our queue. in database, looks missing index in order column of table, this: 0, 1, 2, 4. when queue loaded java, missing index becomes null element in queue. we using pessimistic locking on storequeuecollection object prevent inconsistent interleaved updates, it's not working expect. logging, see strange sequences this: - changeticketst...

knockout.js - Between two numbers validation in knockout? -

i trying write validation performs similar between . i having textbox , want show error message if failed enter other given range . viewmodel : var vm = function viewmodel() { var self = this; self.mainamount=ko.observable(); self.amount1=ko.observable(2); // dynamic self.amount2=ko.observable(100) self.validation = ko.validatedobservable({ self.mainamount.extend({required:true,number:true,min:self.amount1,max:self.amount2}) }); } i tought min , max acts between i'm wrong , unable work out . i gave tought try validator:{validation:function(param1,param2,param3){ //logic here }, message:'enter between these ..', params: // here unable pass multiple paramters } reference : click here . in article @ last there custom way things confused in return statement inside computed . any appreciated .

delphi - Some API's -MkParseDisplayNameEx, ADsGetObject- are not working well for LDAP on "windows server 2008 64bit" -

i have code running in windows platforms (xp 32bit, xp 64bit, server 2003 32bit, server 2008 32bit, windows 7 32bit), can't run on "windows server 2008 r2 64bit" api causes exception can't handled: "application defined exception (code 0x0eedfade) @ 0x7773c42d" and code used: function getobject(apath: string): idispatch; var moniker: imoniker; eaten: integer; bindcontext: ibindctx; dispatch: idispatch; begin result := nil; olecheck(createbindctx(0, bindcontext)); olecheck(mkparsedisplaynameex(bindcontext, pwidechar(widestring(apath)), eaten, moniker)); olecheck(moniker.bindtoobject(bindcontext, nil, iunknown, dispatch)); result := dispatch; end; the exception appears in line : olecheck(mkparsedisplaynameex(bindcontext, pwidechar(widestring(apath)), eaten, moniker)); i tried code none-handled exception appears: function getobject(apath: string): idispatch; begin adsgetobject(apath, idispatch, result); end; i passing sa...

genetic algorithm - Simple GA very fast convergence -

i'm trying apply ga solve problem , having couple questions. first question selection - i've seen in many implementations population sorted according score/fitness prior selection. necessary? example in tournament selection individuals should picked uniformly sorting seems have no meaning. or lets consider roulette wheel selection. following implementation sorting again seems unnecessary (pseudo code): totalfitness = sum individuals i.fitness roulettevalue = totalfitness * random 0.0 1.0 selected = null = 0; while roulettevalue >= 0.0 selected = individuals[i++] roulettevalue -= selected.fitness return selected so necessary sort population selection? another question quick convergence: i'm trying out simple ga crossover probability 0.9, mutation probability 0.01, population size 30 , initial population contains 'very-good-solution' (known). crossover produces 2 offsprings always, 1 iteration follows (pseudo code): for = 0 population-size mot...

c# - Do closures break serialization -

today faced serializationexception refered anonymous inner class +<>c__displayclass10 stating not serializable, when iis tried store session in asp.net state service: type 'xyz.generalunderstandingtests+aserializabletype+<>c__displayclass10' in assembly 'xyz, version=1.2.5429.24450, culture=neutral, publickeytoken=null' not marked serializable. i looked lambdas in code , found quite few, of them not new , did never have issues in serialization. noticed had built in new lambda expression "happened" build closure. searching stackoverflow closure serialization found q&as reveal closures cannot serialized in other languages such php *) did not manage find such statement c#. have been able build simple example seems confirm closures not serializable whereas "normal" functions are [testfixture] public class generalunderstandingtests { [serializable] private class aserializabletype { private readonly fu...

c# - Unable to delete a desktop folder -

problem: unable delete folder (including contents) within desktop folder programatically c#. if copy value of desktopdestinationpath , paste windows explorer, can open folder (conclusion, path valid) test - directory.exists(desktopdestinationpath) - returns true , drop code block (conclusion, path valid) directory.delete(desktopdestinationpath, true) - throws exception (conclusion, path no longer valid) if copy path value exception , paste windows explorer, can open folder (conclusion, path valid) what have tried: build, rebuild, clean solution, restart visual studio. also, if delete folder manually , run code, folder built. however, when run second time, exception. result: puzzled , post. sorry if put detail. open solution , criticism on how posted (both me learn) in advance! visual studio info toward bottom of entry. using: microsoft visual studio premium 2013 (c#). my code: // preceded other code in method if (directory.exists(desktopdestinationpath)) // deskt...

zurb foundation - Display error if no checkbox is checked in checkbox group -

how display error message foundation 5's abide html5 form validation library when no checkboxes checked within same checkbox group? you have write own abide validator, quite simple. working example: codepen link javascript $(document).foundation({ abide: { validators: { checkbox_limit: function(el, required, parent) { var group = parent.closest('.checkbox-group'); var min = group.attr('data-abide-validator-min'); var checked = group.find(':checked').length; if (checked >= min) { group.find('small.error').hide(); return true; } else { group.find('small.error').css({ display: 'block' }); return false; } } } } }); html <form data-abide> ...

ruby on rails - Using multiple has_many associations on one model -

i working in rails app company has_many orders. order has name , it. order can have_many television_spots, radio_placements, , newspaper_placements, data in these tables not same have split up. if order has_many radio_placements not have television_spots or newspaper_placements. question bad practice have has_many relationship on model if not exist?, better better make company have_many television_orders , television_order have_many television_spots? , company have_many radio_orders , radio_order have_many radio_placements, , on. think first option dryer using second strategy result in cleaner more understandable code app grows , data changes. it's not bad practice have has_many association not have models associated. real question object type radio_placements , television_spots , newspaper_placements should associated to. if should in fact related order model, place associations there. understanding of question/data shape appear want these relationships o...

Nancy/TinyIoC multiple concrete classes for single interface -

we have 2 auth methods different modules – userauthmodule , serviceauthmodule . we’ve created 2 base classes modules derive from. we’ve interfaced authproviders iauthprovider . have dependency in constructors should correct authprovider injected. however, can’t find way tell nancy/tinyioc concrete class use. here pseudo-code: abstract class userauthmodule : nancymodule { public userauthmodule(iauthprovider authprovider) // should userauthprovider concrete class } abstract class serviceauthmodule : nancymodule { public serviceauthmodule(iauthprovider authprovider) // should serviceauthprovider concrete class } here's example of 1 of concrete module's class declaration: public class accountmodule : userauthmodule we stuck: how register 2 concrete classes iauthprovider interface? name them, can’t figure out how nancy knows class inject when constructor injection. inside our bootstrapper have: container.register<iauthprovider, userauthprovider>(“userauth...

android - 4 rows of Buttons in LinearLayout fill screen width -

Image
i have vertical linearlayout 4 horizontal linearlayouts . each horizontal layout contains 4 buttons . want buttons in each horizontal linearlayout fill screen width evenly. looks this: the first button of each row takes width , other 3 buttons per row not visible. know how can fix this? <linearlayout android:id = "@+id/ll_screen_bttns" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margintop="20dp" android:orientation="vertical" > <linearlayout android:id="@+id/ll1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_weight = "1"> <button android:id="@+id/button0" android:layout_width="fill_parent" android:layout_height="@dimen/size...

php - Installing PhantomJS on server -

i'm using phantomjs on windows , accessing files through command line. want install on server i'm working on local host want installed on apache, may integrate phantom html , php used within web page. i'm using windows 8.1 , apache server localhost. can that? how use in web services now? how use if have make web online? should have t ask hosting provider place thing on server me? i'm using phantomjs develop web service takes url input , returns image file of screen shot of website. the "installation" of phantomjs adding path path environment variable. running through php since you're using php, invoke phantomjs php script shown here need provide full path phantomjs executable. can use putenv extend path directly php seen here . can return phantomjs script in $output variable of exec , parse it. running through webserver module phantomjs provides web server module . can write script listens requests, creates page on request ,...

here api - Interact with user-saved placemarks and collections via REST API? -

i have nokia/here.com account stores severals collections of placemarks. there way use rest api interact these user/account-specific placemarks, list , update them? if yes, where's best place start? aware of example? thanks, john we not have such api @ moment sent follow-up inquiry related product team , have more feedback in coming days. otherwise, have custom location extension (cle) api of interest. please see: documentation: http://developer.here.com/rest-apis/documentation/custom-location/topics/overview.html rest examples: http://developer.here.com/api-explorer#cls stay tuned! boris

Convert an array of logical type to an array of integer/double type -

i using silverfrost ftn95 and, since not expert, need create function takes input array of logical variables , returns array of integer variables, 0 false , 1 true. wrote simple code semplify how tried implement it: program main logical, dimension(2,1) :: integer, dimension(2,1) :: b integer, dimension(2,1) :: toint a(:,1)=.false. b=toint(a) write(*,*)b end program function toint(log) result(val) logical, dimension(2,1), intent(in) :: log integer, dimension(2,1) :: val i=1,2 if (log(i,1)) val(i,1) = 1 else val(i,1) = 0 end if end end function this code gives me error: integer expression expected in array bounds subscript, variable 'a' not have integer type (at line "b=toint(a)"), , can't find error is. suggestions or other ways solve problem helpful. thanks the error message comes because in program main you've declared toint array, statement toint(a) interpreted attempt index arr...

ruby - Rails is not routing to my webpage -

i new ruby on rails , have been setting demo page test stuff out on app set up, routes aren't being set reason. routing file: http://electrithm.net/routes.rb trying specifying route like: get 'hw/hworld', to: 'hw/hworld' and implement controller+action: class hwcontroller < applicationcontroller def hworld render # should render app/views/hw/hworld.html.erb end end

audit - django data history/auditing -

i'm requiring model data history django project, , have come across following products: django-reversion django-revisions django-simple-history django-audit-log cleanerversion i can't find recent recent comparison of these; 2011 comparison ( http://treyhunner.com/2011/09/django-and-model-history/ ) provided pros , cons, wondering if has more recent. support schema migrations (both south , 1.7 native) necessary, seeing user changed nice, , support foreignkeys , m2m nice. the model-audit grid on djangopackages gives proper comparison of various model history/auditing packages available. see https://www.djangopackages.com/grids/g/model-audit/ .

ruby - How pass oAuth2 server URL in config/gitlab.yml under providers -

we have setup gitlab , working well. have our own oauth2 server we'd connect to, account in our oauth2 server can have access gitlab. we've installed omniauth-oauth2 ( https://rubygems.org/gems/omniauth-oauth2 ) , have enabled in gitlab.yml this: omniauth: enabled: true providers: - { name: 'oauth2' } when restart gitlab see oauth2 button on login page, url our oauth2 server wrong, , haven't set out app_id , app_secret. my question is: how pass params , related data app_id, app_secret , oauth2 server url via settings file. we've tried number of things far, haven't gotten far. notes: i've never used ruby before week. learned lot far! we've attempted set additional args args: { url: 'url-to-our-oauth2-server' } i believe need create own strategy file, plan on doing based on supplied omniauth-oauth2 strategy file to use our own oauth server, had write our own strategy implements omniauth, , import via ...

What is the difference between a library and a package in R? -

in r difference between library , package ? i have come across posts people refer packages within library. based on idea interpret package lives in library (i.e store packages designated library). confused when want use package 'x' . i under imperssion need call library function package 'x' in use ? and once have have called upon package 'x' functions of package 'x' become available me ? in r, package collection of r functions, data , compiled code. location packages stored called library. if there particular functionality require, can download package appropriate site , stored in library. use package use command "library(package)" makes package available you. call appropriate package functions etc.

Matlab convert form hex to float -

i'm working device send me hex values, , need convert values real float value. know how convert hex values float in matlab? thx take @ hex2dec , convert hex decimal. hex format inherently integer (the floating point position not defined), have give more info: hex represent mantissa-exponent floating point number? represent fixed-point number?

WCF 4.0 Service crashes -

Image
i have wcf service hosted in iis 7.0. working past year, it's crashing , restarting every few minutes. looked @ trace file, , see error don't know means. tried googling no luck. checked settings in iis. looks ok. this how trace looks like. if can me understand trace, good. this pure assumptions, far guess looking @ traces , wrote: you using net.pipe wcf host the endpoint address of host net.pipe://tstwebashitv... something, not using net.pipe://localhost/... format (assuming tstwebashitv not server name, , net.pipe not remote) the service used work long time so assume there possibility named pipe wcf host running on same machine, , might cause conflict. that's why suggest check points: have net.pipe endpoints adresses under format: net.pipe://localhost/something instead of net.pipe://something . check hostnamecomparisonmode setting in netnamepipebinding section : better set exact ensure running hosts receives messages addressed them. ...

java - Validate the string length in SWT Text -

i have many modules in project, in every module have text box. i want validate input(alphabet). have write common method. need examples. thanks in advance. listen swt.verify on text , check condition. if want prevent given input, e.doit = false . here example allows @ 10 characters in text : public static void main(string[] args) { display display = new display(); shell shell = new shell(); shell.settext("stackoverflow"); shell.setlayout(new gridlayout(1, false)); final text text = new text(shell, swt.border); text.addlistener(swt.verify, new listener() { @override public void handleevent(event e) { string olds = text.gettext(); string news = olds.substring(0, e.start) + e.text + olds.substring(e.end); if(news.length() > 10) e.doit = false; } }); shell.pack(); shell.open(); while (!shell.isdisposed()) { if...

python - Django Rest Framework - Authentication credentials were not provided -

i'm developing api using django rest framework. i'm trying list or create "order" object, when i'm trying access console gives me error: {"detail": "authentication credentials not provided."} views: from django.shortcuts import render rest_framework import viewsets django.contrib.auth.models import user rest_framework.renderers import jsonrenderer, yamlrenderer rest_framework.response import response rest_framework.views import apiview order.models import * api.serializers import * rest_framework.permissions import isauthenticated class orderviewset(viewsets.modelviewset): model = order serializer_class = orderserializer permission_classes = (isauthenticated,) serializer: class orderserializer(serializers.hyperlinkedmodelserializer): class meta: model = order fields = ('field1', 'field2') and urls: # -*- coding: utf-8 -*- django.conf.urls import patterns, include, url django.co...

javascript - Round number to nearest thousand, up or down depending on the number -

i want round number nearest thousand, @ moment i'm using this: math.ceil(value/1000)*1000; but goes up, if type 1001 go 2000, want go or down depeding on number, example 1001 goes 1000 or 1400 goes 1000 1500 goes 2000 edit: if(value<1000){ value = 1000; }else{ value = math.round(value/1000)*1000; } this want: math.round(value/1000)*1000 examples: math.round(1001/1000)*1000 1000 math.round(1004/1000)*1000 1000 math.round(1500/1000)*1000 2000

node.js - Cannot attach to Appium with WebStorm debugger -

i have git-cloned appium , trying debug using jetbrains webstorm . remote debugging i set environment remote debug node application , provided following parameters: host: 127.0.0.1 port: 8877 so first run appium issuing: appium --port 8877 . after run debugger. problem debugger reports: connecting localhost:8877... in spite of appium running , executing test, debugger cannot attach it. problem here? for remote debugging application should running parameter --debug=<port debugging> or --debug-brk=<port debugging> . see http://confluence.jetbrains.com/display/wi/running+and+debugging+node.js+application#runninganddebuggingnode.jsapplication-debuggingnode.jsappthatrunsremotely

iphone - Status bar behave weird in landscape mode on iOS 8.1 and work fine with iOS 7.1 -

Image
i having uncommon problem. im application status bar not show in landscape mode. issue happen ios 8. work fine in ios 7. please see attached screen shots both ios 7 , ios 8. this may you in plist set view controller-based status bar appearance: no and add code in view controller -(void)didrotatefrominterfaceorientation:(uiinterfaceorientation)frominterfaceorientation { [[uiapplication sharedapplication] setstatusbarhidden:no withanimation:uistatusbaranimationnone]; }

What is ".NET Core"? -

Image
recently in official .net framework blog announced .net core going open source . ironically author mentions what .net core explained in next post. more details mentioned in another announce post . from supplied diagram: and articles text itself, assume .net core (beside obvious things being open-sourced) modular re-implementation of full .net. i.e. framework components loaded necessary, nuget packages loaded now. , asp.net 5 1 of modules implemented. understanding of .net core correct? maybe i'm missing something? i have found recent article found both short , good. covers .net standard, .net core , .net framework , relationships. highly recommend it. from .net blog announcing .net 2015 preview: new era .net : .net core has 2 major components. includes small runtime built same codebase .net framework clr. .net core runtime includes same gc , jit (ryujit), doesn’t include features application domains or code access security. runtime delivered via nuge...

angularjs - Can I re-factor Angular JS validation conditionals to streamline code? -

the below code 1 row of form. i replicate "addcarform.ucarname.$dirty && addcarform.ucarname.$invalid" several times throughout snippet. can refactor variable, updated answer conditional user's input changes/ better way of refactoring? <div class="form-group required " ng-class="{'has-error': addcarform.ucarname.$dirty && addcarform.ucarname.$invalid}"> <label class=" control-label col-lg-5 " for="ucarname">name:</label> <div class="col-lg-7 "> <input type="text" ng-model="cardetails.carname" name="ucarname" class="form-control" required /> </div> <div class="row"> <div ng-show="addcarform.ucarname.$dirty && addcarform.ucarname.$invalid" class="error-msg col-lg-offset-5 col-lg-7"> <span ng-show="addcarform.ucarname.$error.requi...

javascript - NodeJS Express 4.0 routing regex error -

after updating express module 4.0 version following url regexp stop working: app.get("/admin/list001/(userid/:userid)?/(name/:name)?/(email/:email)?/order/:order/field/:field/first/:first/rows/:rows/curriculums.:format(json)", function(request, response){ syntaxerror: invalid regular expression: /^\/admin\/list001\/(?(?:([^\/]+?))\/(?:([^\/]+?)))?\/name(?:\/([^\/]+?))?\/email(?:\/([^\/]+?))?\/order\/(?:([^\/]+?))\/field\/(?:([^\/]+?))\/first\/(?:([^\/]+?))\/rows\/(?:([^\/]+?))\/curriculums(?:\.(json))\/?$/: invalid group there other way of achieving same result? edit: (progress) /admin/list001(/userid/:userid)?(/name/:name)?(/email/:email)?(/order/:order)?(/field/:field)?(/first/:first)?(/rows/:rows)?/curriculums.:format(json) this works. request.params vars don't catch right values: { '0': '/field/userid', '1': 'userid', '2': '/first/0', '3': '0', '4': '/rows/20', ...

java - Calling Methods of Pattern Library into Activity -

i using android pattern lock library from: https://code.google.com/p/android-lockpattern/source/browse/ after import library not able call single function of library, whenever run app,getting force close inflate exception.please solve problem. sorry bad english package com.example.otpdemo; import group.pals.android.lib.ui.lockpattern.lockpatternactivity; import android.os.bundle; import android.app.activity; import android.content.intent; import android.widget.button; public class mainactivity extends activity { char[] savedpattern; private static final int req_create_pattern = 1; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); intent intent = new intent(lockpatternactivity.action_create_pattern, null, mainactivity.this,lockpatternactivity.class); startactivityforresult(intent, req_create_pattern); } @override protected void onactivityresu...