Posts

Showing posts from April, 2014

Passing data between Fragments in Android -

i know many have answered question, still cannot mine work. in startworkout class data chronometer, , since data in milliseconds use method coded called showelapsedtime(). convert milliseconds seconds,minutes, , hours. want pass data class called workouts, reason not working.i not getting data because nullpointerexecption here code. startworkout class package com.example.d_jara.apprunners; public class startworkout extends fragment{ button button; button button2; chronometer mchronometer; private int hours = 0; private int minutes = 0; private int seconds=0; @override public view oncreateview( layoutinflater inflater, viewgroup container, bundle savedinstancestate) { view rootview = inflater.inflate(r.layout.lay_startworkout, container, false); mchronometer = (chronometer) rootview.findviewbyid(r.id.chronometer); // mchronometer.setformat("h:mm:ss"); butto

c++ - Is there a gtest equivalent for fixture-level setup/teardown? -

so, know there's "literally" fixtures gtest, constructor/destructor , setup/teardown functions execute after each test rather after entire set of tests in fixture . i can think of ways of hacking around this, there built-in support i'm not finding? you can define static methods setuptestcase , teardowntestcase in test fixture class. more information on in googletest wiki . be careful spelling of these static method names.

syntax - Haskell Guards and SublimeText 3 -

Image
i switched on sublime text 3 coding haskell in st3 noticed quite odd, syntax highlighting logic guards. as can see, when write way, highlights first guard in white colour , different sign in mix of white/magenta: only when use wrong syntax (with equal sign after argument) displays correctly. does know how fix this? you're using default haskell syntax highlighting. recommend disabling haskell package , installing sublimehaskell . syntax highlighting better, , recognizes things otherwise being "built-in" (it's prelude functions considered built-in). if you're using built-in haskell highlighting, can check it's buggy using ctrl alt shift p shortcut. highlight each guard pipe individually , hit shortcut. in status bar it'll briefly show syntax scope names associated region. first pipe, you'll source.haskell meta.function.type-declaration.haskell , , second you'll source.haskell keyword.operator.haskell . using sublim

caching - Magento + Varnish -> module double effect + show poll block even if disabled -

Image
i'm hosted on siteground , have enbaled cache option (i'm using magento 1.9.1): varnish static cache varnish dynamic cache memcached unfortunately second 1 duplicate effect of minicart module , xml: <layout version="0.1.0"> <default> <reference name="head"> <action method="additem"><type>skin_js</type><name>js/hm/minicart.js</name><params/></action> <action method="addcss"><stylesheet>css/hm/minicart.css</stylesheet></action> </reference> <reference name="header"> <reference name="top.links"> <remove name="checkout_cart_link"/> <block type="minicart/view" name="minicart_toplink" template="minicart/toplink.phtml" > <block type="checkout/cart_sidebar&qu

python - Get the current user from BlobstoreUploadHandler -

i want current user blobstoreuploadhandler. i'm using endpoints web application, (outside of endpoints) built /uploadurl upload files blobstore. the image uploads correctly. so, need link image uploaded user, users.get_current_user() returns none . on frontend side user logged using oauth2. idea issue? if use endpoints.get_current_user() raise error: no valid endpoints user in environment this code: class uploadhandler(blobstore_handlers.blobstoreuploadhandler): def post(self): upload_files = self.get_file_infos() file_info = upload_files[0] gcs_filename = file_info.gs_object_name file_key = blobstore.create_gs_key(gcs_filename) file(file=gcs_filename, owner=users.get_current_user() ).put() each app requires own login, , every class needs have users imported , declared if want use user class in code. from google.appengine.api import users import webapp2 class myhandler(webapp2.requesthandler): def get(

php - INSERT INTO mySQL from client side with AJAX -

