Posts

Showing posts from March, 2013

tuples - Guards in Haskell, performing operations using checks -

so have searched different ways of approaching "if" statements in haskell , have doubt guards, have tuple , want perform +,-,*,/ checking conditions: given (x,y) if x < y +,* want integers, furthermore check division x mod y == 0 or not, compiles can-t run operaciones (x,y) = (x,y) x,y | x < y = [(x, y, '+', x+y), (x, y, '*', x*y)] | (x > y) && (x `mod ` y == 0) = [(x, y, '+', x+y), (x, y, '*', x*y), (x, y, '-', x-y) , (x, y, '/', x/y)] | (x > y) && (x `mod ` y /= 0) = [(x, y, '+', x+y), (x, y, '*', x*y), (x, y, '-', x-y)] | otherwise = [(x, y, '+', x+y), (x, y, '*', x*y), (x, y, '-', x-y) , (x, y, '/', x/y)] i took idea haskell: multiple case statements in single function but failed, otherwise if x == y i wouldn't recommend style; you're repeating way much. understand it, want function: operaci

Copy Array to text file c++ error munmap_chunk() -

hi trying create text file stores value of array. program runs when try insert code copy text file error munmap_chunk(): invalid pointer munmap_chunk(): invalid pointer the text file created empty #include <iostream> #include <string> #include <cstdlib> #include <fstream> using namespace std; int generator(void){ int state; state = 1 + rand() % 2; return state; } int main() { int nwalks,nsteps,x,state; double xsum1,xsum2,xaccum; int *arxaccum = new int[nwalks]; int *arxsquared = new int[nwalks]; cout << "give number of walks : "; cin >> nwalks; cout << "give number of steps : "; cin >> nsteps; ofstream arraydata("/home/path/xaverage.txt",ios::app); srand(1256); xaccum = 0.0; xsum1 = 0.0; xsum2 = 0.0; (int walks = 1; walks <= nwalks; walks++) { x = 0; (int steps = 1; steps <= nsteps; steps++) { state = generator() ; if (state == 1) x += +1; else

android - sqlite is not being used by pouchdb to store the data -

i developing hybrid application using cordova4.1.1, angularjs , cordova. have imported following libraries in following order. cordova.js sqliteplugin.js ng-cordova.js pouchdb-5.2.1.js angular.js when try check pouchdb db settings parameter { adapter:websql }, getting output sqlite_plugin:false .

list - how to keep position of other link when mouse is over a link-html Css? -

i have ul list float:right li. want set center of page. margin , left doesnt work well. i want when mouse on link ,keep position of other link , dont move forward. my css code this: #menu2 li { -webkit-transition: 0.3s ease; -moz-transition: 0.3s ease; -o-transition: 0.3s ease; -ms-transition: 0.3s ease; transition: 0.3s ease; } #menu2 li a:hover { border: none; font-size: 30px; } <!--===============================================================<!--===============================================================--> --> ul, li { display: inline-block; } #menu2 ul { list-style-type: none; background-color: #003; text-align: center; } #menu2 li { float: left; list-style-type: none; padding: 15px 15px; } #menu2 { min-width: 800px; margin-top: 15%; right: 65% !important; } #menu2 li { display: block; color: white; text-align: center; padding: 14px 16px; text-decoration: none; backgro

rust - How to conditionally assign a type to a reference -

