Thursday 15 April 2010

What does `impl TraitX for TraitY` mean in Rust? -



What does `impl TraitX for TraitY` mean in Rust? -

for example:

trait traitx { } trait traity { } impl traitx traity { }

i figured mean same as

impl<a: traity> traitx { }

but error message suggests otherwise:

$ rustc --version rustc 0.12.0-nightly (a70a0374e 2014-10-01 21:27:19 +0000) $ rustc test.rs test.rs:3:17: 3:23 error: explicit lifetime bound required test.rs:3 impl traitx traity { } ^~~~~~

does impl traitx traity (or variant of explicit lifetime) mean in rust? if so, illustration of use?

impl traitx traity using traity a dynamically sized type (dst). if add together required lifetime bound (see e.g. this more info necessity of lifetime bound), compiler complain in manner:

trait traitx { } trait traity { } impl<'a> traitx traity+'a { } fn main() {}

<anon>:3:1: 3:34 error: trait `core::kinds::sized` not implemented type `traity+'a` <anon>:3 impl<'a> traitx traity+'a { } ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ <anon>:3:1: 3:34 note: trait `core::kinds::sized` must implemented because required `traitx` <anon>:3 impl<'a> traitx traity+'a { } ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

playpen

the errors saying traity+'a not sized, is, doesn't have size known @ compile time (e.g. u8 has size 1, vec<t> size of 3 pointers).

the syntax implementing traitx traity trait objects (these covered in "object types" section of reference), allowing handled (behind pointer) in places value implementing traitx expected. working usage involves sized? annotations, these whatever they're attached optionally (?) sized (the default things assumed sized).

#![allow(dead_code)] // indicate it's ok implement trait dsts trait traitx sized? { } trait traity { } trait traitz { } impl<'a> traitx traity+'a { } // sized? allow dsts passed this. fn example<sized? t: traitx>(_: &t) {} fn call_it(x: &traity, _y: &traitz) { example::<traity>(x); // possible if `traity` impls `traitx`. // error: // example::<traitz>(_y); // `traitz` doesn't impl `traitx`. } fn main() {}

playpen

the explicit ::<traity> type hint required when calling function unsized type now, bug #17178. moment, there's still quite few bugs dst it's not easy utilize in practice, improve.

the major motivation dst making handling trait objects more consistent other pointer types, e.g. back upwards &trait , box<trait> trait objects, dst designed allow other pointer types rc<trait>, arc<trait>. dst allows treating real pointers, e.g. if obj: box<trait> &*obj possible dst, illegal because trait objects fat pointers, not normal pointers.

rust

database - Auto-generate UUID in Slick -



database - Auto-generate UUID in Slick -

wonder if slick supports auto-generation of primary key of table uuid?

i have table has primary key (long format) beingness autogenerated each time insert table auto-incrementing. now, want alter uuid autogenerated id.

slick doesn't back upwards auto-generating uuids, database might. why not in db?

database primary-key uuid slick auto-generate

javascript - Uploading a file from a web app with dropzone.js -



javascript - Uploading a file from a web app with dropzone.js -

i building web app. have allow user upload image or drag-and-drop 1 browser. help this, i'm using dropzone.js. challenge is, need customize appearance bit.

my customization requires features seem pretty forwards in dropzone.js. basically, need: 1 file can uploaded @ once. while file beingness uploaded, need show progress bar. 1 time uploaded, need allow user either a) remove existing image or b) replace image one. in effort this, have next html:

<div id="mydropzone" style="cursor:pointer;"> <div class="files" id="previews"> <div id="template" class="file-row"> <ul class="list-inline"> <li> <span class="preview" style="width:300px;"><img data-dz-thumbnail /></span> <p class="size" data-dz-size></p> </li> <li style="vertical-align:top;"> <ul id="pictureactions" class="list-unstyled"> <li> <button class="btn btn-default dz-clickable file-input-button"> <i class="glyphicon glyphicon-picture"></i> <span>pick...</span> </button> </li> <li> <button data-dz-remove class="btn btn-danger btn-block" style="margin-top:8px;"> <i class="glyphicon glyphicon-trash pull-left"></i> <span>delete</span> </button> </li> </ul> </li> </ul> <div id="uploadprogress" class="progress" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"> <div class="progress-bar progress-bar-warning" style="width:0%;" data-dz-uploadprogress> <span>please wait...</span> </div> </div> </div> </div> <div id="uploadprompt">drag-and-drop image here</div> </div>

i initializing code dropzone using next javascript:

$(function () { var previewnode = document.queryselector("#template"); previewnode.id = ""; var previewtemplate = previewnode.parentnode.innerhtml; previewnode.parentnode.removechild(previewnode); var picturedropzone = new dropzone("div#mydropzone", { url: "/pictures/upload", clickable: true, uploadmultiple: false, autoprocessqueue: true, previewtemplate: previewtemplate, previewscontainer: "#previews", init: function () { this.on("complete", function (data) { $('#pictureactions').show(); $('#uploadprogress').hide(); $('#uploadprompt').hide(); }); }, uploadprogress: function (e, progress) { $('#uploadprogress').css('width', progress); }, removedfile: function () { $('#previews').hide(); $('#uploadprompt').show(); } }); });

there several problems though. if click text drag-and-drop image here, file picker not open. if click outside of text, file picker opens. also, code works initial process of choosing file. however, if click "pick..." button, page post back. in reality, expecting file picker appear again. if click "delete" button, , take file 1 time again file picker, picture, upload progress , action buttons never appear.

i sense i'm screwing initialization of dropzone somehow. doing wrong? why can't take image or delete image , take 1 or open file picker if click prompt text?

i have changed code

