Posts

Showing posts from March, 2011

ruby on rails - How can I invite users (using devise_invitable) and populate additional fields during the invite process? -

for example, when go users/invitations/new , field :email . i'd invite user and, in addition providing email, provide: first_name last_name role company ( user belongs_to company ) i created users::invitationscontroller < devise::invitationscontroller : class users::invitationscontroller < devise::invitationscontroller private def resource_params params.permit(user: [:email, :invitation_token, :role, :company_id])[:user] end end and added fields users/invitations/new . invitation sends fine, when accept , input password, validation fails saying no role selected (b/c of validation). how can set these fields before sending invite , have them persist , save when invite accepted? thanks! rails 5 here solution using accepts_nested_attributes_for . if custom attributes directly on user model should able replace profile_attributes: [:first_name, :last_name] :first_name, :last_name, :role, :company . here controller. class invitations

swift - takePicture() with cameraOverlayView -

i'm using cameraoverlayview create custom camera. however, i'm not sure how make button shoot photo. apple docs takepicture() function use. not compile: neither attempt works: let shootpicture = uibarbuttonitem(barbuttonsystemitem: uibarbuttonsystemitem.camera, target: self, action: takepicture()) let shootpicture = uibarbuttonitem(barbuttonsystemitem: uibarbuttonsystemitem.camera, target: self, { action -> void in takepicture() }) updated attempt: let shootpicture = uibarbuttonitem(barbuttonsystemitem: uibarbuttonsystemitem.camera, style: uibarbuttonitemstyle.plain, target: self, action: "takepicture") // separate function func takepicture() { imagepicker.takepicture() } still getting syntax error: missing argument parameter 'landscapeimagephone' in call but when add landscapeimagephone: uibarbuttonsystemitem.camera , "extra argument 'landscapeimagephone' in call" for else stuck on

c# - Cant get sql data into listview from a different foreign table (2 tables) -

been stuck on same problem days , have been searching around web answer. my question is : in code below got 2 tables has 1 foreignkey. want display nvarchar in table not id. in aspx page got listview. <asp:listview id="listview_fruit" itemtype="differentfruit.model.fruit" selectmethod="listview_getdata" datakeynames="fruitid" runat="server" deletemethod="listview_del" updatemethod="listview_update" > <layouttemplate> <table> <tr> <th>fruitid</th> <th>fruit name</th> <th>typeoffruitid</th> </tr> </table> </layouttemplate> <itemtemplate> <tr> <td><%# item.fruitid %></td> <td><%# item.fruitname %></td> <td><%# item.type

php - Strange results with mysqli_stmt_bind_result -

i using prepared statement query database astronomical magnitude value $mid = $_get["mid"]; $stmt = mysqli_prepare($mysqli, 'select eid, band, value, error, notes mags id=?'); mysqli_stmt_bind_param($stmt, "i", $mid); mysqli_stmt_execute($stmt); mysqli_stmt_bind_result($stmt, $eid, $band, $value, $error, $notes); mysqli_stmt_fetch($stmt); mysqli_stmt_close($stmt); i display results on html page. $value displays 12.345000267029 though value in database 12.345. ideas why happening? if use regular query (i.e. not prepared statement) value displays correctly. $query = "select eid, band, value, error, notes mags id=$mid"; $res = mysqli_query($mysqli,$query); while ($row = mysqli_fetch_assoc($res)) { $eid = $row["eid"]; $band = $row["band"]; $value = $row["value"]; $error = $row["error"]; $notes = $row["notes"]; }

javascript - [JS]Return to index page -

how can return registration page oauth authentication? put url of app(as &redirect_uri=) when user accept authentication, script fails: error: access 'app://6cb90889-d3dd-4ca7-8bab-ea11831b922d/reg.html#access_token=xxxxxxxxxxx' script denied it should close browser , return app! idea? redirection of url taken care server. server has understand redirect_uri= attribute , need redirect it. in case of j2ee. done as public void doget(httpservletrequest request, httpservletresponse response) throws servletexception, java.io.ioexception { string contextpath= "http://www.java2s.com"; response.sendredirect(response.encoderedirecturl(contextpath + "/maps")); } let me know if trying someting different. regards, chandra.

osx - fswatch + rsync alternative or better inplementation -

