Wednesday 15 August 2012

Enforcing compatibility between numpy 1.8 and 1.9 nansum? -



Enforcing compatibility between numpy 1.8 and 1.9 nansum? -

i have code needs behave identically independent of numpy version, underlying np.nansum function has changed behavior such np.nansum([np.nan,np.nan]) 0.0 in 1.9 , nan in 1.8. <=1.8 behavior 1 prefer, more of import thing code robust against numpy version.

the tricky thing is, code applies arbitrary numpy function (generally, np.nan[something] function) ndarray. there way forcefulness new or old numpy nan[something] functions conform old or new behavior shy of monkeypatching them?

a possible solution can think of outarr[np.allnan(inarr, axis=axis)] = np.nan, there no np.allnan function - if best solution, best implementation np.all(np.isnan(arr), axis=axis) (which require supporting np>=1.7, that's ok)?

in numpy 1.8, nansum defined as:

class="lang-py prettyprint-override">a, mask = _replace_nan(a, 0) if mask none: homecoming np.sum(a, axis=axis, dtype=dtype, out=out, keepdims=keepdims) mask = np.all(mask, axis=axis, keepdims=keepdims) tot = np.sum(a, axis=axis, dtype=dtype, out=out, keepdims=keepdims) if np.any(mask): tot = _copyto(tot, np.nan, mask) warnings.warn("in numpy 1.9 sum along empty slices zero.", futurewarning) homecoming tot

in numpy 1.9, is:

class="lang-py prettyprint-override">a, mask = _replace_nan(a, 0) homecoming np.sum(a, axis=axis, dtype=dtype, out=out, keepdims=keepdims)

i don't think there way create new nansum behave old way, given original nansum code isn't long, can include re-create of code (without warning) if care preserving pre-1.8 behavior?

note _copyto can imported numpy.lib.nanfunctions

numpy

web services - javax.net.ssl.SSLException: hostname in certificate didn't match in Android -



web services - javax.net.ssl.SSLException: hostname in certificate didn't match in Android -

i updating web service url of android application, using https protocol. see current https url working migrating new domain creating problem.

i have checked many threads on stackoverflow javax.net.ssl.sslexception: hostname in certificate didn't match android didn't find reply answering bypass security or allow all.

javax.net.ssl.sslexception: hostname in certificate didn't match:

//httpget getmethod = new httpget(string.format(httpurl)); httpget getmethod = new httpget(httpurl); defaulthttpclient client = new defaulthttpclient(); responsehandler<string> responsehandler = new basicresponsehandler(); httpparams params = client.getparams(); params.setparameter(coreconnectionpnames.connection_timeout, 60000); params.setparameter(coreconnectionpnames.so_timeout, 60000); client.setparams(params); responsebody = client.execute(getmethod, responsehandler); responsebody = responsebody.trim();

thanks in advance.

if works in browser not in app might problem missing sni support, see why android wrong ssl certificate? (two domains, 1 server).

android web-services ssl https

javascript - Listening horizontal scroll -



javascript - Listening horizontal scroll -

javascript has ability hear scrolling on fly (scrolltop(); isn't it). there function hear i've scrolled if i'm doing horizontally?

i have div of images, can scrolled horizontally ( see: http://jsfiddle.net/j5q1b8x9/).

.scroll-container { overflow-x: scroll; overflow-y: hidden; white-space: nowrap;

}

and want when scroll right, reddish box move left , vice versa. i've tried scrollleft(); , fires when i've reached end of images, isn't listening coordinates on fly.

bonus, it's possible implement kind of function each of images, using foreach path? i.e. if scroll 1 image viewport left right, reddish box move right left, , when new image pops viewport, jazz begins again, new image.

any ideas should test out create reddish box move mirror when scrolling left right?

if understand question works demo

var container = $(".scroll-container"); var box= $(".test-div"); var scrollx =container.scrollleft(); container.scroll(function(){ var delta =container.scrollleft() - scrollx; // direction < 0 left right scrollx =container.scrollleft(); if (delta<0) box.css({left:0, right:'auto'}); else box.css({left:'auto', right:0});

});

javascript jquery

c# - visual studo item template with wizard and T4 -



c# - visual studo item template with wizard and T4 -

i looking sample on how create item template wizard in visual studio 2012.

i need wizard mvc controller.

when user selects add together item, want show dialog user enters input parameters, including class in solution.

then on pressing ok generate form (including designer , resx) want add together project.

currently have t4 files , programme this, using external tools (texttransform.exe), copying files in folder of solution , manipulating csproj file manually.

// set text transform programme (this alter according windows version) p.startinfo.filename = "c:\\program files (x86)\\common files\\microsoft shared\\texttemplating\\11.0\\texttransform.exe"; // specify t4 template file p.startinfo.arguments = "-out " + "\"" + output + "\"" + " \"" + template + "\""; //manipulating csproj var formnode = new xelement(@"{http://schemas.microsoft.com/developer/msbuild/2003}compile", new xattribute("include", frompath)); formnode.add(new xelement(@"{http://schemas.microsoft.com/developer/msbuild/2003}subtype", "form")); programnode.addbeforeself(formnode);

c# visual-studio templates visual-studio-2012 t4

python - Would any CPython 2.7 code work in Jython 2.7b3? -



python - Would any CPython 2.7 code work in Jython 2.7b3? -

frank wierzbicki in blog post has written "jython 2.7b3 brings language level compatibility 2.7 version of cpython."

does mean cpython 2.7 code work jython?

i have big code written in cpython 2.7. since want integrate java modules, extremely interested in way of migrating jython without rewriting of code. considering libraries, utilize lot of lxml (as described here) not compatible previous versions jython.

no, not all code works in cpython 2.7 work in jython, in same way code tied specific os , won't work on other os-es (e.g. windows-specific python code won't work on linux, , vice versa).

the syntax work, if script requires specific add-on modules such lxml, not work. because lxml c-api extension, , jython doesn't back upwards python c-api.

similarly, if code uses multiprocessing module, won't work on jython, because part of standard library not included.

python migration lxml jython

neo4j - how to match relationships with multiple properties passed as a query parameter? -



neo4j - how to match relationships with multiple properties passed as a query parameter? -

let's have next info model:

(user)-[r:has_permissions]->(n) , properties of 'r' permissions in boolean values, view=true, create=true.

i want find users have permissions entity, passed query parameter.

naively want like:

match (u:user)-[r:has_permissions {permissions}]->(n) homecoming u, know isn't right {permissions} can used create statement..

the passed permissions parameter map, {view: true}

i'm thinking of like:

match (u:user)-[r:has_permissions]->(n) all(p in {permissions} r.{p} = {permissions}.p) homecoming u

obviously won't work permissions property map , not array , need access it's keys , values somehow.

am in right direction ? how can accomplish i'm looking ?

you can pass each of properties of permissions variable independently.

match (u:user)-[r:has_permissions { view: {view}, create: {create} }]->(n) homecoming u

then pass in parameters view , create.

if don't know permissions properties may be, handle in app. in ruby, i'd this:

def permissions_parameter(permissions) permission_keys = [] permission_values = [] permissions.each |k, v| permission_keys.push("r.#{k}: {#{k}}") permission_values.push("'#{k}': '#{v}'") end permission_keys_cypher = permission_keys.join(', ') permission_params_cypher = permission_values.join(', ') [permission_keys_cypher, permission_params_cypher] end permissions = permissions_parameter({ create: true, view: true }) puts "match (u:user)-[r:has_permissions { #{permissions[0]} }]->(n) homecoming u" # match (u:user)-[r:has_permissions { r.create: {create}, r.view: {view} }]->(n) homecoming u puts "params: #{permissions[1]}" # params: 'create': 'true', 'view': 'true'

neo4j cypher

c# - Camera Lerp seems to be incrementing every loop -



c# - Camera Lerp seems to be incrementing every loop -

i have 7 positions iterate between , have difference on x axis of 4.5 position0 = 0, position1 = 4.5 & position = 9, on , forth.

however, appears when go position0 position1, x continues grow 4.5. iterate through array works increases 4.5 every frame. doing wrong?

void start () { _positionarray[0] = position0; _positionarray[1] = position1; _positionarray[2] = position2; _positionarray[3] = position3; _positionarray[4] = position4; _positionarray[5] = position5; _positionarray[6] = position6; endposition = position0; } public void changedestination() { if (_leapmanager.swipeperformed) { swipedirection = _leapmanager.swipedirection; if (swipedirection == "left" && posinarray >= 0 && posinarray < 5) { debug.log("called"); posinarray++; endposition.position = _positionarray[posinarray].position; } else if (swipedirection == "right" && posinarray <= 5 && posinarray > 0) { posinarray--; endposition.position = _positionarray[posinarray].position; } } } // update called 1 time per frame void update () { transform.position = vector3.lerp(transform.position, endposition.position, speed * 3.0f * time.deltatime); }

c# unity3d

jquery - Selecting a list item that doesn't have a sublist with CSS -



jquery - Selecting a list item that doesn't have a sublist with CSS -

i wondering if possible select list item not contain ul's or ol's pure css. note list item contain anchor, allowed. css3 can used well. know how jquery, i'd utilize css(3).

first of all, there (currently) no selector in css, check if element contains elment or if doesn't. (i played bit around :not() didn't work.)

but there trick this, :only-child selector. if can there <a> tag in list , no other element <ul>, can this:

html

<ul class="list"> <li><a href="#">test</a></li> <li> <a href="#">test</a> <ul> <li>test2</li> </ul> </li> </ul>

css

.list > li > a:only-child { color: red; }

so select <a> tags kid of parent tag.

this might not perfect solution, work if have construction html code.

have @ jsfiddle see solution: http://jsfiddle.net/2lxaah61/

jquery css list css-selectors

javascript - Where to save JWT and how to use it -



javascript - Where to save JWT and how to use it -

i trying implement jwt in authentication scheme , have questions jwt.

for saving token, utilize cookie possible too, utilize localstorage or sessionstorage, best choice?

i have read about, jwt protect site csrf. can not imaging that, how works. assume, save jwt token in cookie storage, how protect csrf?

update 1 saw samples in net like

curl -v -x post -h "authorization: basic ve01ennfem9fzg9nrerjvejjbxrbcwjgdtbfytpyuu9urexinlbbohjvuhjfsktrthhustnsegnh"

how can implement that, when create request server browser. saw too, implement token in address bar like:

http://exmple.com?jwt=token

if create request via ajax, set header jwt:token , can read token header.

update 2

in google chrome installed advanced rest client, @ image

as can see, can set header data. possible set headers info via javascript, when making request server?

look @ web site: https://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/

is recommended not store jwt, if want store them, should utilize localstorage if available. should utilize authorization header, instead of basic scheme, utilize bearer one:

curl -v -x post -h "authorization: bearer your_jwt_here"

with js, utilize folliowing code:

<script type='text/javascript'> // define vars var url = 'https://...'; // ajax phone call $.ajax({ url: url, datatype : 'jsonp', beforesend : function(xhr) { // set header if jwt set if ($window.sessionstorage.token) { xhr.setrequestheader("authorization", "bearer " + $window.sessionstorage.token); } }, error : function() { // error handler }, success: function(data) { // success handler } }); </script>

javascript web-services security cookies jwt

Laravel passing data using ajax to controller -



Laravel passing data using ajax to controller -

how pass id ajax phone call testcontroller getajax() function? when phone call url testurl?id=1

route::get('testurl', 'testcontroller@getajax'); <script> $(function(){ $('#button').click(function() { $.ajax({ url: 'testurl', type: 'get', data: { id: 1 }, success: function(response) { $('#something').html(response); } }); }); }); </script>

testcontroller.php

public function getajax() { $id = $_post['id']; $test = new testmodel(); $result = $test->getdata($id); foreach($result $row) { $html = '<tr> <td>' . $row->name . '</td>' . '<td>' . $row->address . '</td>' . '<td>' . $row->age . '</td>' . '</tr>'; } homecoming $html; }

your ajax's method in controller utilize $_post value. problem.

you can

$id = $_get['id'];

but in laravel, have pretty method this. it's here. not need worry http verb used request, input accessed in same way verbs.

$id = input::get("id");

if want, can filter request type command exception. docs here

determine if request using ajax

if (request::ajax()) { // }

ajax laravel routes

git - What is the difference between merging master into branch and merging branch into master? -



git - What is the difference between merging master into branch and merging branch into master? -

i have branch called master , called dev. usually, tests , improvements on dev, , when decided ok, merge master, tagging , release new version of application. met 2 cases of merging:

merge master dev, and merge dev master,

but not sure how 2 different... explanation welcome.

merging 1 branch not symmetric operation:

merging dev master, and merging master dev,

are, in general, not equivalent. here illustrative illustration explains difference between two. let's assume repo looks follows:

if merge dev master

if master checked out (git checkout master),

and merge dev (git merge dev), end in next situation:

the master branch points new merge commit (f), whereas dev still points same commit (e) did before merge.

if merge master dev

if, on other hand, dev checked out (git checkout dev),

and merge master (git merge master), end in next situation:

the dev branch points new merge commit (f', whereas master still points same commit did before merge (d).

putting together

git merge

auto increment - How to create id with AUTO_INCREMENT on Oracle? -



auto increment - How to create id with AUTO_INCREMENT on Oracle? -

it appears there no concept of auto_increment in oracle, until , including version 11g.

how can create column behaves auto increment in oracle 11g?

there no such thing "auto_increment" or "identity" columns in oracle. however, can model sequence , trigger:

table definition:

create table departments ( id number(10) not null, description varchar2(50) not null); alter table departments add together ( constraint dept_pk primary key (id)); create sequence dept_seq;

trigger definition:

create or replace trigger dept_bir before insert on departments each row begin select dept_seq.nextval :new.id dual; end; /

update: identity column available on oracle 12c version, see this:

create table t1 (c1 number generated default on null identity, c2 varchar2(10));

oracle auto-increment

python - Django NoReverseMatch error Reverse for 'detail' with arguments '('',)' and keyword arguments '{}' not found -



python - Django NoReverseMatch error Reverse for 'detail' with arguments '('',)' and keyword arguments '{}' not found -

i've looked @ few similarly-titled questions on here, none seem help. error:

noreversematch @ /articles/ reverse 'index' arguments '('',)' , keyword arguments '{}' not found. 1 pattern(s) tried: [u'articles/$'] error during template rendering in template c:\projects\django\the_bluntist\articles\templates\articles\index.html, **error @ line 7** reverse 'index' arguments '('',)' , keyword arguments '{}' not found. 1 pattern(s) tried: [u'articles/$'] 1 {% load staticfiles %} 2 3 <link rel="stylesheet" type="text/css" href="{% static 'articles/style.css' %}" /> 4 {% if latest_articles_list %} 5 <ul> 6 {% article in latest_articles_list %} 7 <li><a href="{% url 'articles:index' content.slugline %}">{{ content.title }}</a></li> 8 {% endfor %} 9 </ul> 10 {% else %} 11 <p>no articles available.</p> 12 {% endif %}

articles/urls.py:

from django.conf.urls import patterns, url articles import views urlpatterns = patterns('', url(r'^$', views.indexview.as_view(), name = 'index'), url(r'^(?p<slugline>[-\w\d]+),(?p<pk>\d+)/$', views.detailview.as_view(), name='detail') )

index.html:

{% load staticfiles %} <link rel="stylesheet" type="text/css" href="{% static 'articles/style.css' %}" /> {% if latest_articles_list %} <ul> {% article in latest_articles_list %} <li><a href="{% url 'articles:index' content.slugline %}">{{ content.title }}</a></li> {% endfor %} </ul> {% else %} <p>no articles available.</p> {% endif %}

main urls.py:

from django.conf.urls import patterns, include, url django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^articles/', include('articles.urls', namespace="articles")), url(r'^admin/', include(admin.site.urls)), )

a lot of code taken django tutorial. i've been comparing mine against stock code, , can't seem find problem.

you're trying pass argument index view, reason; view doesn't take one. should be:

<a href="{% url 'articles:index' %}">

python django

bash - Make gcc default c compiler on Yosemite/disable clang -



bash - Make gcc default c compiler on Yosemite/disable clang -

i updgraded mac yosemite , usual there growing pains. first 1 seems default c compiler.

i compiling code in bash external tool uses gcc, needs compile other code (that did not write). reason, clang beingness used compile code, i'd prefer utilize gcc. guess why clang has been set default compiler , compiling code using default compiler sub-compilation. there way forcefulness gcc default c compiler on yosemite. tried looking around i've seen far in terms of making default in xcode tools, rather on bash.

c bash gcc osx-yosemite

java - Android equivalent of iOS's beginIgnoringInteractionEvents -



java - Android equivalent of iOS's beginIgnoringInteractionEvents -

this reply suggest iterate through childviews , disable them. doesn't smell right me (performance wise)

what's best approach disable touch events in application prevent user interacting application (during animation, let's say)?

check out how solved this overriding dispatch methods in activity.

java android ios objective-c

python - Updating django version in virtaulenv but still showing old version -



python - Updating django version in virtaulenv but still showing old version -

i trying upgrade django version within virtualenv , showing django updated still not updated.

d:\testenv>tan\scripts\activate.bat (tan) d:\testenv>pip freeze beautifulsoup==3.2.1 django==1.4.3 distribute==0.6.15 django-export-xls==0.1.1 jdcal==1.0 openpyxl==2.0.4 pypm==1.3.4 pythonselect==1.3 pywin32==214 virtualenv==1.6.1 wsgiref==0.1.2 xlwt==0.7.5 (tan) d:\testenv>pip install django --upgrade downloading/unpacking django downloading django-1.7.1.tar.gz (7.5mb): 7.5mb downloaded running setup.py egg_info bundle django warning: no previously-included files matching '__pycache__' found under directory '*' warning: no previously-included files matching '*.py[co]' found under directory '*' installing collected packages: django found existing installation: django 1.4.3 not uninstalling django @ c:\python27\lib\site-packages, outside environment d:\testenv\tan running setup.py install django warning: no previously-included files matching '__pycache__' found under directory '*' warning: no previously-included files matching '*.py[co]' found under directory '*' installing django-admin-script.py script d:\testenv\tan\scripts installing django-admin.exe script d:\testenv\tan\scripts installed django cleaning up... (tan) d:\testenv>pip freeze beautifulsoup==3.2.1 django==1.4.3 distribute==0.6.15 django-export-xls==0.1.1 jdcal==1.0 openpyxl==2.0.4 pypm==1.3.4 pythonselect==1.3 pywin32==214 virtualenv==1.6.1 wsgiref==0.1.2 xlwt==0.7.5 (tan) d:\testenv>python activepython 2.7.2.5 (activestate software inc.) based on python 2.7.2 (default, jun 24 2011, 12:21:10) [msc v.1500 32 bit (intel)] on win32 type "help", "copyright", "credits" or "license" more information. >>> import django >>> dir(django) ['version', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'get_version'] >>> django.get_version <function get_version @ 0x022f7ab0> >>> django.get_version() '1.4.3' >>>

as django old verion 1.4.1 after upgrading should 1.7.1 , showing message successfully installed django still showing old version of django. how should update django version here. plus need help update django version 1.6.1 here.

i think key in:

not uninstalling django @ c:\python27\lib\site-packages, outside environment d:\testenv\tan

you have django installation outside virtualenv , somehow ignoring 1 installing , taking one. remove , seek again.

as side note, tried working django/python in windows long time...then gave begging windows allow me work , switched so. if want remain in windows advice @ to the lowest degree utilize vagrant, create life easier in long run.

python django virtualenv

javascript - EmberJS set defaultValue from parent's model -



javascript - EmberJS set defaultValue from parent's model -

i need set defaultvalue of cost attribute cost of item. don't want utilize computedproperty because when item's cost change, transaction_detail's cost changed too, , scenario set price value on first time & shouldn't changed.

here transactiondetail.js.

var transactiondetail = ds.model.extend({ transaction: ds.belongsto('transaction'), item: ds.belongsto('item', { async: true }), borrowed_at: borrowedat, max_returned_at: maxreturnedat, returned_at: ds.attr('date'), price: ds.attr('number', { defaultvalue: function( detail) { homecoming detail.get('item.price'); // expect item's price, actual null } }), });

and below item.js

var item = ds.model.extend({ name: ds.attr('string'), is_available: ds.attr('boolean', { defaultvalue: true }), price: ds.attr('number', { defaultvalue: 0 }) });

update: after read this, add together file on initializers/reopen-store.js , edit content below:

import ds 'ember-data'; export function initialize(container, application) { var store = container.lookup('store:main'); store.reopen({ createrecord: function(type, properties) { if (type === 'transactiondetail') { if (typeof properties.price !== 'number') { properties.price = properties.item.get('price'); } } homecoming this._super.apply(this, arguments); }.on('createrecord') }); }; export default ds.store.extend({ name: 'reopen-store', initialize: initialize });

but when debugger; on model, this.get('item.price') still undefined. idea?

update 2:

thanks gjk response. reply still no luck me. here app/store.js:

import ds 'ember-data'; export default ds.store.extend({ init: function() { console.log('init called!'); homecoming this._super.apply(this, arguments); }, createrecord: function(type, properties) { console.log('prepare createrecord!'); debugger; if (type === 'transactiondetail') { if (typeof properties.price !== 'number') { properties.price = properties.item.get('price'); } } homecoming this._super.apply(this, arguments); } });

in console, output init called!. no 'prepare createrecord!' , debugger not triggered in chrome. idea?

in defaultvalue function, item.price coming null because item relationship hasn't been initialized yet. personally, take care of in store when create record, not in model.

app.store = ds.store.extend({ createrecord: function(type, properties) { if (type === 'transactiondetail') { if (typeof properties.price !== 'number') { properties.price = properties.item.get('price'); } } homecoming this._super.apply(this, arguments); } });

a bit more error checking required, idea. if cost isn't given @ time of creation, fill in , allow store handle rest.

javascript ember.js ember-data

c++ - Method questions - What changes the value and what doesn't? What's invalid? -



c++ - Method questions - What changes the value and what doesn't? What's invalid? -

i have homework question

what  does  v  contain  after  these  methods  and  why?  if  the  method  is  invalid,  explain  why.

template <typename t> void reset1(mathvector<t> v) {v[0] = 0;} template <typename t> void reset2(mathvector<t> &v) {v[0] = 0;} template <typename t> void reset3(const mathvector<t> &v) {v[0] = 0;}

my previous experience tells me first leave vector unchanged because it's not beingness passed value rather copy, sec changed properly, , 3rd invalid because parameter specifies const.

however i'm pretty sure in c++ arrays passed value because doesn't automatically invoke re-create constructor or anything. suspect might true of vectors i'm not sure. if case, first 1 alter vector , sec 1 invalid because you're trying operate on vector's pointer doesn't create sense? i'm not sure here

template <typename t> void reset1(mathvector<t> v) {v[0] = 0;}

this passes vector by value, modification vector v local only, , original vector unchanged 1 time function complete.

template <typename t> void reset2(mathvector<t> &v) {v[0] = 0;}

this passes vector by reference, changing first element modifying original vector. here first element have been changed 0.

template <typename t> void reset3(const mathvector<t> &v) {v[0] = 0;}

here vector passed by reference, const. means may not effort modify vector, should @ to the lowest degree produce compiler warning.

c++ templates methods vector const

c# - Only Remove SPGroups that Contain a specific Character -



c# - Only Remove SPGroups that Contain a specific Character -

i need remove groups sharepoint site contain underscore in name. need below code, unable utilize .contains on collgroups.

any thought how can this?

using (spsite osite = new spsite(spsite)) { using (spweb oweb = osite.openweb()) { spgroupcollection collgroups = oweb.sitegroups; if(collgroups.contains("_")) //this doens't work, need { group.delete(); } } }

for future reference: here ended writing, gunr2171 pointing me in right direction!

using (spsite osite = new spsite(spsite)) { using (spweb oweb = osite.openweb()) { var result = (from g in oweb.groups.oftype<spgroup>() g.name.contains("_") select g).tolist(); foreach (spgroup grouping in result) { spgroupcollection collgroups = oweb.sitegroups; collgroups.remove(group.name); console.writeline("removed " + group.name); } console.writeline("process complete!"); }

c# sharepoint-2010

Setting connection parameters in iOS-Corebluetooth Framework -



Setting connection parameters in iOS-Corebluetooth Framework -

according core bluetooth framework reference there alternative argument on cbcentralmanager.connectperipheral method, there no documentation describes other mention "a dictionary customize behavior of connection.".

i'm assuming how caller specify initial connection interval , slave latency. please provide dictionary details(i.e key of dictionary).

please suggest me, how give key , value connection parameters dictionary(mentioned above).

thanks , regards -ibrahim sulaiman

the options in documentation.

they -

cbconnectperipheraloptionnotifyonconnectionkey cbconnectperipheraloptionnotifyondisconnectionkey cbconnectperipheraloptionnotifyonnotificationkey

and command creation of alerts prompting user launch app when corresponding bluetooth events occur , haven't specified bluetooth background mode.

you cannot alter connection interval ios app, peripheral can request change. refer lastly paragraph on this page

ios

html - how to remove default border/outline from image -



html - how to remove default border/outline from image -

hey guys want know how remove border/outline image tag, include not using image in , illustration test code fiddle

html

<img src="" class="testclass">

css

.testclass{ width: 100%; margin-left: 0%; height: 150px; border: 0px; outline : none; }

what see there browser's "broken image url" image. that's when browser can't load image. doesn't have border; browser renders can see how big missing image be. therefore, can't influence result css much.

what can set display: none hide image altogether. if want space empty, wrap in div same size.

html image

doctrine2 - MySQL: ignore constraint within SQL transaction -



doctrine2 - MySQL: ignore constraint within SQL transaction -

for collection multiple items want update ordering of items. in mysql have constraint (order + collection_id) unique. so, cannot have 2 items @ order 1 in same collection.

however, want update ordering of items "atomically". orm, updated entities new order , performed flush write them downwards database. orm converts them multiple queries , straight results in constraint violation mysql.

example:

i have items in order a, b, c. a=1, b=2 , c=3. perform update order c, b, a. c=1, b=2, a=1. these 2 queries , first update straight runs constraint violation. in pseudo:

update item set order=1 id=c

my idea

is possible start transaction, remove constraint, apply changes , enable constraint again? if enabling fails, rollback ensure set back.

alternative

an alternative remove constraint altogether, not fond of solution :)

mysql doctrine2 constraints

php - Syncronising MySQL database across multiple devices -



php - Syncronising MySQL database across multiple devices -

i utilize both desktop pc , laptop develop web applications.

both devices run on latest version of ubuntu apache2. maintain actual files synchronised via git have no way of keeping mysql database synchronised across both machines.

i wouldn't mind if have force changes manually, how git works, want work available on both machines wherever am.

does have ideas of solution this?

your database should thought of in few different parts. relational databases contain @ least

a schema (table definitions, constraints, etc.), application data, e.g. 1 table might contain list of country codes, and instance data, e.g. users have registered, or blog posts have been saved.

the first 2 of these part of application. must synchronized particular code revisions or else can conflicts. ideally, should somehow tracked in revision command scheme , committed alongside related source code.

a popular approach utilize schema migrations. track text files define migrations, each of can executed forwards (and backward), each of modifies database schema , / or application data.

for instance, particular migration might

create new table states, and pre-populate info table.

reversing migration simple deleting table.

there many libraries back upwards this, e.g. doctrine migrations (specific doctrine php library), or liquibase, language-agnostic.

one nice thing approach database schema doesn't limit revisions can work on. if makes sense create new branch old revision, run migrations point , start working. can utilize migration scripts on production server, though in general you'll want run them forwards there.

the instance info not part of application, , should not tracked in way. may take manually migrate info between instances, or may not. either way, migrations should modify user info remains consistent schema.

for instance, if migration splits table should move info old columns new table. reverse migration should move info new table old columns.

php sql git ubuntu synchronisation

java - PIG/Hadoop issue: ERROR 2081: Unable to setup the load function -



java - PIG/Hadoop issue: ERROR 2081: Unable to setup the load function -

i'm running pig 0.13.0 , hadoop 2.5.1, both installed apache distros, they're not packages horton or cloudera or anything.

i'm working tutorial , can work fine when running pig locally ($> ./pig -x local), when trying run on hadoop instance error i'm having hard time researching on internet.

this command:

movies = load '/home/hduser/pig-tutorial-master/movies_data.csv' using pigstorage(',') (id,name,year,rating,duration); dump movies;

works fine running locally. when run in hadoop/mr mode, seems work fine when run first line of code:

grunt> movies = load '/home/hduser/pig-tutorial-master/movies_data.csv' using pigstorage(',') (id,name,year,rating,duration); 2014-10-29 18:16:26,281 [main] info org.apache.hadoop.conf.configuration.deprecation - fs.default.name deprecated. instead, utilize fs.defaultfs 2014-10-29 18:16:26,281 [main] info org.apache.hadoop.conf.configuration.deprecation - mapred.job.tracker deprecated. instead, utilize mapreduce.jobtracker.address

but when seek $> dump movies gives me trace:

grunt> dump movies 2014-10-29 18:17:15,419 [main] info org.apache.pig.tools.pigstats.scriptstate - pig features used in script: unknown 2014-10-29 18:17:15,420 [main] info org.apache.pig.newplan.logical.optimizer.logicalplanoptimizer - {rules_enabled=[addforeach, columnmapkeyprune, groupbyconstparallelsetter, limitoptimizer, loadtypecastinserter, mergefilter, mergeforeach, partitionfilteroptimizer, pushdownforeachflatten, pushupfilter, splitfilter, streamtypecastinserter], rules_disabled=[filterlogicexpressionsimplifier]} 2014-10-29 18:17:15,445 [main] warn org.apache.pig.data.schematuplebackend - schematuplebackend has been initialized 2014-10-29 18:17:15,469 [main] error org.apache.pig.tools.grunt.grunt - error 2081: unable setup load function. details @ logfile: /usr/local/pig/pig_1414606194436.log

the error 2081 i'm trying diagnose, can't find helps point me in right direction. ideas of start? assume it's hadoop installation , not pig, don't know. suggestions helpful.

thanks,

mark

edit: here total log output:

error 2081: unable setup load function. org.apache.pig.impl.logicallayer.frontendexception: error 1066: unable open iterator alias movies @ org.apache.pig.pigserver.openiterator(pigserver.java:912) @ org.apache.pig.tools.grunt.gruntparser.processdump(gruntparser.java:752) @ org.apache.pig.tools.pigscript.parser.pigscriptparser.parse(pigscriptparser.java:372) @ org.apache.pig.tools.grunt.gruntparser.parsestoponerror(gruntparser.java:228) @ org.apache.pig.tools.grunt.gruntparser.parsestoponerror(gruntparser.java:203) @ org.apache.pig.tools.grunt.grunt.run(grunt.java:66) @ org.apache.pig.main.run(main.java:542) @ org.apache.pig.main.main(main.java:156) @ sun.reflect.nativemethodaccessorimpl.invoke0(native method) @ sun.reflect.nativemethodaccessorimpl.invoke(nativemethodaccessorimpl.java:57) @ sun.reflect.delegatingmethodaccessorimpl.invoke(delegatingmethodaccessorimpl.java:43) @ java.lang.reflect.method.invoke(method.java:606) @ org.apache.hadoop.util.runjar.main(runjar.java:212) caused by: org.apache.pig.pigexception: error 1002: unable store alias movies @ org.apache.pig.pigserver.storeex(pigserver.java:1015) @ org.apache.pig.pigserver.store(pigserver.java:974) @ org.apache.pig.pigserver.openiterator(pigserver.java:887) ... 12 more caused by: org.apache.pig.backend.executionengine.execexception: error 0: exception while executing (name: movies: store(hdfs://localhost:54310/tmp/temp-1276361014/tmp-2000190966:org.apache.pig.impl.io.interstorage) - scope-1 operator key: scope-1): org.apache.pig.backend.executionengine.execexception: error 2081: unable setup load function. @ org.apache.pig.backend.hadoop.executionengine.physicallayer.physicaloperator.processinput(physicaloperator.java:289) @ org.apache.pig.backend.hadoop.executionengine.physicallayer.relationaloperators.postore.getnexttuple(postore.java:143) @ org.apache.pig.backend.hadoop.executionengine.fetch.fetchlauncher.runpipeline(fetchlauncher.java:160) @ org.apache.pig.backend.hadoop.executionengine.fetch.fetchlauncher.launchpig(fetchlauncher.java:81) @ org.apache.pig.backend.hadoop.executionengine.hexecutionengine.launchpig(hexecutionengine.java:275) @ org.apache.pig.pigserver.launchplan(pigserver.java:1367) @ org.apache.pig.pigserver.executecompiledlogicalplan(pigserver.java:1352) @ org.apache.pig.pigserver.storeex(pigserver.java:1011) ... 14 more caused by: org.apache.pig.backend.executionengine.execexception: error 2081: unable setup load function. @ org.apache.pig.backend.hadoop.executionengine.physicallayer.relationaloperators.poload.getnexttuple(poload.java:127) @ org.apache.pig.backend.hadoop.executionengine.physicallayer.physicaloperator.processinput(physicaloperator.java:281) ... 21 more caused by: org.apache.hadoop.mapreduce.lib.input.invalidinputexception: input path not exist: hdfs://localhost:54310/home/hduser/pig-tutorial-master/movies_data.csv @ org.apache.hadoop.mapreduce.lib.input.fileinputformat.singlethreadedliststatus(fileinputformat.java:321) @ org.apache.hadoop.mapreduce.lib.input.fileinputformat.liststatus(fileinputformat.java:264) @ org.apache.pig.backend.hadoop.executionengine.mapreducelayer.pigtextinputformat.liststatus(pigtextinputformat.java:36) @ org.apache.hadoop.mapreduce.lib.input.fileinputformat.getsplits(fileinputformat.java:385) @ org.apache.pig.impl.io.readtoendloader.init(readtoendloader.java:190) @ org.apache.pig.impl.io.readtoendloader.<init>(readtoendloader.java:146) @ org.apache.pig.backend.hadoop.executionengine.physicallayer.relationaloperators.poload.setup(poload.java:95) @ org.apache.pig.backend.hadoop.executionengine.physicallayer.relationaloperators.poload.getnexttuple(poload.java:123) ... 22 more ================================================================================

after searching solution error 2081, started looking @ errors in log file more closely. issue of trying access local files mr mode. hadn't noticed in documentation how access info in mr vs. local, issue.

if running in mr, must access files via hdfs://hostname:54310. locally can access them path.

this s.o. question solution: how load files on hadoop cluster using apache pig?.

java apache hadoop apache-pig

SQL Server 403 Error When Setting a Geography Type for Update -



SQL Server 403 Error When Setting a Geography Type for Update -

all need 1 geography value table , store in table. there logic row take origin table it's not straight select.

in of 50 possible variants of this, error when hitting update target table:

msg 403, level 16, state 1, line 1 invalid operator info type. operator equals not equal to, type equals geography.

my sql looks @ moment:

declare @equipmentid int , @currentlocationid int , @currentgeolocation geography , @lastupdated datetime select @equipmentid = ( select top 1 equipmentid equipment order equipmentid ) select @currentlocationid = (select top 1 equipmentlocationid equipmentlocation equipmentid = @equipmentid order lastupdated desc) select @lastupdated = (select top 1 lastupdated equipmentlocation equipmentid = @equipmentid order lastupdated desc) update dbo.equipment set currentlocationdatetime = @lastupdated , currentgeolocation = (select geolocation equipmentlocation equipmentlocationid = @currentlocationid) , modifiedby = 'system' , modifiedbyuserid = -1 , modifieddate = getdate() equipmentid = @equipmentid

i have had currentgeolocation set in variable of same type, selected same statement see in update.

i have had @currentgeolocation variable populated geography::stgeomfromtext geography::point() function call.

i've used lat , long variables phone call point , fromtext functions.

all same result, above 403 error. understand when concatenating various permutations of geomfromtext function needs known text format point parameter, field value field value killing me, fact error no matter how seek give origin point info target table.

thoughts?

update: i've been experimenting little , found next works fine:

declare @gl geography select @gl = (select geolocation equipmentlocation equipmentlocationid = 25482766) print convert(varchar, @gl.lat) print convert(varchar, @gl.long) update equipment set currentgeolocation = geography::point(@gl.lat, @gl.long, 4326)-- @newgl equipmentid = 10518

but when apply plan original script, i'm same error.

the info in test working off exact same records in original script. original script working off collection of equipmentids, on first one, encounter problem. short test script uses same equipmentlocationid , equipemntid selected values used update first equipment record in collection.

solved!

the error had nil geography type sql reported. pulling items in , out of update statement in effort isolate why still error if save currentgeolocation , update geography, found currentlocationdatetime (datetime, null) culprit. deleted column, added back. problem solved. original script works expected.

don't know happened datetime column caused throw errors against geometry type, it's fixed.

sql sql-server geography

java - Truly top-aligning text in Android TextView -



java - Truly top-aligning text in Android TextView -

i trying display textview in android such text in view top-aligned:

@override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); // create container layout framelayout layout = new framelayout(this); // create text label textview label = new textview(this); label.settextsize(typedvalue.complex_unit_px, 25); // 25 pixels tall label.setgravity(gravity.top + gravity.center); // align text top-center label.setpadding(0, 0, 0, 0); // no padding rect bounds = new rect(); label.getpaint().gettextbounds("gdyl!", 0, 5, bounds); // measure height label.settext("good day, world! "+bounds.top+" "+bounds.bottom); label.settextcolor (0xff000000); // black text label.setbackgroundcolor(0xff00ffff); // bluish background // position text label framelayout.layoutparams layoutparams = new framelayout.layoutparams(300, 25, gravity.left + gravity.top); // 25 pixels tall layoutparams.setmargins(50, 50, 0, 0); label.setlayoutparams(layoutparams); // compose screen layout.addview(label); setcontentview(layout); }

this code outputs next image:

the things note:

the bluish box 25 pixels tall, requested the text bounds reported 25 pixels tall requested (6 - (-19) = 25) the text not start @ top of label, has padding above it, ignoring setpadding() this leads text beingness clipped @ bottom, though box technically tall enough

how tell textview start text @ top of box?

i have 2 restrictions possible answers:

i need maintain text top-aligned, though, if there trick bottom-aligning or centering vertically instead, can't utilize it, since have scenarios textview taller needs be. i'm bit of compatibility-freak, if possible i'd stick calls available in android apis (preferably 1, no higher 7).

textviews utilize abstract class android.text.layout draw text on canvas:

canvas.drawtext(buf, start, end, x, lbaseline, paint);

the vertical offset lbaseline calculated bottom of line minus font's descent:

int lbottom = getlinetop(i+1); int lbaseline = lbottom - getlinedescent(i);

the 2 called functions getlinetop , getlinedescent abstract, simple implementation can found in boringlayout (go figure... :), returns values mbottom , mdesc. these calculated in init method follows:

if (includepad) { spacing = metrics.bottom - metrics.top; } else { spacing = metrics.descent - metrics.ascent; } if (spacingmult != 1 || spacingadd != 0) { spacing = (int)(spacing * spacingmult + spacingadd + 0.5f); } mbottom = spacing; if (includepad) { mdesc = spacing + metrics.top; } else { mdesc = spacing + metrics.ascent; }

here, includepad boolean specifies whether text should include additional padding allow glyphs extend past specified ascent. can set (as @ggc pointed out) textview's setincludefontpadding method.

if includepad set true (the default value), text positioned baseline given top-field of font's metrics. otherwise text's baseline taken descent-field.

so, technically, should mean need turn off includefontpadding, unfortunately yields next result:

the reason font reports -23.2 ascent, while bounding box reports top-value of -19. don't know if "bug" in font or if it's supposed this. unfortunately fontmetrics not provide value matches 19 reported bounding box, if seek somehow incorporate reported screen resolution of 240dpi vs. definition of font points @ 72dpi, there no "official" way prepare this.

but, of course, available info can used hack solution. there 2 ways it:

with includefontpadding left alone, i.e. set true:

double top = label.getpaint().getfontmetrics().top; label.setpadding(0, (int) (top - bounds.top - 0.5), 0, 0);

i.e. vertical padding set compensate difference in y-value reported text bounds , font-metric's top-value. result:

with includefontpadding set false:

double ascent = label.getpaint().getfontmetrics().ascent; label.setpadding(0, (int) (ascent - bounds.top - 0.5), 0, 0); label.setincludefontpadding(false);

i.e. vertical padding set compensate difference in y-value reported text bounds , font-metric's ascent-value. result:

note there nil magical setting includefontpadding false. both version should work. reason yield different results different rounding errors when font-metric's floating-point values converted integers. happens in particular case looks improve includefontpadding set false, different fonts or font sizes may different. easy adjust calculation of top-padding yield same exact rounding errors calculation used boringlayout. haven't done yet since i'll rather utilize "bug-free" font instead, might add together later if find time. then, should irrelevant whether includefontpadding set false or true.

java android textview vertical-alignment

emacs - Rstudio: shared libraries not easily searched -



emacs - Rstudio: shared libraries not easily searched -

i have 'workflow' type of question rstudio gui. have multiple projects active, each accessing number of libraries. edit or search source code library function definition , calls, need libraries open because beingness shared libraries, not in project directory 'goto file/function' not apply, nor 'function menu'. means multiple files open in code pane, there room modest number of tabs along top - not wrap. can pull downwards menu of them, not alphabetical , cannot resequenced without close/reopen. find important productivity drag. so: powerfulness users utilize external editor functionality, , take advantage of rstudio's dynamic update of externally edited , saved code? editor? still utilize winedt , rwinedt? emacs still living or extinct? realise question may zapped beingness vague of import me.

emacs much alive, , packages back upwards using r development, specifically:

ess polymode

emacs rstudio

How to validate an input form using php -



How to validate an input form using php -

i have created form follows need validate user input using php. security measure should not rely on javascript/ html 5 form validation validate form submissions. should employ server side validation verify info beingness submitted write php code following: 1. validate firstname, lastname , email required 2. validate age if entered number 3. validate email , website entries ensure valid

<!doctype html> <html> <head> <title>page title</title> </head> <?php $firstname=""; $lastname=""; $email=""; $age=""; $website=""; if ($_server["request_method"] == "post") { if (empty($_post["firstname"])) { $firstname = "first name required"; } else { $firstname = test_input($_post["firstname"]); } if (empty($_post["lastname"])) { $lastname = "last name required"; } else { $lastname = test_input($_post["lastname"]); } if (empty($_post["email"])) { $email = "email required"; } else { $email = test_input($_post["email"]); } if (is_numeric ($_post["age"])) {} else { $age ="age must numeric"; } } echo $firstname; echo $lastname; echo $email; echo $age; ?> <form action="." method="post"> <input type="text" name="firstname" placeholder="*first name" /><br> <input type="text" name="lastname" placeholder="*last name" /><br> <input type="text" name="email" placeholder="*email" /><br> <input type="text" name="age" placeholder="age" /><br> <input type="text" "name="website" placeholder="website" /><br> <input type="submit" name="submit" value="submit" /> </form> <body> </body> </html>

so looks this:

here, form happen have in scripts library, , can modify suit needs.

strangely enough, has function called test_input() , wanted achieve.

sidenote: sure alter own $myemail = "email@example.com";

<?php ob_start(); ?> <!doctype html public "-//w3c//dtd xhtml 1.0 strict//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-strict.dtd"> <style> .error {color: #ff0000;} h6 { font-family: bookman old style; font-size:20px; text-align: center; font-weight: normal; } h5 { font-family: bookman old style; font-size:15px; text-align: center; font-weight: normal; } </style> <?php $nameerr = $emailerr = $websiteerr = $commenterr = $categoryerr = ""; $name = $email = $comment = $website = $category = ""; if ($_server["request_method"] == "post") { if (empty($_post["name"])) { $nameerr = "name required"; $err = 1; } else { $name = test_input($_post["name"]); if (!preg_match("/^[a-za-z ]*$/",$name)) { $nameerr = "only letters , white space allowed"; } } if (empty($_post["email"])) { $emailerr = "email required"; $err = 1; } else { $email = test_input($_post["email"]); if (!filter_var($email, filter_validate_email)) { $emailerr = "invalid email format"; $err = 1; // die(); } } if (empty($_post["website"])) { $websiteerr = "url required"; $err = 1; } else { $website = test_input($_post["website"]); if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) { $websiteerr = "invalid url"; } } if (empty($_post["comment"])) { // $comment = ""; $commenterr = "comment required"; $err = 1; } else { $comment = test_input($_post["comment"]); } // if (empty($_post["category"])) { if ($_post["category"] == "" ) { $categoryerr = "category required"; $err = 1; } else { $category = test_input($_post["category"]); } } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); homecoming $data; } ?> <?php echo htmlspecialchars($_server["php_self"]);?> <h6>link submission</h6> <h5><span class="error">* required field.</span> <form method="post" action="<?php echo htmlspecialchars($_server["php_self"]);?>"> name of site: <input type="text" name="name" value="<?php echo $name;?>"> <span class="error">* <?php echo $nameerr;?></span> <br><br> e-mail: <input type="text" name="email" value="<?php echo $email;?>"> <span class="error">* <?php echo $emailerr;?></span> <br><br> url: <input type="text" name="website" value="<?php echo $website;?>"> <span class="error">* <?php echo $websiteerr;?></span> <br><br> description: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea><span class="error">* <br><?php echo $commenterr;?></span> <br><br> category of site: <select size="1" name="category"> <option value="<?php echo $category;?>"> -- please select -- </option> <option>arts</option> <option>business</option> <option>computers</option> <option>games</option> <option>health</option> <option>home</option> <option>kids , teens</option> <option>news</option> <option>recreation</option> <option>reference</option> <option>science</option> <option>shopping</option> <option>society</option> <option>sports</option> <option>world</option> </select><span class="error">* <?php echo $categoryerr;?></span> <br><br> <input type="submit" name="submit" value="submit"> </form> </h5> <?php if(isset($_post['submit'])){ if ($err != 1){ $myemail = "email@example.com"; $subject = "link submission"; $message = "your link submission form has been submitted by: website name: $name e-mail: $email url: $website category: $category description: $comment"; $headers = "from: ". $name . " <" . $email . ">\r\n"; mail($myemail, $subject, $message, $headers); // header('location: submit_thanks.php'); echo "ok"; } } ?>

php forms validation

r - dplyr: count of a count -



r - dplyr: count of a count -

let's have info frame

df <- data.frame(x = c("a", "a", "b", "a", "c"))

using dplyr count, get

df %>% count(x) x n 1 3 2 b 1 3 c 1

i want count on resulting n column. if n column named m, result i'm looking is

m n 1 1 2 2 3 1

how can done dplyr?

thank much!

dplyr seems have problem count(n).

for instance:

d <- data.frame(n = sample(1:2, 10, true), x = 1:10) d %>% count(n)

a workaround rename n:

df %>% # using info defined in question count(x) %>% rename(m = n) %>% count(m)

r count dplyr

ios7 - iOS 7 BUG - NSAttributedString does not appear -



ios7 - iOS 7 BUG - NSAttributedString does not appear -

last week asked question simulator bug nsattributedstring not displaying: ios 7 simulator bug - nsattributedstring not appear

unfortunately appears not simulator bug ios 7 bug. have reproduced issue on iphone 5 device.

the bug appears combination of using nsunderlinestyleattributename & nsparagraphstyleattributename attributes nsattributedstring.

i have tested on 2 ios 7 devices far, , issue has appeared on 1 of them. after have both been upgraded exact same version:

1st iphone 5 ios 7.0 (11a465): text not appear

1st iphone 5 after upgrading 7.0.2 (11a501): text not appear

2nd iphone 5 running ios 7.0 (11a4449d): text displays correctly

2nd iphone 5 after upgrading 7.0.2 (11a501): text not appear

so appears apple introduced bug after ios 7.0 (11a4449d). i've filed bug them , update on response get.

steps reproduce bug

if running ios 7.0.2 should able reproduce bug.

either download , run project on device https://github.com/rohinnz/ios-7-bug---nsattributedstring-does-not-appear

or

1) in xcode 5 create new 'single view application'. phone call whatever.

2) in viewcontroller.m, replace viewdidload method with:

- (void)viewdidload { [super viewdidload]; nsmutableparagraphstyle* paragraph = [[nsmutableparagraphstyle alloc] init]; paragraph.alignment = nstextalignmentcenter; nsattributedstring* attrstr = [[nsattributedstring alloc] initwithstring:@"lorem ipsum dolor sit" attributes: @{nsunderlinestyleattributename:@(nsunderlinestylesingle), nsparagraphstyleattributename:paragraph}]; uilabel* mylabel = [[uilabel alloc] initwithframe:cgrectmake(10, 30, 0, 0)]; mylabel.backgroundcolor = [uicolor greencolor]; mylabel.attributedtext = attrstr; [mylabel sizetofit]; [self.view addsubview:mylabel]; }

3) compile , run on device. depending on version of ios 7, text either display, or not. uilabel's background color display in both cases.

screenshots

iphone 5 ios 7.0 (11a465)

iphone 5 ios 7.0 (11a4449d)

my question

is able reproduce issue on device?

i have found workaround bug. in github code, utilize workaround, this:

nsattributedstring* attrstr = [[nsattributedstring alloc] initwithstring:@"lorem ipsum dolor sit\n" // <--- attributes: @{nsunderlinestyleattributename:@(nsunderlinestylesingle), nsparagraphstyleattributename:paragraph}]; uilabel* mylabel = [[uilabel alloc] initwithframe:cgrectmake(10, 30, 0, 0)]; mylabel.backgroundcolor = [uicolor greencolor]; mylabel.attributedtext = attrstr; [mylabel sizetofit]; mylabel.numberoflines = 2; // <---

i have made 2 changes: i've appended newline character original string, , i've set label's numberoflines 2.

what workaround forcefulness label's text against top of label. seems solve problem. in other words, bug appears stem label's effort vertically center text; if deliberately create text long size of label juggling label's height, numberoflines, , excess newline characters @ end of text, attributed string drawn.

edit i've found workaround along same lines: allow label resize fit text. see code , explanation here: http://stackoverflow.com/a/19545193/341994 in code, same thing opposite end, were: give label fixed width constraint flexible height constraint, , setting own height, label brings top of text against top of itself, , able display text correctly. in other words, way of preventing label centering text vertically, seems trigger bug.

further edit have sense bug may fixed in ios 7.1.

ios7 xcode5 nsattributedstring

c# - Creating Edges with OrientDB-NET.binary in a transaction -



c# - Creating Edges with OrientDB-NET.binary in a transaction -

i trying utilize orientdb-net.binary, extending improve ease-of-use among development team. trying create syntax similar dapper, that's we're using our mssql , mysql connections. should create easier on our development team swapping between 2 technologies.

i'd extensions function transactions.

here's insert extension now:

class="lang-c# prettyprint-override">public static void insert<t>(this odatabase db, t model, otransaction transaction) t : abasemodel, new() { inserthelper(db, model, transaction, new list<object>()); } private static void inserthelper<t>(odatabase db, t model, otransaction transaction, icollection<object> exclude, orid parent = null) t : abasemodel, new() { // avoid next loops stack overflow if (exclude.contains(model)) return; exclude.add(model); odocument record = new odocument(); record.oclassname = model.gettype().name; propertyinfo[] properties = model.gettype().getproperties( bindingflags.public | bindingflags.instance | bindingflags.setproperty | bindingflags.getproperty); icollection<propertyinfo> linkableproperties = new list<propertyinfo>(); foreach (propertyinfo prop in properties) { if (reservedproperties.contains(prop.name)) continue; oproperty aliasproperty = prop.getcustomattributes(typeof(oproperty)) .where(attr => ((oproperty)attr).alias != null) .firstordefault() oproperty; string name = aliasproperty == null ? prop.name : aliasproperty.alias; // record properties of model, store properties linking other // vertex classes later if (typeof(abasemodel).isassignablefrom(prop.propertytype)) { linkableproperties.add(prop); } else { record[name] = prop.getvalue(model); } } transaction.add(record); model.orid = record.orid; foreach (propertyinfo prop in linkableproperties) { orid outv, inv; abasemodel propvalue = prop.getvalue(model) abasemodel; if (!exclude.select(ex => ex abasemodel ? ((abasemodel)ex).orid : orid_default).contains(propvalue.orid)) { methodinfo insertmethod = typeof(databaseextensions) .getmethod("inserthelper", bindingflags.nonpublic | bindingflags.static).makegenericmethod(propvalue.gettype()); insertmethod.invoke(null, new object[] { db, propvalue, transaction, exclude, model.orid }); } outv = model.orid; inv = propvalue.orid; oedgeattribute edgetype = prop.getcustomattributes(typeof(oedgeattribute)) .firstordefault() oedgeattribute; oproperty propertyalias = prop.getcustomattributes(typeof(oproperty)) .where(p => ((oproperty)p).alias != null) .firstordefault() oproperty; string alias = propertyalias == null ? prop.name : propertyalias.alias; if (edgetype != null) { oedge link = new oedge(); link.oclassname = alias; link["out"] = outv; link["in"] = inv; if(edgetype.isinv) { orid tmp = link.outv; link["out"] = link.inv; link["in"] = tmp; } // not create border if there border // connecting these vertices ienumerable<tuple<orid,orid>> excludedlinks = exclude .select(ex => ex oedge ? new tuple<orid,orid>(((oedge)ex).outv,((oedge)ex).inv) : new tuple<orid,orid>(orid_default, orid_default)); if (excludedlinks.contains( new tuple<orid, orid>(link.outv, link.inv))) continue; exclude.add(link); transaction.add(link); } } }

abasemodel abstract class intended extended model classes in application. oedgeattribute attribute lets me specify if property representing 'in' border or 'out' border on vertex. orid_default equal new orid()

the above extension method works fine... mostly. using next model classes:

class="lang-c# prettyprint-override">public class person : abasemodel { [oproperty(alias = "residenceaddress")] [oedge(isoutv = true)] public address residence { get; set; } [oproperty(alias = "shippingaddress")] [oedge(isoutv = true)] public address shipping { get; set; } } public class dependent : person { public string firstname { get; set; } public string lastname { get; set; } // etc... } public class address : abasemodel { public string addressline1 { get; set; } public string addressline2 { get; set; } // etc... [oproperty(alias = "propertyaddress")] public person resident { get; set; } }

i 'import' several hundred dependents mapping set of entries in table:

class="lang-c# prettyprint-override">oclient.createdatabasepool("127.0.0.1", 2424, "persephone", odatabasetype.graph, "admin", "admin", 10, "persephone"); // persephoneconnection has access odatabase , otransaction, // , methods dispatch them ipersephoneconnection persephone = new persephoneconnection(); persephone.begintransaction(); // traverse functioning extension method calls // `traverse * {0}` , maps result model objects ienumerable<tmped> eds = persephone.connection.traverse<tmped>("tmped"); foreach (tmped model in eds) { dependent dep = new dependent { firstname = model.firstname, lastname = model.lastname, // etc... }; address residence = new address { addressline1 = model.addres_line1, addressline2 = model.address_line2, // etc... resident = dep }; dep.residence = residence; address shipping = new address { addressline1 = model.shippingaddress_line1, addressline2 = model.shippingaddres_line2, // etc... resident = dep }; dep.shipping = shipping; persephone.connection.insert(dep, persephone.transaction); } persephone.commit(); persephone.dispose();

after running code, database contains 273 dependent records (extends person extends v) right values properties, 546 address records (extends v) right values properties, 273 residenceaddress records (extends propertyaddress extends e) right out , in rids, , 273 shippingaddress records (extends propertyaddress) right out , in rids.

however, none of dependents or addresses can see edges connect them. traverse * #29:0 brings first dependent, doesn't bring residence or shipping address. select expand(out('residenceaddress')) dependent returns empty result set.

after tinkering, appears cause of because otransaction.add performing insert {0} when transaction committed, rather create vertex {0} or create border {0}.

i can alter code utilize odatabase.create.vertex() , odatabase.create.edge() instead of otransaction.add(), instead of committing transaction in case, have phone call osqlcreateedge.run() or osqlcreatevertex.run(), processes record creation immediately, , rollback isn't option.

is there way edges created (as opposed inserted records) while still using transactions?

to create heavy edges via transaction need proper set links between documents

look illustration here

var v1 = new odocument { oclassname = "testvertex" }; v1.setfield("name", "first"); v1.setfield("bar", 1); var v2 = new odocument { oclassname = "testvertex" }; v2.setfield("name", "second"); v2.setfield("bar", 2); var e1 = new odocument { oclassname = "testedge" }; e1.setfield("weight", 1.3f); // add together records transaction _database.transaction.add(v1); _database.transaction.add(v2); _database.transaction.add(e1); // link records v1.setfield("in_testedge", e1.orid); v2.setfield("out_testedge", e1.orid); e1.setfield("in", v1.orid); e1.setfield("out", v2.orid); _database.transaction.commit();

c# orientdb

javascript - Is there any in GWT to get notification about which fragment is going to be downloaded -



javascript - Is there any in GWT to get notification about which fragment is going to be downloaded -

our gwt application has various fragments , each of them big in size(1+ mb). show progress bar when gwt downloading fragment. using gwtp based code splitting.

i not find related fragment loading event in gwt source code. have thought how javascript on page can notified fragment going downloaded next?

there not direct way, can workaround in 2 ways

1.- extending crosssiteiframelinker , overriding method getjsinstallscript() can homecoming customised javascript content alert somehow user permutation beingness loaded or show spinner. note script should contain code similar installscriptearlydownload.js or installscriptdirect.js

// linker class public class myxsilinker extends crosssiteiframelinker { @override protected string getjsinstallscript(linkercontext context) { homecoming "/your_namespace/your_script.js"; } } // "/your_namespace/your_script.js" script function installscript(filename) { } // module file <define-linker name="mylinker" class="...myxsilinker" /> <add-linker name="mylinker" />

2.- using window.__gwtstatsevent function. can define function in index.html start loading spinner when script loading app going added document, utilize gwt code remove that.

// in index.html <head> <script> window.__gwtstatsevent = function(r) { if (r.type == 'scripttagadded') { d = document.createelement('div') d.id = 'loading' d.innerhtml = 'loading...' document.body.appendchild(d); } } </head> </script> // in entrypoint class document.get().getelementbyid("loading").removefromparent();

to show accurate progress-bar quite hard because <script> tag not back upwards progress events. best approach should linker loading permutation using ajax, can utilize html5 progress events in xhr object.

i utilize #2 approach showing nice spinner animated css.

javascript gwt

c# - LibreOffice Convert XLSX to PDF in ASP.NET MVC -



c# - LibreOffice Convert XLSX to PDF in ASP.NET MVC -

version 4.3

in c# trying utilize headless alternative convert xlsx pdf nil happens when run asp.net or simple command prompt.

var pdfprocess = new process(); pdfprocess.startinfo.filename = exe; pdfprocess.startinfo.arguments = param + " \"" + fulldocpath +"\""; pdfprocess.start();

where exe , params are:

c:\program files (x86)\libreoffice 4\program\soffice.exe -norestore -nofirststartwizard -nologo -headless -convert-to pdf "c:\uds_docs\temp\teller roster national.xlsx"

i used gui test libreoffice can convert file , worked fine.

here how convert excel, word etc pdf on asp.net mvc web site @ no cost:

install libreoffice, free

set current directory same folder existing xls. seems missing piece.

run this:

"c:\program files (x86)\libreoffice 4\program\soffice.exe" -norestore -nofirststartwizard -headless -convert-to pdf "thefile.xlsx"

in c#:

var pdfprocess = new process(); pdfprocess.startinfo.filename = exepdf; pdfprocess.startinfo.arguments = "-norestore -nofirststartwizard -headless -convert-to pdf \"thefile.xlsx\""; pdfprocess.startinfo.workingdirectory = docpath; //this of import pdfprocess.start();

make sure workerprocess has access exe, default not.

c# asp.net-mvc pdf libreoffice

ios - Download multiple(Paralllel) files(.mp4) with progressbar and save it to gallery -



ios - Download multiple(Paralllel) files(.mp4) with progressbar and save it to gallery -

i have download multiple .mp4 videos , show progressbar each. have display these progress in tableview. know how download single video , know how save gallery using ...

currently using code..

dispatch_async(dispatch_get_global_queue(dispatch_queue_priority_default, 0), ^{ nslog(@"downloading started"); nsstring *urltodownload = @"http://original.mp4"; nsurl *url = [nsurl urlwithstring:urltodownload]; nsdata *urldata = [nsdata datawithcontentsofurl:url]; if ( urldata ) { nsarray *paths = nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes); nsstring *documentsdirectory = [paths objectatindex:0]; nsstring *filepath = [nsstring stringwithformat:@"%@/%@", documentsdirectory,@"thefile.mp4"]; //saving done on main thread dispatch_async(dispatch_get_main_queue(), ^{ [urldata writetofile:filepath atomically:yes]; nslog(@"file saved !"); }); } });

first approach

first of how can show progress while downloading using above code. then don't know downloading. want know path above code save .mp4 video , want modify(save in gallery). i want show download progress each video.

second approach

i think have utilize nsoperationqueue run downloads asynchronously, allow number done in parallel,etc . don't know how implement progress ..

i created had download multiple tasks , shows progress of each on too: http://github.com/manavgabhawala/caen-lecture-scraper (this mac) need create custom uitableviewcell class has progress bar within of , iboutlet bar. create class of cell conform nsurlsessiondownloaddelegate progress comes in. further, used semaphore ensure 3 downloads happened simultaneously. here's class convenience:

let downloadsallowed = dispatch_semaphore_create(3) class progresscellview: uitableviewcell { @iboutlet var progressbar: uiprogressview! @iboutlet var statuslabel: uilabel! var downloadurl : nsurl! var savetopath: nsurl! func setup(downloadurl: nsurl, savetopath: nsurl) { self.downloadurl = downloadurl self.savetopath = savetopath statuslabel.text = "waiting queue" // optionally phone call begin download here if don't want wait after queueing cells. } func begindownload() { statuslabel.text = "queued" allow session = nsurlsession(configuration: nsurlsessionconfiguration.defaultsessionconfiguration(), delegate: self, delegatequeue: nsoperationqueue()) allow task = session.downloadtaskwithurl(downloadurl)! dispatch_async(dispatch_get_global_queue(dispatch_queue_priority_default, 0), { dispatch_semaphore_wait(downloadsallowed, dispatch_time_forever) dispatch_async(dispatch_get_main_queue(), { self.statuslabel.text = "downloading" }) task.resume() }) } } extension progresscellview : nsurlsessiondownloaddelegate { func urlsession(session: nsurlsession, downloadtask: nsurlsessiondownloadtask, didwritedata byteswritten: int64, totalbyteswritten: int64, totalbytesexpectedtowrite: int64) { progressbar.setprogress(float(totalbyteswritten) / float(totalbytesexpectedtowrite), animated: true) } func urlsession(session: nsurlsession, downloadtask: nsurlsessiondownloadtask, didfinishdownloadingtourl location: nsurl) { // todo: write file downloaded. // re-create file `location` `savetopath` , handle errors necessary. dispatch_semaphore_signal(downloadsallowed) dispatch_async(dispatch_get_main_queue(), { self.statuslabel.text = "downloaded" }) } func urlsession(session: nsurlsession, didbecomeinvalidwitherror error: nserror?) { print(error!.localizeddescription) // todo: error handling. } }

change creation of semaphore value whatever want (the number of concurrent downloads allowed). note must phone call setup on cell downloadurl , savetopath after instantiating it. if want queue , download videos phone call begindownload() within of setup(). otherwise, phone call on each , every cell whenever want start downloading videos.

ios objective-c grand-central-dispatch nsoperationqueue

netlogo - Trying to get a turtle breed to avoid a specific colour of patch -



netlogo - Trying to get a turtle breed to avoid a specific colour of patch -

;num-holes global variable. i'm trying them avoid black patches(holes in floor)

if any? patches in-radius num-holes with[pcolor = black] [ set heading (towards min-one-of num-holes[distance myself]) + 180 - random 10 + random 10 ]

i'm trying zombies seek , avoid black patches know netlogo won't take global 'num-holes' how can see , avoid patches ? here wider scope of code incase makes problem clearer.

go inquire zombies [ ;set heading (heading + 45 - (random 90)) allow closest-player min-one-of players[distance myself] set heading towards closest-player ;wait 1 forwards 1 if pcolor = black [death] if pcolor = black [death] ;num-holes global variable. i'm trying them avoid black patches(holes in floor) if any? patches in-radius num-holes with[pcolor = black] [ set heading (towards min-one-of zombies[distance myself]) + 180 - random 10 + random 10 ] ] end

please , give thanks :)

if any? patches in-radius 5 with[pcolor = black] [ stuff]

netlogo

android - Center items in listview vertically -



android - Center items in listview vertically -

i have listview, listviews width , height should set match parent. so, if listview stretched , has 2 items in it, @ top of listview , on bottom much useless space. want know, if possible center these 2 items in listview vertically, if yes, how?

list height depends on height of list item, populating list. if have 2 items in list why don't utilize linear layout instead weightsum?

anyway, if want accomplish result requested in question have display height using method

getresources().getdisplaymetrics().heightpixels in activity context.

after need set height of list item height retrieved before divided 2. , set gravity center_vertical textviews in list.

android listview

hibernate - Why hikaricp gives me Method not found: setUrl at startup? -



hibernate - Why hikaricp gives me Method not found: setUrl at startup? -

i developing gwt app without maven nor spring, want utilize hikaricp connection pool downloaded hikaricp-2.2.4.jar maven's central repository along pgjdbc-ng-0.3-complete.jar postgresql driver; have updated hibernate libraries 4.1 4.3.

i using next hikaricp properties on hibernate.cfg.xml

<property name="hibernate.connection.provider_class">com.zaxxer.hikari.hibernate.hikariconnectionprovider</property> <property name="hibernate.hikari.datasourceclassname">com.impossibl.postgres.jdbc.pgdatasource</property> <property name="hibernate.hikari.datasource.user">user</property> <property name="hibernate.hikari.datasource.password">pass</property> <property name="hibernate.hikari.maximumpoolsize">10</property> <property name="hibernate.hikari.datasource.url">jdbc:postgresql://localhost:5432/db</property>

now, when start application gives me next exception:

org.hibernate.hibernateexception: java.lang.runtimeexception: java.beans.introspectionexception: method not found: seturl @ com.zaxxer.hikari.hibernate.hikariconnectionprovider.configure(hikariconnectionprovider.java:84) @ org.hibernate.boot.registry.internal.standardserviceregistryimpl.configureservice(standardserviceregistryimpl.java:111) @ org.hibernate.service.internal.abstractserviceregistryimpl.initializeservice(abstractserviceregistryimpl.java:234) @ org.hibernate.service.internal.abstractserviceregistryimpl.getservice(abstractserviceregistryimpl.java:206) @ org.hibernate.engine.jdbc.internal.jdbcservicesimpl.buildjdbcconnectionaccess(jdbcservicesimpl.java:260) @ org.hibernate.engine.jdbc.internal.jdbcservicesimpl.configure(jdbcservicesimpl.java:94) @ org.hibernate.boot.registry.internal.standardserviceregistryimpl.configureservice(standardserviceregistryimpl.java:111) @ org.hibernate.service.internal.abstractserviceregistryimpl.initializeservice(abstractserviceregistryimpl.java:234) @ org.hibernate.service.internal.abstractserviceregistryimpl.getservice(abstractserviceregistryimpl.java:206) @ org.hibernate.cfg.configuration.buildtyperegistrations(configuration.java:1887) @ org.hibernate.cfg.configuration.buildsessionfactory(configuration.java:1845) @ org.persistencias.hibernatesessionfactory.(hibernatesessionfactory.java:43) @ org.persistencias.basehibernatedao.getsession(basehibernatedao.java:14)

. . . caused by: java.lang.runtimeexception: java.beans.introspectionexception: method not found: seturl @ com.zaxxer.hikari.util.propertybeansetter.setproperty(propertybeansetter.java:129) @ com.zaxxer.hikari.util.propertybeansetter.settargetfromproperties(propertybeansetter.java:58) @ com.zaxxer.hikari.util.poolutilities.initializedatasource(poolutilities.java:134) @ com.zaxxer.hikari.pool.hikaripool.(hikaripool.java:142) @ com.zaxxer.hikari.pool.hikaripool.(hikaripool.java:109) @ com.zaxxer.hikari.hikaridatasource.(hikaridatasource.java:78) @ com.zaxxer.hikari.hibernate.hikariconnectionprovider.configure(hikariconnectionprovider.java:80) ... 49 more caused by: java.beans.introspectionexception: method not found: seturl @ java.beans.propertydescriptor.(propertydescriptor.java:110) @ com.zaxxer.hikari.util.propertybeansetter.setproperty(propertybeansetter.java:120) ... 55 more

i have searched here on stackoverflow , googled have not found far, can give me hint this?

thank you!

the pgjdbc-ng pgdatasource not have setter url property. url "composed" internally pgjdbc-ng. need setup datasource using individual properties:

hibernate.hikari.datasource.host=localhost hibernate.hikari.datasource.port=5432 hibernate.hikari.datasource.database=db

hibernate maven jetty hikaricp

Compile opencore-amr for iOS,but always "configure: error: C++ compiler cannot create executables" -



Compile opencore-amr for iOS,but always "configure: error: C++ compiler cannot create executables" -

i got source code here

https://github.com/feuvan/opencore-amr-ios

but when run .sh file, "configure: error: c++ compiler cannot create executables"

----------------------------------- ....... checking bsd-compatible install... /opt/local/bin/ginstall -c checking whether build environment sane... yes checking thread-safe mkdir -p... /opt/local/bin/gmkdir -p checking gawk... no checking mawk... no checking nawk... no checking awk... awk checking whether create sets $(make)... yes checking how create ustar tar archive... gnutar checking whether create supports nested variables... yes checking whether enable maintainer-specific portions of makefiles... no checking build scheme type... x86_64-apple-darwin13.4.0 checking host scheme type... x86_64-apple-darwin13.4.0 checking whether c++ compiler works... no configure: error: in `/users/jun/downloads/opencore-amr-ios-master': configure: error: c++ compiler cannot create executables see `config.log' more details -----------------------------------

osx 10.9.4, xcode 6.1 , command line tools

who can help ?

c++ ios configure

Should I be using Facebook user IDs inside my app? -



Should I be using Facebook user IDs inside my app? -

i'm building new website utilize facebook login authentication.

should using user's facebook id user id in app?

or should give users new user ids?

i'm thinking creating mysql table "users" have entry containing facebook id each user (as primary key), used foreign key on rest of database.

is recommeneded? missing anything?

thank much.

recommended what? recommend not it, @ to the lowest degree because in future want have authentication via site (e.g. google, twitter , on).

facebook user

ios - how to export signing identity from Xcode 6? -



ios - how to export signing identity from Xcode 6? -

in xcode 6, clicked: xcode -> preferences -> accounts

i've shoosen business relationship , clicked on "settings wheel in bottom left corner , : export accounts...

i've set name , password exported business relationship , clicked save , i've got message:

have thought how can export business relationship import on mac?

the signing identity private key in keychain on mac made certificate request apple. determining right private key may take trial , error if names , descriptions not help.

export private key /applications/utilities/"keychain access".

import private key "keychain access" on other mac want authorized sign app.

after verifying private key works on destination mac, may want delete private key original mac security.

ios objective-c xcode provisioning-profile

asp.net mvc - Razor If-condition not working -



asp.net mvc - Razor If-condition not working -

i can't seem if-condition of string comparing work. here code foreach block.

@foreach (var item in model){ <tr onclick="getdata('@item.discountdescs');"> <td></td> <td>@html.displayfor(modelitem => item.discountdescs)</td> <td> @if (string.equals(item.discountform, "c")) { @:card } else { @:other } </td> <td>@html.displayfor(modelitem => item.discounttype)</td> <td>@html.displayfor(modelitem => item.discountmode)</td> <td>@html.displayfor(modelitem => item.discountvalue)</td> <td>@html.displayfor(modelitem => item.isactive)</td> <td>@html.displayfor(modelitem => item.isscheme)</td> </tr> }

the td display "other".

you need trim value coming database.

use trim() function

item.discountform.trim()

this omit spaces , compare string.

asp.net-mvc if-statement razor

scala - How to verify a method is called N times exactly in specs2? -



scala - How to verify a method is called N times exactly in specs2? -

in specs2, can verify invocation times of method by:

there one(user).getname there two(user).getname there three(user).getname

but how check n times? i'm looking like:

there times(n, user).getname

unlucky there no such api

if @ implementation of specs2 bindings mockito, you'll find like

def one[t <: anyref](mock: t)(implicit anorder: option[inorder] = inorder()): t = verify(mock, org.mockito.mockito.times(1))(anorder)

so guess can define own times method, mimicking one:

def times[t <: anyref](n: int, mock: t)(implicit anorder: option[inorder] = inorder()): t = verify(mock, org.mockito.mockito.times(n))(anorder)

or utilize mockito explicitly:

val mocker = new mockitomocker {} verify(user, org.mockito.mockito.times(42)).getname

scala unit-testing specs2

text - Eclipse move the cursor left/right/up/down without using arrow keys -



text - Eclipse move the cursor left/right/up/down without using arrow keys -

i'm lazy , hate have move right hand arrow keys or mouse every 5 seconds move cursor around , edit text. there way can maintain hands in typing position , move cursor around?

you can alter these settings in specific preferences window:

windows -> preferences-> general-> keys.

there can find associations:

line up line down next column previous column.

in binding, , press buttons. after can select keystroke assign to:

for example:

alt+j <- colum. alt+i line. alt+k downwards line. alt+l -> colum.

eclipse text editing

How to deal with "HelperDb.ExecuteSql(@"..SomeQuery.sql")" in unit testing? C# .NET -



How to deal with "HelperDb.ExecuteSql(@"..SomeQuery.sql")" in unit testing? C# .NET -

i'm new unit testing, , know test depending upon external resource (like file or database) not unit test, it's integration test instead.

please consider next code snippet:

[testclass] public class mytestclass { [classinitialize] public static void init(testcontext context) { if (system.io.file.exists("../database_scripts/test_scripts/some_query.sql")) { helperdb.executesql("../database_scripts/test_scripts/some_query.sql"); } } ... }

i don't have database installed on server , don't want install it, , wanna test using rhinomocks. how can perform test? help or comments warmely welcome :)

c# unit-testing dependency-injection

python - Multiple QThread keep crashing PySide -



python - Multiple QThread keep crashing PySide -

i trying implement programme multiple threads. in __init__ of main window, threads created. gui starts up, while threads run in background. problem keeps crashing. if add/uncomment line print statement, programme works fine.

class testthreadingwin(qtgui.qmainwindow): def __init__(self, parent=rsui.getmayamainwindow()): ''' constructor ''' super(testthreadingwin, self).__init__(parent) self.setwindowtitle('test threading') self.centralwidget = qtgui.qplaintextedit() self.setcentralwidget(self.centralwidget) self.centralwidget.appendplaintext("test") numthreads = 7 self._threads = [] in range(numthreads): #print self._threads # <-- uncomment line, , works?! testthread = qtcore.qthread() # maintain reference thread object or deleted when # goes out of scope, if has not finished processing. self._threads.append(testthread) worker = testthreadworker(i) worker.movetothread(testthread) worker.finishedprocessing.connect(self.updatestuff) worker.finishedprocessing.connect(testthread.quit) testthread.started.connect(worker.dostuff) testthread.finished.connect(self.deletethread) testthread.start() qtcore.qcoreapplication.processevents() print 'done creating threads' def deletethread(self): """ destroy thread object , remove reference self._threads list. """ print 'delete thread' threadtodelete = self.sender() threadindex = self._threads.index(threadtodelete) del self._threads[threadindex] threadtodelete.deletelater() def updatestuff(self, message): self.centralwidget.appendplaintext(message) class testthreadworker(qtcore.qobject): finishedprocessing = qtcore.signal(str) def __init__(self, num): super(testthreadworker, self).__init__() self._num = num def dostuff(self): time.sleep(1) choicelist = ['cat', 'bat', 'hat', 'tissue', 'paper', 'qwerty', 'mouse'] stuff = random.choice(choicelist) stuff2 = '{0} {1}'.format(self._num, stuff) self.finishedprocessing.emit(stuff2) def openthreadingwin(): '''this ensures 1 instance of ui open @ time.''' global testingthreadingwin try: testingthreadingwin.close() testingthreadingwin.deletelater() except: pass testingthreadingwin = testthreadingwin() testingthreadingwin.show()

it weird print statement create stop crashing. overlooking?

i got working using qthreadpool. manages threads me, don't have worry trying access destroyed. key differences:

the worker class inherits both qtcore.qobject , qtcore.qrunnable. (it has inherit qobject in order emit signal.) __init__ function of both parent classes must called, or programme crash. no more code set connections ensure thread destroyed when done. no more code maintain references threads or delete references when thread destroyed.

here new code:

class testthreadpoolwin(qtgui.qmainwindow): def __init__(self, parent=rsui.getmayamainwindow()): ''' constructor ''' super(testthreadpoolwin, self).__init__(parent) self.setwindowtitle('test threading') self.centralwidget = qtgui.qplaintextedit() self.setcentralwidget(self.centralwidget) self.centralwidget.appendplaintext("test") numthreads = 7 threadpool = qtcore.qthreadpool.globalinstance() in range(numthreads): runnable = testrunnableworker(i) runnable.finishedprocessing.connect(self.updatestuff) threadpool.start(runnable) print 'done creating threads' def updatestuff(self, message): self.centralwidget.appendplaintext(message) class testrunnableworker(qtcore.qobject, qtcore.qrunnable): finishedprocessing = qtcore.signal(str) def __init__(self, num, parent=none): # sure run __init__ of both parent classes, or else # crash. qtcore.qobject.__init__(self, parent) qtcore.qrunnable.__init__(self) self._num = num def run(self): time.sleep(1) choicelist = ['cat', 'bat', 'hat', 'tissue', 'paper', 'qwerty', 'mouse'] stuff = random.choice(choicelist) stuff2 = '{0} {1}'.format(self._num, stuff) self.finishedprocessing.emit(stuff2) def openthreadpoolwin(): '''this ensures 1 instance of ui open @ time.''' global testingthreadpoolwin try: testingthreadpoolwin.close() testingthreadpoolwin.deletelater() except: pass testingthreadpoolwin = testthreadpoolwin() testingthreadpoolwin.show()

python pyside qthread

uuid - Docker MAC Address Generation -



uuid - Docker MAC Address Generation -

i had question applications running within docker containers , uuid generation.

here’s our scenario:

currently our applications using event driven framework.

for events generate uuid’s based on mac address, pid, time-stamp , counter.

for running containers on distributed scheme coreos (while very low chance), there no guarantee parameters used generate uuid unique each container 1 container on 1 server in cluster generate uuid using same mac, pid, time-stamp , counter container on cluster.

in essence if these 2 uuid’s both generate event , send our messaging bus, there conflict.

in our analysis, scenario seems boil downwards uniqueness of mac addresses on each docker container.

so frank:

how unique mac addresses within containers? how mac addresses generated if not manually set?

from reading of generatemacaddr function, mac addresses generated docker ipv4 address of container's interface on docker0 bridge: guaranteed consistent ip address.

the docker0 bridge's subnet have operate in, 255.255.0.0 per this example of 172.17.42.1/16, has 65,534 routable addresses. cut down entropy uuid generation, mac address collision isn't possible ips must unique, , scenario of identical mac, pid, time , counter in 2 containers on same docker server/coreos host should not possibility.

however 2 coreos hosts (each running 1 docker server) potentially take same random subnet, resulting in possibility of duplicated macs containers on different hosts. evade setting fixed cidr docker server on each host:

--fixed-cidr=cidr — restrict ip range docker0 subnet, using standard cidr notation 172.167.1.0/28. range must , ipv4 range fixed ips (ex: 10.20.0.0/16) , must subset of bridge ip range (docker0 or set using --bridge). illustration --fixed-cidr=192.168.1.0/25, ips containers chosen first half of 192.168.1.0/24 subnet.

this should ensure unique mac addresses across cluster.

the original ieee 802 mac address comes original xerox ethernet addressing scheme. 48-bit address space contains potentially 248 or 281,474,976,710,656 possible mac addresses.

source

if concerned lack of entropy (the ip mac mapping reduces considerably), improve alternative may utilize different mechanism uuid generation. uuid versions 3, 4 , 5 do not take mac address account. alternatively include host machine's mac in uuid generation.

of course, whether "considerable mac space reduction" have impact of uuid generation should tested before code changed.

source linked above:

// generate ieee802 compliant mac address given ip address. // // generator guaranteed consistent: same ip yield same // mac address. avoid arp cache issues. func generatemacaddr(ip net.ip) net.hardwareaddr { hw := make(net.hardwareaddr, 6) // first byte of mac address has comply these rules: // 1. unicast: set least-significant bit 0. // 2. address locally administered: set second-least-significant bit (u/l) 1. // 3. "small" possible: veth address has "smaller" bridge address. hw[0] = 0x02 // first 24 bits of mac represent organizationally unique identifier (oui). // since address locally administered, can whatever want long // doesn't conflict other addresses. hw[1] = 0x42 // insert ip address lastly 32 bits of mac address. // simple way guarantee address consistent , unique. copy(hw[2:], ip.to4()) homecoming hw }

docker uuid mac-address linux-containers