Posts

Showing posts from July, 2012

.net - How to implement Multi-type IComparable / IEquatable in C# -

let have following class: public sealed class scalevalue : icomparable, icomparable<scalevalue>, iequatable<scalevalue> { public double value { get; set;} public string definition { get; set;} // interface methods ... } if want make class comparable double should include icomparable<double> , implement way or have way? and when want class comparable doubles should double.compareto give same result scalevalue.compareto ? and how equals ? i think put responsibilities wrong in design. think best option make scale class containsvalue(double value) method. way can value , keep responsibilities needed. what class comparable you. make comparable anything , non-generic version of icomparable interface takes object ; in implementation of compareto method , can sniff type of object (unless null ). when use generic version of icomparable<t> , you're making statement implement strongly-typed comparison metho

asp.net mvc - Accessing entities model from other project in same solution -

i have mvc web project , other project have entities "database first" entity approach. referenced entities project web project seen on image below structure: http://i.imgur.com/h5zppig.png now created simple controller automatic crud operations. the error still complaining not having entities referenced: http://i.imgur.com/1javqr9.png this how type implemented in view: @model ienumerable<entities.users> what seems problem? you need register assembly razor view engine. you can put in web.config exists in views folder. <system.web> <controls> <add assembly="system.web.mvc, version=3.0.0.0, culture=neutral, publickeytoken=31bf3856ad364e35" namespace="system.web.mvc" tagprefix="mvc" /> <add yourassembly here /> </controls> </system.web> how register assembly in razor view engine

vhdl - Is the (concurrent) signal assignment within a process statement sequential or concurrent? -

from understand, statements inside process executed sequentially. happens concurrent signal assignment(<=)? work same way sequential assignment (:=) or execute after delta delay? if executes after delta delay, how can statements inside process called sequential? if executes immediately, there difference between := , <= in process? the signal assignment (<=) performed after sequential code in processes done executing. when active processes timestep done. as example why is: suppose have event triggers 2 processes. these 2 processes use same signal, 1 of them changes value of signal. simulator able perform 1 process @ time due sequential simulation model (not confuse concurrent model of vhdl). if process simulated first , changes signal, b have wrong signal value. therefore signal can changed after triggered processes done. the variable assignment (:=) executes immidiatly , can used e.g. temporarely store data inside process.

boxplot - How do I get box plot key numbers from an array in PHP? -

say have array values like: $values = array(48,30,97,61,34,40,51,33,1); and want values able plot box plot follows: $box_plot_values = array( 'lower_outlier' => 1, 'min' => 8, 'q1' => 32, 'median' => 40, 'q3' => 56, 'max' => 80, 'higher_outlier' => 97, ); how in php? function box_plot_values($array) { $return = array( 'lower_outlier' => 0, 'min' => 0, 'q1' => 0, 'median' => 0, 'q3' => 0, 'max' => 0, 'higher_outlier' => 0, ); $array_count = count($array); sort($array, sort_numeric); $return['min'] = $array[0]; $return['lower_outlier'] = $return['min']; $return

java - Displaying JLabel movement -

i attempting create simple animation in series of bubble rotate around centre point. have 1 version of animation bubbles spread centrepoint before begin rotate, works fine, click 1 of images (which sparks animation) screen freezes moment , bubbles appear in end position, rather showing each step made. what have far is: while(bubble[1].getdegree() != 270) { long time = system.currenttimemillis(); //the below if statement contains function calls //the rotating bubble animations. next(); draw(); // delay each frame - time took 1 frame time = (1000 / fps) - (system.currenttimemillis() - time); if (time > 0) { try { thread.sleep(time); } catch(exception e){} } } public void draw() { for(int = 1; < bubble.length; i++) { iconlabel[i].setlocation(bubble[i].getx(), bubble[i].gety());

java - Eclipse plugin: menu button greyed out -

i'm trying create simple eclipse button based on org.eclipse.ui.commands, org.eclipse.ui.menus , org.eclipse.ui.handlers but when debugging, button created greyed out: http://i.stack.imgur.com/rnpbz.png here plugin.xml , loginhandler.java plugin.xml <?xml version="1.0" encoding="utf-8"?> <?eclipse version="3.4"?> <plugin> <extension point="org.eclipse.ui.views"> <category name="server browsing" id="com.abc.serverapi"> </category> <view name="server browser" icon="icons/sample.gif" category="com.abc.serverapi" class="com.abc.serverapi.views.serverbrowser" id="com.abc.serverapi.views.serverbrowser"> </view> </extension> <extension point="org.eclipse.ui.perspectiveextens

mysql - Multiple concurrent database connections in rails -

i have rails application used several customers. each client access trough domain, domains work same rails app: my-client-1.mycompany.com my-client-2.mycompany.com my-client-n.mycompany.com the application works multiple databases, 1 database per client. of databases have same structure, identical. have 1 configuration per database in database.yml: my-client-1: adapter: username: my-client-2: adapter: username: ... i need indicate app based on domain used 1 user, must change database corresponding. example if user enters through my-client-2.mycompany.com database use must my-client2. i have done including in application_controller.rb code: before_filter :set_db_connection def set_db_connection d = request.host.split('.') current_domain = d[0] activerecord::base.establish_connection current_domain end now have next 2 questions: ¿is right way solve problem? ¿what happens if 1 user processing , takes 60 seconds, , in moment user ente

java - How to search for a pattern within a String/Char array? -

i need pattern in input given user. , return (start,end)position if found. eg:- input = a b c d b c d pattern = d c a output = 3,6 the pattern need not occur consecutively. it can d @ start of input, c @ middle , @ end. - valid scenario. two things confused about. how take input? array? if yes, string or char array? how pattern? the format of input not matter here: can take both string , sequence strings. trick deciding on algorithm use solve problem. in case, greedy strategy work: read 2 strings, s (string) , p (pattern). make 2 indexes - si string, , pi pattern, , set them both zero. search letter p.charat(pi) in s starting @ si . if letter cannot found in substring si end, pattern not exist otherwise, take first occurrence of p.charat(pi) in s , set si index plus one, , advance pi one. if reach end of p , done otherwise, go search step, , continue processing until either find pattern, or exhaust string. if need print indexes seque

php - How to host an yii project in Heroku cloud platform? -

can 1 explain how host yii project in heroku. i have tried , pushed yii project heroku. but not loading , shows server error. you'll want app setup can see debugging errors (yii_debug in index.php file). you're running permissions errors on runtime folder. see more details: heroku + yii "application runtime path not valid"

angularjs - Injecting a HTML template to DOM on click the clean way (Create an instance of a class)? -

in angularjs project have (it's dropdown menu customer names. click on 1 of names scrum card should appear customer's names inserted in card.): <ul class="dropdown-menu red" > <li ng-repeat="customer in customers" ng-click="addcard()"> // here goes html code </li> </ul> i want accomplish card inserted on every click. problem is, card has multiple lines of html code. better insert whole new template. can't insert template ng-click, right? besides that, put html in variable , push list quite dirty, isn't it? so, thought creating card class in coffeescript , create instance on every click. practive create class on click html template/partial? how tell angular create new instance of class card? (before created directive had templateurl attribute partial. same problem: want inject directive on ng-click , not manually including directive in code ... btw, angular , coffeescript beginner ...) t

elasticsearch - Wrong count for nested facets -

i'm building search products , variants. 1 product can have many nested variants. example: 1 t-shirt can in 2 variants, white 50 euros , green 60 euros. it's still same product , should displayed once on results page. this mapping: {"product" => { "properties" => {"vendor_variants" => {"type" => "nested"}}}} and query i'm doing: "query" => { "filtered" => { "query" => { "match_all" => {} }, "filter" => { "bool" => { "must" => [ { "terms" => { "categories" => [122] } } ] } } } }, "facets" => { "brand" => { "terms" => {"field" => "filter_brand"} }, "price_range" =&

java - JavaFX: How to ask for user input before a GUI is displayed -

i'm having little bit of trouble javafx in netbeans 7.3.1. i'm attempting make game rolls die. program supposed ask user if die fair or not, along other information (such number of sides) initialize die roll. when roll button clicked, roll die. my issue since javafx ignores main program when launches gui, i'm not sure (or how) ask user information before gui loads. public class dicegame extends application { @override public void start(stage primarystage) { button btn = new button(); btn.settext("roll die!"); btn.setonaction(new eventhandler<actionevent>() { @override public void handle(actionevent event) { // // code rolling die goes here. } }); stackpane root = new stackpane(); root.getchildren().add(btn); scene scene = new scene(root, 300, 250); primarystage.settitle("dice game"); primarystage.setscene(scene); primarystage.show(); } /** * main(

mp3 - How can I reliably load and display images from ID3 tags using javascript? -

i'm trying display image loaded id3 , id3v2 files. i'm able of tag fields off of id3 , id3v2 files, , picture big string of data. i've tried doing like: var image = 'data:image/png;base64,' + (tags.picture); and creating image element, doesn't work. so i'm wondering, image data in id3 tag not base64? , if so, perhaps i'm not reading format of image correctly? i'm new working sort of file, hints or tips amazing.

Read Excel sheet in Powershell -

the below script reads sheet names of excel document.... how improve extract contents of column b (starting row 5 - row 1-4 ignored) in each worksheet , create object? e.g. if column b in worksheet 1 (called london) has following values: marleybone paddington victoria hammersmith and column c in worksheet 2 (called) nottingham has following values: alverton annesley arnold askham i'd want create object looks this: city,area london,marleybone london,paddington london,victoria london,hammersmith nottingham,alverton nottingham,annesley nottingham,arnold nottingham,askham this code far: clear sheetname = @() $excel=new-object -com excel.application $wb=$excel.workbooks.open("c:\users\administrator\my_test.xls") ($i=1; $i -le $wb.sheets.count; $i++) { $sheetname+=$wb.sheets.item($i).name; } $sheetname this assumes content in column b on each sheet (since it's not clear how determine column on each sheet.) , last

php - Magento - Quickly translate catalogue/product info -

i created store view each language , installed necessary language packs. know how create product , switch store view translate name/description. the problem process slow in case need insert lot of products. question: there way faster (such using translation files or being able insert names/descriptions in 1 page)? magento use files localization (app/locale). these files, can translate except product description , cms pages. have create different description each language. 1 product fine, not when have thousands of products. if have lot of products, may want try extension. source: http://www.magentocommerce.com/magento-connect/google-translate.html

linux - Seamless memory-mapped files in C -

i'm creating several programs in c have communicate through files. they using files because communication not linear, i.e. program #5 use file program #2 created. the execution of these programs linear (serial). there single control program manages execution of these cascading programs. program 1 creating files, , should pass file names programs since disk i/o slow (lets assume os doesn't cache these operations), need use memory-mapped files. however, requirement control program can seamlessly switch between regular , memory-mapped files - means cascading programs have unaware of whether they're writing/reading to/from memory-mapped file or regular one. how can create file, presents rest of system normal file (has place in fs hierarchy, file name, can read , written), in fact in memory , not on disk? the terminology you're using here little weird - memory-mapping way of accessing file (any file), not separate type of file 1 that's stored on

java - Compare two objects, and return string. But one object doesn't take parameters? -

this homework. goal: want compare date of 2 objects decide whether person object adult or not , store in string. the strange thing is, values of date d1 0; public class date { public int day, month, year; public string child date(date d1, date d2) { if ((d1.year - d2.year > 18) || ((d1.year - d2.year == 18) && (d2.year> d1.year)) || ((d1.year - d2.year == 18) && (d2.year == d1.maand) && (d2.day > d1.day))) { child = adult; } else { child = child; } date(int a, int b, int c) { = year; b = month; c = day; } date (string birthdate) { string pattern = "\\d{2}-\\d{2}-\\d{4}"; boolean b = birthdate.matches(pattern); if (b) { string[] str = birthdate.split("-"); (string s: str) this.day = integer.parseint(str[0]); this.month = integer.parseint(str[1]); this.year = integer.p

java - Create a timed application -

i create simple game requires guess number within amount of turns (eg. 10). however, makes quite easy beat. need how keep track of how long game has been going on for. this have thought of far (minus game logic), doesn't seem working random rannum = new random(); double input; // input long starttime; // time game started long curtime; // time game ended double randnum = rannum.nextint(100); while (curtime > 1000){ curtime = system.currenttimemillis(); input = textio.getlndouble(); if (input = math.abs(randnum)){ system.out.println("you got correct answer"); } // end if statement else { system.out.println("you did not have correct answer"); system.out.println("the number was" + randnum + "."); } // end else statement } // end while statement you have current timestamp before

ruby - Check if string contains one word or more -

when looping through lines of text, neatest way (most 'ruby') if else statement (or similar) check if string single word or not? def check_if_single_word(string) # code here end s1 = "two words" s2 = "hello" check_if_single_word(s1) -> false check_if_single_word(s2) -> true since you're asking 'most ruby' way, i'd rename method single_word? one way check presence of space character. def single_word?(string) !string.strip.include? " " end but if want allow particular set of characters meet your definition of word, perhaps including apostrophes , hyphens, use regex: def single_word?(string) string.scan(/[\w'-]+/).length == 1 end

c# - SlideInEffect and TurnstileFeatherEffect not working -

anyone ever had problems slideineffect , turnstilefeathereffect windows phone toolkit? i trying make slideineffect work on longlistselector , longlistmultiselector no luck far. also turnstilefeathereffect not work when page loading work when navigating away them. same applies pages (panorama / pivot / normal pages). take example code on normal page: <phone:phoneapplicationpage x:class="samplepage.pages.about" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:phone="clr-namespace:microsoft.phone.controls;assembly=microsoft.phone" xmlns:shell="clr-namespace:microsoft.phone.shell;assembly=microsoft.phone" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" fontfamily="{staticresource phonefontfamilynormal}&q

javascript - Backbone.Model. Replace attributes hash -

is there options set method or other way replace current attributes of model ones provided? here want: var instance = new backbone.model(); instance.set({foo: 1}); instance.set({bar: 2}, {replace: true}); //just example console.log(instance.tojson()); //returns {bar: 2} i guess looking this: http://backbonejs.org/#model-clear instance.clear().set({bar: 2});

inheritance - Detructors and inherited functions c++ -

if have 2 classes this: class { public: virtual print(){}; ~a(){print();} }; class b:public { public: print(){}; ~b(){} }; void main() { b *b1=new b; delete b1; } in destructor in class call print class , not b because when in class destructor,class b technically destructed? yes, thats right. class destructed calling destructor itself, , destructor parent classes, means time destruct a, b gone. see similar behaviour if invoke virtual, overriden functions in base classes when constructing. it considered bad practice call virtual functions in constructors or destructors, behaviour, while well-defined, can misleading uninitiated. it's easy trip if initiated.

Filter a string for words that starts with a "?" and put them in a <span> - PHP -

what wanna filter string one: "?group title" and output this: <span class="group">group</span> title my question offcourse is: possible php? , how this? try this $text = preg_replace('/\?(\w+)/', '<span class="$1">$1</span>', $text);

iphone - How to replace OpenGL ES 1.1 EAGLLayer view with OpenGL view from GLKit? -

i have simple game uses eagllayer directly. had set runloop , opengl es boilerplate. game crashes because of opengl backgrounding problems. heard glkit has robust boilerplate opengl view takes care of opengl initialize , suspension. is possible set glkit view opengl 1.1 , start? this rather open-ended question, it's best start getting background glkit , ask more questions if have specific issues. take @ code when creating new xcode project using "opengl game" template -- sets glkview , glkviewcontroller you. there's description of how these classes work , how use them in apple's opengl es programming guide . the overall gist of it: glkview of framebuffer, renderbuffer, , viewport setup , presentation basic opengl es drawing (including framebuffer juggling multisampling if want that) have issue drawing commands. glkviewcontroller owns glkview , runs animation timer calls drawing code -- default, makes sure not call drawing code when app in b

xcode5 - xcode, argument set but being ignored when launched from device -

i have argument setup on 1 of apps. when app launched xcode, argument passed fine, can see being outputted console. when app launched phone, not xcode, argument missing, returns 0 on following code nsprocessinfo *proc = [nsprocessinfo processinfo]; nsarray *args = [proc arguments]; if([args count] > 1) { nsstring *myarg = [args objectatindex: 1]; if([myarg isequaltostring:@"proversion"]) [appdata setispro:true]; } nslog(@"is pro: %hhd", [appdata ispro]); in scheme, argument set in product->run apple library says solved problem using preprocessor macro defined in build settings instead

How can I do a multithreading twisted python -

i have question bothers me long time, i'm working on daemon operating requests outside. server-client. in project, i'm using twisted python framework, , successful build non-multithreading server, works! now, need serve several customers @ once. don't know how can in twisted framework. tried know... please me :| class server(protocol.protocol, protocol.factory): def buildprotocol(self, addr): if addr.host in iplist: log.msg("connected ip: " + addr.host) return self return none def datareceived(self, data): reactor.callfromthread(self.actioncreator(data)) def actioncreator(self, data): jsondata = json.loads(data) if not jsondata["action"]: log.msg("incorrect data ip: " + self.transport.getpeer().host + " data: " + data) self.transport.write(json.dumps({'response' : '300'})) elif jsondata["action"] == 'echo'

class - How to create an equals Method in Java for 2 credit cards -

so i'm having issue writing code such able create equals method return true if 2 credit cards equal if have same security code, company , account number. heres code far. public class creditcard { private double balance; public static double interestrate; public static string personname; public static string company; public static double creditline; public creditcard () { balance = 0; } public static void setintrate (double rate) { interestrate = rate; system.out.println("the interest rate card : " + interestrate); } public static double getintrate () { return interestrate; } public static void setpersonname (creditcard card ,string pname) { personname = pname; system.out.println("name on card: " + personname); } public static void setcompany (creditcard card, string compname) { company =compname; system.out.println("the company name : "+ company); } //creates new card number public static void cardnum (credi

java - Using Volley and Gson: Parse item and items list -

one thing i've never liked gson fact have pass class object or typetoken based on if you're getting item or list of items. now, when trying use volley gson problem persists , i'm trying make gsonrequest class can used both things. my solution quite ugly, 2 different constructors: 1 getting class<t> parameter , 1 getting type parameters. then, in parsenetworkresponse , gson.fromjson called either 1 of fields, keeping in mind 1 has null . any idea of how implement in better way? (i don't having gsonrequest , gsoncollectionrequest almost-equal classes) my code, here: public class gsonrequest<t> extends request<t> { private final gson gson; private final class<t> clazz; private final type type; private final listener<t> listener; private final map<string, string> headers; private final map<string, string> params; public gsonrequest(int method, string url, gson gson, class<t> claz

android - How do I design my own custom schedule calendar? -

an event object stores usertask object , int scheduledtime , , boolean[] daysofweektorepeat denoting days of week when should repeated. these event objects inserted sparse array list<arraylist<event>> calendareventsmatrix. the structure has been tried , tested, works. next step design ui allows user see events on calendar. user can click on events , add, edit, or delete events. here current design plan: create eventslot.class extends linearlayout. basis entire calendar. each eventslot view have own onclicklistener. create weekcolumn.class extends linearlayout. weekcolumn vertical linearlayout fill bunch of eventslot views somehow numbered every hour of day. create eventsframe.class extend linearlayout. eventsframe horizontal linearlayout fill 7 of these weekcolumn views (one every day of week). create calendarframe.class extend viewgroup. container eventsframe, other useful textviews , labels. calendarframe inflated , placed fragment. assuming of has b

jquery - Ajax within an each() method -

i have 3 scripts the first 1 dynamically generates form contain several inputs values contain id_mensaje i'm intereted in. want delete mysql registries related id_mensaje. i'd rather show scripts 1.- correo.php <div id='eliminar_mensaje'><a href='#'>eliminar</a> </div> <form> <input class='elim_msg' type='checkbox' value='id_mensaje_".$i."' /> ... more inputs whith same class name </form> 2.- correo.js $('#eliminar_mensaje a').on('click', function(){ $('#loading').show(); $('.elim_msg').each(function(i,e){ var value = $(e).val(); var checked = $(e).prop('checked'); if(value != 'ok' && checked == true){ $.ajax({ url: 'private/control_correo.php', type: 'post', data: '

JavaFX - Set focus border for Textfield using CSS -

i want have textfield 3 different borders 3 cases: a white border when not hovered or focused a grey border when hovering a blue border when focused , typing i started this: #custom-text-field { -fx-border-width: 2; -fx-border-color: white; } #custom-text-field:hover{ -fx-border-width: 2; -fx-border-color: #909090; } #custom-text-field:focused{ -fx-border-width: 2; -fx-border-color: #0093ef; } the problem border focusing never shows up. how set correctly? i use this .custom-text-field { -fx-background-color: #ffffff, #ffffff; -fx-background-insets: 0, 2; -fx-background-radius: 0, 0; } .custom-text-field:focused { -fx-background-color: #0093ef, #ffffff; } .custom-text-field:hover { -fx-background-color: #909090, #ffffff; } .custom-text-field:focused:hover { -fx-background-color: #0093ef, #ffffff; }

php - Using a variable to direct traffic -

i sure error variable not being gotten table. can not see error asking data @ same time asking username , password. table consists of [username],[password],[company]. goal have user directed based on name in company after username , password have been verified. keep getting echo @ end. here code function registeruser($usename, $password, $company) { // hash pwd $hpwd = hash('sha256',$password); $q ='insert users values(username, password, company) values(?,?,?)'; $stmt = pdo::prepare($q); $stmt->exectue(array( $username, $hpwd, $company)); } // validate user , return company if successfull function validateuser($username, $password, &$company) { $hpwd = hash('sha256',$password); $q ='select company users username=? , password=?'; $stmt = pdo::prepare($q); $stmt->exectue(array( $username, $hpwd)); if( ($company = $stmt->fetch(pdo::fetch_column)) === false ) { $company = header( 'locati

cryptography - Why DES can be used only with 56bit key? And why the plaintext must be 64 bits in length? -

why des can used 56bit key? happens if use longer key? also, why plaintext must 64 bits in length? us regulations @ time required users of stronger 56-bit keys, submit "key recovery" enable law enforcement back-door access. thus des, standard, specified @ maximum allowed key length of 56 bits. if used longer key, not compatible other des systems. see: http://en.wikipedia.org/wiki/56-bit_encryption if implementing system & have choice of encryption, more modern & stronger ciphers absolutely recommended. current standard aes (advanced encryption system) available, strong , allows key sizes 128 - 256 bits. for desktop or server applications, aes-256 default choice. see: http://en.wikipedia.org/wiki/advanced_encryption_standard when encrypting data, plaintexts must "padded" minimum size. ciphers rely on jumbling , interactions between multiple bits, preserve secrecy of plaintext & avoid potentially revealing key. short plaintext with

c# - Should i StrongName / Strong-Sign an OSS dll? -

i have number of open source projects have nuget packages available. recently, asked strong-sign 1 of these oss nuget packages (well, dll in package, more concise). so - questions: if strong-sign it, can other dll's not strong signed, use it? do/should commit .snk file public repository? if yes, wouldn't defeat purpose of having 'secretly' signed? cheers! it's interesting set of questions. if strong-sign it, can other dll's not strong signed, use it? i believe answer yes. strong signing means create "chain of trust". can use signed dll's without signing consuming dll. do/should commit .snk file public repository? if yes, wouldn't defeat purpose of having 'secretly' signed? yes. if publish .snk file defeat purpose of strong signing (for part) because can sign dll. people want consume publicly available source project should take responsibility signing own uses. if have customer wants or distr

performance - MongoDB Given a list of keys, get all matching docs and create new docs for non-matching keys -

say i've got collections of user documents indexed email address. given list of email addresses, need to: 1. each user doc email in list 2. create new user doc each email in list no user exists. i can solve first problem $in query, hoping there way $in query return list of emails not found in db. can efficiently insert new docs. otherwise, have loop on docs find emails weren't picked up. what's efficient way accomplish both of above tasks? there fast way batch insert new user docs set of unique emails? i hoping there way $in query return list of emails not found in db. you use $nin . unfortunately, $ne , $nin can't make use of indexes , might not best bet (but maybe worth try). the best approach depends on 'cache-miss-rate', should work if number of existing matches isn't high (pseudocode) var emails; var matchingmails = users.find({"email" : {$in : emails}}, {"email":1, "_id":0}); var newemails =

accumulate - VB.NET - Accumulating Numbers and Calculating Average -

i have started on , working intended except 2 of accumulating totals, calculation not working way need to. instead of adding previous sales total tacks new sale on end... for example: input 1 snowboard , 1 snowboard boots, works, 1 shown in summary both snowboards , snowboards boots. when try input again in order keep running total of sales have problem, enter 1 snowboard , 1 snowboard boots, , summaries show 11 rather 2. why happen? ' declare module-level variables , constants. private snowboardssold, bootssold, salecount integer private itemssold integer private totalsales decimal const snowboard_rate decimal = 20d const boots_rate decimal = 30d private sub calculatebutton_click(byval sender system.object, byval e system.eventargs) handles calculatebutton.click ' calculate prices dim snowboards, boots integer dim snowboardsale, bootssale, thissale, averagesalesever decimal try ' convert snowboard input numeric variable. snowbo

ruby on rails - Why can't I install any gems on my Mac? -

i tried doing gem install gem , have been getting errors. think need reset , or update on computer not sure what. here of command line code errors: error: not find valid gem 'multi_json' (>= 0), here why: unable download data https://rubygems.org/ - ssl_connect returned=1 errno=0 state=sslv3 read server certificate b: certificate verify failed (https://s3.amazonaws.com/production.s3.rubygems.org/latest_specs.4.8.gz) error: not find valid gem 'cowsay' (>= 0), here why: unable download data https://rubygems.org/ - ssl_connect returned=1 errno=0 state=sslv3 read server certificate b: certificate verify failed (https://s3.amazonaws.com/production.s3.rubygems.org/latest_specs.4.8.gz) sudo gem install rubygems-update password: error: not find valid gem 'rubygems-update' (>= 0), here why: unable download data https://rubygems.org/ - ssl_connect returned=1 errno=0 state=sslv3 read server certificate b: certificate ver

How to use a variable path in MySQL query in a Python script -

i having trouble getting variable path mysql query in python script. path variable either resolved double backslashes or none @ all. this works: cursor.execute ("""load data local infile 'm:/users/jonathan/dropbox/bchs_3015/spatial data/cartographic data/usa/acs_data/sequence_number_and_table_number_lookup.csv' table sequence_table_lookup fields terminated ','enclosed '"' lines terminated '\r\n' ignore 1 lines (file_id,table_id,sequence_number,line_number, subject_area)"""); this following returns error: _mysql_exceptions.internalerror: (22, "file 'm:usersjonathandropbox\x08chs_3015spatial datacartographic datausaacs_datasequence_number_and_table_number_lookup.txt' not found (errcode: 22)") cursor.execute ("""load data local infile '%s' table sequence_table_lookup

c - Does libuv provide any facilities to attach a buffer to a connection and re use it -

i evaluating libuv library c/c++ server writing. protocol length prefixed can read 32 bit integer stream should able tell size of buffer should allocate. documentation says uv_read_start function might called multiple times. uv_extern int uv_read_start(uv_stream_t*, uv_alloc_cb alloc_cb, uv_read_cb read_cb); since using length prefixed protocol, once know right size of buffer allocate , re use subsequent reads till have received bytes. there easy way libuv? right seems uv_alloc_cb function has take care of this. can associate buffer stream object instead of putting in map or something? since using length prefixed protocol, not allocate buffer on heap @ till can read first 4 bytes (32 bits). possible me allocate on stack buffer of size 4 , have uv_read_cb function heap allocation? uv_read_cb function invoked synchronously part of uv_read_start function? if seems should able allocate on stack when know don't have buffer attached stream. answering own question.

c# 4.0 - Do we need this keyword in .net 4.0 or 4.5 -

i reviewing code written in c#, visual studio 2012. in lot of places, code written using key word, ex: this.pnlphonebasicdtls.visible = true; this.setphaggstats(ostats); there many other places controls of page referred using key word. can advise need use here? consequences of removing keyword? thanks in advance.. the this keyword usually optional. it's used disambiguate fields arguments if same name being used both, example: void main() { var sc = new someclass(); sc.somemethod(123); console.writeline(sc.thing); } public class someclass { public int thing; public void somemethod(int thing) { this.thing = thing + 1; } } in example above make difference. inside somemethod , this.thing refers field , thing refers argument. (note simpler assignment thing = thing picked compiler error, since no-op.) of course, if use resharper unnecessary this. (together unused using statements, unreachable code, etc.) greyed

Using HttpRequest in Windows Phone -

i have binary stream takes photo stream photochooser task in windows phone. trying upload picture user chooses onto web server. how copy photo stream httprequest stream? so far have this binarystream bstream = new binarystream(streamfromphotochooser); httprequest request = new httprequest() i know how set properties httprequest uploads right place. problem actual uploading of picture. you can write or copy binary stream request stream getting request stream , writing stream it. here sort of code may find useful web request httpwebrequest , problem capy photo stream in httprequest stream done in getrequeststreamcallback() private void uploadclick() { httpwebrequest myrequest = (httpwebrequest)webrequest.create("your url of server"); myrequest.method = "post"; myrequest.contenttype = "application/x-www-form-urlencoded"; myrequest.begingetrequeststream(new asynccallback(getrequeststreamcallback), myr

Custom 'Edit Profile' Location in Wordpress -

what trying have edit profile option in admin bar @ top of wordpress page go url. basically instead of going /wp-admin directory i trying go the /editprofile.php page. you can use filter edit_profile_url : add_filter( 'edit_profile_url', 'custom_profile_link_so_19216787', 10, 3 ); function custom_profile_link_so_19216787( $url, $user, $scheme ) { return site_url( 'editprofile' ); } i suppose /editprofile.php page using template , address example.com/editprofile . if that's not case, put full url instead of site_url($slug) . related: where put code: plugin or functions.php?

angularjs - Angular with socket.io & backend php -

i working on realtime app (chat) & using angular , backend php(codeigniter restapi) database in mongodb hear somewhere socket.io best library socket (use real time) , , see socket.io use node.js , may need basic knowledge of node or other feasible way work socket.io , angular , php you have 3 ways: * use node.js server * it depends how large api. in opinion mongodb , sockets node.js better php.why? mongodb using json format , nodejs javascript server better handle json. nodejs have non-blocking io faster socket php. can read more here . nodejs simple learn. * use php sockets * you don't need start new node.js server if have alredy php. can use library similar socket.io. lets check: elephant io * use php api , node socket * i think don't need use data api socket. can create node server sockets calls , php server api calls.

Displaying unicode characters in codemirror -

i have xml lots of unicode characters. coming out of database original ¶ represented &#182; (which in turn correctly rendered ¶ in html). however, codemirror displays &#182;. there way of having codemirror render these sequences html does, ie ¶? figured out solution -- convert entities before submitting codemirror. see value &# unicode convert

php - Calculate Rate based on distance range -

i have been working project have following table structure start | end | rate ------------------ 1 | 50 | 10 51 | 100 | 20 101 | 150 | 40 151 | 200 | 80 201 | 0 |100 here last record means 200 infinite value has rate 100 here have calculate total rate based on start , end values given users i have tried following query in mysql input start - 30, end - 170 select sum((end+1 - start) * amount) table start > 30 , end < 170 which gives 2nd , 3rd record values sum, have query first , last records separately. how achieve in single query? let's assume have following 2 parameters declared: set @start = 30, @end = 170; first rows fall within range (overlapping), ( sql fiddle ): select start, end table1 start <= @end or end >= @start then massage start , end of ranges first , last rows. capping first part of range @ @start , second part of range @ @end ( sql fiddle ): select case when @start > start @start else start e