Posts

Showing posts from February, 2015

javascript - How can I instantiate an ArrayBuffer from a hexadecimal representation of an octet stream? -

i have binary information coming on tcp connection (websocket). traced console in encoded format so: 53 54 41 52 54 45 44 3a 31 34 32 38 36 30 32 30 38 37 i presume hex encoding of each of bytes. the information protocol buffer information. write function decode using library have. first step me create buffer object of kind encapsulate binary information supply library. i not yet know precise type expectation of library, expects binary buffer of sort. the protocol buffer decoding library api looks so: library.bytebuffertoresponse(buffer); how can instantiate "binary buffer" of kind hexadecimal representation of octet stream? var octetstream = '34 36 10 04 1a 05 0a 01 30'; var arraybuffer = new arraybuffer(); // how can initialize binary data? you'll want use typed array access buffer. can directly put array literal have constructor, construct buffer or appropriate size. like body=53 54 41 52 54 45 44 3a 31 34 32 38 36 30 32 30 3

I am getting space between jquery mobile menus -

Image
why getting space between listview menu here code <script id="panel-init"> $( document ).on( "pagecreate", function() { $( "body > [data-role='panel']" ).panel(); $( "body > [data-role='panel'] [data-role='listview']" ).listview(); }); $( document ).one( "pageshow", function() { $( "body > [data-role='header']" ).toolbar(); $( "body > [data-role='header'] [data-role='navbar']" ).navbar(); }); </script> html: <div data-role="header" data-position="fixed"> <h3>order</h3> <a class="ui-btn ui-btn-left ui-btn-icon-notext ui-icon-back" data-rel="back"></a> <a class="ui-btn ui-btn-right ui-btn-icon-notext ui-icon-bars" href="#rightpanel"></a> </div> here

javascript - Best Way to Have Webpack Manage Quirky AMD Defines -