i'm trying watch folder, , subfolders changes in files (html/css/js/etc). once file has changed, want upload mounted drive remote server. currently, using in terminal: fswatch -o ~/desktop/site/ | xargs -n1 sh ~/documents/app\ syncs/rsync_files.sh rsync_files.sh: rsync -rvzut --info=progress2 --delete-after --delete-excluded --exclude-from=/users/me/documents/app\ syncs/exclude_list.txt /users/me/desktop/site/ /volumes/devroot$/site; the thought fswatch call rsync each time there change in file structure. works, slow, esp on crappy connection. my question is, doing right or there better solution i'm trying accomplish? can rsync command better optimized? there app made thing me? basically want mimic file panel in dreamweaver 2014 without having use dreamweaver. setup sublime text 3 , codekit 2. i guess depends on bottleneck is, not clear in question. 1 thing though: if connection "crappy", i'd worry fixing connection before trying tune rsy

scala - Reader Monad for Dependency Injection: multiple dependencies, nested calls -

when asked dependency injection in scala, quite lot of answers point using reader monad, either 1 scalaz or rolling own. there number of clear articles describing basics of approach (e.g. runar's talk , jason's blog ), didn't manage find more complete example, , fail see advantages of approach on e.g. more traditional "manual" di (see the guide wrote ). i'm missing important point, hence question. just example, let's imagine have these classes: trait datastore { def runquery(query: string): list[string] } trait emailserver { def sendemail(to: string, content: string): unit } class findusers(datastore: datastore) { def inactive(): unit = () } class userreminder(finduser: findusers, emailserver: emailserver) { def emailinactive(): unit = () } class customerrelations(userreminder: userreminder) { def retainusers(): unit = {} } here i'm modelling things using classes , constructor parameters, plays nicely "traditional" di appro

javascript - Access object child properties using a dot notation string -

this question has answer here: accessing nested javascript objects string key 28 answers i'm temporarily stuck appears simple javascript problem, maybe i'm missing right search keywords! say have object var r = { a:1, b: {b1:11, b2: 99}}; there several ways access 99: r.b.b2 r['b']['b2'] what want able define string var s = "b.b2"; and access 99 using r.s or r[s] //(which of course won't work) one way write function splits string on dot , maybe recursively/iteratively gets property. there simpler/more efficient way? useful in of jquery apis here? here's naive function wrote while ago, works basic object properties: function getdescendantprop(obj, desc) { var arr = desc.split("."); while(arr.length && (obj = obj[arr.shift()])); return obj; } console.log(getdescendantp

javascript - Dynamically load a bootstrap modal body -

i looking load modal data before showing it. <button data-dismiss="modal" data-target="#mymodaltest" href="#mymodal3" class="btn btn-primary" id="1">view database details</button> when button clicked, populate listbox , open modal show data comes empty. here first part modal div want reload (specifically modal body form field): <div class="modal" id="mymodal3" data-backdrop="static"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h4 class="modal-title">second modal title</h4> </div><div class="container"></div> <div class="modal-body"> schemas available:<b

ruby on rails - Only give method block and yield if block_given? -

let's have basic td_tag helper wraps content_tag method in application_helper.rb def td_tag(*args) if block_given? content_tag(:td, *args) yield end else content_tag(:td ,*args) end end what ruby-way of making code shorter? this example works, in way, doesn't seem nessesary call same function same parameters, , without block? by appending block_given? yield row inside block doesn't work, since have given next function block work with. accept block argument , pass through. no need use block_given? . this functionally identical code: def td_tag(*args, &block) content_tag(:td, *args, &block) end it's safe; if not give method block, block nil , block_given? inside content_tag false.

c - Printing the nodes of a linked list through a recursive function -

i've been asked make couple of programs using c. in 1 of these programs, need create linked list can stuff it. but, not allowed use global variables nor loops (while, for, etc.) in of these programs. here small program wrote fresh linked lists: #include <stdio.h> #include <stdlib.h> struct node { int number; struct node *next; }; void create (struct node *, struct node *); void insert (struct node *, struct node *); void display (struct node *); int main(void) { struct node *head; struct node *current; struct node *temp; create ( head, current ); insert ( head, current ); temp = head; display ( temp ); } void create ( struct node *head, struct node *current ) { int a; printf("insert: "); scanf("%d", &a); current = malloc(sizeof(struct node)); current -> number = a; current -> next = null; head = current; } void insert ( struct node *head, struct node *curr

In Android how to make ObjectAnimator translate on top of the other imageviews and not below? -