i want insert data client side remote mysql database i calling function , passing variable it. function uploadmetrics(email){ var email; $.ajax({ type: 'post', url: 'php/insertconvertdata.php', data: { data: {"email" : email }, //data:email, }, success: function(result) { console.log(result); } }); } on server have php file $user = $_post['email']; echo $user; echo '<pre>'; print_r($_post); // viewing array var_dump($_post); // viewing info of array echo '</pre>'; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("connection failed: " . $conn->connect_error); } $sql = "insert cms_conversion_funnel (email) values ('" . $user . "')"; if ($conn->query($sql) === true) { echo "new record created successfully"; } else { echo "error: "

ruby - Why am I seeing inaccurate diff deltas in libgit2 / rugged? -

when using rugged remove files stage commit, diff commit comes out false information files deleted. files supposed there still there , resulting state of project correct. it's diff reporting incorrectly. i may misunderstanding / misusing rugged::tree::builder , other diffs, seems come out correctly. note leaving empty tree object here, don't see why should affect this. project structure: demo-project/ └── masterdir ├── directory1 │   ├── file1 │   ├── file2 │   └── file3 ├── directory2 │   ├── file4 │   └── file5 ├── directory3 │   └── file6 └── directory4 └── file7 call sequence require 'rugged' repo = rugged::repository.new("/users/davetakahashi/demo-project") # tree "masterdir/directory1" tree = repo.lookup(repo.head.target.tree.path("masterdir/directory1")[:oid]) # initialize builder tree builder = rugged::tree::builder.new(tree) # remove files builder.remove("file

java - Divisors inside an array -

i need write method takes array of integers , checks every element if divisors (except number , 1) present in array. if yes, method return true. for example, following array return true: 4,5,10,2 i can't think of efficient enough implemented. guys me out here? i've been thinking iterate through every element in array, search of divisors, put them on array, return array , compare elements in original array. this possible solution , work want know of other possible solutions. edit: here code i've came super slow. guys me optimise little bit?: import java.util.arrays; public class divisors { public static void main(string[] args) { int[] numbers = { 4, 5, 10, 2 }; boolean flag = true; (int num : numbers) { if (num % 2 != 0) { (int subnum = 1; subnum < num / 2; num += 2) { if(num%subnum == 0 && sub

ios - UIWebView: Sending data back to previous controller using unwind segues without button -

say, instance have uiwebview. if status code of 404, want return data previous view controller knows refresh list of webpages. i heard unwind segues . however, have found on sounds has implemented via storyboard button. is there anyway perform unwind segue in code. meaning if find error - set kind of variable previous view controller knows how handle error? thanks! you should try searching before ask, answered on here: how perform unwind segue programmatically? look @ vadim , dean answers

Exporting Dart APIs to JavaScript, without a Dart VM -

i'd export dart api javascript on browsers without dart vm. example, given class a: class { string name; a(); a.withname(this.name); } i'd create javascript object using exported api with: var = new a(); an answer previous question pointed me js-interop. however, i'm not able expected result when working through readme example . appears dart library isn't being exported javascript. pubspec.yaml : name: interop description: > library useful applications or sharing on pub.dartlang.org. version: 0.0.1 dev_dependencies: unittest: dependencies: js: git: url: git://github.com/dart-lang/js-interop.git transformers: - js - js/initializer example/main.dart library main: import 'package:js/js.dart'; main() { initializejavascript(); } lib/a.dart library a; import 'package:js/js.dart'; @export() class { string name; a(); a.withname(this.name); } index.html <html> <head> &l

ElasticLinq doesn't seem to use the correct URL -

i'm having problem simple elasticlinq search return result. problem seems it's sending url elasticsearch isn't correct search url. here i've tried: var connection = new elasticconnection(new uri("http://localhost:9200"), index: "mytypes"); var context = new elasticcontext(connection); var results = (from in context.query<mytype>() select a).take(10).toarray(); when execute last line, here url see in fiddler: http://localhost:9200/mytypes/mytypes/_search the problem appears mytypes used twice in url rather 1 time. i've tried not supplying default index elasticconnection constructor, in case search url following: http://localhost:9200/_all/mytypes/_search in both cases no results back. if submit query using http://localhost:9200/mytypes/_search i results back. any ideas how elasticlinq use correct search url? the second mytypes in url strong t type query() there default convention clr type equivalent elastic

Multilingual in Meteor -

i'm developing multilingual app in meteor.js know best way in opinion that; example here wat i'm doing right (pretty sure can done better); first save items in mongodb properties neted in language root: { en: { name: "english name", content: "english content" }, it: { name: "italian name", content: "italian content" }, //since images same both, not nested images: { mainimage: "dataurl", mainthumb: "dataurl" } } then publish subscription using currentlang session variable: meteor.publish("elementscurrentlang", function(currentlang) { var projection = { images: 1 }; projection[currentlang] = 1; return elements.find({}, projection); }); i subscribe on route using iron router waiton hook: router.route('/eng/elements', { waiton: function() { return meteor.subscribe("municipalitiescurren

machine learning - Weird results with the randomForest R package -

i have data frame 10,000 rows , 2 columns, segment (a factor 32 values) , target (a factor 2 values, 'yes' , 'no', 5,000 of each). trying use random forest classify target using segment feature. after training random forest classifier: > forest <- randomforest(target ~ segment, data) the confusion matrix biased toward 'no': > print(forest$confusion) no yes class.error no 4872 76 0.01535974 yes 5033 19 0.99623911 out of 10,000 rows, less 100 got classified 'yes' (even though original counts 50/50). if switch names of labels, opposite result: > data$target <- as.factor(ifelse(data$target == 'yes', 'no', 'yes')) > forest <- randomforest(target ~ segment, data = data) > print(forest$confusion) no yes class.error no 4915 137 0.02711797 yes 4810 138 0.97210994 so not real signal ... furthermore, original cross-table relatively balanced: > table(data$target, data$segmen

java - How to show "count" MySQL query into JTextField? -

right now, i'm stuck problem: want show total amount of songs in database inside gui (through jtextfield). this got far: txttotalsongs = new jtextfield(); txttotalsongs.addactionlistener(new actionlistener() { public void actionperformed(actionevent arg0) { try { string q = "select count (title) songs"; preparedstatement ps=conn.preparestatement(q); ps.setint(1, 20); resultset rs = ps.executequery(); while(rs.next()) { txttotalsongs.settext(string.valueof("title")); } } catch (exception e) { // todo: handle exception } } }); txttotalsongs.setbounds(591, 458, 86, 20); contentpane.add(txttotalsongs); instead of while loop, try if(rs.first()) xttotalsongs.settext(rs.getstring("title")); rs.first() returns true (and moves pointer first) if there row in result set. getstring returns val

python - Splitting a string in two parts -

i want split string in 2 parts this: >>> label = ('a1') ['a', '1'] is there method in python? i tried: >>> label = label.split(',') ['a1'] as can see comma not printed. you can use list : >>> label = 'a1' >>> list(label) ['a', '1'] >>> list iterate on string , collect characters new list. also, cannot use str.split here because method designed split on characters/substrings , remove them resulting list. example, 'a b c'.split() split on whitespace , remove characters returned list, ['a', 'b', 'c'] . want break string individual characters while still keeping of them.

php - How to upload ONLY images in database -

i want upload pictures , in database using php. tried is, <?php if (isset($_post['upload'])) { $con = mysql_connect("localhost", "root", ""); if (!$con) { die('could not connect: ' . mysql_error()); } mysql_select_db("iis", $con); $image = $_files["product_image"]["name"]; $imagetype = mysql_real_escape_string($_files["product_image"]["type"]); if (substr($imagetype, 0, 5) == "image") { if (!file_exists("product_images")) { mkdir("product_images"); } if ($_files["product_image"]["error"] > 0) { $error = "error return code :" . $_files["product_image"]["error"] . "<br />"; } else { move_uploaded_file($_files["product_image"]["tmp_name"], "product_images/&q

javascript - jQuery Each Incremented Counter vs. Selectors -

i finished aspect of project required looping through rows of html table , depending on class of td , text. approached issue 2 different methods , i'm wondering considered best coding practice. also, there advantage using 1 method on other? method 1: $('#table tr').each(function(){ var = $(this).find('[class*=someclass]').html(); //do 'something' }); method 2: var x = 0; $('#table tr').each(function(){ var = $(this).find('.someclass' + x).html(); //do 'something' x++; }); this may more opinion-based, personally, this: $('#table tr').each(function(i){ var = $(this).find('.someclass' + i).html(); //do 'something' }); the index of each element passed argument. edit: to expand on karl-andrégagnon said, 2 '.someclass' selectors behave differently. in first example, select elements 'someclass', regardless of numerical suffix. second example sele

multithreading - How do I parallelize GPars Actors? -

my understanding of gpars actors may off please correct me if i'm wrong. have groovy app polls web service jobs. when 1 or more jobs found sends each job dynamicdispatchactor i've created, , job handled. jobs self-contained , don't need return main thread. when multiple jobs come in @ once i'd them processed in parallel, no matter configuration try actor processes them first in first out. to give code example: def poolgroup = new defaultpgroup(new defaultpool(true, 5)) def actor = poolgroup.messagehandler { when {integer msg -> println("i'm number ${msg} on thread ${thread.currentthread().name}") thread.sleep(1000) } } def integers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] integers.each { actor << } this prints out: i'm number 1 on thread actor thread 31 i'm number 2 on thread actor thread 31 i'm number 3 on thread actor thread 31 i'm number 4 on thread actor thread 31 i'm number 5 on t

api - Android: How to draw multiple routes from source to destination on map? -

i able draw single route using polyline between 2 geo points on android map v2. don't know how draw multiple routes source destination tried add "alternatives=true" still getting 1 route on map. please me out how research on web, still can't able find easy understandable solution this. googledirection.java @suppresslint("newapi") public class googledirection { public googledirection(context context) { mcontext = context; } public string request(latlng start, latlng end, string mode) { final string url = "http://maps.googleapis.com/maps/api/directions/xml?" + "origin=" + start.latitude + "," + start.longitude + "&destination=" + end.latitude + "," + end.longitude + "&sensor=false&units=metric&mode=" + mode + "alternatives=true"; if(islogging) log.i("googledirection", "url : " + url);

woocommerce - Wordpress and Woocmmerce - how to access settings from theme? -

im trying pull settings woocommerce admin. found this: http://oik-plugins.eu/woocommerce-a2z/oik_api/woocommerce_settings_get_option/ $string = woocommerce_settings_get_option( $option_name, $default ); it looks public function cannot access theme files. gives me fatal error: call undefined. have idea how can access setting theme? i'm trying 'woocommerce_frontend_css_primary', $colors['primary'] can tie them rest of theme. woocommerce write values directly .less file. woocommerce docs bit misleading, turns out there function called get_option... long know name of option can use. eg. array of front end colors: $woo_styles = get_option( 'woocommerce_frontend_css_colors' );

java - Should be returning true but returns false instead? -

Image
code: bukkit.getserver().broadcastmessage("check " + chatcolor.stripcolor(i)); bukkit.getserver().broadcastmessage("that starts " + chatcolor.stripcolor(chatcolor.translatealternatecolorcodes('&', guishop.instance.getconfig().getstring("messages." + type + "label")))); bukkit.getserver().broadcastmessage(chatcolor.stripcolor(i).startswith(chatcolor.stripcolor(chatcolor.translatealternatecolorcodes('&', guishop.instance.getconfig().getstring("messages." + type + "label")))) + ""); and image of returning false instead of true: could me being stupid.. not sure edit1: ok eckes pointed out being stupid.. how check if "buy: 50.0" started "buy: price". if %price% false correct, " buy: 50.0 " not start " buy: %price% ". , should not mix color logic translation logic business logic. make code readable, helps find problem yourself. if

sql - Getting Invalid use of group function for lengthy MySql query -

i've been trying query right when thought done , tried running it, error. i'm pretty sure line: -> , sum(cr.file_size) > 5000000000 select ss.title -> ,sum(cr.file_size) -> ,gr.user_id -> ,ru.givenname -> ,ru.sn -> ,ru.mail -> content_resource cr -> ,sakai_site ss -> ,sakai_realm_rl_gr gr -> ,sakai_realm rl -> ,rutgers_user ru -> ,sakai_user_id_map map -> cr.context = ss.site_id -> , sum(cr.file_size) > 5000000000 -> , rl.realm_id = concat ('/site/',ss.site_id) -> , rl.realm_key = gr.realm_key -> , gr.role_key in (7,3) -> , gr.user_id = map.user_id -> , map.eid = ru.uid -> outfile '/tmp/sitecontentusage.csv' fields terminated ',' enclosed '"' lines terminated '\n'; you need having clause. aggregati

go - Using struct method in Golang template -

struct methods in go templates called same way public struct properties in case doesn't work: http://play.golang.org/p/xv86xwjnja {{with index . 0}} {{.firstname}} {{.lastname}} {{.squareage}} years old. {{end}} error: executing "person" @ <.squareage>: squareage not field of struct type main.person same problem with: {{$person := index . 0}} {{$person.firstname}} {{$person.lastname}} {{$person.squareage}} years old. in constrast, works: {{range .}} {{.firstname}} {{.lastname}} {{.squareage}} years old. {{end}} how call squareage() method in {{with}} , {{$person}} examples? as answered in call method go template , method defined by func (p *person) squareage() int { return p.age * p.age } is available on type *person . since don't mutate person object in squareage method, change receiver p *person p person , , work previous slice. alternatively, if replace var people = []person{ {"john", "s

java - Android - Add custom layout to popup menu item -

i've been working @ while. i'm trying create popupmenu top item looks different rest of items - header item contains title. i've tried setting android:actionlayout item, linking particular item xml file should generate desired layout. however, seems have absolutely no effect. there tried set actionview programmatically - creating custom view , setting item. still no effect. i've done research here on , looked @ least 10 tutorials; maybe suck @ googling today, cannot find way this. here last attempt: // * my_menu.xml <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <group android:id="@+id/menu_title_group" > <item android:id="@+id/menu_title_item" android:title="" app:actionlayout="@layout/popup_menu_title_header_layout" /> </group> </me

while loop - Python Curiosity -

i curious how program reads. have foo functions top. "thing" global variable. sets "thing" equals 100 "item" equals 100. return "item" == 0 not sure about. "item" equal 0? going down flag = false. "when not flag:" called, asks users input , whatever reason until enter "0" flag turns true , "thing" equals 0. if can explain how works appreciate it def foo(item): global thing thing = item return item == 0 thing = 100 flag = false while not flag: flag = foo(int(input("give me want here: "))) print(thing) item set whatever user responded when prompted give me want here , converted integer. in turn thing set value ( thing = item binds global thing whatever item points at). so if user enters 0 , item set 0 , thing set 0 , item == 0 returns true , ending while loop.

c# - How I do know if SQL Server Stored Procedure that performs an Update worked? -

say have stored procedure have no control on (and no access third party db). how know if worked? begin update usr set usr_psswrd = @newpassword usr_usrnme = @username , usr_psswrd = @oldpassword end i know how rows when there's select statement in stored procedure , read rows have no idea how check if stored procedure worked or not. this i'm doing far doesn't work. stored procedure works because password change don't know after fact. using (sqlconnection connection = new sqlconnection(connectionstring)) { // create command , set properties. sqlcommand command = new sqlcommand(); command.connection = connection; command.commandtext = "usp_changepassword"; command.commandtype = commandtype.storedprocedure; command.parameters.add("@username", sqldbtype.varchar).value = email; command.parameters.add("@oldpassword&

css - 100% height responsive sidebar -

Image
how go setting full height side bar using responsive grid system, similar bootstrap? the issues running .main wrapper div collapses height of .primarycol div. i 'm using pull , push classes adjust visual layout .secondarycol div looks on left hand side, though after .primarycol div in code. <div id="main" class="main content"> <div class="row"> <div id="primarycolumn" class="primarycol col12 col9-768 col3-768-push" role="main"></div> <div id="secondary" class="secondarycol col12 col3-768 col9-768-pull col7-1024-pull" role="complementary"></div> </div> </div> normally without .secondarycol` class, div , this. i have tried adding min-height:100% .main div , height:100% body tag, makes main div height ever height of browser window , not content. any suggestions on how can remedy welcome. this codepen of base structure.

sas - Using macro in proc sql with ODBC connection to Access database -

i have macro variable called filename. tried use in proc sql connects access databse through odbc. however, code have either has error or not recognizing macro variable. here code: %let filename=myfile.name proc sql; connect odbc ("dsn=ms access database;"|| "dbq=&dbname;"|| "fil=ms access;" || "maxbuffersize=512;" || "pagetimeout=600;" || "uid=admin"); create table t1 select * connection odbc (select * tablea filename='&filename'); quit; this returns 0 row. if replace macro variable real value in query, return 1 row correct data. if use double quotation around &filename, following error: error: cli describe error: [microsoft][odbc microsoft access driver] '' not valid name. make sure not include invalid characters or punctuation , not long. could tell me how should pass macro variable query? thanks.

sql - Join with conditional IN with Doctrine2 -

not sure possible, looks should in video entity, i've got manytoone associate product entity here, trying acquire published products, , acquire videos belong product join // productrepository.php public function findpublished() { $q = $this->getentitymanager()->createquerybuilder(); $q->select(['p', 'v'])->from($this->getentityname(), 'p') ->leftjoin('p.videos', 'v', 'on', 'p in v.products') ->where('p.published = :published') ->setparameter('published', true); $results = $q->getquery()->getresult(); return $results; } the exception comes this: [syntax error] line 0, col 76: error: expected end of string, got 'on' [1/2] queryexception: select p, v company\corebundle\entity\product p left join p.videos v on p in v.products p.published = :published if entities mapped correctly, don't need specify join con

java - Singly Linked List Delete Value -

i making singly linked list need put delete method getting error help? public void remove(int index) { getnode(index - 1).next = getnode(index + 1); } many possible errors can happen here. one, definitively put more verification before making changes if are on first element (then header 2nd element); are on last element (then getnode(index+1) returning correctly null or throwing exception)?

javascript - Why does this angularjs directive not work? -

i stuck trying follow tutorial on angularjs directives. i've been unable find syntax errors in code, , i've tried adding jquery. main.js var app = angular.module("app", []); app.directive = ("enter", function () { return function (scope, element) { element.bind("mouseenter", function () { console.log("i'm inside of you!"); }); } }); ng.php <body ng-app="app"> <div enter>i'm content!</div> </body> both angularjs , main.js linked correctly. there no console errors reported. what missing? app.directive function, not property. where have: app.directive = ('enter'... should be: app.directive('enter', function() ...) so calling function register directive, instead of overriding assignment can never have directives ever again. :)

c++ - how to make method calls of multiple objects of same class in different thread? -

i'm noob in c++ , have class (mystack), there's method (push) in can called using mystack a; a.push(); now have created multiple instances of class , each of them want call push method, i'm wondering how can call them in different threads, thanks. edit the full code below (it's long quite simple , straightforward), there 2 instances of class mystack, each of them make sequence of method calls, want make method calls of different instance in different threads, want make push , pop operations of instance stc in thread , same operations in stc2 in thread, how achieve this? #include "stdafx.h" #include <string> #include <iostream> #include <thread> #include <vector> #include <mutex> using namespace std; //static recursive_mutex mtx; struct mystack { int *p; unsigned int limit, counter; public: unsigned int max() { return limit; } ~mystack() { delete p; } mystack