i'm working large js module base (for front-end code) uses amd style definitions. typically this: define('twittermodule', [ 'vendor/jquery/jquery', 'vendor/moment/moment', 'vendor/jquery/jquery.ie.cors' ], function ($, moment) { ... the problem dependency declarations don't represent dependencies are. without directory resolution magic: define('twittermodule', [ __dirname + '/vendor/jquery/content/scripts/jquery', __dirname + '/vendor/moment/content/scripts/moment', __dirname + '/vendor/jquery/content/scripts/jquery.ie.cors' ], function ($, moment) { ... so i'm trying figure out cleanest way resolve these directory problems. namely, define root path , inject '/content/scripts' part paths webpack receives. webpack resolve , webpack shims possibly solve this, i'm looking feedback has experience addressing weird amd definitions keep me focused on best possible solution.

Input 5 elements into array, check validation then output C++ -

i'm working on project required me input 5 numbers 20-101 one-dimensinal array. after that, shows output of 5 numbers. if enter non-numeric/float number/duplicate/out-range, reject , ask user input again. have try , catch codes. also, program able shows bad input @ end. here got far , got stuck, i'm totally lost. check out-range numbers int arrayreader::checkinput(int number) { if (number >= 20 && number <= 101) { return number; } else { throw invalid_argument("out-range-number entered"); } } main code #include <iostream> #include <stdexcept> #include <iomanip> #include "arrayreader.h" using namespace std; int main() { arrayreader value; int number = 0; int dup; int array[5]; int currentarray = 0; cout << "enter number 20 - 101: "; (int = 0; < 5; i++) { cin >> number; dup = 0; if (number >

Python 3 - sum of all numbers in a file -

i have directory consisting of many files, each having of format : vertie,f,5 wilma,f,17 john,m,11 william,m,15 for files need check if particular name occurs @ specific line number. if sum of 3rd column 'f'. i have written following code doesn't seem work : f1 = open('abc.txt') f2 = open('abc.txt') i, line in enumerate(f1): line = line.strip() name, sex, count = line.split(',') if == 2 , name == 'wilma': line in f2: line = line.strip() name, sex, count = line.split(',') if sex == 'f': result += int(count.strip()) any tips going wrong? any reason you're using python this? it's pretty simple in awk : awk -f, 'begin{sum=0}/wilma/{sum+=$3} end{print sum}' file1 file2 ... edit based on comment : safe, can explicitly check first

java - Conditions regarding parsed integer from JTextField -

in program value of jtextfield , parse integer: string string = jtext.gettext(); int stringval = integer.parseint(str); my question how i'm able check if value parsed integer? tried this, didn't hold results wished accomplished , received errors. if(str == null) { joptionpane.showmessagedialog(null, "integer not parsed", "message", joptionpane.information_message); } if wasn't able parsed int throw exception. try using try catch statement boolean tryparseint(string value) { try { integer.parseint(value); return true; } catch(numberformatexception nfe) { return false; } } you use this if(tryparseint(myinput)) { integer.parse(myinput); } or if want without method int stringval; bool success = true; try { stringval = integer.parseint(str); } catch (numberformatexception nfe) { success = false; joptionpane.showmessagedial

Oracle SQL pull data for a selected date from a table that is daily partitioned -

what pull data set busy hour on every friday 1 year period. have used following query: select to_char(datetimelocal,'dd/mm/yyyy hh24:mi:ss'), cola,colb,colc,cold schema_x.table_y datetimelocal between '1-apr-2014' , '1-apr-2015' , to_char(datetimelocal,'d')=6 , to_number(to_char(datetimelocal,'sssss')) between 57600 , 64800 this query worked, got following warning message system admin have exhausted system resources. "there user xxx running query on schema_x tables , scanning whole table , not doing partition pruning. user should use partitioned field reduce date range, big" i found table_x daily partitioned, don't know how use partitions wisely reduce system load. partitions this: partition_name,high_value,high_value_length,tablespace_name,compression,num_rows,blocks,empty_blocks,last_analyzed,avg_space,subpartition_count 20121230,to_date(' 2012-12-31 00:00:00', 'syyyy-mm-dd hh24:mi:ss',

ios - Programatically autolayout not centering vertically -

Image
i want use autolayout center view vertically , horizontally somehow i'm having troubles doing so. i'm running on ios8 simulator , ios8 device. there 2 versions of code have tried , none of them works. below snippets: first let's allocate view we're using: uiview *inputview = uiview.new; //don't hate me dot syntax :) inputview.translatesautoresizingmaskintoconstraints = no; inputview.backgroundcolor = uicolor.redcolor; [self.view addsubview:inputview]; attempt #1: nslayoutconstraint *constraint = [nslayoutconstraint constraintwithitem:inputview attribute:nslayoutattributecenterx relatedby:nslayoutrelationequal toitem:self.view attribute:nslayoutattributecenterx multiplier:1.0f constant:0.0f]; //center view horizontally [self.view addconstraint:constraint]; constraint = [nslayoutconstraint constraintwithitem:inputview attribute:nslayoutattributewidth relatedby:nslayoutrelationequal toitem:self.view attribute:nslayoutattributewidth multiplier:1.0f constan

java - Automating IE8 download window using WinApi -

my current task automated testing of enterprise web-based software suite using selenium on java. i've more or less done trick using jna , winapi, unfortunately, i've hit nasty snag. while changing path download location via wm_settext message, visual content of file path changes, , after clicking save button still saves suggested location. gives? is there way can make ie8 think entered path manually, or, perhaps send other message trigger processing of changed address? a little background: unfortunately, selenium cannot handle file downloads, , need verify validity of to-be-downloaded file simple http 200 code check not suffice. automatic file downloading out, i'm stuck ie8, not support it. direct http requests out - sso authentication , https have caused many problems down research vector. p.s.: unfortunately, cannot provide direct code snippet due nda, proprietary limits , other dull limitations...

c# - How do I store Excel File without getting the warning -

i trying replace file gives me warning: the file exists. want replace file in code, not want warning code: string fromfile = @"\\test.net\excel\123.xls"; string tofile = @"\\test.net\excel\123.xls"; microsoft.office.interop.excel.application app = new microsoft.office.interop.excel.application(); microsoft.office.interop.excel.workbook wb = app.workbooks.open(fromfile, type.missing, type.missing, type.missing, type.missing, type.missing, type.missing, type.missing, type.missing, type.missing, type.missing, type.missing, type.missing, type.missing, type.missing); file.delete(tofile); wb.saveas(tofile, microsoft.office.interop.excel.xlfileformat.xlworkbookdefault, type.missing, type.missing, false, false, microsoft.office.interop.excel.xlsaveasaccessmode.xlexclusive, microsoft.office.interop.excel.xlsaveconflictresolution.xllocalsessionchanges, false, type.missing, type.missing, type.missing); wb.close(false, type.missing

How to delete a folder in Android Studio emulator by using Android Device Manager? -

android device manager's file explorer lets me delete number of files on avds refuses rid of folders. specifically, minus sign icon hovering tooltip says "delete selection" stays grayed out no matter do. short of writing utility app i'm out of options :\ suggestions? little nifty command-line wizardry, perhaps? how delete folder in android studio emulator using android device manager? that's not available, sorry. ideally, be. a little nifty command-line wizardry, perhaps? adb shell gives linux shell onto device or emulator, so... adb shell rmdir /whatever/the/directory/path/is would remove /whatever/the/directory/path/is . note adb program in sdk's platform-tools/ directory.

string - Why does the output of this C++ program produce a giant mess in cmd? -

i have since figured out how make program correct, wondering why incorrect program question follows produces whole bunch of characters , different machine information, , if such error damage machine: exercise 3.10: write program reads string of characters including punctuation , writes read punctuation removed. #include <iostream> #include <string> using std::string; using std::cin; using std::cout; using std::endl; int main() { string s("some! string!s."); (decltype(s.size()) index = 0; index != s.size(); ++index){ if (!ispunct(s[index])){ cout << s[index]; ++index; } else { ++index; } } return 0; } now, know incorrect, , have since made version correctly output needed: #include <iostream> #include <string> using std::string; using std::cin; using std::cout; using std::endl; int main() { strin

plot - Interpolating the end points in Matlab's polarPlot -

Image
i managed connect end points in normal polarplot data([1:end 1],1) but doing interpolation not interpolate extended path data = load('rem_angle_2.dat'); n = 30; phi = interp(data([1:end 1],1)*pi/180, n); h = interp(data([1:end 1], 3), n); mu = 4 * 3.14e-7; ms = 1.2e6; k = 4.5e4; h = mu .* ms .* h / (2 .* k); cosphi = h .* abs(cos( phi )) + (cos( phi ) ) .^2; polar(phi, cosphi, 'r-x'); example output in red circle data 0 0.0314410000000000 0.940571096308908 15 0.0349230000000000 0.969954146597296 30 0.0313780000000000 0.839337718198396 45 0.0248700000000000 0.745214472624085 60 0.0231580000000000 0.478142525177060 75 0.0199550000000000 0.296548109978132 90 0.0270400000000000 0.155780680534267 105 0.0203080000000000 0.344801658689296 120 0.0254600000000000 0.592786274973634 135 0.0290010000000000 0.754378087574740 150 0.0238800000000000 0.834979038161321 165 0.0208110000000000 1.07503919352428 180 0.0312170000000000 0.950446840

R linear model category to dummy variables -

i have r linear model created 7 dummy variables factor 8 levels. understand why there 7 variables, don't understand how relate them original data's levels based on names. extensions .l .q .c ^4 ^5 , ^6 mean? quality.l quality.q quality.c quality^4 quality^5 quality^6 i trying convert fitted model executable formula in ruby can run predictions in rails after model built in r.

c# - Remove controlBox, minimizeBox, and maximizeBox in full screen -

Image
i trying create interface has mdi child forms open in full screen mode within parent , controlbox, minimizebox, , maximizebox show in full screen though have them set false. know how fix this? here code using switch between screens (children forms) should open in full screen mode because default set them with, need rid of minimize, maximize, , control buttons. public partial class parent : form { form activeform = new form2(); public parent() { initializecomponent(); } private void parent_load(object sender, eventargs e) { activeform.mdiparent = this; activeform.show(); } private void toolstripbutton1_click(object sender, eventargs e) { if(toolstriptextbox1.text == "1") { activeform.close(); activeform = new form2(); activeform.mdiparent = this; activeform.show(); } if (toolstriptextbox1.text == "2") {

node.js - Watson User Modeling service returns error "Cannot read property '0' of undefined when reading from VCAP_SERVICES -

it seems watson user modeling service removed application. i'm getting following error in app. 2015-04-09t15:23:38.44-0400 [app/0] err /home/vcap/app/lib/config.js:33 2015-04-09t15:23:38.44-0400 [app/0] err return vcapservices["user_modeling"][0].credentials.url; 2015-04-09t15:23:38.44-0400 [app/0] err ^ 2015-04-09t15:23:38.44-0400 [app/0] err typeerror: cannot read property '0' of undefined 2015-04-09t15:23:38.44-0400 [app/0] err @ object.watsonurl (/home/vcap/app/lib/config.js:33:53) 2015-04-09t15:23:38.44-0400 [app/0] err @ getpersonality (/home/vcap/app/lib/app.js:203:25) 2015-04-09t15:23:38.44-0400 [app/0] err @ async.waterfall.personalityuser1 (/home/vcap/app/lib/app.js:278:13) 2015-04-09t15:23:38.44-0400 [app/0] err @ fn (/home/vcap/app/node_modules/async/lib/async.js:641:34) 2015-04-09t15:23:38.44-0400 [app/0] err @ object._onimmediate (/home/vc

python - error 400 - bad request when trying to set q search parameter in Soundcloud with Scrapy item -

im trying search soundcloud track related artists name. works if type artist name in q search parameter, want use item ['artist'] variable. think theres prbably simple programming error causing 'bad request' error. here relevant code. guys!! def parse_me(self, response): info in response.xpath('//div[@class="entry vevent"]'): item = tutorialitem() # extract items items folder. item ['artist'] = info.xpath('.//span[@class="summary"]//text()').extract() # extract artist information. #item ['genre'] = info.xpath('.//div[@class="header"]//text()').extract() yield item # retreive items in item client = soundcloud.client(client_id='xxxx', client_secret='xxxx', callback='http://localhost:9000/#/callback.html') tracks = client.get('/tracks', q=item['artist'], limit=1) track in tracks: print tr

datatable - How to "join" with the split-apply-combine method in Julia -

i have complex join (in sql sense) perform in julia, can't figure out how working in split-apply-combine method (although can written out hand). seems should easy though. problem looks this. have dataframe of data on turtles running races: using dataframes data = dataframe() data[:turtle] = ["suzy", "suzy", "bob", "batman", "batman", "batman", "bob"] data[:event] = ["5k", "5k", "1k", "5k", "5k", "1k", "1k"] data[:time] = [6.2 , 6.7 , 2.1, 3.2, 3.1, 0.9, 2.4] data[:photo] =["111.jpg","123.jpg","145.jpg","167.jpg","189.jpg","190.jpg","195.jpg"] data i datatable consists of rows of table each turtle's personal (turtlenal?) best in event ran. can need bestfinishes = by(data, [:turtle, :event]) df dataframe(fastesttime = minimum(df[:time])) end but need ph

java - Swing GridBagLayout - Alignment issue -

Image
i have jpanel jlabel, jtextfield , jpanel jlabel in it. createdomainpanel = new jpanel(new gridbaglayout()); gridbagconstraints gbc = new gridbagconstraints(); //createdomainpanel.setsize(600, 300); gbc.fill=gridbagconstraints.horizontal; gbc.gridx=0; gbc.gridy=0; createdomainpanel.add(new jlabel("enter name of domain"), gbc); gbc.gridx=0; gbc.gridy=1; createdomainpanel.add(domainname, gbc); jpanel result = new jpanel(new flowlayout()); result.add(successmessage); gbc.anchor=gridbagconstraints.last_line_start; gbc.gridx=0; gbc.gridy=2; createdomainpanel.add(result); the last jlabel result prints success message after operation. public void actionperformed(actionevent e) { simpledbconnect dbc = new simpledbconnect(); string name = ""; if (e.getsource()==domainname){ name=e.getactioncommand(); boolean success = dbc.adddomain(name);

android - How do I find out which is clicked on my ActionBar MenuItem? -

how know if item clicked? since understand if, event a occur following button of actionbar clicked, how implement such thing? the method creating in onoptionsselected(menuitem item) method works onclicklistener buttons. it asks id of menu item trough method getitemid() , handles each item specific click. example starting settingsactivity, when settings menu clicked but check out tutorial of comments further information. the code need implement it: @override public boolean oncreateoptionsmenu(menu menu) {     // inflate menu items use in action bar     menuinflater inflater = getmenuinflater();     inflater.inflate(r.menu.main_activity_actions, menu);     return super.oncreateoptionsmenu(menu); } @override public boolean onoptionsitemselected(menuitem item) {     // handle presses on action bar items     switch (item.getitemid()) {         case r.id.action_search:             opensearch();

node.js - How to setup gulp browser-sync for a node / react project that uses dynamic url routing -

i trying add browsersync react.js node project. problem project manages url routing, listening port , mongoose connection through server.js file when run browser-sync task , check localhost url http://localhost:3000 cannot / . is there way force browser-sync use server.js file? should using secondary nodemon server or (and if how can cross-browser syncing work)? lost , examples have seen add more confusion. help!! gulp.task('browser-sync', function() { browsersync({ server: { basedir: "./" }, files: [ 'static/**/*.*', '!static/js/bundle.js' ], }); }); we had similar issue able fix using proxy-middleware( https://www.npmjs.com/package/proxy-middleware ). browsersync lets add middleware can process each request. here trimmed down example of doing: var proxy = require('proxy-middleware'); var url = require('url'); // base url forward request

mysql - SQL - merge 2 columns into 1 from separated tables (not concat) -

baisicly want take 2 table 2 columns have same information , combine them 1 table has 1 column data other 2. i explain example: table 1 id | number | 1 | 100 | 2 | 150 | 3 | 160 | 4 | 170 | table 2 id | number | 1 | 110 | 2 | 120 | 3 | 130 | 4 | 180 | result (with sql query using select, can check result): number 100 150 160 170 110 120 130 180 select number table_1 union select number table_2 or union instead of union all if want remove duplicated values

Android Action Button Icons are missing -

i'm new android & attempting follow tutorials. initial tutorial going hit one https://developer.android.com/training/basics/actionbar/adding-buttons.html where i'm finding can't action buttons display icon. if set android:showasaction="always" in attempt workaround issue started similar tutorial http://www.androidhive.info/2013/11/android-working-with-action-bar/ but ended hitting same issue. i'm using api 11 & not going near support bundle. can text menu items appear in drop down. can't seem icons. i tried both sets of icons action bar icon set. res folder has following drawable structure - drawable - drawable-hdpi - drawable-mdpi - drawable-xhdpi - drawable-xxhdpi with nothing in drawable & appropriate icons in other folders. this seems such basic step i'm surprised i'm stuck. any suggestions? edit: adding code suggested mainactivity.java package com.example.gannons.actionbar; import android.support

php - WooCommerce create new attributes programmatically -

how can create attributes woocommerce plugin? find : wp_set_object_terms( $object_id, $terms, $taxonomy, $append); from this stack-question but approach required id of product. need generate attributes not attached products. to create term can use wp_insert_term() like so: wp_insert_term( 'red', 'pa_colors' ); where colors name of attribute. taxonomy name of attribute prepended pa_ . edit attributes merely custom taxonomies. or dynamic taxonomies manually created user in back-end. still same custom taxonomy rules apply. you can see source code here loops through attributes , runs register_taxonomy() on each. create new attribute (remember taxonomy) need run register_taxonomy() , simple prepend pa_ start of taxonomy name. mimicking of values of taxonomy args core, 'colors' attribute. add_action( 'woocommerce_after_register_taxonomy', 'so_29549525_register_attribute' ); function so_29549525_register_attribute

angularjs - ui-router reinitializing angular controllers on state change -

is there easy way using ui-router force controllers initialized once? singleton. of right now, every time change state, controller linked state reinitialized. don't want happen. seems should simple, not find solution anywhere online. a common way handle things one-time or global operations have application level controller on element wraps ui-views: <html ng-app="app"> <head>...</head> <body ng-controller="applicationcontroller"> <div ui-view></div> </body> </html> applicationcontroller can reponsible one-time operations. gets initialised once (when app starts) , persist between route , state changes. the controllers associated states should concerned constructing own views, not performing one-time operations. if state controllers need access shared data, data should stored in service suggested abos. state controllers should request shared data service, , service should 1 deci

asp.net mvc - Kendo DataSource read() fails because of redirection for authentication -

i have mvc website uses kendo controls in many of views. the code - view @(html.kendo().multiselectfor(model => model.certificateids) .htmlattributes(new { style = "width: 140%" }) .datatextfield("certificatename") .datavaluefield("certificateid") .placeholder("select certificates") .datasource(source => { source.read(read => { read.action("getcertificates", "account"); }); }) ) controller [httpget] [outputcache(duration = int.maxvalue, location = outputcachelocation.any)] public jsonresult getcertificates() { return json(_accountsmanager.getallcertificates(), jsonrequestbehavior.allowget); } the problem - read.action() should certificates me, , 9 ou

memory - Android onSaveInstanceState Bundle -

when android kills process due system constraints gives ability persist data across processes storing data in bundle. bundle saved if process killed? process live in? in memory live in? live in kernel memory? kernel memory protected memory space critical code kernel code reside. prevent interference of data user , of kernel , other performance , design reasons. kernel memory persist through reboot. the data being persisted in bundle passed in method of onsaveinstancestate() - before user leaves activity not before activity gets destroyed. means memory not written in static memory area memory card. bundle indeed persisted in more dynamic way. while question has not been directly answered, looks memory on ram. when @ performance of android devices, more recent devices more ram seem capable of holding on apps longer from official documentation @ http://developer.android.com/training/basics/activity-lifecycle/recreating.html , understood memory tracked android itself.

javascript - Trying to Mask a Page: Postion Absolute & fixed ruin formatting -

i'm trying create loading image masks page (when call made). i'm using handlebars, html, css, , javascript. i have .hbs page looks this: <div id="spinner"></div> <div class="special-container"></div> <div class="special-container"></div> which filled in javascript puts content each of above containers, spinner , special-container. (made names forgive me if there ever typo) what pushed spinner div following: <div id="mask"> <div id="spinner"> hello world spinner page <span class="icon icon-house margin-right-10" ></span> </div> </div> i have .less file contains css. looks this: .special-container { max-width: 1170px; position:absolute; // have tried position:fixed; } #spinner { position: relative; z-index: 100; } when render page above code first div (spinner) above 2 other divs on top of each o

sql - Rails code readability for my validation -

the code works fine in detecting overlapping dates not save booking if exist given room. however, had twist code make work because validation make update in controller not valid instead of save . want know wrong code not valid should apply save , not update. in fact, tell me booking cannot saved instead of throwing error, did not update booking.end_date in contoller while should raise error when save , not when try update it: i have controller create new booking room (this want improve): def create_book_now @room = room.find(params[:room_id]) booking = @room.bookings.build(booking_params) if booking.save #i want not save if model validation not ok if @room.bookings.last.update(end_date: booking.start_date + booking.length.days) # have check if true validation work, sure not normal flash[:notice] = "booking done" redirect_to root_path else flash[:error] = "booking.errors.full_messages.first if booking.errors.

CSS: Image scaling issue with flexbox in Firefox/Internet Explorer -

i'm trying use flexbox place 2 images side side in content flow. in chrome/safari scales images properly, in firefox/ie aspect ratio not respected , images distorted. overall width of content flow depends on width of browser. images therefor needs readjust window gets narrower. this how looks in chrome/safari (webkit): aspect ratio respected http://pluto.justdied.com/w2box/data/chrome.png while how looks in firefox/internet explorer: image stretches http://pluto.justdied.com/w2box/data/exhibit.png this 2 column view comes in long line of images. the html markup: <div class="grid"> <img src="../images/mille_bornes_02.jpg"> <img src="../images/mille_bornes_08.jpg"> </div> and css follows: .grid { z-index: 1; margin: 0px 0px 16.5px; position: relative; flex-direction: row; width: 100%; height: 100%; display: flex; padding: 0; border: 0; } .grid img { position: relative; display: block

file - In Windows, why are some characters illegal? -

as of know, windows bans following characters in file names: * . " / \ [ ] : ; | = , linux, , other unix based systems, ban \0 (the null character) , / (the path separator) reasons seem obvious. why windows have many banned characters? i've looked, , every answer find variation of "is valid" or "what valid", nothing discussing design decisions caused windows (dos?) team make them illegal. to take them in order: * prohibited because win32 wildcard character. note unlike linux, wildcards processed api, not shell. . not prohibited (obviously!) although have special semantics when appears @ end of file name, i.e., removed. backwards compatibility fat file systems and/or applications designed them. " kernel wildcard character . the backward slash path separator, , forward slash treated path separator (sometimes) compatibility unix. [ , ] not prohibited. : is used indicate alternate data stream . ; not prohibited. |

How to change cursor to "finger pointer" when rolling over hide/show text (javascript) -

on website have hide/show javascript (below). used commonly in faqs see list of questions , when rolling on question changes color , clicking on opens text. i cursor change "finger pointer" (the usual shape of when linked) when rolling on text. what should added code below? the words text represent various text put in specific site. thank you! <a onclick="javascript:showhide('item')"> text </a> <div class="mid" id="item" style="display: none;"><p> text </p></div> <br> <script type="text/javascript">// <![cdata[ function showhide(divid) { if(document.getelementbyid(divid).style.display == 'none') { document.getelementbyid(divid).style.display='block'; } else { document.getelementbyid(divid).style.display = 'none'; } } // ]]> </script>

php - Getting Content from Specific Column in Row -

ok, straight point, table: http://i.gyazo.com/a9e71a1ecb7030cb2dc75d2ed431dbae.png and want display content row id 1 , column content. (more rows in there soon), , want display id 2, etc on different pages. this code have far: <?php include 'databaseconnect.php'; //- queries table content rows - $queryselect = "select title,tags,content,image pages;"; //----------------- query table, store content in php variable ----------------- $result = mysql_query($queryselect); //-------------- store content id = 1 in array -------------- ------------------- include 'logo.html'; while($row = mysql_fetch_array($result)){ //- main content - echo '<div class="wrapper">'; ?> <?php echo '<div class="imagecontainer">'; echo $row['content']; echo'</div>'; echo'</div>'; } ?> this display content row, other pages how use id display content second row in t

do ios webviews check urls for malware before opening them? -

if open arbitrary urls in ios application, have own malware/phishing/etc... checks? webview (implicitly) work on behalf (or have switch setting somewhere?)? in short: no. uiwebview has restricts javascript same-origin policy, , ios has it's own ssl certificates validation (tls chain validation) can uiwebview little bit safe. if want check malware, phisinng, ... you're free it.

javascript - Converting milliseconds while detecting single digit integers -

i created function detects , converts milliseconds minutes , seconds. i'd prepend 0 on either (or both) minute , second variables if number comes out less ten. instance if had integer 184213 evaluates 3:4 i'd 03:04 . there short , concise way without having write out long conditional or ternary? mstotime(184213); function mstotime(milliseconds) { var minutes = parseint(milliseconds/(1000*60)%60), seconds = parseint((milliseconds/1000)%60); return minutes + ':' + seconds; } a different approach utilizing date , slice : function mstotime(milliseconds) { var date = new date(milliseconds); return date.totimestring().slice(3,8); } mstotime(184213); // outputs: "03:04" a small caveat of course have limit of "23:59" , floor value milliseconds value on minutes not shown.

c# - Opacity Mask Direction Top to Bottom? -

i fade text of wpf textbox top down. not left right. there way in xaml? below have far <textbox x:name="txtdesc" text="{x:static model:carmanager.desc}" verticalalignment="top" horizontalalignment="left" textwrapping="wrap" verticalscrollbarvisibility="auto" width="466" fontweight="bold" height="263" margin="304,195,0,0" borderbrush="{x:null}" borderthickness="0" background="{x:null}"> <textbox.foreground> <lineargradientbrush endpoint="0.5,1" startpoint="0.5,0"> <gradientstop color="#ff8f8f8f" offset="0"/> <gradientstop color="white"/> </lineargradientbrush> </textbox.foreground> <textbox.opacitymask> <lineargradientbrush startpoint="0,0" endpoint=&q

java - Performance of ArrayList vs HashSet -

i know prefer arraylist on hashset when need store duplicates, , hashset uses hashcode() function calculate index each element in array. so, means if want store single element, arraylist should take less time hashset . please correct me if wrong anywhere. but when checking performance through code getting different behavior. case 1: import java.util.*; class hashsetvsarraylist { public static void main(string args[]) { arraylist<integer> a1=new arraylist<integer>(); long nanos = system.nanotime(); a1.add(1); system.out.println("arraylist time:"+(system.nanotime()-nanos)+"ns"); hashset<integer> h1=new hashset<integer>(); nanos = system.nanotime(); h1.add(2); system.out.println("hashset insertion time:"+(system.nanotime()-nanos)+"ns"); } } output: arraylist time:495087ns hashset insertion time:21757ns case 2: import java.util.*; class hashsetvsarraylist { public static void m

java - Can't make any sort of Database type connecction on Netbeans 8.0.2 -

i have spent hours looking through forums , other sites try find solution problem. i've tried countless number of things try , fix it, it's still not working. i've pretty come conclusion netbeans program cannot make sort of connection beyond opening programs. see started when tried create new database. window opened, filled out information, , got error said "an error occurred while creating database: java.sql.sqlnontransientconnectionexception:java.net.connectionexception : error connectingto server localhost on port 1527 message connection timed out: connect.." i tried connect sample database comes netbeans , database wouldn't connect. i've tried , need help. before ask, yes have opened port, yes tried changing security file have suggested, yes have tried making new connection(which didn't work way), yes have tried creating database through coding in project (didn't work), , yes have played around proxy setting in tools>options>gener

Azure Remote App: Import Excel Range Into Access -

i have following code within form startup procedure in access front end accessing sql end. code below, opens excel file, goes data tab , retrieves value named range, works fine. however, when migrate front end azure image , publish in remote desktop, while value retrieved , updated database, procedure hangs up. using alt-ctl-end open task manager, find excel still open, , need end task on excel before access front end moves forward in procedure. hunch, excel waiting response on something, there no dialogs open deal with. ideas? set xl = createobject("excel.application") set xlbook = xl.workbooks.open(srwfile) set xlsheet = xlbook.worksheets("data") xl.visible = false xlbook.windows(1).visible = false xlsheet dvalue = .range(srwrange) end xlbook.close , true set xlsheet = nothing set xlbook = nothing set xl = nothing

swift - All stored properties of a class instance must be initialized before returning nil from an initializer -

i'm trying use code in class though keep on getting above message. let filepath: nsstring! let _filehandle: nsfilehandle! let _totalfilelength: cunsignedlonglong! init?(filepath: string) { if let filehandle = nsfilehandle(forreadingatpath: filepath) { self.filepath = filepath self._filehandle = nsfilehandle(forreadingatpath: filepath) self._totalfilelength = self._filehandle.seektoendoffile() } else { return nil //the error on line } } how fix don't error: all stored properties of class instance must initialized before returning nil initializer you can make work variables , call super.init() (for creating self before accessing properties): class test: nsobject { var filepath: nsstring! var _filehandle: nsfilehandle! var _totalfilelength: cunsignedlonglong! init?(filepath: string) { super.init() if let filehandle = nsfilehandle(forreadingatpa

ios - uiscrollview's autolayout,The view hierarchy is not prepared for the constraint -

i want add scrolling imageviews scrollviews using autolayout. the view hierarchy folllows: ---| |---placeholder view |---scroll view the code follows: -(uicollectionviewcell*)collectionview:(uicollectionview *)collectionview cellforitematindexpath:(nsindexpath *)indexpath { static nsstring* identifier = @"wcollectionviewcell"; wcollectionviewcell* cell =[collectionview dequeuereusablecellwithreuseidentifier:identifier forindexpath:indexpath]; cell.imagescrollview.backgroundcolor=[uicolor orangecolor]; uiimageview* imageview1 = [[uiimageview alloc]init]; imageview1.image =[uiimage imagenamed:@"1.jpg"]; imageview1.translatesautoresizingmaskintoconstraints=no; [cell.imagescrollview addsubview:imageview1]; nsdictionary* views = @{@"imageview1":imageview1,@"placeview":cell.placeholderview,@"scrollview":cell.imagescrollview}; //set imageview'size nsarray *img_constraint_h = [nslayoutconstraint constraintswithvisualf

jquery - CSRF token mismatch for ajax post using nodejs express -

environment: express 4, jquery, krakenjs, font-awesome in controllers/products/index.js module.exports = function (router) { router.post('/add',function(req,res){ // }); }; in html file, users click icon , add products cart {?products} {#products} <ul id="{.id}"> <li class="add"><i class="fa fa-plus"></i></li> </ul> {/products} {/products} for each product, following script ajax post backend. $('.add').click(function(e){ var _id = this.parentelement.id; $.ajax({ url: "/products/add", type: 'post', contenttype: 'application/json', datatype: 'json', data: json.stringify({ id: _id }) }); }); the server responds 500 (internal server error) , states 'error: csrf token mismatch'. need insert csrf token

java - How to obtain a OutputStream on Soundcloud account to upload my content using Outstream.write() ?? -

here detailed objective of mine get input stream of audio publicly available link get output stream of soundcloud can write after reading input stream using inputstream input = new url("http://mywebsite.com/my.mp3').openstream(); bytesread = input.read(buffer); while (bytesread != -1) { outputstreamofsoundcloud.write(buffer, 0, bytesread); bytesread = input.read(buffer); } the java wrapper soundcloud needs file access audio upload (discussed here how upload audio in soundcloud via app , want send id server ) .. how outstream/buffer write soundcloud upload content ??

android - Terminating a third-party application like the button "App Info -> Force stop" does -

i can terminate application this: android.os.process.killprocess(android.os.process.mypid()); how can terminate application (or ones allow that) button app info -> force stop does? firstly cannot kill processes application has not created. processes started application can kill them using public static final void killprocess (int pid) docs if want kill background processes can public void killbackgroundprocesses (string packagename) docs but need kill_background_processes permission that. afaik kill process, won't kill task in memory. when app restarted, activity stack/task re created last time unless ofcourse system kills freeing resources. so afaik can never achieve same effect app info -> force stop programmatically because there no way clear tasks in memory , system can that.

How to display Json data using PHP? -

i have json file , want display data in php file. tried code below not work. $json_output = file_get_contents("https://gdata.youtube.com/feeds/api/playlists/pl3n6kxxrigdat31zif_7wlqtt3i20oqll?v=2&alt=jsonc"); $json = json_decode($json_output, true); foreach($json->data->items->thumbnail $day) { echo $day->sqdefault; echo $day->hqdefault; } and json file {"apiversion":"2.1","data":{"id":"pl3n6kxxrigdat31zif_7wlqtt3i20oqll","author":"tutorial top","title":"دورة سيو للمبتدئين [ali baba]","description":"","thumbnail":{"sqdefault":"https://i.ytimg.com/vi/xihvzqcvqhs/default.jpg","hqdefault":"https://i.ytimg.com/vi/xihvzqcvqhs/hqdefault.jpg"},"content":{"5":"http://www.youtube.com/p/pl3n6kxxrigdat31zif_7wlqtt3i20oqll"},"totalitems":31,"startin

java - AND Gate in Logical Circuit -

folks... i'll best explain method gets lot of members other classes logic should straightforward. so, in and gate of logical circuit, if input signal 0 output 0 ; if all of input signals 1 output 1 ; if have signals 0 , x(unknown signal) , ouput 0 ; when 1 , x output should x . have bug in code of method because when, let's 0x signals fed in gate, i'm getting x instead of 0 . smb please me? note: signal.hi 1 , signal.lo 0 , signal.x x . please let me know if more information needed. public boolean propagate() { signal inputsignal; signal outputfinalsignal; signal temp = getoutput().getsignal(); list<wire> inputs = getinputs(); for(int = 0; < inputs.size(); i++) { inputsignal = inputs.get(i).getsignal(); if(inputsignal == signal.lo) { getoutput().setsignal(signal.lo); break; } else if(inputsignal == si

javascript - Knockoutjs does not update viewmodel -

in view have file input: <input type="file" class="file-input" name="file_source" size="40" onchange=''> and span, in showing uploaded filename: <span class='label label-info' id="upload-file-info" data-bind="text: image"></span> $(".file-input").change(function() { var elem = $("#upload-file-info"); elem.html = $(this).val(); }); this span binded knockoutjs: viewmodel = { image: ko.observable() } ko.applybindings(viewmodel); the problem observable not updates when update span text. althought have filename in span, observable empty. how can make observable update when span text changes ? i did quick fiddle according comment on question. should work: jquery(document).ready(function ($) { 'use strict'; $(".file-input").change(function () { var elem = $("#upload-file-info"

Mysql Create table with best method -

i have customer table i have article table i have distribution article table i want send 1 article customers. in distribution table. adding duplicate rows each article customer id. how can avoid this, if make customers column, new customer added need alter distribution table.

php - How get content of a dynamically appended <div> on click? -

this question has answer here: event binding on dynamically created elements? 19 answers i have php file: $sql = mysql_query("select id, name table") or die(mysql_error()); if (mysql_num_rows($sql) > 0){ while($row = mysql_fetch_array($sql)){ echo "<div class=\"content-row\"> <div class=\"row-1\">".$row['id']."</div> <div class=\"row-2\">".$row['name']."</div> </div>; } } in js file: success: funxction(data){ $(".content").html(data); } in html file have: <div class="content"> // here ajax put divs </div> how can content of <div class="row-1"></div> or <div class="row-2"></div> when click on button? b

How to have menu items streched in full width menu with css for any screen automatically -

i have menu items must streched automatically in full width menu.how best way type of screen automatically css? i tried .report_types_section ul li { position: relative; display: inline-block; width: auto; }.report_types_section ul li { float: left; text-decoration: none; color: #74a9d4; font-size: 18px; display: block; text-align: center; width: 100%; padding-left: 15px; padding-right: 35px; text-transform: uppercase; }.report_types_section ul li a:after { content: " | "; color: #74a9d4; font-size: 18px; float: right; padding-left: 23px; position: absolute; } screen here need increase padding not good. in absence of having provided markup- have made few inferences- wish achieve can used css tables (in absence of greater support flexbox) html, body { width: 100%; margin: 0; } ul, li { padding: 0; margin: 0; } .report_types_section ul { display: table; table-layout: fixed; width: 100%; } .report_types_section ul li {

android - How to hide some strings with certain condition? -

i have simple yet problem cannot solve. want program show parentheses when string length greater 1 or when not null. however, condition doesn't work. there problems in code? string _name = json.getstring("name"); if(_name.length()>3){ _name = "("+_name+")"; }else{ } map1.put("name", _name); i want save string parentheses when json data not null or empty. doesn't seem work. shows parenthesis time empty space between them. as per requirement, " show parentheses when string length greater 1 or when not null ". string _name = json.getstring("name"); put below condition. // check null of string here. can check length here based on condition. if(_name != null && _name != "" && !_name.equalsignorecase("") && _name.length() > 1 ) { _name = "("+_name+")"; } else { //other stuff here }

java - Jackson map different attributes based on json in the same class -

i have class response has attribute data . a json file mapped object. data attribute can of type taskdata or submitdata on json. if json has object of type taskdata object mapper must map taskdata class or should map `submitdata' class. you need type response class follows: public class response<t> . then, when deserializing input, provide typereference jackson indicate desired type. see example: import java.io.ioexception; import java.io.stringreader; import java.io.stringwriter; import com.fasterxml.jackson.core.jsongenerationexception; import com.fasterxml.jackson.core.type.typereference; import com.fasterxml.jackson.databind.jsonmappingexception; import com.fasterxml.jackson.databind.objectmapper; public class testjacksontyping { public static void main(string[] args) throws jsongenerationexception, jsonmappingexception, ioexception { objectmapper mapper = new objectmapper(); response<taskdata> taskresponse = new