i have imageviews translating using objectanimator movey = objectanimator.offloat(stone, "y", catpos[1] ); when translates specified position,and there image view there, places under imageview. want newly moved imageview seen on top. how can that? adding code bringtofont() worked.

Linked List in C not working Valgrind Error -

the program supposed read words of file linked list. got linked list working i'm faced error. i'm getting segmentation fault when using large file. it working smaller lists (3-10 words) not larger ones. -----code----- #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct node //struct linked list { char* word; struct node* next; } node; int main (void) { char* dictfile = "large"; file* dict = fopen(dictfile, "r"); if (dict == null) return 1; node* head = null; char* oneword = malloc(sizeof(node)); //to store word fgets() while ((fscanf (dict, "%s", oneword)) > 0) { node* temp = (node*)malloc(sizeof(node)); char* tempword = (char*)malloc(sizeof(node)); //gives me new pointer store string (as pointed out antione) strcpy(tempword, oneword); temp->word = tempw

javascript - CORS request not going through. Unsure why -

console telling me... cross-origin request blocked: same origin policy disallows reading remote resource @ "example.com". can fixed moving resource same domain or enabling cors. i've got xhr object created in createcorsrequest function , makecorsrequest function. request executes using url parameter php file contains code that's supposed allow access origin. below bits cors functions , php file. // create xhr object function createcorsrequest(method, url) { var xhr = new xmlhttprequest(); if ("withcredentials" in xhr) { // xhr chrome/firefox/opera/safari xhr.open(method, url, true); } else if (typeof xdomainrequest != "undefined") { // xdomainrequest internet explorer xhr = new xdomainrequest(); xhr.open(method, url); } else { // cors not supported. xhr = null; } return xhr; } // helper method parse title tag response. function gettitle(text) { return text.match('<title>(.*)?</title

ruby on rails - Uninitialized constant ActionDispatch::Routing::Mapper::Scope (name Error) -

i'm trying debug error. @scope = actiondispatch::routing::mapper::scope.new( path: "", shallow_path: "", constraints: {}, defaults: {}, options: {}, parent: nil ) but receive error: nameerror: uninitialized constant actiondispatch::routing::mapper::scope any idea? i'm using rails 4.1.6 actiondispatch::routing::mapper::scoping http://api.rubyonrails.org/classes/actiondispatch/routing/mapper/scoping.html

c++ - §7.1.6.3/1 (C++14) doesn't accept the construction in the second snippet below. Why is this? -

first part : i'm studying in detail opaque-enum-declaration s , elaborated-type-specifier s few days already, , confirm this. gcc , vs2013 don't compile code (clang does) , believe clang in accordance §7.1.6.3/1, enum e elaborated-type-specifier not sole constituent of declaration enum e e = e::b; . analysis correct? #include <iostream> enum class e : char {a = 'a', b}; int e; enum e e = e::b; // doesn't compile in gcc , vs2013 int main() { std::cout << (char)(e) << '\n'; } second part: the snippet below, similar 1 above, doesn't compile. understand why doesn't (the elaborated-type-specifier enum e sole constituent of declaration enum e; , §7.1.6.3/1 doesn't allow this). i'd know why can't compiler accept construction? #include <iostream> enum class e : char {a = 'a', b}; int e; enum e; // doesn't compile. e e = e::b; int main() { std::cout <

How do I override the controller name for a rails url helper? -

i have post model category attribute , corresponding postscontroller . i override default url helper produce folowing: @post = post.create(category: 'posts') <%= link_to 'post link', @post %> # /posts/1 @post = post.create(category: 'articles') <%= link_to 'article link', @post %> # /articles/2 i call default url helper post have create different urls based upon category column. update i ended overriding url helpers: module postshelper def post_path(post, options={}) self.send("#{post.category}_path", post, options) end def post_url(post, options={}) self.send("#{post.category}_url", post, options) end end named routes want: get 'posts/:id', to: 'posts#<controller-action>', as: 'posts' <%= link_to 'post link', posts_path(@post) %> get 'articles/:id', to: 'posts#<controller-action>', as: 'articles'

String is initialized to be all '\0' in C? -

i tried this: char s[100]; for(int i=0; i<100; i++) { if(*(s+i) == '\0') printf("end of string\n"); } and "end of string" printed 96 times. if change string definition char *s[120]; "end of string" 100 times why that? how string initialized exactly. i trying check every 3 char in string, need test going happen if pointer pass end of string. edit: sorry, typo. should char s[100] instead of char *s[100] if array s automatic variable, pointers in array have indeterminate value. not initialized can de-reference or read without invoking undefined behaviour. note : have array of pointers, not "string".