this.on("complete", function (data) { $("#previews").show(); //this line added ... , it's worked... $('#pictureactions').show(); $('#uploadprogress').hide(); $('#uploadprompt').hide(); });

i think line: $('#previews').hide(); have hidden preview element, , not alter status when append new image. :).

and word but, can see old image added, think it's new bug... trying solute it... have thought it.

http://jsfiddle.net/qek0xw1x/15/

javascript dropzone.js

jquery - How to add class to html elements in layout [ASP.NET MVC] -



jquery - How to add class to html elements in layout [ASP.NET MVC] -

i have next problem.

in layout have menu

<!-- collect nav links, forms, , other content toggling --> <div class="collapse navbar-collapse navbar-responsive-collapse"> <ul class="nav navbar-nav"> <li class="active"> @html.actionlink("blog","posts","blog",null,null) </li> <li> @html.actionlink("książki", "books", "books", null,null) </li> <li> @html.actionlink("o mnie", "aboutme", "blog", null,null) </li> </ul> </div> <!--/navbar-collapse-->

i want set class='active' element clicked, wrote script below (ignore can written better) in layout page.

<!-- js global compulsory --> <script type="text/javascript" src="~/scripts/assets/plugins/jquery-1.10.2.min.js"></script> <script type="text/javascript" src="~/scripts/assets/plugins/jquery-migrate-1.2.1.min.js"></script> <script type="text/javascript" src="~/scripts/assets/plugins/bootstrap/js/bootstrap.min.js"></script> <!-- js implementing plugins --> <script type="text/javascript" src="~/scripts/assets/plugins/back-to-top.js"></script> <!-- js page level --> <script type="text/javascript" src="~/scripts/assets/plugins/countdown/jquery.countdown.js"></script> <script type="text/javascript" src="~/scripts/assets/plugins/backstretch/jquery.backstretch.min.js"></script> @rendersection("scripts", required: false) <script type="text/javascript" src="~/scripts/assets/js/app.js"></script> <script type="text/javascript"> jquery(document).ready(function () { app.init(); $('.navbar-nav li').click(function () { var lis = $('.navbar-nav li'); lis[0].classlist.remove('active'); lis[1].classlist.remove('active'); lis[2].classlist.remove('active'); this.classlist.add('active'); }); }); </script>

but after click on link doesn't change. mean changes when step on script, after seems whole page requested 1 time again , changes overriden. how solve this?

thanks replies.

paweł

it seems confused how javascript works respect separate http requests , loading of page. javascript code part of current page , executes in client's browser. 1 time navigate different page, whole process starts on again. page loads, , javascript code executed.

your javascript code may doing intend do, after runs, page left , page loaded server, client-side state lost.

this code should set on server, instead of in javascript on client. when render html in views, should set active class on appropriate element @ point. when user clicks link, request different page server, , when render html page, set active class accordingly. no javascript code required.

jquery html asp.net asp.net-mvc

asp.net mvc - C# Entity Framework SQL Error -



asp.net mvc - C# Entity Framework SQL Error -

i have emailhistorymodel :

public class emailhistory { public guid id { get; set; } public string companyid { get; set; } public guid? userid { get; set; } public datetime createddate { get; set; } public datetime sentdate { get; set; } public datetime updatedate { get; set; } public string outcome { get; set; } public datetime emaildelivereddate { get; set; } public datetime emailopened { get; set; } public string emailaddress { get; set; } public string htmlemail { get; set; } public string integrationdocumentid { get; set; } public rules rulesid { get; set; } public int transactionid { get; set; } }

i maintain getting error when trying access model. @ moment trying run next :

var emailhistorytotal = !emailhistory.any() ? 1 : emailhistory.count();

this keeps giving me error : "entityframework.dll not handled in user code

additional information: conversion failed when converting character string uniqueidentifier"

i'm not sure has changed working ok.....

if run next in sql, returns ok!?: select * [dbo].[emailhistory]

in sql columns set unique identifier id, rulesid_id , userid.

the emailhistory comming repository (see below method)

public iqueryable<emailhistory> getemailhistorybyuser(string userid) { homecoming _autosendcontext.emailhistory.asqueryable(); }

the _autosendcontext global variable interact db

any help or guidance great!

ok... nil email history table. error due info migrations, auto migration trying alter field in database nvarchar unique identifier.

this statement scheme trying run : alter table [dbo].[transactions] alter column [companyid] [uniqueidentifier] null

c# asp.net-mvc entity-framework

css - Efficient way to set 100% height for all the parents -



css - Efficient way to set 100% height for all the parents -

i want div 100% height of viewport. basic code this:

http://jsfiddle.net/c247opd6/

now, in real web page situation more this:

http://jsfiddle.net/akrv5cgm/ div nested within other divs.

i know code of sec illustration doesn't work because in order element have 100% of height of parent, parent must either have explicitly defined height or 100% of height of parent. fix:

.four, .three, .two { height: 100%; }

however start adding code solution becomes harder , harder mantain. there shorter css rule allow me set 100% height parent divs? nth-child, except parents.

i want div 100% height of viewport.

you utilize viewport relative units:

5.1.2. viewport-percentage lengths: ‘vw’, ‘vh’, ‘vmin’, ‘vmax’ units

the viewport-percentage lengths relative size of initial containing block. when height or width of initial containing block changed, scaled accordingly.

in case utilize height: 100vh, 1vh equivalent 1% of viewport.

updated example

.one { height: 100vh; background-color: reddish }

browser back upwards these units can found here.

it's worth pointing out element won't take height of direct parent consideration.

css

asp.net mvc - MVC - AJAX Post - Open Partial View in Dialog Box -



asp.net mvc - MVC - AJAX Post - Open Partial View in Dialog Box -

in bootstrap dialog box, have ajax form :-

@using (ajax.beginform("method", "settings", formmethod.post, null)) { <div class="container"> <div class="row form-horizontal" id="fieldslist"> .... <button type="submit" class="btn">back</button> } [httppost] public actionresult method(formcollection form) { .... homecoming partialview("pagepartial",model); }

when nail submit button, dialog box closes & see new page.

how open partialview in dialog itself?

try as

@using (ajax.beginform("method", "settings", new ajaxoption{httpmethod="post", onsuccess="onsuccess"})) { <div class="container"> <div class="row form-horizontal" id="fieldslist"> .... <button type="submit" class="btn">back</button> } <script> function onsuccess(result){ //your code } </script>

ajax asp.net-mvc

javascript - Set an item from localStorage in a protractor test -



javascript - Set an item from localStorage in a protractor test -

describe('the feature', function() { beforeeach(function () { browser.executescript('localstorage.setitem("key","value");'); }); it('should this', function() { }); });

but error when test run against selenium chromedriver 2.10 , chrome 37

executing: [execute script: window.localstorage.setitem("key","value");, []]) 15:31:29.747 warn - exception thrown org.openqa.selenium.webdriverexception: <unknown>: failed read 'localstorage' property 'window': storage disabled within 'data:' urls. (session info: chrome=37.0.2062.120) (driver info: chromedriver=2.10.267518,platform=linux 3.11.0-26-generic x86_64) (warning: server did not provide stacktrace information)

any thought problem cam ?

according 1 of answers @ remove item localstorage in protractor test, happens when seek access localstorage without hitting browser (say, browser.get) first when using chrome driver. solution seems to nail browser first (maybe root page) page loaded in chrome can manipulate localstorage. @ to the lowest degree have been doing our project. hope helps!

javascript selenium-webdriver protractor angularjs-e2e

java - Checking text length is divisible by 2 -



java - Checking text length is divisible by 2 -

i want check whether length of input text divisible 2.

so

if text length 3, result 1.5 , display not divisible 2 , if text length 6, result 3.0 , display divisible 2

but codes display output "not divisible 2" regardless text length. have done wrong?

import java.util.scanner; public class test1 { public static void main (string[]args) { string =null; int l = 0; double result = 0.0; scanner scan = new scanner(system.in); system.out.println("enter string\n"); = scan.nextline(); l = a.length(); result = (double)l/2.0; system.out.println(result); if((double)result % 2 != .0) { system.out.println("not divisiable 2"); } else { system.out.println("divisiable 2"); } } }

first, length() returns int, , it's simpler work integers, why casting length double? % (modulo) operator meant work integers, not doubles; remember, double numbers floating-point numbers, there's room numerical error if utilize them.

second, don't need utilize many variables; maintain simple:

a = scan.nextline(); if(a.length() % 2 == 0) system.out.println("length of string divisible 2"); else system.out.println("length of string not divisible 2");

easier read (and write), don't think?

java

c# - Data type mismatch in criteria expression Access 2013 -



c# - Data type mismatch in criteria expression Access 2013 -

oledbcommand computerstatus = new oledbcommand("update computer set status= 'occupied' pcnumber='" + cbocomputerno.text + "'", con); computerstatus.executenonquery();

this code. pcnumber autonumber getting error wants me alter info type string need autonumber.

autonumber auto number. since numerical value, don't need utilize single quotes it.

but more important, should utilize parameterized queries. kind of string concatenations open sql injection attacks.

also utilize using statement dispose oledbconnection , oledbcommand.

using(oledbconnection con = new oledbconnection(constring)) using(oledbcommand computerstatus = con.createcommand()) { computerstatus.commandtext = "update computer set status= ? pcnumber = ?"; computerstatus.parameters.addwithvalue("@status", "occupied"); computerstatus.parameters.addwithvalue("@number", cbocomputerno.text); computerstatus.executenonquery(); }

as larstech pointed, may wanna check cbocomputerno.text string valid integer using int.tryparse method.

c# ms-access insert-update

angularjs - cannot change the syntax of the controller creation in typescript -



angularjs - cannot change the syntax of the controller creation in typescript -

i have angular controller wrote in typescript , declared way

angular.module('myapp').controller("gestioneprogetto", ["$scope", "palmariservice", "soluzioniservice", "progettoservice", "wmsservice", "bingservice", "$modal", "settoreservice", ($scope, dispositivi, soluzioni, progetti, wms, bing, modal, settore) => new palmare.controllers.gestioneprogetto($scope, dispositivi, soluzioni, progetti, wms, bing, modal, settore)])

and working fine. want alter removing here di references, moving

static $inject = ["$scope", "palmariservice", "soluzioniservice", "progettoservice" , "wmsservice", "bingservice", "$modal", "settoreservice"];

and changing

angular.module('myapp').controller("gestioneprogetto", ($scope, dispositivi, soluzioni, progetti, wms, bing, modal, settore) => new palmare.controllers.gestioneprogetto($scope, dispositivi, soluzioni, progetti, wms, bing, modal, settore));

this approach worked fine factoriesi changes, trying first controller doing obtain message

error: [$injector:unpr] unknown provider: dispositiviprovider <- dispositivi

am missing something?

in case definition this:

module palmare.controllers { export class gestioneprogetto { static $inject = ["$scope", "palmariservice", "soluzioniservice", ...]; ...

this should work angular:

angular .module('myapp') .controller("gestioneprogetto", palmare.controllers.gestioneprogetto);

angularjs typescript

vb.net - Showing IP address on Textbox after select combobox -



vb.net - Showing IP address on Textbox after select combobox -

i want show ip address on textbox after select network adapter combobox list. working code showing adapter list on combobox.

dim ni = system.net.networkinformation.networkinterface.getallnetworkinterfaces dim niethernet = ni.where(function(x) x.networkinterfacetype = net.networkinformation.networkinterfacetype.ethernet) combobox1.datasource = niethernet.select(function(x) x.name).tolist()

i have no problem in selecting adapter. problem want textbox show ipv4 address depends on adapter take combobox list. how can that?

in selectedindexchanged event, based on combobox selected item:

private sub combobox1_selectedindexchanged(sender system.object, e system.eventargs) handles combobox1.selectedindexchanged 'will set textbox selected item in combobox textbox1.text = combobox1.selecteditem 'or set based on combo selection select case combo1.selecteditem case "local connection" textbox1.text = "some ip address" case "something else" textbox1.text = "something else" end select end sub

vb.net combobox textbox ipv4

back stack - Android onBackPressed avoid exit -



back stack - Android onBackPressed avoid exit -

when user press button on device want move previous activity not go home.

for example, if user has opened activities, stack supposed be:

activity_a activity_b activity_c [ displayed ]

when user presses back button, it's supposed get:

activity_a activity_b [ displayed ]

and the, if presses button 1 time again:

activity_a [ displayed ]

then want disable button avoid go home screen.

is possible ?

so far, i'm using method, i've read won't supported on android l:

protected int getactivitiesstacksize() { activitymanager = (activitymanager) getsystemservice(activity_service); list<activitymanager.runningtaskinfo> tasklist = am.getrunningtasks(1); homecoming tasklist.get(0).numactivities; } @override public void onbackpressed() { // pop activity if (getactivitiesstacksize() != 1) super.onbackpressed(); }

activity_a may activity in project.

you can override button event , move between activities except on activity button should still exit. example

@override public boolean onkeydown(int keycode, keyevent event) { // check if key event button if ((keycode == keyevent.keycode_back)) { //move previous activity homecoming true; } // if wasn't key, bubble default // scheme behavior homecoming super.onkeydown(keycode, event); }

android back-stack onbackpressed

html - How to pop a balloon precisely over an image grid that is responsive cross-browser safe? -



html - How to pop a balloon precisely over an image grid that is responsive cross-browser safe? -

i trying have balloon pop above image depending value passed page through php code.

the problem solution bit messy on safari, , amm not sure why getting errors there. slider showing way much right. tested firefox, ie, , chrome, , render semi-ok, safari worst job doing so.

here’s on jsfiddle.

and code, jquery:

$().ready(function () { var score = 64; var = 0; $('.hers').find('.cll').each(function () { if (score != null) { if (i == score) { var me = $(this); me.append(' ' + score); bubbleme(me); $(window).resize(function () { bubbleme(me); }); } i++; } }); function bubbleme(me) { $('.bubbleimage').css('left', me.position().left - 7); $('.bubbleimage').css('top', me.position().top - 7); $('.bubbleimage').css('background-image', 'url("http://olthofhomes.com/dev/communities/img/slider_30_60.png")'); $('.bubbleimage').css('background-repeat', 'no-repeat'); } });

css:

.cll, .cll:empty { position: relative; width: calc(100% / 155); height: auto; display: inline-block; color: #000; z-index: 101; font-weight: bold; } .bubbleimage { position: absolute; width: 60px; height: 80px; left: 0px; top: 0px; z-index: 100; }

html (generated 155 or div's using php, , each have 100% / 155th width)

<div class="hers" style="margin-left: 5px;"> <br /> <br /> <br /> <br /> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="cll"></div> <div class="bubbleimage"></div> <a href="#hersindex"><img src="http://olthofhomes.com/dev/images/hers.jpg" class="imghers" width="100%"></a> </div>

i have used jquery slider instead. should cross-browser safe.

<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css"> <script src="http://code.jquery.com/jquery-1.10.2.js"></script> <script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script> <script> $(function() { $("#slider").slider({ min: 0, max: 160, value: <?php echo $model['hersscore']; ?> }); $('#slider .ui-slider-handle').text("<?php echo $model['hersscore']; ?>"); }); </script> <div id="slider"></div> <img src="hers.jpg" id="slider_image"> </div>

some css

<style> .container99 { width: 100%; height: auto; border: 0px solid black; position: relative; } #slider { width: 100%; position: absolute; top: calc(50% - 5px); height: 0px; border: 0; } #slider_image { width: 100%; height: auto; } .ui-slider { outline:none; } #slider .ui-slider-handle { background-image: url(communities/img/slider_30_60.png); background-size: 100% 100%; background-color: green; border: 0; width: 30px; padding: 0 0 0 7px; margin: 0 0 0 0; color: #fff; } </style>

html css dynamic safari responsive-design

Git Authenticated push over apache -



Git Authenticated push over apache -

i have several git repositories. of them can accessed through apache server , r/w access given all. repository should have authenticated force it. have done this

<locationmatch "^/.*/git-receive-pack$"> authtype basic authname "git access" authbasicprovider file # password file created htpasswd authuserfile /sample/password require valid-user </locationmatch>

but asking username , password repositories. want enable few repositories.

some background

the thought when pushing via http[s], git performs requests this

http://user@server/git/foo.git/info/refs?service=git-receive-pack

the part of uri <location> or <locationmatch> directives consider when matching is

/git/foo.git/info/refs?service=git-receive-pack

it can broken downwards several parts:

the mutual prefix, including name of repository:

/git/foo.git

that's directly specify in repository's uri when telling git, when doing git clone http://user@server/git/foo.git.

the technical bits, telling server-side git want request:

/info/refs?service=git-receive-pack

this part added client-side git, , have no command on it.

how prepare problem @ hand

the .* bit in directive matches 0 or more characters, matches in git uris.

you need refine pattern somehow refer repos want force restriction applied to. , maintain in mind if you're using mutual prefix (like /git/ in examples above) have matched well.

now it's writing proper regular expression.

one approach specify them directly—using so-called alterations—like in

<locationmatch "^/git/(repo1|repo2|repo3)/.*/git-receive-pack$">

while move repos requiring protection under mutual directory, say, priv, , utilize like

<locationmatch "^/git/priv/.*/git-receive-pack$">

the latter approach not require updating apache's configuration , reloading when add together repository requiring authenticated pushes: drop in directory mapped /priv prefix.

of course, exact parts of uri specification depends on rest of configuration (like whether utilize ^/git/ prefix of not etc).

git apache

vba - Copy data from multiple excel sheets and append that to a single excel sheet using VBScript -



vba - Copy data from multiple excel sheets and append that to a single excel sheet using VBScript -

the scenario follows:

i have excel (.xls) file data. (eg. a.xls) the info on excel file on single worksheet (sheet 1). the number of columns in file fixed i.e. 8 however, number of rows containing info may vary time time. (this file updated programme time time) now, have excel file (eg. b.xls) similar type of info not same contents of a.xls. the number of columns in b.xls 8 well. however, number of rows containing info unknown.

i want re-create contents of a.xls, 2nd row onwards (excluding 1st row containing column headers) , append/paste same b.xls file, without over-writing existing info on b.xls.

with these details in mind, want write vbscript automate task.

please help.

thanks lot, in advance.

it needs lot of cleanup, should work. i'll clean bit , create edit.

sub copyrows() ' take name of sec workbook , lastly column. ' must in same directory first workbook. secondworkbook = "b.xls" lastcolumn = "h" ' couple more variables currentworkbook = thisworkbook.name workbooks.open thisworkbook.path & "\" & secondworkbook ' in first workbook, find , select first empty ' cell in column on first worksheet. windows(currentworkbook).activate worksheets(1).columns("a:a") set c = .find("", lookin:=xlvalues) if not c nil ' select , re-create a2 end. secondaddress = replace(c.address, "$a$", "") range("a2:" & lastcolumn & cstr(cint(secondaddress) - 1)).select selection.copy end if end ' activate sec workbook windows(secondworkbook).activate worksheets(1).columns("a:a") set c = .find("", lookin:=xlvalues) if not c nil ' select , paste info first workbook range(c.address).select activesheet.paste end if end end sub

update: should trick. copied wrong workbook first time around, too. allow me know if have questions.

excel vba excel-vba vbscript

java - Retaining data in Apache Kafka -



java - Retaining data in Apache Kafka -

i have started reading apache kafka few days sort of newbie in technology. have doubts/queries , need clarification. such as:

as per configuration: log.retention.hours can set duration in hours here. can info retention time extended 2 years ?

as per link says:

the kafka cluster retains published messages—whether or not have been consumed—for configurable period of time. illustration if log retention set 2 days, 2 days after message published available consumption, after discarded free space. kafka's performance constant respect info size retaining lots of info not problem.

as says perfomance constant respect info size. mean can store info much possible ? require additional configuration or monitor ?

1) sure. log.retention.hours integer. 2 years 17520 hours. below maximal value integer.

2) can store much info fit in disks have. note while kafka's performance not degrade if store more data, consumer seek massive amounts of info disk absolutely impact performance. best performance create sure consumer read relatively recent info while still retained in memory.

java apache-kafka

c# - What is the proper definition of Externals in Code Map? -



c# - What is the proper definition of Externals in Code Map? -

i've found feature of visual studio 2013 can see code calls particular method. see occurrences of validate function , point externals. word saying source code of mvc?

c# visual-studio-2013

java - Getting Fractions of a Cent -



java - Getting Fractions of a Cent -

hey guys got first java job if things go may never need code again. need connect database , apply involvement big number of transactions. having problem getting math work right on local machine. must right within fraction of cent. ideas? in advance!

public connection getconnection() throws sqlexception { connection conn = null; properties connectionprops = new properties(); connectionprops.put("user", "my_user"); connectionprops.put("password", "my_password"); if (this.dbms.equals("mysql")) { conn = drivermanager.getconnection( "jdbc:" + this.dbms + "://" + "yr1f4k3qas3rv3r" + ":" + this.portnumber + "/", connectionprops); } else if (this.dbms.equals("derby")) { conn = drivermanager.getconnection( "jdbc:" + this.dbms + ":" + this.dbname + ";create=true", connectionprops); } system.out.println("connected database"); homecoming conn; } public static void applyinteresttohighvolumeaccounts(connection con, string dbname, string interesttoapply) throws sqlexception { statement stmt = null; string query = "select * "from " + dbname + ".highvolumeaccounts"; seek { stmt = con.createstatement(); resultset rs = stmt.executequery(query); while (rs.next()) { string accountname = rs.getstring("accountname"); int accountnumber = rs.getint("accountnumber"); int balance = rs.getint("balance"); int involvement = interesttoapply int newbalance = balance + (balance * interest) - (balance * 0.00000001%) int addtoretirement = balance * 0.000001% string getrich = "update tbl_accounts set balance=balance" + addtoretirement + " accountname=privateaccountinthecaymens"; resultset rs = stmt.executequery(getrich); string adjustbalance = "update tbl_accounts set balance=balance" + newbalance + " accountname=accountname"; resultset rs = stmt.executequery(adjustbalance); } } grab (sqlexception e ) { jdbctutorialutilities.printsqlexception(e); } { if (stmt != null) { stmt.close(); } } }

i think close. bigdecimals 1 way go. utilize next code verbatum , should fine:

import java.sql.*; import java.math.bigdecimal; import java.math.mathcontext; public class adjustaccounts{ static final string jdbc_driver = "com.mysql.jdbc.driver"; static final string db_url = "jdbc:mysql://yr1f4k3qas3rv3r"; static final string user = "my_user"; static final string pass = "my_password"; public static void main(string[] args) { connection conn = null; statement stmt = null; try{ class.forname("com.mysql.jdbc.driver"); system.out.println("connecting database..."); conn = drivermanager.getconnection(db_url,user,pass); stmt = conn.createstatement(); string sql; sql = "select * highvolumeaccounts"; resultset rs = stmt.executequery(sql); while(rs.next()){ //retrieve column name int accountnumber = rs.getint("accountnumber"); bigdecimal balance = rs.getbigdecimal("balance"); string accountname = rs.getstring("accountname"); double pennyshave = 0.000000001; bigdecimal difference = balance.multiply(new bigdecimal(pennyshave)); //pad business relationship sql = "update tbl_accounts set balance=balance +" + difference + " accountnumber=00098793302999"; //don't worry number, java thing stmt.executequery(sql); //adjust other one. sql = "update tbl_accounts set balance=balance -" + difference + " accountname="+ accountname; stmt.executequery(sql); } rs.close(); stmt.close(); conn.close(); }catch(sqlexception se){ se.printstacktrace(); }catch(exception e){ e.printstacktrace(); }finally{ try{ if(stmt!=null) stmt.close(); }catch(sqlexception se2){ } try{ if(conn!=null) conn.close(); }catch(sqlexception se){ se.printstacktrace(); } } }

}

java math

php - Issue on store credit of opencart 1.5.6 -



php - Issue on store credit of opencart 1.5.6 -

i want create order client in administration. client has credit (let's $200). order total calculated order total - customer's credit = new order total.

the problem customer's credit not alter after creating order.

for example:

the order total is: $500 credit is: $200 then order total : $500 - $200 = $300 but customer's credit still: $200

has else had same problem?

i seek alter status of order, both processing , setting, doesn't work.

the transaction in client info page not change.

i have checked code in backend - there no code operate oc_customer_transaction table.

in frontend, there function in /catalog/model/total/credit.php

class="lang-php prettyprint-override">public function confirm($order_info, $order_total) { $this->language->load('total/credit'); if ($order_info['customer_id']) { $this->db->query("insert " . db_prefix . "customer_transaction set customer_id = '" . (int)$order_info['customer_id'] . "', order_id = '" . (int)$order_info['order_id'] . "', description = '" . $this->db->escape( sprintf($this->language->get('text_order_id'), (int)$order_info['order_id'])) . "', amount = '" . (float)$order_total['value'] . "', date_added = now()"); } }

it called during checkout process recalculate customer's credit balance. haven't found such code in backend.

i prepare that.

code:

$this->db->query("insert " . db_prefix . "customer_transaction set customer_id = '" . (int)$order_info['customer_id'] . "', order_id = '" . (int)$order_info['order_id'] . "', description = '" . $this->db->escape( sprintf($this->language->get('text_order_id'), (int)$order_info['order_id'])) . "', amount = '" . (float)$order_total['value'] . "', date_added = now()");

just add together credit calculate code when @ next place:

1./admin/model/sale/order.php addorder method

a. when add together product new client order in backend, scheme send request frontend (/catalog/checkout/mannual.php index ) wo calculate order total(such as: subtotal, credit, shipping, total). after request, order total in page refreshed

b. when save order, (admin/model/sale/order.php) addorder method called eventually. need add together code above function.

insert into..... customer_transaction means utilize credit

2./admin/model/sale/order.php editorder method

a. when edit order, each item in totals changed. so, should delete credit used order before.

delete * oc_customer_transaction 'order_id'=$order_id

b. since each item of totals(involve credit) has been recalculated in step1, method receive new credit amount. insert new amount code blow

3.you not need alter admin/model/sale/order.php deleteorder method because delete totals, include item in info table oc_customer_transaction

things done!

php opencart

php - Decoding JSON array -



php - Decoding JSON array -

i'm struggling parse simple json array, new trying learn.

here's data:

{"data":[ {"name":"john","id":"123"}, {"name":"dave","id":"345"} ], "other": {"foo":"bar"} }

i want data information.

here's i'm trying (also else tried):

$list = json_decode(file_get_contents($jsonurl),true); foreach ($list $element){ //$id = $element->data->id; // didn't work either //$name = $element->data->name; // didn't work either $id = $element[data][id]; $name = $element[data][name]; $message .= $id.' - '.$name.'</br>'; }

any ideas why returns nothing?

$json = '{"data":[ {"name":"john","id":"123"}, {"name":"dave","id":"345"} ], "other": {"foo":"bar"} }'; $list = json_decode($json,true); foreach ( $list['data'] $item ) { echo $item['id'] . "\n"; echo $item['name'] ."\n\n"; }

here perfect illustration of how work data.

php json

shell - Python fabric How to send password and yes/no for user prompt -



shell - Python fabric How to send password and yes/no for user prompt -

i have created fabfile multiple hosts.

i automating experiment. when run command "sudo adduser --ingroup hadoop hduser" inquire following.

new unix password confirm password. full name room,ph,etc is info correct? y/n

i pass info part of script without prompting user. how can ?

thanks

navaz

why didn't utilize pipes?

for example, automated auto accept, utilize yes, outputs neverending stream of y.

yes | rm *.txt

in case:

local('echo 'your_super_password\n' | sudo adduser --ingroup hadoop hduser')

python shell hadoop fabric

rails association belongs_to -



rails association belongs_to -

i know sty must wrong in way build db please take min answering : building supermarket model, 1 user has shopping list, each list has many products. :

class user < activerecord::base has_many :lists end class list < activerecord::base belongs_to :user has_many :products end class product < activerecord::base ???? end

a list has several products products don't belong lists. should have users having many lists, , lists having many products ? regards,

have class links them via has_many through.

class listitem < activerecord::base belongs_to :list belongs_to :product end class list < activerecord::base belongs_to :user has_many :list_items has_many :products, through: :list_items end

ruby-on-rails associations belongs-to

magento - Show CMS block only for customers who have not subscribed to a Newsletter -



magento - Show CMS block only for customers who have not subscribed to a Newsletter -

i'm looking way show cms block customers (who logged in anyways) have not subscribed newsletter.

could help me code? know how implement cms block, not sure how check whether client has subscribed or not.

thanks lot, johannes

magento check client email exits or not below code

class="snippet-code-html lang-html prettyprint-override">$status = mage::getmodel('newsletter/subscriber')->subscribe($email); $subscriber = mage::getmodel('newsletter/subscriber')->loadbyemail($email); if($subscriber->getid()) { if ($status == mage_newsletter_model_subscriber::status_not_active) { // 'confirmation request has been sent.'; } else { //thank subscription; } } else{ //no subcription }

magento newsletter subscriber

javascript - Sorting Accordion Header -



javascript - Sorting Accordion Header -

i got error angular js returning link

http://errors.angularjs.org/1.2.26/$injector/unpr?p0=uniquefilterprovider%20%3c-%20uniquefilter

but dont understand how impliment this.

can help me guys prepare problem. im newbee..sorry

this html:

<accordion-group class="div-recipe-header" ng-repeat="keyw in recipe_data | orderby:'keyword':false"/> <accordion-heading><div class="headhover" >{{keyw.keyword}}</div></accordion-heading> </accordion-group>

sample json info homecoming web api

{ id: "0908", name: "fanini" keyword: "appetizer" }, { id: "3232", name: "adobo" keyword: "main courses" }, { id: "3242", name: "buko" keyword: "salads" }, { id: "8473", name: "ceasar" keyword: "salads" } { id: "9737", name: "sinigang" keyword: "main courses" }, { id: "7423", name: "tomatoes" keyword: "appetizer" },

this actual screenshot on website

http://i.imgur.com/lskmle2.png?1

javascript html angularjs accordion

Error in Server provisioning through Chef, Oracle Virtual Box and Vagrant -



Error in Server provisioning through Chef, Oracle Virtual Box and Vagrant -

i working on chef- provisioning. trying utilize chef-provisioning, oracle virtual box , vagrant purpose. executed command:

"**gem install chef-provisioning chef-provisioning-vagrant**" got next error: **error: not find valid gem 'chef-provisioning-vagrant'**

i moved ahead without bothering it. , when executed "chef-client -z vagrant_linux.rb simple.rb" got next error:

**fatal: loaderror: cannot load such file -- chef/provisioning_vagrant**

why chef server not able locate "chef-provisioning-vagrant". file renamed or changed or else. help?

regards manish mehra

if box has no chef installed (e.g. using own box made scratch or using chef/debian-7.4), need install gem "chef". don't know other gems install doing, not aware of issues normale "chef" gem:

sudo gem install --no-rdoc --no-ri chef

you can have @ repo take plain debian box, install chef , basic packages: https://github.com/sgoettschkes/va/tree/master/debian7

vagrant chef provisioning

Meteor Server Websockets -



Meteor Server Websockets -

i looking create websocket on meteor server (not client) connect external site. know url going hitting info expect, unclear how create websocket itself. searching presents me solutions client, have yet run serves server solution.

is there out there missed fills purpose? atmosherejs.com doesn't list anything, , searching around on google/github didn't reveal either. there built meteor accomplishes this?

meteor websocket server

Oracle SQL MAX function not returning max on VARCHAR to NUMBER conversion -



Oracle SQL MAX function not returning max on VARCHAR to NUMBER conversion -

i attempting highest scheme number set of rows. scheme number preceded sys, select system_id table yield, {sys901,sys87,sys3024.....}

this query i'm attempting use:

select max(replace(system_id,'sys','')) table

the possible results are

{901,87,3024,20,1}

it returning 901 value i'm expecting see 3024 value. assume problem field varchar not number. how address problem, not know.

select max(to_number(replace(system_id,'sys',''))) table;

use to_number convert varchar2 number otherwise oracle compares strings using ascii codes ('9' > '3')

sql oracle

python - pandas reindex with data frame -



python - pandas reindex with data frame -

i have dataframe multiindex 3 levels, instance:

col1 col2 ... chrom pos label chr1 43 stra ... ... ... strb ... ... ... 66 strc ... ... ... strb ... ... ... chr2 29 strd ... ... ... ... ... ... ... ... ...

and series multiindex first 2 levels of dataframe index:

val chrom pos chr1 43 v1 66 v2 chr2 29 v3 ... ... ...

i add together column series dataframe, repeating values v1, v2... every index first 2 levels match, this:

col1 col2 new ... chrom pos label chr1 43 stra ... ... v1 ... strb ... ... v1 ... 66 strc ... ... v2 ... strb ... ... v2 ... chr2 29 strd ... ... v3 ... ... ... ... ... ... ... ...

note series has no missing rows, is, (chrom,pos) in dataframe in series. have working solution:

pandas.series(variant_db.index.map(lambda i: cov_per_sample[sample].loc[i[:2]]), index=variant_db.index)

but, because of lambda, quite slow big info (hundreds of thousands of rows). tried much faster:

df['new'] = s.reindex(df.index, method='ffill')

but in way there many nans in df['new'], should not happen. using method='bfill' nans in different positions, rows nans in both cases, using both not work.

i way using library function only, efficiency. can help?

you can seek simple solution big info performance:

df1=pandas.dataframe([ {'chrom':'chr1','pos':43,'label':'stra'}, {'chrom':'chr1','pos':43,'label':'strb'}, {'chrom':'chr1','pos':66,'label':'strc'}, {'chrom':'chr1','pos':66,'label':'strb'}, {'chrom':'chr2','pos':29,'label':'strd'}]) df2=pandas.dataframe([ {'chrom':'chr1','pos':43,'val':'v1'}, {'chrom':'chr1','pos':66,'val':'v2'}, {'chrom':'chr2','pos':29,'val':'v3'}]) i,r in df2.iterrows(): df1.ix[(df1['chrom']==r['chrom']) & (df1['pos']==r['pos']),'new']=r['val']

or using indexes:

df1=pandas.dataframe([ {'chrom':'chr1','pos':43,'label':'stra','col':''}, {'chrom':'chr1','pos':43,'label':'strb','col':''}, {'chrom':'chr1','pos':66,'label':'strc','col':''}, {'chrom':'chr1','pos':66,'label':'strb','col':''}, {'chrom':'chr2','pos':29,'label':'strd','col':''}]).set_index(['chrom','pos','label']) df2=pandas.dataframe([ {'chrom':'chr1','pos':43,'val':'v1'}, {'chrom':'chr1','pos':66,'val':'v2'}, {'chrom':'chr2','pos':29,'val':'v3'}]).set_index(['chrom','pos']) i,r in df2.iterrows(): df1.ix[(i[0],i[1]),'new']=r['val']

python pandas

mysql - SQL Query returning thousands of empty rows -



mysql - SQL Query returning thousands of empty rows -

i have table ~180,000 rows currently. have query:

select `item_id`, count(*) count `user_items` grouping `item_id`

which runs on table columns: 'combination_id', 'user_id' , 'item_id'. there 6000 item_ids , of course of study 180,000 combination_ids mentioned.

i want homecoming number of occurrences of each item_id. when run query in phpmyadmin 180,000 rows in result of empty (as there 6000 or unique item_ids).

could explain why happening?

mysql sql phpmyadmin

javascript - Getting extra brackets using array push -



javascript - Getting extra brackets using array push -

i trying build little custom logger , noticing array force getting brackets , cannot figure out going on. here sample output

{ "guestcheckout": [ { "log": "product id: 78-1212121", "screenshot": "" }, [ { "log": "product color: undefined product size: 6 lb qty: 2", "screenshot": "" } ], [ { "log": "", "screenshot": "results/screenshots/guest checkout - failed.jpg" } ] ] }

here class has logger function

var logs = {}, curlogs = []; module.exports = { logger: function(log, screenshot) { isscreenshot = screenshot || "false"; curtestname = testname.replace(/ /g,''); curlogs = []; if (isscreenshot == "true") { curlogs.push({ "log": "", "screenshot": log }); } else { curlogs.push({ "log": log, "screenshot": "" }); } if (curtestname in logs) { logs[curtestname].push(curlogs); } else { logs[curtestname] = curlogs; } console.log(curlogs); } }

you notice first log , screenshot wrapped around {} sec instances in wrapped []. logger function called multiple times. think has way force building wrong. thanks

update: 1 solution output looks now

{ "guestcheckout": [ [ { "log": "product id: 36-5173230", "screenshot": "" } ], [ { "log": "product color: undefined product size: 6 lb qty: 2", "screenshot": "" } ], [ { "log": "", "screenshot": "results/screenshots/guest checkout - failed.jpg" } ] ] }

the problem {logs, screenshots} wrapped in brackets.

the issue starts when log test exists. if log exists, pushing array rather object. prepare this, have 2 options. either pull existing array test , force directly, or, force each new log entry test afterwards.

var logs = {}, curlogs = []; module.exports = { logger: function(log, screenshot) { isscreenshot = screenshot || "false"; curtestname = testname.replace(/ /g,''); if (!logs[curtestname]) { // initialize logs entry logs[curtestname] = []; } // logs entry curlogs = logs[curtestname]; if (isscreenshot == "true") { curlogs.push({ "log": "", "screenshot": log }); } else { curlogs.push({ "log": log, "screenshot": "" }); } console.log(curlogs); } }

or

var logs = {}, curlogs = []; module.exports = { logger: function(log, screenshot) { isscreenshot = screenshot || "false"; curtestname = testname.replace(/ /g,''); curlogs = []; if (isscreenshot == "true") { curlogs.push({ "log": "", "screenshot": log }); } else { curlogs.push({ "log": log, "screenshot": "" }); } if (curtestname in logs) { array.push.apply(logs[curtestname], curlogs); } else { logs[curtestname] = curlogs; } console.log(curlogs); } }

javascript node.js

c# - OleDbCommand with bind variables -



c# - OleDbCommand with bind variables -

i trying utilize bind variables oledbcommand. have next code

var sql = @"select * table order_no = '@order_no'"; using (var cmd = new oledbcommand(sql, connection)) { cmd.parameters.add(new oledbparameter("@order_no", "1234")); using (var dr = cmd.executereader()) { while (dr.read()) { // } } }

when run code nil returned database. if alter sql be

var sql = @"select * table order_no = '1234'";

a result returned. doing wrong?

remove apostrophes around @order_no:

var sql = @"select * table order_no = @order_no";

otherwise it's not parameter string literal , you're looking order_no = @order_no.

c# database oracle oledbcommand

mysql - How to login user and Admin in same page -



mysql - How to login user and Admin in same page -

i trying login username , password in way.based on input values pages should redirect.but not able login.

<%@include file="database.jsp" %> <% string user = request.getparameter("user"); string pass = request.getparameter("pass"); if (user.equals("admin") && pass.equals("admin123")) { response.sendredirect("adminhome.jsp"); } else { response.sendredirect("adminerror.jsp"); } if (user != "admin") { string sql = "select * user username='" + user + "' , password='" + pass + "'"; rs = st.executequery(sql); if (rs.next()) { response.sendredirect("userhome.jsp"); } else { response.sendredirect("usererror.jsp"); } } %>

you using scriplet when should utilize servlets. servlets simpler write, test , debug scriplets.

in code, never reach user part. either give right admin user , pass , should redirected adminhome.jsp, else pass through response.sendredirect("adminerror.jsp");

if user admin should redirected adminhome.jsp (provided there nil else after show). else phone call twice sendredirect should cause error.

you should @ to the lowest degree test separately user , password admin part avoid response.sendredirect("adminerror.jsp"); branch if user not admin , multiple redirection error.

you should seek type straight in browser url adminhome.jsp sure correctly accessible browser.

mysql jsp

javascript - Trigger button animation on event in AngularJS -



javascript - Trigger button animation on event in AngularJS -

i'm trying utilize $animate service in custom directive. i'm running issue $animate service not applying specified class (likely issue $apply's timing), nor first animation finish before $animate removes class.

i want:

mousedown start animation the animation finish the animation 'hold' extended mousedown events the animation end after both finishing animation and mouseup have occurred.

in other words never want animation jump. i'd prefer utilize $animate, @ point i'm willing seek other solutions…

please not utilize jquery in solution.

class="snippet-code-js lang-js prettyprint-override">angular.module('app', []) .directive('onactivate', function($parse, $q, $animate, $timeout) { homecoming { restrict: 'a', link: function(scope, element, attr) { var hastouch = false; var handler = $parse(attr.onactivate); element.one('mousedown', function() { if (!hastouch) { console.log('clicked!'); scope.$apply(function() { $animate.addclass(element, 'pressed'); }); element.on('mousedown', function() { scope.$apply(function() { $animate.addclass(element, 'pressed'); }); }); element.on('mouseup', function() { scope.$apply(function() { $animate.removeclass(element, 'pressed'); }); }); element.on('click', function(event) { scope.$evalasync(handler(scope, { $event: event })); }); } }); element.one('touchstart', function(event) { hastouch = true; $animate.addclass(element, 'pressed'); element.on('touchstart', function() { $animate.addclass(element, 'pressed'); }); element.on('touchend touchcancel', function() { $animate.removeclass(element, 'pressed'); }); element.on('touchend', function(event) { scope.$evalasync(handler(scope, { $event: event })); }); }); } } }) class="snippet-code-css lang-css prettyprint-override">/* vendor prefixes handled automatically prefixfree */ @keyframes grow { { transform: scale(1); } { transform: scale(0.75); } } button { width: 5rem; height: 2rem; transition: 1s ease; } button.pressed { transition: none; animation: grow 1s ease; transform: scale(0.75); } button:not(.pressed) { transform: scale(1); } class="snippet-code-html lang-html prettyprint-override"><script src="//cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <body ng-app="app"> <button on-activate=""> click me </button> <p style="font-family: sans-serif;">the animation jumps unless user holds button down. want <code>.pressed</code> animation finish regardless of how long users holds button down.</p> </body>

javascript html css angularjs animation

JavaFX 8 hiding side panel and mini window with button -



JavaFX 8 hiding side panel and mini window with button -

good evening.

after playing around few java fx 8 tutorials , making simple applications, decided take more hard project.

i had old swing map application displayed maps, layers , meteorological info db using map objects , taking maps local map server. wish update application pure java fx 8 , geoserver java api, added old swing app.

the first thing did, seek build model application in scene builder 2.0, have general idea. since making scratch, wished create little more modern.

and here problem. wish have map in tabbed pane, taking whole screen, minor panel bellow displaying info ( have yet decide of old info useful), , menu bar on top. user border pane central app, menu bar north, pane south , tab in center.

so far good. but, cannot figure out how add together button user can hide/unhide accordion pane , minimap of whole world, image bellow show:

i think accordion panel map within hbox, map panel having hgrow set , button resizing accordion panel hide/unhide it. also, want mini-map on top of both windows.

however, have no thought how set buttons there. tried many different layouts , tricks, have found no actual solution. cannot find examples, , unfortunately 2 books bought not go beyond given layouts. there way this?

also, while not priority, javafx have capability drag , drop components (p.ex. minimap) , lock on place? user perhaps want minimap down-right corner instead?

i suggest using/writing custom pane.

add map, sidebar, sidebar togglebutton, minimap togglebutton , minimap children. (don't forget phone call tofront() , toback accordingly set the elements in right layers.)

now there 2 ways on how position elements:

overwrite layoutchildren() method of stackpane , set coordinate of components there relocate(x,y) or resizerelocate(x,y,width,height). or set managed property of aforementioned elements false (setmanaged(false)) , bind layoutx , layouty properties desired values.

if going #1 (not code, idea):

the minimap button, should left bottom so: x = 0 | y = pane.getheight() - button.getheight() the sidebar button should left center: x = sidebar.getwidth() - button.getwidth() | y = pane.getheight() / 2 - button.getheight() / 2 and on...

if going #2 (again not tested code):

the minimap button: setlayoutx(0) | layouty.bind(pane.heightproperty()) the sidebar button: layoutxproperty.bind(sidebar.widthproperty().subtract(button.widthproperty)) | `layoutyproperty.bind(pane.heightproperty().divide(2).subtract(button.heightproperty().divide(2))) and on...

and yes can move minimap mouse gestures have @ setonmousepressed , setonmousedragged. first event typically store current coordinate , sec event calculate delta adjust layoutx/layouty values.

edit:

you might have @ controlsfx, have hiddensidespane , masterdetailpane might (partly) looking for.

javafx

node.js - http request does not emit 'end' after proxy -



node.js - http request does not emit 'end' after proxy -

i need able utilize http request body in request proxy application , 1 time again in actual web service. using restreamer 'reset' stream (and wrote middleware myself no change). web service receives body fine, because end never emitted, cannot go on request.

testing postman, sending raw body, content type set. suggestions appreciated. thanks!

var express = require('express') , bodyparser = require('body-parser') , http = require('http') , restreamer = require('connect-restreamer') , httpproxy = require('http-proxy') var app = express(); app.use(function (req, res, next) { var body = ''; req.on('data', function (chunk) { body += chunk.tostring('utf8'); }); req.on('end', function (chunk) { req.body = json.parse(body) next(); }); }); app.use(restreamer()); var proxy = httpproxy.createserver(); app.all('*', function (req, res) { proxy.web(req, res, { target: 'http://localhost:8001' }); }); http.createserver(app).listen(8000); app2 = express(); app2.use(function (req, res, next) { var body = ''; req.on('data', function (chunk) { body += chunk.tostring('utf8'); }); req.on('end', function (chunk) { req.body = json.parse(body) next(); }); }); app2.all('*', function (req, res) { res.send(req.body) }); http.createserver(app2).listen(8001);

using request library in application, worked:

var request = require('request') request.post({ url: 'http://localhost:8000', json: {content: 123, type: "greeting", access_token: "here am"} },function(err, res,data){ console.log('return:' ,err, data) });

but using curl file containing same message, not work:

curl -x post -d @data.json http://localhost:8000 --header "content-type:application/json"

i compared request objects against each other , found few differences , when got request header content-length, found editing "correct" length end steam (and web server send response).

i create modifications needed , commit connect-restreamer module.

node.js express node-http-proxy

c++ - Vector fails to get initialized -



c++ - Vector fails to get initialized -

i trying initialize vector of self-defined type datacard:

vector<datacard> dataset; dataset.reserve(200);

however compiler doesn't allow me indicating error @ sec line (where seek reserve space container):

required here

however when alter declaration following

vector<datacard*> dataset;

it starts working.

what reason compiler not allowing me utilize type is, letting me utilize pointer type? need vector of objects, not pointers them.

edit

header file of datacard

#include <card.h> class datacard { char* name; // name according filename char class; // classes: 2, 3, 4, 5, 6, 7, 8, 9, t, j, q, k, double distancetoquery; public: void resetdistance(); int numblacktotal (bitmap* bmp); bitmap image; int numofblackpixels; char* getname(); void setname(char* n); void setclass (char* c); char* getclass(); void setdistance(double distance); double getdistance (); datacard(const char* fname); datacard(); virtual ~datacard(); };

here's error message compiler

/usr/include/c++/4.7/bits/stl_uninitialized.h:77:3: required ‘static _forwarditerator std::__uninitialized_copy<_trivialvaluetypes>::__uninit_copy(_inputiterator, _inputiterator, _forwarditerator) [with _inputiterator = datacard*; _forwarditerator = datacard*; bool _trivialvaluetypes = false]’ /usr/include/c++/4.7/bits/stl_uninitialized.h:119:41: required ‘_forwarditerator std::uninitialized_copy(_inputiterator, _inputiterator, _forwarditerator) [with _inputiterator = datacard*; _forwarditerator = datacard*]’ /usr/include/c++/4.7/bits/stl_uninitialized.h:260:63: required ‘_forwarditerator std::__uninitialized_copy_a(_inputiterator, _inputiterator, _forwarditerator, std::allocator<_tp>&) [with _inputiterator = datacard*; _forwarditerator = datacard*; _tp = datacard]’ /usr/include/c++/4.7/bits/stl_vector.h:1112:8: required ‘std::vector<_tp, _alloc>::pointer std::vector<_tp, _alloc>::_m_allocate_and_copy(std::vector<_tp, _alloc>::size_type, _forwarditerator, _forwarditerator) [with _forwarditerator = datacard*; _tp = datacard; _alloc = std::allocator<datacard>; std::vector<_tp, _alloc>::pointer = datacard*; std::vector<_tp, _alloc>::size_type = long unsigned int]’ /usr/include/c++/4.7/bits/vector.tcc:76:70: required ‘void std::vector<_tp, _alloc>::reserve(std::vector<_tp, _alloc>::size_type) [with _tp = datacard; _alloc = std::allocator<datacard>; std::vector<_tp, _alloc>::size_type = long unsigned int]’ /home/ppsadm01/documents/vgv/src/main.cc:145:22: required here /usr/include/c++/4.7/bits/stl_construct.h:85:7: error: no matching function phone call ‘datacard::datacard(const datacard&)’

as error message suggests need implement re-create constructor datacard::datacard(const datacard&). need because illustration vector<datacard>::push_back() re-create datacard instances.

when write re-create constructor, careful all fellow member variables copied - in right way. illustration implementation be

datacard::datacard(const datacard &rhs) { strcpy(name, rhs.name); class = rhs.class; distancetoquery = rhs.distancetoquery; image = rhs.image; // create sure ok! }

c++ pointers vector

sql - Join two tables to get counts different dates -



sql - Join two tables to get counts different dates -

i have table columns:

id, transactiondate, pointsordered

table b

id,redemptiondate,pointsused

table c

as

id,joindate

what want

all info needed date range lets 2014-01-01 2014-02-01 in yyyy-mm-dd

count of total ids date ( count of ids table a)

count of accounts had first transaction on date

total points ordered date ( sum of points table a)

count of accounts redeemed on date ( count of ids table b )

countofpointsued on date ( sum of points table b)

new customers joined date

i understand id foreign key table b , table c how ensure match dates ?

for eg if bring together date such a.transactiondate=b.redemption.date gives me customers had transaction on date , redeemed on date.

where want count of customers had transaction on date , customers redeemed on date ( irrespetive of fact when did have transaction)

here had tried

select count( distinct a.id) noofcustomers, sum(a.pointsordered), sum(b.pointsused), count(distinct b.id) transaction bring together redemption b on a.transactiondate=b.redemptiondate .transactiondate between '2014-01-01' , '2014-02-01' grouping a.transactiondate,b.redemptiondate

i first grouping info table , bring together results date. shouldn't utilize inner bring together because may lose info if there no matching record on 1 side no transaction on given date redemption. help if you'd have list of dates in range. if don't have can build 1 using cte.

declare @from date = '2014-01-01' declare @to date = '2014-02-01' ; dates ( select @from [date] union select dateadd(day, [date], 1) d dates [date] < @to ) , orders ( select transactiondate [date], count(distinct id) noofcustomers, sum(pointsordered) pointsordered [transaction] transactiondate between @from , @to grouping transactiondate ) , redemptions ( select redemptiondate [date], count(distinct id) noofcustomers, sum(pointsused) pointsused [redemption] redemptiondate between @from , @to grouping redemptiondate ) , joins ( select joindate [date], count(distinct id) noofcustomers [join] joindate between @from , @to grouping joindate ) , firsts ( select transactiondate [date], count(distinct id) noofcustomers [transaction] t1 transactiondate between @from , @to , not exists ( select * [transaction] t2 t2.id = t1.id , t2.transactiondate < t1.transactiondate) grouping transactiondate ) select d.[date], isnull(o.noofcustomers,0) noofcustomersordered, isnull(o.pointsordered,0) totalpointsordered, isnull(f.noofcustomers,0) noofcustomersfirsttran, isnull(r.noofcustomers,0) noofcustomersredeemed, isnull(r.pointsused,0) totalpointsredeemed, isnull(j.noofcustomers,0) noofcustomersjoined dates d left bring together orders o on o.[date] = d.[date] left bring together redemptions r on r.[date] = d.[date] left bring together joins j on j.[date] = d.[date] left bring together firsts f on f.[date] = d.[date]

please note didn't run query may errors, think general thought clear.

sql sql-server join count

Arranging the row data into Columns using VBA in excel? -



Arranging the row data into Columns using VBA in excel? -

i adapting off of question: re-arranging row info in columns

i have excel info set follows;

collection latdd londd date location method specie1 specie2 specie3(+-110 species columns in total) abs1 11.35 -10.3 2003-02-01 bucket 0 1 3 abs2 11.36 -10.4 2003-02-02 b stick 2 0 6

i info appear so:

collection specie count latdd londd date location method abs1 specie1 11.35 -10.3 2003-02-01 bucket abs1 specie2 1 11.35 -10.3 2003-02-01 bucket abs1 specie3 3 11.35 -10.3 2003-02-01 bucket abs2 specie1 2 11.36 -10.4 2003-02-02 b stick abs2 specie2 -11.36 -10.4 2003-02-02 b stick abs2 specie3 6 -11.36 -10.4 2003-02-02 b stick

i attempted adapt ripsters original vba code reply unfortunately unable figure how need alter it. could please advise me on how adjust code produce desired output?

here orginal vba code:

sub example() dim resources() string dim rng range dim row long dim col long dim x long redim resources(1 (activesheet.usedrange.rows.count - 1) * (activesheet.usedrange.columns.count - 1), 1 3) 'change source sheet sheets("sheet1").select 'read info array row = 2 activesheet.usedrange.rows.count col = 2 activesheet.usedrange.columns.count x = x + 1 resources(x, 1) = cells(row, 1).value ' name resources(x, 2) = cells(1, col).value ' date resources(x, 3) = cells(row, col).value ' value next next 'change destination sheet sheets("sheet2").select 'write info sheet range(cells(1, 1), cells(ubound(resources), ubound(resources, 2))).value = resources 'insert column headers rows(1).insert range("a1:c1").value = array("resource", "date", "value") 'set strings values set rng = range(cells(1, 3), cells(activesheet.usedrange.rows.count, 3)) rng.value = rng.value end sub

try this:

sub example() dim row long dim col long dim x long h1 = "sheet1" h2 = "sheet2" sheets(h1).select x = 2 'headers sheet2 sheets(h2).cells(1, 1).value = sheets(h1).cells(1, 1) sheets(h2).cells(1, 2).value = "specie" sheets(h2).cells(1, 3).value = "count" sheets(h2).cells(1, 4).value = sheets(h1).cells(1, 2) sheets(h2).cells(1, 5).value = sheets(h1).cells(1, 3) sheets(h2).cells(1, 6).value = sheets(h1).cells(1, 4) sheets(h2).cells(1, 7).value = sheets(h1).cells(1, 5) sheets(h2).cells(1, 8).value = sheets(h1).cells(1, 6) row = 2 activesheet.usedrange.rows.count col = 7 activesheet.usedrange.columns.count sheets(h2).cells(x, 1).value = sheets(h1).cells(row, 1).value sheets(h2).cells(x, 2).value = sheets(h1).cells(1, col).value sheets(h2).cells(x, 3).value = sheets(h1).cells(row, col).value sheets(h2).cells(x, 4).value = sheets(h1).cells(row, 2).value sheets(h2).cells(x, 5).value = sheets(h1).cells(row, 3).value sheets(h2).cells(x, 6).value = sheets(h1).cells(row, 4).value sheets(h2).cells(x, 7).value = sheets(h1).cells(row, 5).value sheets(h2).cells(x, 8).value = sheets(h1).cells(row, 6).value x = x + 1 next next end sub

sheet1:

sheet2:

a short versión:

sub example() dim row long dim col long dim x long set sh1 = thisworkbook.worksheets("sheet1") set sh2 = thisworkbook.worksheets("sheet2") sh1.select 'headers sheet2 sh2.cells(1, 1).value = sh1.cells(1, 1) sh2.cells(1, 2).value = "specie" sh2.cells(1, 3).value = "count" = 4 8 sh2.cells(1, i).value = sh1.cells(1, - 2) next x = 2 'starting row of sheet2. row = 2 activesheet.usedrange.rows.count col = 7 activesheet.usedrange.columns.count sh2.cells(x, 1).value = sh1.cells(row, 1).value sh2.cells(x, 2).value = sh1.cells(1, col).value sh2.cells(x, 3).value = sh1.cells(row, col).value = 4 8 sh2.cells(x, i).value = sh1.cells(row, - 2).value next x = x + 1 next next sh2.select end sub

excel vba excel-vba rows

Upload Video To Facebook from my android app fail with error extended permission requiren status 403 -



Upload Video To Facebook from my android app fail with error extended permission requiren status 403 -

in android app want share video android app facebook wall. below code doing so-

request.callback callback5 = new request.callback() { public void oncompleted(response response) { toast.maketext(mcontext,"success",toast.length_short).show(); mdialog.dismiss(); } }; file mfile = new file(videopath); request request5; seek { request5 = request.newuploadvideorequest(session, mfile, callback5); requestasynctask task5 = new requestasynctask(request5); task5.execute(); } grab (filenotfoundexception e) { e.printstacktrace(); }

also made changes in fb api console.but when upload video-

{response: responsecode: 403, graphobject: null, error: {httpstatus: 403, errorcode: 200, errortype: oauthexception, errormessage: (#200) requires extended permission: publish_actions}, isfromcache:false}

edit: permissions have added-

` session s = new session(mcontext); session.setactivesession(s); s.openforpublish(new session.openrequest(postvideotofbwall.this).setcallback(callback).setpermissions("public_profile","email","publish_actions"));`

android facebook publish-actions

ggplot2 - combine facet_grid and boxplot -



ggplot2 - combine facet_grid and boxplot -

i want create facet-grid combined boxplots. facets should variable experiment boxplot should show value against fc every variable.the variable , experiment has multiple levels. need utilize gridextra? tried this, wrong:

df.m fc experiment variable value 1 -1.36811678 ago2 knockout pos1 no 2 -0.59630399 ago2 knockout pos1 yes 3 -0.09747337 ago2 knockout pos1 no 4 1.71652821 ago2 knockout pos1 yes 5 -1.13473546 ago2 knockout pos1 no 6 -0.44012950 ago2 knockout pos1 yes ggplot(df.m,aes(value,fc,fill=as.factor(value))) + geom_boxplot(notch=t) + facet_grid(~experiment)

you can simulate info if there's much post (and, knowing levels of various factors helpful), on right track plot, needed add together interaction variable , value. did next facet_wrap utilize facet_grid:

class="lang-r prettyprint-override">library(ggplot2) # create reproducible simulated info set.seed(1492) dat <- data.frame(fc=runif(100, min=-2, max=2), experiment=rep(c("ago1", "ago2", "ago3", "ago4"), 25), variable=rep(c("pos1", "pos2", "pos3", "pos4", "pos5"), 20), value=sample(c("yes", "no"), 100, replace=true), stringsasfactors=false) gg <- ggplot(dat, aes(x=interaction(variable, value), y=fc)) gg <- gg + geom_boxplot(aes(fill=value)) gg <- gg + facet_wrap(~experiment) gg <- gg + labs(x="") gg <- gg + theme_bw() gg <- gg + theme(strip.background=element_rect(fill="black")) gg <- gg + theme(strip.text=element_text(color="white", face="bold")) gg

you have created column combined variable , value factor instead of using interaction explicitly in ggplot call, create easier change/have more command x-axis labeling.

ggplot2 reshape2

haskell - Including other *.o files with Cabal -



haskell - Including other *.o files with Cabal -

i'm building simple library wraps parts of qt. want able utilize qt's qmake configuration scheme find qt libraries on given system, etc, build c wrapper code. can work , produce *.o file, no problem.

but how can cabal include *.o file in *.a generates? assume i'll have write custom setup.hs create work, reading on cabal library documentation don't see obvious way it.

on #haskell suggested utilize postbuild add together files *.a after generated, how path generated *.a within postbuild?

haskell cabal

java - Why this Spring MVC controller returns corrupted UTF-8 String? -



java - Why this Spring MVC controller returns corrupted UTF-8 String? -

i have modified many places create spring mvc work utf-8, including char filter, contexttype in jsp, , fixed mysql well, project working utf-8.

however, newly added function wouldn't right

@requestmapping(value = "/uploadfile", method = requestmethod.post, produces = "text/plain;charset=utf-8") public @responsebody string uploadfilehandler( @requestparam("name") string name, @requestparam("type") string type, @requestparam("file") multipartfile file//, httpservletresponse response ) throws ioexception { // response.setcharacterencoding("utf-8"); if (file.isempty()) homecoming "Empty";

as can see, have set procudes, , setcharacterencoding. returned string used in ajax , have

var ajax = new xmlhttprequest(); ajax.overridemimetype('text/xml;charset=utf-8');

here origin of form in jsp

<form name = "myform" method="post" onsubmit="return validateform()" enctype="multipart/form-data">

but webpage still shows ????. else missing? don't have jquery, hoping solution without using unless must.

found link responsebody problem homecoming utf-8 string due spring web "bug"

summary:

set org.springframework.web.filter.characterencodingfilter in web.xml enforce utf-8 set <value>text/plain;charset=utf-8</value> in spring-servlet.xml stringhttpmessageconverter problem eliminated creating own class

java ajax spring-mvc utf-8

Pointers in C with recursion -



Pointers in C with recursion -

i programme in java , watching c codes. came across programme , don't know how pointer thing working. know pointer stores address , couldn't create through program. please tell how output coming 8 ?

#include <stdio.h> int fun(int n, int * f_p) { int t, f; if (n <= 1) { *f_p = 1; homecoming 1; } t = fun(n - 1, f_p); f = t + *f_p; *f_p = t; homecoming f; } int main() { int x = 15; printf("%d\n", fun(5, &x)); homecoming 0; }

what have here recursive function calculates i-th element of fibonacci sequence (indexing 0). each recursive iteration returns 2 values: i-th fibonacci number , (i-1)-th (previous) fibonacci number. since function in c can homecoming 1 value (well, unless utilize struct homecoming type), other value - previous fibonacci number - returned caller through pointer parameter f_p.

so, when phone call fun(5, &x), function homecoming 8, 5-th fibonacci number, , place 5 x, previous (4-th) fibonacci number.

note initial value of x not matter. 15 not play role in program. apparently there reddish herring.

if know fibonacci sequence is, know next element of sequence sum of 2 previous elements. why function written "return" 2 elements of sequence caller. might not care previous value in top-level caller (i.e in main), nested recursive calls need calculate next number. rest pretty straightforward.

c pointers recursion

IPC between Node.js and Arduino Sketch on Intel Galileo -



IPC between Node.js and Arduino Sketch on Intel Galileo -

i want communicate between node.js server , arduino sketch. discovered there 3 ways it:

files udp ipc

i can implement files, need read sensor values , send them node.js, , seems slow , cut down life of sd card.

i have found 1 some instructions udp , ipc implementation. want implement same node.js. how do it?

this 1 of tasks galileo must perform. surprised see little back upwards it

node.js arduino ipc communication intel-galileo

java - Need help creating an object oriented validation class -



java - Need help creating an object oriented validation class -

what i'm assigned create object-oriented validator. user prompted input integer, , application validates it. end result display on console follows (first 3 inputs beingness invalid, 4th beingness valid):

welcome validation tester application

int test

enter integer between -100 , 100: x

error! invalid integer value. seek again.

enter integer between -100 , 100: -101

error! number must greater -101

enter integer between -100 , 100: 101

error! number must less 101

enter integer between -100 , 100: 100

i've been assigned create validation class before never in way i'm beingness asked now. before, i've been able pass sc , prompt validation class , have methods process them accordingly. example:

//main scanner sc = new scanner(system.in); int x = validator.getint(sc, "enter integer: ", 0, 1000); //validation class public class validator{ public static int getint(scanner sc, string prompt) { int = 0; boolean isvalid = false; while (isvalid == false) { system.out.print(prompt); if (sc.hasnextint()) { = sc.nextint(); isvalid = true; } else { system.out.println("error! invalid integer value. seek again."); } sc.nextline(); // discard other info entered on line } homecoming i; } public static int getint(scanner sc, string prompt, int min, int max) { int = 0; boolean isvalid = false; while (isvalid == false) { = getint(sc, prompt); if (i <= min) system.out.println( "error! number must greater " + min + "."); else if (i >= max) system.out.println( "error! number must less " + max + "."); else isvalid = true; } homecoming i; }

done above, understand happening.

however i'm assigned same results using similar methods time sc has own constructor.

public class oovalidator { public oovalidator(scanner sc){} public int getint(string prompt){} public int getintwithinrange(string prompt, int min, int max){} }

i'm not asking assignment me in entirety, i'm @ loss how can both prompt user , pass user's input using class has sc , prompt separated.

i've tried several code several difference ways, non of compile.

just create instance of class

//main scanner sc = new scanner(system.in); oovalidator val = new oovalidator(sc); int x = val.getint("enter integer: "); // ... int y = val.getintwithinrange("enter integer: ", 0, 1000); //validation class public class oovalidator { private scanner sc; private static final string error = "error! invalid integer value." + "try again."; public oovalidator(scanner sc) { this.sc = sc; } public int getint(string prompt) { while (true) { system.out.print(prompt); if (sc.hasnextint()) { = sc.nextint(); sc.nextline(); // discard other info entered on line break; } else { system.out.println(error); sc.nextline(); // discard other info entered on line } } homecoming i; } public int getintwithinrange(string prompt, int min, int max) { // same logic - utilize straight sc instance field } }

java class validation object

Android - Draw an inverted circle that moves along with the player -



Android - Draw an inverted circle that moves along with the player -

i building android game ball controlled , moved using motion sensor.

there posts on how draw inverted circle like one, unusable android not back upwards bufferedimage.

i created player using codes below

public class player extends task { private final static float max_speed = 20; private final static float size = 16; private circle _cir = null; private paint _paint = new paint(); private vec _vec = new vec(); private vec _sensorvec = new vec(); public player(){ _cir = new circle( 15, 15, size ); //15,15 initial x,y coordinates } public final circle getpt(){ homecoming _cir; } private void setvec(){ float x = -acsensor.inst().getx()*2; float y = acsensor.inst().gety()*2; _sensorvec._x = x < 0 ? -x*x : x*x; _sensorvec._y = y < 0 ? -y*y : y*y; _sensorvec.setlengthcap(max_speed); _vec.blend( _sensorvec, 0.05f ); } private void move(){ _cir._x += _vec._x; _cir._y += _vec._y; } @override public boolean onupdate(){ setvec(); move(); homecoming true; } @override public void ondraw( canvas c ){ c.drawcircle(_cir._x, _cir._y, _cir._r, _paint); } }

question is, how create inverted circle around player player sees limited distance while outer part filled black color? example, this.

android android-canvas circle shadow invert