Posts

Showing posts from May, 2011

java - Formatting a string to dd/MM/yyyy -

this question has answer here: java.util.date format conversion yyyy-mm-dd mm-dd-yyyy 5 answers i have string thu nov 12 00:00:00 gmt 2015 eee mmm dd hh:mm:ss zzz yyyy . i want convert string string format of dd/mm/yyyy , or in case 12/11/2015 . simpledateformat sfrom = new simpledateformat("eee mmm dd hh:mm:ss zzz yyyy"); simpledateformat sto = new simpledateformat("dd/mm/yyyy"); string result = sto.format(sfrom.parse("thu nov 12 00:00:00 gmt 2015"));

cq5 - Should a site that requires authentication always send the WWW-Authenticate HTTP response header? -

Image
i tried access site (an aem author server) always requires authentication. attempting use basic authentication in url in browser address bar, follows: http://admin:admin@localhost:4502/ but when tried that, got following security confirmation (in firefox 38.0.1): clicking "yes" took me non-authenticated login page, seemingly ignoring basic auth credentials had sent. following questions (and comment on it) helped me understand because aem author server not asking authentication credentials--it not sending www-authenticate http response header: how http://user:pass@host.com authentication work? why browsers not send authentication header when credentials provided in url? hence, browser didn't send basic auth credentials had put in address bar. so led me question why aem author server, requires authentication, isn't sending http www-authenticate header. begs larger question: for site always requires authentication, reasonable expect site always s...

binary - Cannot delete records from filing in C++ -

