Posts

Showing posts from September, 2013

python - hid.find_all_hid_devices() in asyncio coroutine -

in order access a usb hid device connected on computer use function find_all_hid_devices() from pywinusb package. now access hid device asyncio coroutine. following code @asyncio.coroutine def main(): pywinusb import hid = hid.find_all_hid_devices() the following error returned: traceback (most recent call last): file "c:\python34\lib\site-packages\pywinusb\hid\core.py", line 122, in find_all_hid_devices interface_data in winapi.enum_device_interfaces(h_info, guid): file "c:\python34\lib\site-packages\pywinusb\hid\winapi.py", line 466, in enum_device_interfaces byref(dev_interface_data) ): ctypes.argumenterror: argument 1: <class 'overflowerror'>: int long convert the same call hid.find_all_hid_devices() works on own, in plain main without asyncio. is due fact i'm trying access within coroutine? proper way achieve this? pywinusb library synchronous design, should call in thread pool. @asyncio.corout

if statement - Android Studio If Else Conditions -

i require in forming if else code show message. example, if more or equal 50, message "green mark certified" showed in textview box. below codes did simple calculator. need when int sum>=50 , <75, show "green mark certified" in textview box. please kindly show me how code if want achieve it. public void onbuttonclick(view v){ edittext e1 = (edittext)findviewbyid(r.id.edittext); edittext e2 = (edittext)findviewbyid(r.id.edittext2); edittext e3 = (edittext)findviewbyid(r.id.edittext3); edittext e4 = (edittext)findviewbyid(r.id.edittext4); edittext e5 = (edittext)findviewbyid(r.id.edittext5); textview t1 = (textview)findviewbyid(r.id.textview); int num1 = integer.parseint(e1.gettext().tostring()); int num2 = integer.parseint(e2.gettext().tostring()); int num3 = integer.parseint(e3.gettext().tostring()); int num4 = integer.parseint(e4.gettext().tostring()); int num5 = integer.parseint(e5.gettext().tostring());

Unable to send ICMP packets from a raw socket in Python -

i have raw python socket initialized so: mysocket = socket.socket(socket.af_inet, socket.sock_raw, socket.ipproto_raw) mysocket.setsockopt(socket.ipproto_ip, socket.ip_hdrincl, 1) my problem can't send packet socket protocol field in ip header specified '1' (icmp). if field else it'll work fine, including '17' (udp) example. don't errors, packet doesn't display in wireshark, , can't receive on server. i'm generating ip header so: def getipheader(src, dst, proto): version = 4 ihl = 5 dscp = 0 ecn = 0 totallength = 40 identification = 333 flags = 0 fragmentoffset = 0 timetolive = 128 protocol = proto headerchecksum = 0 sourceip = socket.inet_aton(src) destip = socket.inet_aton(dst) options = 0 version_ihl = (version << 4) | ihl dscp_ecn = (dscp << 2) | ecn flags_fragmentoffset = (flags << 13) | fragmentoffset # '!' ensures arguments conve

ruby - weird ActiveRecord time zone behavior in Rails on multiple servers -

our application hosted on aws 8 app servers (unicorn) + 3 rds (1 master + 2 read replica) + 2 redis (master + slave) located in 1 region 8 app servers have bst time zone , 2 redis, have applied time zone 'london' in application.rb, the problem on show page start date, end date displayed value displayed start date friday 01-10-2015 - 18:30 , friday 01-10-2015 - 19:30 value reflect of refresh (ctrl + f5). has faced similar problem? ravi you can fix issue, adding around filter in application_controller override weird behaviour of active_record - timezone. around_filter :use_time_zone private def use_time_zone(&block) time.use_zone('london', &block) end so, whenever default timezone changed utc, override , set bst.

C++ template class confusion -

so experienced c programmer took dive c++ toy-compiler writing. "modernizing" c++ code because current code looks more ansi-c , c++ thing takes advantage of std::vector. so decided use iterators instead of manually iterating through containers , arrays via loop count variable. noticed need middle of several iterators wrote static class function that. now extending function not return iterator middle element return vector of iterators several parts of container. using templates make code more generic, kind of stuck implementation of current function. here definition of class: namespace dbc { template<typename generic_iterator_t> class itertools { public: /* returns iterator points middle element, * same calling get_fraction_iterator fraction = 2 */ static generic_iterator_t get_middle_iterator( generic_iterator_t begin, generic_iterator_t end ); /* splits container several chunks , returns * iterators in vector */ te

python - Matplotlib plot_surface mplot3d with masked array and custom palette gives wrong color -

Image
i'm trying plot surface in 3d using mplot3d matplotlib. want custom color palette values above 1.0 green, below -1.0 blue, 0.0 red(invalid values) , other values according greyscale. i've been able of these right except condition 0.0 should red. following this example thought may able set 0.0 "bad value" in masked array fails. this snippet try plot values: import numpy np import matplotlib.pyplot plt import matplotlib.colors colors matplotlib import cm mpl_toolkits.mplot3d import axes3d ... fig = plt.figure() ax = fig.add_subplot(111, projection='3d') masked_array = np.ma.masked_equal(z,0.0) palette = cm.gray palette.set_over('g', 1.0) palette.set_under('b', 1.0) palette.set_bad('r', 1.0) ax.plot_surface(x,y,masked_array, rstride=1, cstride=1, cmap=palette, norm = colors.normalize(vmin = -1.0, vmax = 1.0, clip = false)) plt.savefig('plot.png') now run z set 2d numpy array many 0.0 values: >>

Python: Storing data in a text file and appending particular/individual lines -

this computer science project i've been working on. test scores saved in text file against students name. example: rob 21 terry 12 mike 33 i can program want read lines of text file , identify if name in existence. if so, should add next score onto end of line. if terry takes test again scores should read: rob 21 terry 12 23 mike 33 this relevant piece of code. starts after test complete , user has input name, class , received score. import fileinput print("well done " +name+ ", score "+ (str(score))) entry = (name +" "+ (str(score))) if classchoice == "a": classfile = open("classa.txt") line in classfile: if name in line: oldline = line newline = (oldline+" "+(str(score))) print (newline) classfile.close() else: classfile = open("classb.txt","a")

java - JMockIt fails with AgentInitializationException: Agent JAR loaded but agent failed to initialize -

i developing plugin eclipse kepler. adding @runwith(jmockit.class) test class causes following error: jmockit: reinitializing under custom class loader org.eclipse.osgi.internal.baseadaptor.defaultclassloader@b7ccec1[com.mypackage.myclass:2.3.9.201508161221(id=1)] java.lang.reflect.invocationtargetexception @ 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) @ sun.instrument.instrumentationimpl.loadclassandstartagent(instrumentationimpl.java:382) @ sun.instrument.instrumentationimpl.loadclassandcallagentmain(instrumentationimpl.java:407) caused by: java.lang.verifyerror @ sun.instrument.instrumentationimpl.redefineclasses0(native method) @ sun.instrument.instrumentationimpl.redefineclasse

jstl - EL expressions not evaluated in JSP -

there's small problem servlets/jsp web application. i'm trying use jstl in jsp page. when use tag example: <c:out value="${command}"/> it shows me ${command} in browser instead of parameter 'command' value. i'm using maven (and guess problem here). here pom xml dependencies: <dependency> <groupid>javax.servlet</groupid> <artifactid>javax.servlet-api</artifactid> <version>3.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupid>jstl</groupid> <artifactid>jstl</artifactid> <version>1.2</version> </dependency> my web.xml declaration tag: <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" versi

linux - error when changing mount location for external hdd -

i admit might bit complicated , maybe not best method if have better solution let me know... i have 'server' put lubuntu 14.4 on. attempting attach external hdd formatted ext3 folder /home/external ftp users able files on without leaving /home directory (to have them 'chained' / chrooted). the hdd mount fine (no errors) automatic mount options. every time try change mount point other /media//external get: error mounting system-managed device /dev/sdd1: command-line `mount "/mnt/ external"' exited non-zero exit status 32: mount: wrong fs type, bad option, bad superblock on /dev/sdd1 missing codepage or helper program, or other error in cases useful info found in syslog - try dmesg | tail or (udisks-error-quark, 0) as far can tell not matter try mount tried /mnt/external same results. output of dmesg | tail (before mount changes): sd 6:0:0:0: [sdd] write protect off sd 6:0:0:0: [sdd] mode sense: 23 00 00 00 sd 6:0:0:0: [sdd] no

javascript - impress.js - bulleted list -

i have question concerning impress.js. wanted use bulleted list inside div element of class "step slide", not able this. is not possible or if is: point me mistake making? code use is: <div class="step slide" data-x="0" data-y="-1500"> <q>aaa</q> <ul> <li>aaa</li> <li>aaa</li> <li>aaa</li> </ul> </div> the text appearing not list. first of all, div doesn't have class of step slide, has class of step , class of slide - make 1 class, make them together: <div class="stepslide"> <div class="step-slide"> <div class="step_slide"> probably style overwriting ul , try adding in head tag: <style> .stepslide ul{ list-style-type: bullet !important; } </style>

linux - How to copy text to system clipboard in emacs while working in terminal buffer? -

i use emacs in text terminal environment manipulate text. in particular situations, however, want interact system's clipboard, example, copy text emacs website. possible yank text system's clipboard directly or emacs? how? terminal in emacs nothing buffer. if running terminal using eshell , can directly copy clipboard using m-w in normal buffer. if running terminal using ansi-term , yanking/copying little tricky. need go term-line-mode using c-c c-j copy whatever want , come term-char-mode using c-c c-k . see this answer more info.

javascript - Add time to date with angular -

in firebase have: firebase generated date created day. terms set user when above generated. so example have: 1439612582756 // formats to: aug 14, 2015 15 // formats to: "net 15" in code my code looks this: <td>{{invoice.settings.created | date}}</td> <td>{{invoice.settings.created + invoice.settings.terms | date}}</td> i have installed moment.js , 'angular-moment.js' able format , play dates, didn't see way add time date. for-each don't want have pre-scripting this. maybe custom filter add terms date? obviously, code above not function. made demonstrate wanting. any appreciated! update using page: http://momentjs.com/docs/#/durations/add/ came filter: .filter('dateterms', function() { return function(created, terms) { var = moment.duration(created, 'd'); var b = moment.duration(terms, 'd'); return a.add(b).days(); } }) but when call it, end 0 ?

java - What is a NullPointerException, and how do I fix it? -

what null pointer exceptions ( java.lang.nullpointerexception ) , causes them? what methods/tools can used determine cause stop exception causing program terminate prematurely? when declare reference variable (i.e. object) creating pointer object. consider following code declare variable of primitive type int : int x; x = 10; in example variable x int , java initialize 0 you. when assign 10 in second line value 10 written memory location pointed x. but, when try declare reference type different happens. take following code: integer num; num = new integer(10); the first line declares variable named num , but, not contain primitive value. instead contains pointer (because type integer reference type). since did not yet point java sets null, meaning "i pointing @ nothing". in second line, new keyword used instantiate (or create) object of type integer , pointer variable num assigned object. can reference object using dereferencing operator . (a dot

node.js - Browserify bundled node js file in chrome extension throws the following error. -

i'm new javascript, i'm trying build chrome extension scraper using node , html, here's part of code javascript file var request = require('request'); var cheerio = require('cheerio'); var href; var text; request("http://url", function (error, response, html) { if (!error && response.statuscode == 200) { var $ = cheerio.load(html); $("a.hp-article-link").each(function(i, element){ text = $(this).text(); href = $(this).attr("href"); console.log(text); console.log(href); } ); } }); if run code in console using node retrieves hrefs , corresponding text, when bundle using browserify , try browser throws cannot fetch absolute path error here's complete error in browser console fetch api cannot load chrome-extension://url. url scheme must "http" or "https" cors here's link images of console , line throwing error in concern http://i.imgur.com/46hk4tv.png?

javascript - Unable to display width of text -

i can't seem display width of text using jquery user fills in input box. followed jquery documentation . maybe missed can't seem see :( as text displayed keyup event, width should displayed text changes, right? further info, have been trying rebuild app this: text changing application here jsfiddle <!--form begin--> <form id="textchanger" onsubmit="return submitform();"> <p>preview:</p> <!--display user input--> <span id="text-preview"><p id="prev" class="form_result"></p></span> <p id="textcount"></p> <!--display width--> <p id="textwidth"></p> <label class="sign-text">enter text <input type="text" name="text" id="text" class="form-control enter-text-field validation-passed" value="enter text"> </label>

python - Pygame screen.blit not working -

in program creating in python/pygame, screen.blit not working. in other programs have made, screen.blit works. error: traceback (most recent call last): file "c:...\main.py", line 46, in <module> screen.blit(sight.image, sight.rect) attributeerror: 'int' object has no attribute 'blit' the error in question caused screen variable being allocated integer instead of pygame.surface() object.perhaps accidentally rewrote variable somewhere? from can make of doing, seems stating position of blit full rect instead of coordinate. when do: screen.blit(sight.image,sight.rect) what program seeing is: screen.blit(sight.image,(sight.rect.x,sight.rect.y,sight.rect.width,sight.rect.height)) i assuming don't intend this. remember rect object consists of position, width , height. to correct code, put (sight.rect.x,sight.rect.y) location goes instead this: screen.blit(sight.image,(sight.rect.x,sight.rect.y)) the .x , .y corres

matlab - Bald detection using image processing -

i wondering if can provide me guideline detect if person in picture bald or not, or better, how hair s\he has. far tried detect face , eyes position. information, estimate forehead , bald area cutting area above eyes high portion of face. then extract hog features , train system bald , not-bald images using svm . now when i'm looking @ test results, see pictures classified bald of them have blonde hair or long forehead hair not visible after cutting process. i'm using matlab these operations. so know method seems bit naive, can suggest way of finding out bald area or extracting hair, if exists. method appropriate kind of problem? very general, answer general unless further info provided use computer vision (e.g matlab computer vision toolkit ) detect face/head head has analogies (for human faces), using these 1 can area of head hair or baldness (it seems have these) calculate (probabilistic color space model) range skin of person lies (most peorple h

objective c - iOS - Core Data - Saving an object that contains an array of Objects -

i'm getting started core data, (and i'm trying use magical record). i'm creating pretty simple payment tracking app. i save payment object has array of debtors. payment object looks like @class debtor; @interface payment : nsobject @property (strong, nonatomic) nsstring *paymentamountstring; @property (strong, nonatomic) nsstring *titlestring; @property (strong, nonatomic) nsarray *debtorsarray; @property (strong, nonatomic) nsdate *duedate; @property (strong, nonatomic) nsstring *notesstring; @end and debtorsarray array of debtor objects @interface debtor : nsobject @property (strong, nonatomic) nsstring *namestring; @property (strong, nonatomic) nsstring *amountowedstring; how should go saving object since contains array. need create 2 different entities, relationship between payment , debtor? how do this, , how ensure fetched properly? create 1 entity payment . have use ' transformable ' data type attribute debtorsarray within entity. t

java - JComponent equivalent in LWJGL 3 -

i've been wondering if there's class in lwjgl 3 similar jcomponent can import , use game character. know blender models can imported easily, i'm wondering if there's way class extend overarching lwjgl class, overriding method in order display 3d object (in same way class might extend jcomponent , override paintcomponent(graphics)). lwjgl 3 doesn't yet support swing/awt, can't use actual jcomponents used to. help! no. lwjgl glfw(for opening windows), opengl(for using graphics card) , openal(for sound) java. you'll have learn opengl , write glsl shaders drawn.

Can we test if objects conforming to the same protocol are identical in swift without casting? -

i trying test if 2 objects generated factory identical, compiler not seem allow identity checking of objects merely conform same protocol. casting both objects anyobject seems fine however. there anyway avoid seems unnecessary casting? here simple example demonstrates seeing (in swift 1.2) protocol foobar { } class foo: foobar { } class bar { let foo1: foobar? let foo2: foobar? init() { foo1 = foo() foo2 = foo() if foo1! as? anyobject === foo2! as? anyobject { // fine } if foo1! === foo2! { // birnary operator '===' cannot applied 2 foobar operands } } } the identity operator === can applied references , i.e. instances of classes . if types conforming foobar protocol classes can declare "class protocol" protocol foobar : class { } then if foo1! === foo2! { ... } compiles , works expected, because compiler "knows" both operands references class instance.

php - Inserting data from user_table into currency_table -

i have 3 tables, currency_types , userdb , , user_currency . userdb has currency fields ( gold , sapphires , amethysts , garnets , , pkeys ). want move data in currency fields user_currency table. user_currency table has fields currency_id , , value fields. currency_id field related currency types . id` field. i thought making while loop each currency can't think of how finish , there must better way of doing not seeing. i know mysql_* deprecated. site being recoded use mysqli there no point in mentioning it. currency_types table: sql query: select * `currency_types` limit 0, 25 ; id name 1 gold 2 sapphires 3 amethysts 4 garnets 5 keys 6 f. stones 7 silk 8 leather 9 copper 10 cotton 11 iron 12 potions 13 silver 14 brass 15 steel 16 adamantine user_currency table: sql query: select * `user_currency` limit 0, 25 ; id user_id currency_id value userdb table: sql query: select `id`, `gold`, `sapphires`, `amethysts`, `garnets

jquery - Jasny offcanvas menu -

i'm using bootstrap jasny bootstrap ( http://www.jasny.net/bootstrap/ ). trying create navbar, off canvas menu 1 on android page http://www.android.com/switch/ . jasny menu closest 1 one: http://www.jasny.net/bootstrap/examples/navmenu/ . the problem face off canvas visible (fixed) when screen larger 992px , navbar hidden. android website want navbar present toggle button, , when toggle button clicked (on screen sizes) off canvas menu appears (just when screen size less 992px). how can have navbar , off canvas working on smaller screen sizes @ times? thanks lot in advance! this should started. $(document).ready(function() { var open = false; var opensidebar = function() { $('.side-collapse').addclass('open-side'); $('.navbar-toggle').addclass('open-side'); $('#navbar-toggle').addclass('open-side'); open = true; } var closesidebar = function() { $('.side-collapse')

Noflo-ui no runtime installed -

i followed instructions outlined online @ https://github.com/noflo/noflo-ui setup noflo-ui locally on device. build goes fine. however, when access webpage don't see local runtime registered. do have install runtime manually? yes, you'll need setup local runtime manually. please take @ following article instructions on how setup noflo runtime flowhub: http://docs.flowhub.io/article/84-getting-started-node-js

Select any position then Switch Player in JavaScript -

i trying write function allows me select position on board switch players. had attempted write loop either nothing appeared or positions filled "x". believe need stop loop iterating once position selected , created loop addeventlister. (js newbie- thanks!) function player1(){ for(var = 0; i<boardslots.length;i++) //iterate through positions if(boardslots[i].classlist !== "x" || "o"){ //check see if space occupied boardslots[i].classlist.add("x"); //add x player2(); //switch player 2 } } //player 2 selects o function player2(){ for(var = 0; i<boardslots.length;i++) if(boardslots[1].classlist !== "x" || "o"){ boardslots[1].classlist.add("o"); player1(); } } boardslots[i].addeventlistener("click",player1); //select position on board var count = 0; function move1(){ if(count % 2 === 0 && !this.classlist.contain

ruby - Model date validation in Rails -

i'm building calendar app , have problems date validations. want allow users make future events. after adding custom validator class event < activerecord::base belongs_to :user validates :name, presence: true validates :date, presence: true validate :future_event private def future_event errors.add(:date, "can't in past!") if date.parse(date) < time.now end end that's params debug event: !ruby/hash:actioncontroller::parameters name: new date: 08/17/2015 commit: add controller: events action: create and error: no implicit conversion of nil string . what's mistake? date.parse() expects string shown here . if saved :date in approprieate format should able do date < time.now

Facebook OG Sharing of Videos -

http://grandstandserver.herokuapp.com/post/yqjl (sample site) so users click on facebook button share specific post share url onto facebook, video not play after user shares post onto facebook. anyone trying click play button on video receives 'download file' link. suggestions? thinking maybe video player using plain tags, i've tried adjusting og tags.

search - AngularJS sort People into Alphabetical List and Filter -

in angularjs have object keys letters of alphabet , each key array of people. <div ng-repeat="(letter, group) in people"></div> <div ng-repeat="people in letter"></div> </div> this create in html: a. arnold, avery, adam, alex b. bob, boris c. chris, connor, caleb how go filtering each individual field name? example applying this. <div ng-repeat="people in letter | filter:{'name':search.query}"> works fine, however, result when type "a" in: a. arnold, avery, adam, alex b. c. how can collapse b , c? there better organization method data? the trick here store filtered names in scope variable can length check hide empty result. you can following markup: <div ng-repeat="people in filtered = (group | filter: search)"></div> then add ng-if="filtered.length > 0" tag want hide if result 0. please have @ demo below or in jsfiddle .

Python Numpy add hspace between 3D plot and 2D plot with shared axes -

Image
attached image showing current plot. setting fig.subplots_adjust(hspace=0) 2d plots share common x-axis. add space between 3d , 2d plots not quite sure how accomplish hspace set 0. fig.subplots_adjust(hspace=0) ax in [px_t, py_t, pz_t]: plt.setp(ax.get_xticklabels(), visible=false) in case, it's best use 2 separate gridspec instances. way can have 2 separate hspace parameters. alternatively, can manually place top axes. as example of first option: import matplotlib.pyplot plt mpl_toolkits import mplot3d fig = plt.figure(figsize=(8, 10)) gs1 = plt.gridspec(2, 1, hspace=0.2) gs2 = plt.gridspec(8, 1, hspace=0) ax1 = fig.add_subplot(gs1[0], projection='3d') ax1.plot(range(10), range(10), range(10)) ax = fig.add_subplot(gs2[4]) lower_axes = [ax] in range(4, 8): if > 4: ax = fig.add_subplot(gs2[i], sharex=lower_axes[0]) ax.plot(range(10)) ax.locator_params(axis='y', nbins=5, prune='both') lower_axes.appen

java - Spring Security Custom Login Error (on submit login processing url is not invoked) -

i new spring. in need of creating login module using spring security, while using custom login page on submit of form nothing happens , when debugging found getting error code 400 though sending right parameters. using spring 4.0.6.release , spring security 4.0.1.release. below spring security xml file, login.jsp , web.xml, in advance. security-context.xml <beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:security="http://www.springframework.org/schema/security" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd"> <security:http pattern="/static/**" security="

ruby - Weird Behaviors of datetime(timezone) in Rails application -

in our rails 3.2 application, have configured, config.time_zone = 'london' config.active_record.default_timezone = :local and in postgresql configured timezone "europe/london". for past 1 week, our application datetime field not working timezone. for example, if create reminder start_date @ 2015-08-18 10am . creates `2015-08-18 10:00:00 in postgres database. when displaying in template, reminder start date: 2015-08-18 10am (2015-08-18 10:00:00 +0100 ) but,(not always) showing utc time. reminder start date: 2015-08-18 9am (2015-08-18 09:00:00 utc ) it not reproduced in development. if restart unicorn server not occurring 4 hours. anyone faced kind of problem? i fixed issue, adding around filter in applicationcontroller . around_filter :use_time_zone private def use_time_zone(&block) time.use_zone('london', &block) end so, whenever default timezone changed utc , override , set bst .

javascript - How to append something in a specific element? -

how append created element in specific element? container = document.createelement( 'div' ); document.body.appendchild( container ); like this... document.getelementbyid('specific_ele').appendchild(container);

drawing - webGL : draw two separate rect with one buffer -

Image
my problem simple, build array 2 square coord : var vertices = [ -64, -32, 0.0, 64, -32, 0.0, 64, 32, 0.0, -64, -32, 0.0, -64, 32, 0.0, 64, 32, 0.0 ]; vertices.push( -64 + 200, -32, 0.0, 64 + 200, -32, 0.0, 64 + 200, 32, 0.0, -64 + 200, -32, 0.0, -64 + 200, 32, 0.0, 64 + 200, 32, 0.0 ); but resulting drawing looks : expected result should 2 separate rect black color between them. , don't understand behavior. when using triangle strips vertices implicitly indexed: draws series of triangles (three-sided polygons) using vertices v0, v1, v2, v2, v1, v3 (note order), v2, v3, v4, , on. ordering ensure triangles drawn same orientation strip can correctly form part of surface. if 1 want have separate triangles using triangle strips, 1 need add "stop vertices" generate degenerated triangle.

c++ - Qt 5, get the mouse position in a screen -

first of all, i'd mention found related post how mouse position on screen in qt? "just didn't work" me. made tests, , results didn't work expected, decided make new post talk test made , find alternative solution. that's code used make test: qscreen *screen0 = qapplication::screens().at(0); qscreen *screen1 = qapplication::screens().at(1); printf("screen0 %s \n", screen0->name().tostdstring().c_str()); printf("screen1 %s \n", screen1->name().tostdstring().c_str()); // position on first screen. qpoint pos0 = qcursor::pos(screen0); // position on second screen. qpoint pos1 = qcursor::pos(screen1); printf("pos 0: %d, %d \n", pos0.x(), pos0.y()); printf("pos 1: %d, %d \n", pos1.x(), pos1.y()); // position without screen. qpoint pos = qcursor::pos(); printf("pos: %d, %d \n", pos.x(), pos.y()); what expecting, 1 screen return valid position, since cursor @ 1 screen, not on both. it's not cas

java - what are the equivalent folders for values-small, values-normal, values-large, values-xlarge for API>=13? -

i want replace deprecated (from api 13 upwards) folders: values-small values-normal values-large values-xlarge by values-sw(n)dp and/or values-sh(n)dp folders. since docs say: small screens @ least 426dp x 320dp normal screens @ least 470dp x 320dp large screens @ least 640dp x 480dp xlarge screens @ least 960dp x 720dp can confirm correct (if only width considered): values-small = values-sw426dp values-normal = values-sw470dp values-large = values-sw640dp values-xlarge= values-sw960dp since deprecated folder-structure considers hight , docs combining possible: if available height concern you, can same using h(n)dp qualifier. or, combine w(n)dp , h(n)dp qualifiers if need specific. what combined equivalent folders mentioned ones? cannot find example of combined folder.... thank you! the adaptive ui material design guidelines measure things out in terms of device width alone, noting number of breakpoints: 600d

javascript - how to dynamically add REQUIRED attribute to input tags based on output of select tag using jquery? -

i have select tag 2 options 'new' , 'edit' when selects 'new' option input tags in form should marked required , when selects 'edit' few should marked required. <select name="todo" id="todo" required> <option value="">---</option> <option value="new">add</option> <option value="edit">edit</option> </select> now tried functions don't seem work <script> var todo = $('#todo option:selected').text(); if (todo == "new") { $('#name').attr('required',true); } else if (todo == "edit") { //code } </script> and <script> function req() { var selectbox = document.getelementbyid('todo'); var userinput = selectbox.options[selectbox.selectedindex].value; if (userinput == 'new') { $('#name').attr('required',true); }

WPF ControlTemplate Trigger -

all, trying set template window. want change margin , border thickness depending upon state of window. trying using trigger, when run application, triggers don't fire. question is, how can make triggers fire when window state changed? the xaml have (i have removed of code keep posting simple): <window x:class="wpfapplication1.mainwindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:wpfapplication1" background="#ffe8e8e8" style="{dynamicresource chromewindowstyle}" mc:ignorable="d" title="basewindow" width="500" height="300"> <windowchrome.windowchr

java ee - JPA data access object - exception handling and rollback -

i'd know best way of exception handling in data access objects is, i'm interested in production quality code. as example public userdaoimpl implements userdao{ @persistencecontext private entitymanager em; void save(user user){ em.persist(user); } user getbyid(long id){ return em.find(user.class,id); } } let's example have registerservice somewhere @ point i'd save user database. , each user needs have unique email. how check , code go ? check if there's user email in save method using queries before persisting? or code go service? or maybe try catch exceptions? but exceptions far know we'd never know sure happened, try catch constraintviolationexception doesn't tell explicitely happened. how in production quality code? let's example have registerservice somewhere @ point i'd save user database. , each user needs have unique email. how check , code go ? check in same transaction y

java - How do I print a sorted array? -

this question has answer here: what's simplest way print java array? 24 answers the following code supposed sort array initialized below. int[] intarray = { 32, 42, 1, 23, 56, 75, 32, 23 }; int temp = 0; (int = 0; < intarray.length; i++) { (int j = 1; j < intarray.length; j++) { if (intarray[j - 1] > intarray[j]) { temp = intarray[j - 1]; intarray[j - 1] = intarray[j]; intarray[j] = temp; } } } what should type sorted array , should type it? i have tried options such system.out.println(temp) between last 2 closing brackets , 1 before those, not getting values printed, , 32 printing many times instead. writing code system.out.println(j) or system.out.println(i) in same area doesn't work either. can explain why these codes don't work? if want print sorted array, print elements in loop after array