android - How to superimpose a GridLayout on a ImageView? -

i'm making tic tac toe on android fun, , don't know how design it. in fact, made grid layout have 9 interactiv squares don't know how put grid's picture under it. first put grid on background attribute: <gridlayout android:id="@+id/game" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparentbottom="true" android:layout_centerhorizontal="true" android:columncount="3" android:rowcount="3" android:numcolumns="3" android:background="@drawable/grid" > but didn't work : then tried put imageview parent of gridlayout it's impossible. there other way ? the concept of gridlayout or table layout setup grid you've done , add child components each grid element. in case of tictactoe board, i'd suggest added 9 imagebuttons, 1 each box. when user clicks on button, can

javascript - Node.js: Get "Trying to open unclosed connection" when calling method from child process -

i'm getting " error: trying open unclosed connection, " don't believe it's due db issue... , that's why i'm stumped. solutions error, reference db connection issues. my goal here execute external process. if process closes other exit code 0, want email alert example. i using child.on('close', function(code) .... exit value external process (coming "code") if code !=0 want something... maybe rerun test... maybe call different method sends email, etc. each time attempt call method, within child.on('close') , error "trying open unclosed connection." why i'm handling save action in same block. code sample: var spawn = require('child_process').spawn, child = spawn('sipp', ['-s', dnis,server, '-sn', scenario, '-m', '1','-i','127.0.0.1','-recv_timeout','1000']); } child.on('close',function(code){ if(code

xamarin.ios - Creating a Xamarin Binding project for PebbleKit iOS -

for past while i've been trying create binding project in xamarin pebblekit ios (the sdk pebble smart watches). hope in doing can create xamarin c# app communicates pebble smart watch, how in objective - c. here link github page containing code: https://github.com/dankunc/pebblekit-xamarin/tree/master also, here link simple harness project contains button can use test out binding project: https://github.com/dankunc/pebblekit-xamarin-harness note: if of kind enough download code , try out, you'll need update reference path in harness .dll in binding project (pebblekitall/bin/release/pebblekitall.dll) the project compiles, when go use in actual xamarin app, code returns null watch: var watch = pbcentral.defaultcentral(); in objective - c, equivalent method never return null, , i've been struggling quite time. the pebblekit binding project relies on 2 .frameworks pebble (pebblekit , pebblevendor) , handful of other frameworks included in harness project. gene

java - JSpinner with SpinnerDateModel not spinning -

i'm developing java application using swing create gui. have problem jspinner, whih should allow user select time, in hh:mm format, specific range. created custom spinnerdatemodel , dateeditor , seems ok, when run application spinner shows proper value doesn't spinn. import java.util.calendar; import java.util.date; import javax.swing.jspinner; import javax.swing.spinnerdatemodel; public class spinnerexample extends javax.swing.jframe { public static void main(string[] args) { spinnerexample main = new spinnerexample(); main.setvisible(true); } /** * creates new form mainframe */ public spinnerexample() { initcomponents(); myspinner.setmodel(getmyspinnermodel()); myspinner.seteditor(new jspinner.dateeditor(myspinner, "hh:mm")); } public spinnerdatemodel getmyspinnermodel() { spinnerdatemodel spinnermodel = new spinnerdatemodel(); calendar calendar = calendar.getinstance(); calendar.set(calendar.hour_of_day, 12); calen

parsing - How can I extract some data out of the middle of a noisy file using Perl 6? -

i using idiomatic perl 6. i found wonderful contiguous chunk of data buried in noisy output file. i print out header line starting cluster unique , of lines following it, to, not including, first occurrence of empty line. here's file looks like: </path/to/projects/projectname/parametersweep/1000.1.7.dir> used working directory. .... cluster unique sequences reads rpm 1 31 3539 3539 2 25 2797 2797 3 17 1679 1679 4 21 1636 1636 5 14 1568 1568 6 13 1548 1548 7 7 1439 1439 input file: "../../filename.count.fa" ... here's want parsed out: cluster unique sequences reads rpm 1 31 3539 3539 2 25 2797 2797 3 17 1679 1679 4 21 1636 1636 5 14 1568 1568 6 13 1548 1548 7 7 1439 1439 i using idiomatic perl 6. in perl , idiomatic way locate chunk in file read file in paragraph mode , stop reading file when find chunk interested in. if reading 10gb fi

how to redirect specific subfolders to subdomain with .htaccess -

i want redirect subfolders subdomain .htaccess. on webpage, have lot of subfolders begin "page" below: http://example.com/page-one http://example.com/page-two http://example.com/page-three so want achieve this: http://page-one.example.com http://page-two.example.com http://page-three.example.com i did research , way should work this: rewritecond %{http_host} ^example\.com$ [or] rewritecond %{http_host} ^www\.example\.com$ rewriterule ^page-one\/?(.*)$ "http\:\/\/page-one\.example\.com\/$1"[r=301,l] but doing way, have write lot of rules redirecting. there way can "catch" subfolders in name "page" appears , redirect complete folder subdomain?

objective c - SSKeychain implementation load last login and pass -

Image
i new objective-c. can not understand how do, when start program automatically inserts last name saved in nstextfiel , nssecuretextfield. save user name , password : - (void)saveloginpass { if ([checkbox state]==nsonstate) { [sskeychain setpassword:self.passwordfield.stringvalue forservice:@"erclient" account:self.loginfield.stringvalue]; nslog(@"login/pass save"); } else if([checkbox state]==nsoffstate){ nslog(@"don't save login/pass"); } } and [manager post:urlstring parameters:parameter success:^(afhttprequestoperation *operation, id responseobject){ if ([operation.responsestring rangeofstring:@"mainbody"].location == nsnotfound) { alertfild.stringvalue=@"login or pass false"; nslog(@"login or pass false"); nslog(@"responseobject: %@", responseobject); nslog(@"operation.responsestring: %@",operat

jquery each function not working in sharepoint -

in order center of excel app web parts on sharepoint 2013 sp1 page, thought use jquery so. tried following code handle horizontal centering. unfortunately function seems never called. i expect 9 alert() since there 9 divs on page matching selector. in other words there 9 divs class="ewr-sheetcontainer ewr-grdblkcontainer ewa-scrollbars". yes has 3 classes , css allows type of selection maybe jquery not. this code embedded on page , jquery enabled site collection. does see problem script, function, or way each called? goal adjust left attribute selected div. <script type="text/javascript"> $(document).ready(function() { $("div.ewr-sheetcontainer ewr-grdblkcontainer ewa-scrollbars").each( function () { this.css("position","absolute"); this.css("left", math.max(0, (($(window).width() - $(this).outerwidth()) / 2) + $(window).scrollleft())

ios - Update old app on itunes connect with Swift -

didn't find information on while googling. i'll ask here myself. i working on rebuilding app 4-5 years old, written in objective-c. coding in swift updated version of app. how able update current app on itunes connect? enough change bundle identifier in project same old one? or have create swift files within old project? yes, making sure bundle identifier same important part. also, have increase version number in order able upload updated version of app. just create new project , recode in swift.

jquery - When I click one image, all images get highlighted! Any thoughts? -

i'm trying add border image upon click, , use cookies plugin keep clicked style active after refreshing. while managed keep styles stay after refreshing browser, have problem of not being able click images individually. when click 1 image, images hightlighted. $(function() { var img_class = $.cookie('img_class'); if(img_class) { $('img').attr('class', img_class); } $(' img').click(function() { $(this).each(function() { $("a img").toggleclass("active"); $.cookie('img_class', $('img').attr('class')); }); }); }); /* less styles */ @import url(http://fonts.googleapis.com/css?family=raleway); @import url(http://fonts.googleapis.com/css?family=montserrat); @background: #333; @maxhw: 100px; @textclr: #999; @borderclr: #fff; @standardmarg : 5px; @fontfamily: "raleway", sans-serif; body { background-co

c++11 - How to correctly use an unordered_map C++ -

i wanted create std::unordered_map custom hash function. having trouble figuring out declare/how use unordered_map though. here situation. have class called object . it's super simple , merely contains integer id . here header file: // object.hpp class object { public: object(); ~object(){}; int id(); void setid(int i); private: int id; }; i have class called dataset acts container hold millions of these object s. simplicities sake, want able construct dataset , add object dataset , delete object id dataset , clear dataset , , size of dataset . the structure want (and required to) use in dataset class std::unordered_map . map, want key integer id associated object , , actual object* value. have hash function want use unordered_map . here have in dataset header file: // dataset.hpp struct hashkey { unsigned int hash(unsigned int x) { x = ((x >> 16) ^ x) * 0x45d9f3b; x = ((x >> 16)

jquery - how to increase a static number automatically everyday using php -

i use wordpress , have static number field taken sql query. <p class="counter-number">843</p> i increase number everyday. example when page loaded default number 843 next day should show 844 day after should show 845. how can this? prefer php if possible can use jquery. <?php $now = time(); $your_date = strtotime("2010-01-01"); //starting date $datediff = floor(($now - $your_date)/(60*60*24)); ?> <p class="counter-number"><?=$datediff?></p> code taken finding number of days between 2 dates this way show difference starting date now, in days.

angularjs - Unknown provider: eProvider <- e when showing material angular dialog -

i'm trying material angular 's dialog wired up. code below. error, unknown provider: eprovider <- e . js var app = angular.module('app', ['ngmaterial']); var dialogcontroller = app.controller('dialogcontroller', ['$scope', '$mddialog', function($scope, $mddialog) { $scope.hide = function () { $mddialog.hide(); }; $scope.cancel = function () { $mddialog.cancel(); }; $scope.answer = function (answer) { $mddialog.hide(answer); }; }]); app.controller('maincontroller', ['$scope', '$http', '$mddialog', function ($scope, $http, $mddialog) { $scope.showdialog = function (e) { e.preventdefault(); $mddialog.show({ controller: dialogcontroller, templateurl: 'sign-in.html', targetevent: e }); }; }]); html <a href="#" ng-click="showdialog($event)">show dia

Python If statement equal string -

i want jobber() following: if user inputs "talk" runs chat() , "calc" calculator() . this first project , new help. import sys import time def chat(): print('hello there. name?') name = sys.stdin.readline() print('your name %s...interesting. name chat created have small planned out conversation when call me :)' % (name)) time.sleep(2) print('how weather in town today?') weather = sys.stdin.readline() time.sleep(1.5) print('your weather %s? weather in town quite sunny.' % (weather)) time.sleep(2) print('this conversation can make @ moment. please patient while creator trys update me.') def calculator(): print('how money have?') money = int(sys.stdin.readline()) print('how paid?') job = int(sys.stdin.readline()) print('how spend?') spent = int(sys.stdin.readline()) week in range(0,30): money = money + job - spent

ruby - Rails bundle install path -

when use path flag bundle install, why ruby version go 2.1.0 when using version 2.1.5? for example: bundle install --path ~/bundled set structure to: ls ~/bundled/ruby/2.1.0/ bin/ build_info/ bundler/ cache/ doc/ extensions/ gems/ specifications/ why 2.1.0 instead of 2.1.5? 2.1.0 in library path refers ruby library version , not identical ruby version. all 2.1.x versions of ruby can safely share same gems, why when bundle install gems using ruby 2.1.0, 2.1.1, 2.1.2, 2.1.3, , 2.1.4, put gems in same 2.1.0 directory.

How much should a PHP class do? -

i'm oop nooby , i'm struggling grasp concept of how single class should do. i've seen lot of people class should 1 thing see lot of examples of classes doing more 1 thing. example, user login class. say had class like class login { public function __construct() { //connect database } public function checkcredentials() { //verify submitted username , password } public function login() { $this->checkcredentials(); //code log user in } } would want handle user data (add functions pull user information such name, address, etc.) class, extend class, or entirely new class? if i'm going in wrong direction, guys please point me in right direction? thanks in advance! there plenty of articles , talks around topic. generally speaking, recommended class should have one single responsibility . rule of thumb if takes more 1 sentence describe class, doing much. an application should

list - ay Array in python not getting updated -

following code in caller called first module, centroids of float type (an array of numberofcluster * numberoffeatures) labels 1d array of numberofexplanations array not getting updated def caller(centroids, labels): number_of_features = len(centroids[0]) one_column = [0, 0, 0, 0, 0] = 0 j = 0 array = [[0 x in xrange(number_of_features)] x in xrange(5)] while < number_of_features: j = 0 while j < 5: one_column[j] = centroids[j][i] j += 1 rank(one_column, i, array) += 1 return calculatemean(number_of_features, array) def rank(one_column, ithfeature, array): temp_dict = {} = 0 while < 5: temp_dict[one_column[i]] = += 1 number_of_uniquevalues = len(set(temp_dict)) sorted_dict = ordereddict(sorted(temp_dict.items())) = 0 keys_list = sorted_dict.keys() while < 5: array[one_column.index(keys_list[i])][ithfeature] = sort

asp.net - My subdomain .NET project is not directing to my startup file -

my wedding coming , i've printed 100 invites directing guests http://wedding.mydomain.com . similar stand-alone project, i've set startup page default.aspx page demonstrated here: http://blogs.msdn.com/b/zainnab/archive/2010/12/16/set-as-start-page-vstipproj0027.aspx . however, when directed toward http://wedding.mydomain.com , 'maintenance' page. have manually go http://wedding.mydomain.com/default.aspx , desired project. sounds might need set default document. if have using iis7(+) windows hosting can set default document in web.config like <configuration> <system.webserver> <defaultdocument enabled="true"> <files> <add value="default.aspx" /> </files> </defaultdocument> </system.webserver> </configuration> if using plesk interface refer article: https://support.godaddy.com/help/article/6853/changing-your-windows-hosting-acc

eclipse - Eclipe mars error -

i downloaded eclipse mars , on start error below: internal error occurred during: "setup check...". org.xml.sax.saxparseexceptionpublicid: user:/user.setup; systemid: user:/user.setup; linenumber: 1; columnnumber: 1; premature end of file. anybody knows causing error? , how fix it? thanks solved correct workspace solved problem. had 2 workspaces , 1 of them correct 1 , choose 1 solved it. thanks

c programming, disable user input into terminal -

hi there possible way temporarily disable user input terminal in c programming language? there reason why can't (possible malicious uses) if possible, can please illustrate how? maybe there function, setting or obscure system command? for context: friend having issues hard drive, created program ran few terminal command , printed output text file send me. worked fine, didn't know doing printed instructions console instruct him in do. although worked out, thought did occur potentially disable user input particular terminal window until required, , question. its pretty basic question if duplicate (although not find one) please label such.

ruby - I changed my integers to strings, but #gsub only recognizes 0-9 -

i'm self-learning ruby, , 1 assignment make caesar cipher. using #gsub, i've been able change letters integers ('c' => 2), shift them, change new integers strings (2 => "2"). i've hit wall, , ruby documentation isn't helping. when try #gsub strings letters ("2" => 'c') recognizes 0-9. after concatenation of numbers ("12" => 'bc' instead of => 'l'). why ruby this, , how can fix it? thanks guys. code: (i know it's sloppy beginner's code; try edit after passes) def convert_to_integer puts "what encode?" words = gets.chomp words = words.split("") words.map { |words| words.gsub!(/[a-z]/, 'a' => 0, 'b' => 1, 'c' => 2, 'd' => 3, 'e' => 4, 'f' => 5, 'g' => 6, 'h' => 7, 'i' => 8, 'j' => 9, 'k' => 10, 'l' => 11, '

mysql - How to build a real live post system on my page using PHP and MySQLi? -

i building php website. main purpose of website site follows: php check database , see if user's birthdate (day , month) equal today's date (day , month) , if equal, php should echo example "today james oduro's birthday". echoed on main page "go.php" php should check database , show registered members on main page "go.php" includes user's firstname, lastname , birthdates , picture. user should able post simple congratulation message on page other users having birthdays. now, have done 50% percent of work includes "php login script , validation", registration script, , validation using php, php checking database , seeing if user has birthday , echoing on main page , showing registered members on page, logout script , php echoing user's firstname on top of page using sessions variables. my website on testing server , want give account login see how page looks , ask questions regarding it. account login : email:

ruby on rails - How do I create a dropdown list specifically for Indian states and cities? -

my app planned go india , need add location information user profiles. there way create dropdowns myself states , cities or gems india. i mean if feed states , cities myself want showing user , allow him choose his, how do that? i can't work text fields because want make whole thing searchable locations , if users enter different locations quality of search drastically decrease. links tutorials welcome :) you use form select helper. if have possible states in activerecord, can in form: <%= f.select :state_id, state.all.collect {|s| [s.name, s.id]} %> if don't want them in activerecord, define array of in model, , feed form. also, take @ enumerize , gem, it's useful if have finite set of options field. and thing, there countries , cities gems householding city/country data.

java - Get Image/Transform/Shape to rotate to Follow Mouse Cursor in JavaFX -

i have tried this, @ positions, object, in case, imageview , "teleport" degree. how can make not choppy , follow mouse cursor in javafx scene? i did in blog post how create heat seeking missile . the relevant part code fragment: public void move() { spritebase follower = this; if( target != null) { //get distance between follower , target double distancex = target.getcenterx() - follower.getcenterx(); double distancey = target.getcentery() - follower.getcentery(); //get total distance 1 number double distancetotal = math.sqrt(distancex * distancex + distancey * distancey); //calculate how move double movedistancex = this.turnrate * distancex / distancetotal; double movedistancey = this.turnrate * distancey / distancetotal; //increase current speed follower.dx += movedistancex; follower.dy += movedistancey; //get total move distance double totalmove = math.sqrt(follower.dx * follower.dx + fol

pygtk - How to create a Gtk combobox with the interface new_with_area? -

according gtk documentation can create combobox with: gtkwidget * gtk_combo_box_new () gtkwidget * gtk_combo_box_new_with_entry () gtkwidget * gtk_combo_box_new_with_model () gtkwidget * gtk_combo_box_new_with_model_and_entry () gtkwidget * gtk_combo_box_new_with_area () gtkwidget * gtk_combo_box_new_with_area_and_entry () i have found lot of examples gtk_combo_box_new_with_model can't find related use of gtk_combo_box_new_with_area . the langage used doesn't matter. something (pygobject): from gi.repository import gtk area = gtk.cellareabox() combo = gtk.combobox.new_with_area(area=area) cell = gtk.cellrenderertext() area.pack_start(cell, true, true, true) you can add more cellrenderers box (which gtk.box) , whatever need those.

android - How to set gradient dynamically in a appwidget imageView background? -

i have set gradient in drawable\skycolor.xml <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item> <shape> <gradient android:angle="90" android:endcolor="#ff5bdddd" android:startcolor="#ff4688bf" android:type="linear" /> </shape> </item> i want set gradient background of homescreen widget. have imageview placed in widget. <imageview android:layout_width="fill_parent" android:layout_height="match_parent" android:id="@+id/iv_background" android:layout_centervertical="true" android:layout_centerhorizontal="true" android:focusableintouchmode="true" /> how set gradient background color in updateappwidget method? planned way, did not work. imageview iv_skycolor = (imageview)findviewbyid(r.id.iv_background); iv_sk

Android CursorLoader with selection and selectionArgs[] -

i using loader recyclerview.adapter list items. want list specific items database table. did: public loader<cursor> oncreateloader(int id, bundle args) { string selectionargs1[]={"1","13","14"}; string selection1 = databaseopenhelper.column_id + " in ("; (int = 0; < selectionargs1.length; i++) { selection1 += "?, "; } selection1 = selection1.substring(0, selection1.length() - 2) + ")"; string[] projection1 =... return new cursorloader(getactivity(),studentcontentprovider.content_uri1, projection1, selection1,selectionargs1, null); } normally give null,null selection , selectionargs here, list items specific ids . problem arises when new item added table , want list it. cursor returning not aware of new item since gave 3 specific items, detects when there change on 3 items. how list when there new item added id , want list ? should project items database recyc

node.js - Installing nodejs 0.10.36 on Ubuntu Trusty 64 -

how it, exactly? i go way: sudo add-apt-repository ppa:chris-lea/node.js sudo apt-get update sudo apt-get install nodejs but gives me 0.10.33. using apt-get preferable way me set ansible , want degree of compartability bash script like wget http://nodejs.org/dist/v${node_version}/${node_dist}.tar.gz tar xvzf ${node_dist}.tar.gz sudo rm -rf /opt/nodejs sudo mv ${node_dist} /opt/nodejs sudo ln -sf /opt/nodejs/bin/node /usr/bin/node sudo ln -sf /opt/nodejs/bin/npm /usr/bin/npm would latest resort. i run locally on virtualbox vagrant image ubuntu/trusty64. what using n ? n version manager node.js, allow have several version installed (and install them you), , run script version want. you can do: npm install -g n , then, n 0.10.36 or if want last version n latest or last stable: n stable .

c# - Login to SQL Server database not working -

i trying make log in page in c# web page. have written code think correct. user supposed key in correct username , password. before go further modifying after success log in temporarily set label 1 show me whether it's correct or not. doesn't work , every time tried key in correct data, show "failed". protected void imagebutton1_click(object sender, imageclickeventargs e) { sqlconnection con = new sqlconnection(); con.connectionstring = ("data source=localhost;initial catalog=seminardb; integrated security=true;"); try { con.open(); string str = "select * member username='" + signintext.text + "' , password='" + passwordtext.text + "'"; sqlcommand cmd = new sqlcommand(str, con); sqldatareader dr = cmd.executereader(); string login = signintext.text; string pwd = passwordtext.text; while (d