i coding little program university. want delete saved record of employee. when enter id of employee , delete it, seems have been deleted. when check record, still present there. can not figure out why. here code: system("cls"); more = 'y'; while ((more == 'y')||(more == 'y')) { faculty = fopen("employee.txt","rb+"); temp = fopen("temp.txt","wb+"); rewind (faculty); cout<<"employee id: "; cin>>xid; while (fread(&em, empsize, 1, faculty) == 1) { if (xid != em.id) { fseek(temp, 0, seek_end); fwrite(&em, empsize, 1, temp); } else found=1; } fclose (temp); fclose (faculty); remove ("employee.txt"); rename ("temp.txt", "employee.txt"); if (found == 1) { //faculty = fopen("employee","rb+"); cout...

java - JavaCV - Why IplImage.createFrom(image) doesn't exist anymore? -

i'm working javacv @ moment, try simple blob detection. i'm using maven , got javacv 0.11 (more specific org.bytedeco.javacv) repositories. compiles without errors , works fine, method create iplimage bufferedimage seems doesn't exist. eclipse says the method createfrom(bufferedimage) undefined type opencv_core.iplimage i have no idea problem because works fine except 1 method far. the reason... javacv 0.11 has introduced concept of frameconverter . the goal don't create unecessary coupling between application using javacv , api (ffmpeg, java 2d...). instead, javacv uses frame class instances storing audio samples or video image data. frames can later shared between various apis frameconverter s. see more: javacv frame converters the workaround... it's possible copy , paste code of createfrom method own code or refactor using frameconverter s. below (not compiled) code of method taken source repository: public static iplimage crea...

github - Get changes from one branch into another one in git and how can I work on my own branch -

i'm little lost git, it's first use git other people. what want bring changes made in branch branch in working, let's when execute git branch --all see this: master * c remotes/origin/head -> origin/master remotes/origin/a remotes/origin/master remotes/origin/c so, i'm working on branch c, , have friend made ​​some changes in branch a, how can bring changes branch? the other thing not quite understand how can work on own branch, let's suppose fixed in file blah.html.erb, , want commit , upload own branch, ok following? git remote add blah.html.erb origin/c git commit -m "some changes" git push origin origin/c greetings. in order have access friend's branch, first need fetch them remote repository local repository with: git fetch --all this pulls branches remote repository don't exist locally , adds them repository. once you've done this, have merge branch branch. assuming you're on branch (if not r...

How Php To Json converted? -

we can convert php code how json format? may have not accurately php coding beginner learn because i'm new . i'll integrated android application. draw pictures how information ? for example, want this: http://mikepenz.com/android/unsplash/pictures <?php // don't forget change 'username' actual tumblr name $request = 'http://walltumbler.tumblr.com/api/read/json'; $ci = curl_init($request); curl_setopt($ci, curlopt_returntransfer, true); $input = curl_exec($ci); // tumblr json doesn't come in standard form, str replace needed $input = str_replace('var tumblr_api_read = ','',$input); $input = str_replace(';','',$input); // parameter 'true' necessary output php array $value = json_decode($input, true); $content = $value['posts']; // number of items want display $item = 98988; // tumblr provides various photo size, case choose 75x75 square 1 $type = 'photo-url-1280'; ?> { "limit...

Iterating until a key is pressed in C -

this question has answer here: c programming check if key pressed without stopping program 2 answers i need let user stop cycle while still iterating/looping. i want program show "sec" many times, until user pauses it. #include<stdio.h> #include<time.h> #include<conio.h> #include<stdlib.h> #define p printf #define s scanf int main(void) { int i,j; time_t seconds; { i=seconds; seconds=time(null); j=seconds; if(i!=j) { p("sec"); } }while(j==j); getchar(); return(0); } using getch or scanf, stop cycle each time. can 1 me? thinking there might function detects if key being pressed, doesnt wait pressed continue cycle. of course j==j keep infinite cycle. omg founf solution here: c programming check if key pressed without sto...

javascript - Why does a route trigger early with $routeProvider? -

i have set up function ($routeprovider) { $routeprovider .when('/', { templateurl: 'views/pages/home.html', controller: 'homecontroller' }) .when('/terms', { templateurl: 'views/pages/terms/terms.html', controller: 'termscontroller' }) .when('/patients/:patientid/schedule/daily', { templateurl: 'views/pages/schedule/schedule.html', controller: 'schedulehomecontroller' }) .when('/patients/:patientid/schedule/complex', { templateurl: 'views/pages/schedule/schedule.html', controller: 'schedulehomecontroller' }) .when('/error', { templateurl: 'views/pages/error.html', controller: 'homecontroller' }) .otherwise({ redirectto: '/error' ...

arrays - PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" -

i running php script, , keep getting errors like: notice: undefined variable: my_variable_name in c:\wamp\www\mypath\index.php on line 10 notice: undefined index: my_index c:\wamp\www\mypath\index.php on line 11 line 10 , 11 looks this: echo "my variable value is: " . $my_variable_name; echo "my index value is: " . $my_array["my_index"]; what these errors mean? why appear of sudden? used use script years , i've never had problem. what need fix them? this general reference question people link duplicate, instead of having explain issue on , on again. feel necessary because real-world answers on issue specific. related meta discussion: what can done repetitive questions? do “reference questions” make sense? notice: undefined variable from vast wisdom of php manual : relying on default value of uninitialized variable problematic in case of including 1 file uses same variable name. majo...

java - Activity shown immediatly instead of showing a notification -

i'm trying use alarmmanager send notification user later in day, whether using application or not. pasted saw here : http://developer.android.com/guide/topics/ui/notifiers/notifications.html , went wrong because instead of showing notification, androidlauncher activity shown. here code : public void plannotification() { alarmmanager = (alarmmanager)this.getsystemservice(context.alarm_service); notificationcompat.builder mbuilder = new notificationcompat.builder(this) .setsmallicon(r.drawable.icon) .setcontenttitle("my notification") .setcontenttext("hello world!"); intent resultintent = new intent(this, androidlauncher.class); taskstackbuilder stackbuilder = taskstackbuilder.create(this); stackbuilder.addparentstack(androidlauncher.class); stackbuilder.addnextintent(resultintent); pendingintent resultpendingintent = s...

Distance between two gps coodinates - javascript -

i searching know concept behind since last month , till got these resources how calculate distance between 2 latitude-longitude points? geolib.js function calculate distance between 2 coordinates shows wrong calculate distance, bearing , more between latitude/longitude points but still can't figure out right distance between specified coordinates as instance, have 2 coordinates start lat: 26.26594 start long: 78.2095508 destination lat: 21.24386 destination long: 81.611 and got result 655.358 km, (i had measured using bike's odometer) ~3 km far, why getting answer. i had checked implementation on geolib.js (2nd item have specified in list items), showing same result (655.358). i can't figure out js // inititalising distance calculation function geolocationinit() { $('.fd-loc-err').html(''); // empty error shown, if there $('.fd-dist-rest-user').html('<img src="/images/loader.gif" alt="...

c# - Calling jQuery function on Master Page body onload: 0x800a1391 - JavaScript runtime error: function is undefined -

i have master page includes following script: <!doctype html public "-//w3c//dtd xhtml 1.0 strict//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title><asp:contentplaceholder id="titlecontent" runat="server" /></title> <script src="<%=url.content("~/scripts/jquery-1.4.4.min.js") %>" type="text/javascript"></script> <script src="<%=url.content("~/scripts/jquery-ui-1.8.7.custom.min.js") %>" type="text/javascript"></script> <link href="<%=url.content("~/content/site.css") %>" type="text/css" rel="stylesheet" /> <link href="<%=url.content("~/content/jquery-ui/pepper-grinder/jquery-ui-1.8.7.custom.css") %>" type...

Django Filter And-ing of Related vs Original Predicates -

given have these models: class student(model): pass class exam(model): student = models.foreignkey(student) is_hard = models.booleanfield(...) is_completed = models.booleanfield(...) how filtered queryset of students matching these criteria: students have completed exam , hard exam. (i.e. student may have 1 exam hard , 1 completed) students have completed exam hard exam. (the same exam must both hard , completed). i believe latter answered with: student.objects.filter(exam__is_hard=true, exam__is_completed=true) but how former? use q objects . student.objects.filter(q(exam__is_hard=true, exam__is_completed=true)|q(exam__is_hard=true)|q(exam__is_completed=true))

java - Spring MVC Encoding Issue -

i'm using spring mvc thymeleaf. when post form has ® in parameter, displays in windows-1252 format instead of utf-8. here input post form: <input type="checkbox" name="brand" id="brand1" value="brand®"> here how looks in url: http://localhost:8080/categories?brand=brand%ae&x=87&y=37 i've done research , looks ® equal %ae in windows-1252, equal %c2%ae in utf-8. when manually post url %c2%ae, interprets correctly. i'm using intellij 14.1.3 on windows 7, , web server tomcat 8.0.21. starting tomcat 8.0.3-rc, default uri encoding set utf-8 in tomcat, , verified ide , project encodings set utf-8 in intellij. also, html file has <meta charset="utf-8" /> tag @ beginning. do have idea how can resolve issue? thanks in advance

c - Is there an alphabetic wchar_t such that its capital and lower versions are the same? -

i've been wondering whether there char c such iwalpha(c) == 1 , towlower(c) == towupper(c) . i'm trying implement dictionary in trie. each node has wchar_t label , boolean a_word provides information whether node represents word. i'd save such trie file without wasting memory, thought won't save boolean, write labels represent word capital case. question whether i'll lose information way. thanks in advance note iswalpha locale-specific. anyway, if locale supports arabic letters, should met conditions. edit: make example extended latin characters, towupper('ß') == towlower('ß') == 'ß' , long locale supprts eszett

MarkLogic - JavaScript node.js Client API - QueryBuilder - Join between collections -

say have 2 collections this: // city collection <city> <id>1</id> <name>tulsa</name> <stateid>1></stateid> </city> // state collection <state> <id>1</id> <name>oklahoma</name> </state> now want return list of cities state name instead of stateid. how can join efficiently, using node.js client api , query builder? an efficient join can't performed using node.js api. best way approach this, if possible, denormalize content documents contain information need query or return. <city> <id>1</id> <name>tulsa</name> <stateid>1></stateid> <state-name>oklahoma</state-name> </city>

android - Variable loses data when I run another App -

i built variable work session. saving id specific users on log in. i declaring variable inside sign in asynctask @override protected void onpostexecute(string result){ if(result == ""){ this.statusfield.settext("wrong password."); }else{ context.startactivity(new intent(context,listusersactivity.class)); session.suserid = result; } } public static class session{ public static string suserid; } my session class: public class newsession extends application { session session = new session(); public string getuserid() { return session.suserid; } } to id user, need call it: newsession app = (newsession) getapplication(); userid = app.getuserid(); the code working fine, when run google chrome, youtube, or different application, when try run application again, gives me error because session loses value. is there similar way trying do? thanks. the code working fine, when run g...

asp.net - w3wp.exe why it is only one in task manager? -

worker process: worker process (w3wp.exe) runs asp.net application in iis... application pool: application pool container of worker process... took here . having can assume see more 1 w3wp.exe process in task manager if have more 1 application hosted on iis, , have problems example attach process vs(which w3wp.exe choose). there no such problem. how works?

php - Amazon MWS GetLowestOfferListingsForASIN and SimpleXML Not Working -

here sample data trying use: <?xml version="1.0"?> <getlowestofferlistingsforasinresponse xmlns="http://mws.amazonservices.com/schema/products/2011-10-01"> <getlowestofferlistingsforasinresult asin="b006dtxdmo" status="success"> <allofferlistingsconsidered>true</allofferlistingsconsidered> <product xmlns="http://mws.amazonservices.com/schema/products/2011-10-01" xmlns:ns2="http://mws.amazonservices.com/schema/products/2011-10-01/default.xsd"> <identifiers> <marketplaceasin> <marketplaceid>atvpdkikx0der</marketplaceid> <asin>b006dtxdmo</asin> </marketplaceasin> </identifiers> <lowestofferlistings> <lowestofferlisting> <qualifiers> <itemcondition>new</itemcondition> <itemsubcondition>new</itemsubcondition> <fulfillmentchannel>amazon</fulfillmentchanne...

sql server 2008 r2 - ssis swap some values in a data flow if they match a lookup table -

here's problem - midstream in data flow, have values in 1 column want swap other values based on lookup table. for example, if had rowset this: key value 1 2 b 3 4 c 5 d 6 b ... ... if had lookup table in sql server db looked this: value1 value2 c y d z then want package swap values resulting data flow this: key value 1 2 b 3 4 y 5 z 6 b ... ... what components produce simplest solution? you use lookup component , then: set ignore failure values not match return null lookup value use derived column expression populate lookup succeeded isnull(value2) ? value : value2

php - How to set proper JSON response for POST method in RESTful API from FOSRestBundle? -

i making post method restful api. api built on top of fosrestbundle , nelmioapidoc may notice. not able validate when file not uploaded or when rid parameter missing , response proper json. doing: /** * set , upload avatar reps. * * @param paramfetcher $paramfetcher * @param request $request * * @apidoc( * resource = true, * https = true, * description = "set , upload avatar reps.", * statuscodes = { * 200 = "returned when successful", * 400 = "returned when errors" * } * ) * * @requestparam(name="rid", nullable=false, requirements="\d+", description="the id of representative") * @requestparam(name="avatar", nullable=false, description="the avatar file") * * @return view */ public function postrepsavataraction(paramfetcher $paramfetcher, request $request) { $view = view::create(); $uploadedfile = $request->files; // not w...

Scala lambda style (x) => {...} vs { (x) => ... } -

i'm new scala , reading sample code using rescala . in code, appears author uses 2 styles define lambdas: { x => println(x) } (x => { println(x) }) i assume these 2 styles semantically equivalent. think second style allows easy addition of additional statements in lambda body. is correct? way more "idiomatic"? interesting whether {} opens new lexical scope (like in c) or not. i assume these 2 styles semantically equivalent. yes however think second style allows easy addition of additional statements in lambda body. no. or, rather, yes, first style. which way more "idiomatic"? this opinion-based. opinions vary. it interesting whether {} opens new lexical scope (like in c) or not. yes do.

php - Laravel Pagination -

how can create pagination in laravel? my model post function comments() { return $this->hasmany('comment') ->orderby('created_at', 'desc'); } comment function posts(){ return $this->belongsto('post'); } user function posts(){ return $this->hasmany('post'); } function comments(){ return $this->hasmany('comment'); } usercontroller $user = user::find(1); //this give me user's post , comment details //i know can $user = user::paginate(30) 30 user per page what want achieve i want create pagination of 10 comment per page. thanks in advance. you have 2 options: can call paginate() on relationship query, or can manually create paginator. call paginate() on relationship query (uses relationship function): $user = user::find(1); $comments = $user->comments()->paginate(10); manually create paginator (uses relationship attribute): $user = ...

ios - Ionic app image upload from camera / photo library -

i'm working on ionic chat app user can upload photo part of message. i'm looking way upload image webhost server can retrieve later via url. the problem i'm not able upload web server. i'm using these 2 plugins: org.apache.cordova.file-transfer cordova-plugin-camera when run app in xcode simulator , select picture device photolibrary, console gives me following messages: file transfer finished response code 200 void senddelegatemessage(nsinvocation *): delegate (webview:runjavascriptalertpanelwithmessage:initiatedbyframe:) failed return after waiting 10 seconds. main run loop mode: kcfrunloopdefaultmode> success: "" this code use: app.controller('homecontroller', function($rootscope, $scope, $cordovacamera, $ionicactionsheet, $cordovafiletransfer){ ... // open photolibrary $scope.openphotolibrary = function() { var options = { quality: 100, destinationtype: camera.destinationtype.file_uri...

ruby on rails - RoR security with POST method: where - how occurs the validation - howto optimize? -

in forums made experience newbies getting not helpful answers (to describe former experiences nicely) when asking questions things obvious more experienced users. please excuse fear 1 of questions - nevertheless want understand , hope can explain following me in simple words? how ror behave security perspective - when post used? in specific: 1. validation occur in belows example 1.1 serverside? 1.2 clientside? 1.3 both? 1.3.1 if both, remaining points should sorted...(right?) class article < activerecord::base validates :title, presence: true, length: { minimum: 5 } end 2 . if validation occurs on server site: 2.1 couldn´t lead situation uses script "overload" server such invalid requests , keeping server busy wont respond other requests? 2.2 there (an additional) clientside validation performed (or implemented if isn't handled) bypassing clientside validation entering url post strig directly flood server useless re...

css - Disabling sidebar in pelican octopress theme -

can please guide me in disabling sidebar entire blog? the solutions provided on web octopress , not pelican-octopress-theme. in template/base.html , have remove {% include '_includes/sidebar.html' %}

rest - Mule 3.6 and Server Sent Events -

i trying add server sent events rest component of mule 3.6 esb flow. having trouble getting data browser. connect java method after eventsource sent error occurs in browser. appreciated. <http:listener-config name="http_listener_configuration" host="0.0.0.0" port="8082" doc:name="http listener configuration"/> <flow name="restservice" > <http:listener config-ref="http_listener_configuration" path="/*" doc:name="http"> <http:response-builder> <http:header headername="access-control-allow-origin" value="*"/> <http:header headername="access-control-allow-methods" value="get,post"/> </http:response-builder> </http:listener> <jersey:resources doc:name="rest"> <component> <spring-object bean="restservice"/> </component> </jersey:resources> </flow> java code using...

struts2 - How to hide the "action" extension -

when user makes login on success browser redirect http://appname.com/main.action how can make adress line looks http://appname.com/main <action name="login" class="user.action.loginaction" method="execute"> <result name="success" type="redirectaction"> main </result> <result name="error">/login.jsp</result> </action> you must set following property in struts.xml : <constant name="struts.action.extension" value=","/> you can set different extensions, or no extension @ all, specified comma reason, can read in answer . it's used advanced wildcard mappings ,to create user-friendly pretty urls.

c# - Deserialization Error: InvalidCastException: Cannot cast from source type to destination type -

i have problem , i'm not sure how solve it... tried plenty of things , can't find similar online help. note: scene uses script saving , using same .dat file, not sure if that's issue though. public gameobject[] top10 = new gameobject[10]; [system.serializable] public class scoreentry { public string name; public int score; } // use initialization void start () { if (file.exists(application.persistentdatapath + "/hiscores.dat")) { binaryformatter b = new binaryformatter(); var f = file.open(application.persistentdatapath + "/hiscores.dat", filemode.open); list<scoreentry> hiscores = (list<scoreentry>)b.deserialize(f); f.close(); (int = 0; == hiscores.count; i++) top10[i].getcomponent<textmesh>().text += hiscores[i].name + " - " + hiscores[i].score; } } // update called once per frame void update () { } it looks scoreentry class usin...

c# - Mocking Interface as non-nullable instance with RhinoMocks -

i have written method suggested in https://stackoverflow.com/a/79903/976896 . in short method accepts kind of enums argument , basic checking. public void saveintvaluefromenum<t>(t value) t : struct, iconvertible { if (!typeof(t).isenum) { throw new argumentexception("t must enumerated type"); } this.intvalue = convert.toint32(value); } now want write test this, validates when non enum type feed it, exception thrown. wanted generate dummy object follow rhinomocks. var mock = mockrepository.generatemock<iconvertible>(); but method doesn't accepts nullable type. is there way mock structs/non-nullable instances rhinomocks? edit: updated code listing

java - Search a table with the result of another search in servlet -

i have table table1 2 fields id , shift , table table2 3 fields id , name , surname . field id same primary key in both tables. in servlet want select id's have shift != noon. write resultset rs = stmt.executequery("select id table1 shifts!=noon"); so have gather records in rs . now, how can search through second table in order select records id's found in 1st look? you need join: resultset rs = stmt.executequery("select t2.* table1 t1 join table2 t2 on t1.id = t2.id t1.shifts <> 'noon'"); look here: http://www.w3schools.com/sql/sql_join.asp also need enclose strings noon inside single quotes 'noon', , best use <> instead of != standard sql , more compatible other databases.

python - Exposing pandas DataFrame to TraitsGUI Editable Table -

i have noticed in enthought canopy demos, there several bits of code expose lists , numpy arrays traitsui editable table. looking same pandas dataframe. essentially, i'd able edit couple of columns in dataframe , have callback re-calculates other columns (that dependent on edited columns). does know of sample code might me started exposing df object via traitsui table?

java - Accepting multiple simultaneous client sockets on their own threads -

i did different tutorials nothing works, can see i'm doing wrong? private volatile boolean keeprunning = true; public filesharedserver() { } @override public void run() { try { system.out.println("binding port " + port + "..."); // bind port used clients request socket connection // server. serversocket serversocket = new serversocket(port); system.out.println("\tbound."); system.out.println("waiting client..."); socket = serversocket.accept(); system.out.println("\tclient connected.\n\n"); if (socket.isconnected()) { system.out.println("writing client serverid " + serverid + "."); // write serverid plus end character client thru // socket // outstream socket.getoutputstream().write(serverid.getbytes()); socket.getoutputstream().wri...