i have been playing rust afternoon , decided write simple hashing tool can major digesting algorithms. i'm trying (intent should obvious): let mut hasher; match alg { "md5" => { hasher = md5::new() } "sha1" => { hasher = sha1::new() } _ => { println!("algorithm not implemented"); process::exit(1); } } hash_file(&file_name, &mut hasher).unwrap(); when compiling above, due first match, assumes hasher of type md5 , fails when in "sha1" match branch, tries assign sha1 type. of types intend use in match statement implementers of trait digest feel there should way this. i tried: let mut hasher: digest; but didn't work either. it sounds want use trait objects . example this: let mut hasher; match alg { "md5" => { hasher = box::new(md5::new()) box<digest>} "sha1" => { hasher = box::new(sha1::new()) box<digest>} _ => { print

Android Layout; Image takes entire screen -

Image
i trying fill activity 2 views, imageview on left side, , textview on right. image should sized fill entire vertical space. text should occupy whatever space left over. after watching few tutorials, seems need linearlayout horizontal orientation, , textview 's layout_weight property positive integer. this have far: <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingbottom="@dimen/activity_vertical_margin" tools:context=".mainactivity"> <imageview android:id="@+id/imageview" android:layout_width="wrap_content" android:layout_height="match_parent" android:src="@drawable/charsheet" /> <textview andr

c++ - Using smart pointers with MySQL Connector -

most tutorials related mysql connector libraries assume, user use raw pointers. i'd use smart pointers instead. i've written following class: class database{ private: bool _connected = false; std::shared_ptr<sql::driver> _driver; std::shared_ptr<sql::connection> _connection; std::shared_ptr<sql::statement> _statement; std::shared_ptr<sql::resultset> _resource; public: database(); ~database(); bool connect(const std::string &ip, const std::string &user, const std::string password); bool connected(); }; i'm trying implement connect function, receive following error during compilation: /usr/include/c++/5.3.0/ext/new_allocator.h:120:4: error: invalid new-expression of abstract class type ‘sql::driver’ { ::new((void *)__p) _up(std::forward<_args>(__args)...); } it caused following line of code: this->_driver = std::make_shared<sql::driver>

python - NameError: name 'C' is not defined` error Converting Temperature -

i'm working on python code convert fahrenheit celsius , second code converts celsius fahrenheit. wrote each code same way, using (if/else) whenever try make first condition true. example, when temperature f = -400 nameerror: name 'c' not defined error. i tried changed line position c runs before last print line. still no luck. second code part converts c f runs without error. tried putting equation c after last print line still same error. is may missing on first part may preventing me making first condition true? i'm running python 2.7.10 , using terminal on mac os x el capitan (10.11) convert fahrenheit celsius: f = int(raw_input("enter temperature in fahrenheit:")) if f >= (-459.67): print "temperature in absolute 0 cannot achieved" else: c = f - 32 * (0.555556) print "the temperature %.1f" 'c' % c convert celsius fahrenheit: c = int(raw_input("enter temperature in celsius:")) if

JMockit method that isn't mocked doesn't work -

sample class public class test{ @tested classa obja; @test(expected = myexception.class){ string expectedvar = "expectedvar"; new expectations(obja) { { obja.somemethod(); result = expectedvar; } }; // here error, when debug programm doesn't enter following method. // if connent out new expectations(){{...}} block, programm // enter method obja.execute() obja.execute(); } could explain happening here , why setting expectations on method changes behaviour of other method? i didn't find answer, did other way: new mockup<classa>() { @mock string somemethod() { return expectedvar; } }; and worked expected

Grails GORM where method not recognised by IntelliJ -

Image
this more of minor annoyance anything, can explain why intellij (15 in case) isn't able find where method domain objects? able use dynamic finders completion, there where method never completes. in image below can see intellij happy findby*, has no idea on where. case when trying autocomplete method names. debugging etc works fine, it's working somehow internally.

java - Gson custom deserializer not called for null values -

i'm using gson serialization in javafx context. avoid having property boilerplate in serialized json, created handful of custom serializers/deserializers write property's value instead of actual property object, in particular 1 generic property<t> : private static class propertyserializer implements jsonserializer<property<?>> { @override public jsonelement serialize(property<?> property, type type, jsonserializationcontext context) { object value = property.getvalue(); return context.serialize(value); } } private static class propertydeserializer implements jsondeserializer<property<?>> { @override public property<?> deserialize(jsonelement json, type typeoft, jsondeserializationcontext context) throws jsonparseexception { if (json.isjsonnull()) { system.out.println("i never printed"); } type typeparam = ((parameterizedtype) typeoft).getactualtypea

javascript - How to render rest api call in node.js with express and handlebar or other template engine? -

use case using node.js, express , template engine handlebars query rest apis wordpress , couchdb , render results. i have come far var https = require('https'); var express = require('express'); var handlebars = require('express-handlebars') .create({ defaultlayout:'main' }); var app = express(); app.engine('handlebars', handlebars.engine); app.set('view engine', 'handlebars'); app.set('port', process.env.port || 3000); app.set('ip', process.env.ip); var options = { hostname: 'public-api.wordpress.com', path: '/rest/v1.1/sites/somesite.wordpress.com/posts/16', method: 'get' }; app.get('/test', function(req, res) { https.request(options, function(restres) { console.log('status: ' + restres.statuscode); res.render('home', { "title": "test" }); // code works. restres.on('data', function (jsonresult) {

c++ - How do I call a function from another .cpp file into the file where my int main() is? -

this question has answer here: what undefined reference/unresolved external symbol error , how fix it? 27 answers so program requires me make function in 1 file, , call another. i have 1 file called convertdays.cpp this: #include <iostream> int convertdays(int, int, int); int convertdays(int month, int day, int year) { int date; date = year * 1000 + month * 100 + day; return date; } then have file int main() stuff is, this: #include <iostream> using namespace std; int main() { int day, month, year; cout << "please enter month: " << endl; cin >> month; cout << "please enter day: " << endl; cin >> day; cout << "please enter year: " << endl; cin >> year; convertdays(month, day, year); //convertdays stays in red though. //still need add couple of more

python - CreateView for two models -

i'm trying create registration , login view 2 models. i have extended user model, , i'd know how use extensions along base user model inside createview. custom extension looks (in models.py): class userprofile(models.model): .... user = models.onetoonefield(user) display_name = models.charfield(max_length=50, default="null") avatar = models.imagefield(upload_to=generate_user_folder_avatar,storage=overwritestorage(),validators=[is_square_png]) usertype_choices = [ ('pr', 'producer'), ('me', 'mastering engineer'), ('cp', 'composer'), ('si', 'singer'), ('ar', 'artist'), ('ot', 'other'), ] usertype = models.charfield(max_length=2, choices=usertype_choices, default='pr') daw_choices = [ ('fl', 'fl studio'), ('ab', 'live'), ('bt'

angularjs - Angular 2 architecture for server-side communication -

learning angular 2. recommended file structure having components communicating server? so feature, todo feature. may have main todo-component , todo-list-component , todo-item-component , new-todo-component , todo-service (and more). then there feature, personal activity timeline, takes several source (including new , finished todos) , present user. may have same type of files, different not combine them generic ones: main timeline-component , timeline-list-component , timeline-item-component , timeline-service . then want both todo , timeline features communicate server. since both access partly same data, perhaps idea have backend-service take care of server communication both features. but how should components data it's need? should todo components ask todo-service in turn asks backend-service (and similar timeline components)? or should components better use backend-service directly, example todo components use backend-service backend stuff , todo-service ,

html - How to code yellow square, horizontal and vertical line in Step 10 in Make Your Own Mondrian Coder Project? -

i have been trying code coder project called make own mondrian found here: coder projects in step 10, if click on link, asks code bottom row of mondrian art. coded left part blue box in bottom row. having trouble coding rest right part in bottom row. have coded far: html: <body style="background-color:#f6f6f6;"> <div id="painting"> <div id="toprow"> <div id="bigbox" class="red right"></div> <div id="divider1" class="black right"></div> <div id="topleftcolumn" class= "right"> <div class="mediumbox"></div> <div id="divider2" class= "black"></div> <div class="mediumbox"></div> </div> <div id="painting"> <div id="middlerow">

php - jquery not returning markup from server -

so when user on client selects item drop downlist new div container supposed display containing results query. problem have div container pops intended none of markup containing search results query. points of interests data.php <?php if(!isset($_get['name'])) die('a vitamin name required.'); require '../vitamins.php'; $pdo = new pdo('mysql:host=localhost;dbname=vitamins', 'root', 'root'); $table = new vitamins($pdo); $param = $_get['name']; $data = $table->getdata($param); ?> <div class="row"> <?php while($data): ?> <?php $i = 0; while($i < 3){ ?> <div class="column"> <h1><?php print $data['name']; ?></h1> <p>serving</p> <p><?php print $data['grams']; ?>g = <?php print $data['percentage']; ?>%</p> </div>

Python script to convert adblock list in a forbidden file for Polipo proxy (regex) -

on system running polipo proxy, adblock purposes. search on internet i've found many shell scripts convert adblock plus lists in polipo forbidden file format ; of these scripts rely on sed, ruby or python. none of them able generate valid forbidden file: when restart polipo new generated forbidden file, in polipo's log file see message: " couldn't compile regex: unmatched ( or \( " the following python script attempt use, intended convert easylist file in polipo's forbidden file format: #!/bin/python # convert adblock ruleset polipo-forbidden format if __name__ == "__main__": import os import sys import re if len(sys.argv) == 1: sys.exit("usage: %s <adblockrules>" % os.path.basename(sys.argv[0])) if not os.path.exists(sys.argv[1]): sys.exit("the rules file (%s) doesn't exist" % sys.argv[1]) fhandle = file(sys.argv[1]) lines = fhandle.readlines() fhandle.close(

Python 2.7/Selenium 2 AttributeError: 'NoneType' object has no attribute 'group' -

i new python/selenium , have been ceaselessly trying resolve issue code i'd modify no luck. after researching on internet , trying various changes days, i'm @ wits end , hoping here help. apologize in advance if of terminology use misguided or incorrect. if need additional information, please let me know. specifically, run script automate torrent downloading / transcoding / re-uploading. 1 issue in particular i'm having trouble follows: the script written in python , relies on elements of selenium , transmission daemon/remote function. once has navigated website , chosen torrent download, pulls information page using xpaths. i'm not sure if it's part of code or following causing break, when there no release date , / or additional info listed script stops running , returns error. traceback (most recent call last): file "main.py", line 30, in <module> flac, missing, date, media_type, ul_page, cat_num, rel_type, seeders = get_tor

json - How to implement REST API Request URL/Headers/Body into https or code -

i working sabre's api ( https://developer.sabre.com/io-docs ). documentation leave lot desired, noob. sabre giving me following details call response shows rental car availability. have no clue - take data , load https/url? write python code , execute it? please help! request uri https://api.test.sabre.com/v2.4.0/shop/cars request headers authorization: bearer t1rlaqi5v/zsp6o3wmzg10msbqkpekushbce+bj0dkksbv3/rpv3u5ckaacgyuisgzpk607+y43m/veg1tsblwgozpopduj+fa27070vbzfawkmxt5od66o3k1c/n6hu9kknizc2fuplxumkattueprzy8eud+mz9e/0wvcqeqrnu3z9y/79wndw3jgyxk8gb05h5rdjavfpbhjaje/ropqw7fisgzyj56eveyp4bmcswj3bsjkbejbnon82re5iph94ntmx/hpii/7v+g** x-originating-ip: 98.116.41.181 content-type: application/json request body { "ota_vehavailraterq": { "vehavailrqcore": { "querytype": "shop", "vehrentalcore": { "pickupdatetime": "04-08t09:00", "returndatetime": "04-09t

ios - Simulate AVLayerVideoGravityResizeAspectFill: crop and center video to mimic preview without losing sharpness -

Image
based on so post , code below rotates, centers, , crops video captured live user. the capture session uses avcapturesessionpresethigh preset value, , preview layer uses avlayervideogravityresizeaspectfill video gravity. preview extremely sharp. the exported video, however, not sharp, ostensibly because scaling 1920x1080 resolution camera on 5s 320x568 (target size exported video) introduces fuzziness throwing away pixels? assuming there no way scale 1920x1080 320x568 without fuzziness, question becomes: how mimic sharpness of preview layer? somehow apple using algorithm convert 1920x1080 video crisp-looking preview frame of 320x568. is there way mimic either avassetwriter or avassetexportsession? func cropvideo() { // set start time let starttime = nsdate().timeintervalsince1970 // create main composition & tracks let maincomposition = avmutablecomposition() let compositionvideotrack = maincomposition.addmutabletrackwithmediatype(avmediatypevide

javascript - two fixed responsive sidebars and a scrollable content div in the middle of responsive design -

Image
i want place 2 fixed sidebars , middle content div when scroll content scrolling. work overflow scroll have scrollbar in middle div bit ugly. for better understanding here concept: tried bit cant figured out stable solve. thanks every help. based on understood, looking codepen so 2 sidebars fixed: .leftside { position: fixed; left: 10%; top: 150px; height: 300px; width: 10%; background: #ccc; } .rightside { position: fixed; right: 10%; top: 150px; height: 300px; width: 10%; background: #ccc; } for scrollable one: .scrollable { position: relative; top: 10px; height: 1000px; width: 60%; margin: 0 auto; background: green; } if want middle div fixed content inside of move around, need add .scrollable : overflow: scroll; and need add piece of jquery code change height of divs according window resize: $(document).ready(function() { $(".leftside, .rightside").height($(window).height()-100); $(&

hadoop - HIVE UDF error while creating -

while creating udf hive, getting below error: org.apache.ambari.view.hive.client.hiveerrorstatusexception: h110 unable submit statement. error while processing statement: failed: execution error, return code 1 org.apache.hadoop.hive.ql.exec.functiontask [error_status] i working on hortonworks platform. tried create simple udf simulate issue, config issue? udf package hiveudf.hiveudf; import org.apache.hadoop.hive.ql.exec.udf; import org.apache.hadoop.io.text; public final class hiveudfupper extends udf { public text evaluate(final text s) { if (s == null) { return null; } return new text(s.tostring().touppercase()); } } add jar hdfs:///tmp/hiveudf.jar; create temporary function hiveudfupper 'hiveudfupper';

api - Understanding PHP External Classes -

i want access method external class, within file. i have external class, let's say: external/file.php class externalclass { private $myclient; const constant = 'some/path'; public function _constructor($myclient) { $this->myclient = $myclient; } public function getsome($information) { // need access function $data = new stdobject(); $data->information = $information; $result = $this->myclient->post( self::constant, $data ); return($result['code'] == 200 ? json_decode($result['body']) : false); } public static function instance($settings) { return new externalclass(new myclient($settings['externalclass']['host'])); } } ... reference class in file. internal/file.php include_once('external/file.php'); $externalclassinstance = externalclass::instance($settings); // line 3 $externalclass = new externalclass(); // line 4 $externalclassgetsome = $extern

c# - Search algorithm in n-ary tree -

i trying implement search algorithm n-ary tree. following code have written: public class employee { public int employeeid { get; set; } public string level { get; set; } public int billcode { get; set; } public virtual list<employee> reportsto { get; set; } } i need bfs on tree find element in child nodes , stop recursion when element found in tree. code wrote far is: static bool closestmanager(employee a, employee b) //a contains tree elements , b 1 need find { if (a.employeeid == b.employeeid) return true; if (a.reportsto != null) { foreach (var curremployee in a.reportsto) { closestmanager(curremployee, b); } } return false; } this 1 returns false if element exists in subtree. because of return false in end. if remove compiler error saying code path must return value. how stop recursion once element found in tree ? just return

computer architecture - How many memory addresses are there in 32k byte RAM? -

i'm aware 32k = 32 * 2^10 equals **32768 memory addresses** . byte throwing me off here. indicate width of addressable memory? how byte come play here? indicate byte addressable? if word addressable slash available memory locations half? replies in advance there 2 things in computer architecture: 1:address bus(n-bit processor) 2:memory, here, address bus defines number of addresses in system, suppose if have 16 bit processor, means may have 2^16 address space, , if have 32k byte ram, represents memory of system. now, how these 32k memory represented in 2^16 address space different , how memory accessed based on type of addressing, whether byte addressable or word addressable.

android - Why Imageloader is not working? -

i want show images in view pager . have created class pageradapter , using imageloader library fetch images internet nothing appears on screen. my log cat 1 line in red: 02-08 12:34:12.582 3560-3560/? e/libegl: call opengl es api no current context (logged once per thread) my pager adapter class: package autogenie.dg10; import android.content.context; import android.support.v4.view.pageradapter; import android.view.layoutinflater; import android.view.view; import android.view.viewgroup; import android.widget.imageview; import android.widget.linearlayout; import com.nostra13.universalimageloader.core.imageloader; import com.nostra13.universalimageloader.core.imageloaderconfiguration; import java.util.list; public class pageradapter extends pageradapter { context mcontext; layoutinflater mlayoutinflater; list<string> l = mainactivity.list; imageloader mimageloader; public pageradapter(context context) { mcontext = context;

jquery - How to set the phone number in hidden field, and then get that hidden value and set it on changing the dropdown -

i want autofill integer field phone number of users whenever thier name selected in dropdown.i have jquery onchange function(of dropdown)where both values in same page , can , set value anywhere in page using jquery.but code not applicable in case because phone number diplayed field in other page , dropdown in page.the field autofilled in same page of dropdown.now how phone number of corresponding users selected dropdown. below juery code <%= javascript_tag %> $(document).ready(function() { $("#issue_custom_field_values_119").change(function() { var seloption = $(this).val(); var test = $("table.person tr td.phones").text(); alert(test); $("#phones").val(parseint($("#num-" + seloption).text())); }); }); <% end %> <html> <head> <script src="http://code.jquery.com/jquery-1.10.2.js"></script> <script> $(document).ready(function () { $('select'

php - What is the difference between Location and EffectiveURI? -

i created bucket named ghazals-ghulam-ali on aws , in return got 2 url's: location : http://ghazals-ghulam-ali.s3.amazonaws.com/ effectiveuri : https://s3-us-west-2.amazonaws.com/ghazals-ghulam-ali what difference between location , effectiveuri ? how both useful me? i created bucket using aws php sdk follows: public function create_bucket($user_id) { try { $this->s3client = new s3client($this->options); $isbucketcreated = $this->s3client->createbucket(array( 'bucket' => _global::bucketnameprecursor.$user_id )); }catch(exception $exc){ $isbucketcreated = false; } return $isbucketcreated; } value echo $isbucketcreated : (bucketname : ghazals-noor-jahan) { "location": "http:\/\/ghazals-noor-jahan.s3.amazonaws.com\/", "@metadata": { "statuscode": 200, "effectiveuri": "https:\/\/s3-us-west- 2.amazonaws.com\/ghazals-noor-jahan

c# - How to save automatically for the user changes -

how save automatically validation part in windows form, for example in windows form page have tab control name called validation if user make changes i.e., checking check box , changing color box changes should save automatically without clicking on save button? auto save complex operation. because interrupts user activity while auto saving. 1 simple method implementing auto save create 1 timer , boolean flag variables . start timer when application started. set flag if changes done user activity. call auto save function according timer interval. if flag set complete application changes saved , reset flag.

sql server 2012 - How to replace special character in sql table and replace by desired character dynamically? -

eg 'è' 'e' 'á'by a '¾' '3/4' ó 'o' 'ñ' by'n' 'á' 'a' not working ...but result above want. while exsits (select id #tmp_dirtytable) begin -- step 1: read required data row temp table declare @id int declare @special_character varchar(100) declare @special_character_to_replace_with varchar(100) select @id = id, @special_character = special_character, @special_char_bal_bla = #tmp_dirtytable -- step 2: write replace logic here -- step 3: delete row have processed temp table delete #tmp_dirtytable id = @id end if using sql server, query you create proc specialcharacterreplacer @tblname varchar(1000), @column_name varchar(1000) begin declare @query varchar(max) set @query = 'update '+@tblname +' set ' +@column_name + ' = dbo.replacespecialcharacter('+@column_name+')' exec(@query) end create function replacespecialcharacter ( @input varchar(max) )