Posts

Showing posts from July, 2010

c# - How to manage User Control in List Box using MVVM? -

Image
i know there many question of this, don't find correct answer, or don't understand correct way solve. have list box in mainwindows, populated custom object (fooobjclass). <listbox x:name="foolistbox"> <listbox.itemtemplate> <datatemplate> <foonamespace:fooobjview/> </datatemplate> </listbox.itemtemplate> </listbox> the fooobjview user control <usercontrol x:class="plcs7_test.smartobjrecognize.smartobjview" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:test.fooobjrecognize" mc:ignorable="d&qu

c# - Dataset not found in my namespace -

i creating visual c# forms application in visual studio, , trying use data set. have imported data set using wizard, , used in data grid, yet when debug program, gives me these errors: 1>c:\users\danie\documents\visual studio 2015\projects\viadmin\viadmin\home.designer.cs(219,25,219,37): error cs0426: type name 'staffdataset' not exist in type 'viadmin' 1>c:\users\danie\documents\visual studio 2015\projects\viadmin\viadmin\home.designer.cs(221,25,221,50): error cs0426: type name 'staffdatasettableadapters' not exist in type 'viadmin' i not sure why doing this, able see of columns in designer when not running it. have tried declaring like private dataset staffdataset; but vs tells me defined? if help, using vs 2015 community

encryption - Break MD5 hashed string exact format by knowing part of it -

is possible break/guess/detect format of md5 hashed string when know parts of (in case 1 login can changed, second supplied in opentext along hash) , can change of them , recalculate hash? length extension attack not usable in case because data can in middle of hashed text. bruteforce not possible. no it's not possible. the best can bruteforce missing parts.

ruby on rails - How can I cleanly broadcast to multiple channels at once with ActionCable? -

i have code: actioncable.server.broadcast "posts_#{self.post_id}", { object: some_object } i'd send same payload multiple broadcastings. obvious way pass array of broadcastings: actioncable.server.broadcast ["posts_#{self.post_id}", "all_posts"], \ { object: some_object } but seems treat entire array being identifier: [actioncable] broadcasting ["posts_30453", "all_posts"]: ... and neither broadcasting recieves message. it seems there should cleaner way calling actioncable.server.broadcast multiple times. there? i build tiny helper gem ( multicable ) this. adds broadcast_multiple method actioncable::server: > actioncable.server.broadcast_multiple ["broadcasting1", "broadcasting2"], { payload: "whatever" } [actioncable] broadcasting broadcasting1: {:payload=>"whatever"} [actioncable] broadcasting broadcasting2: {:payload=>"whatever"} eith

python - Scrape webpage after form fill -

im trying scrape response website using pre-filled zip: zip who (i.e. zip code filled in.) tried using scrapy shell follows scrapy shell http://zipwho.com/?zip=77098&mode=zip but response not contain form-filled page, content main zipwho.com page , without details specific zip code. tried filling in form information using requests , lxml, doing wrong. import requests import lxml.html lh url = 'http://zipwho.com' form_data = { 'zip': '77098' } response = requests.post(url, data=form_data) tree = lh.document_fromstring(response.content) tree.xpath('//td[@class="keysplit"]') and table element data (td class = 'keysplit') still not exist. if have ideas working (hopefully simple in requests & lxml) best. the reason can't find data in html it's generated dynamically script. if @ first script in html, you'll see function called getdata contains data want. script later uses function bui

algorithm - What is the most compact way in JavaScript to sort an array of objects by a particular key, where the sorting order is defined in an array? -

this question has answer here: sort array containing objects based on array [duplicate] 2 answers here's mean. suppose have array of objects var objs = [ { foo: 5, bar: "something"}, { foo: 4912, bar: "blah" }, { foo: -12, bar: "hehe" } ]; and array defines ordering on bar values, var arr = ["blah", "something", "hehe"] does javascript have way of getting version of objs to [ { foo: 4912, bar: "blah" }, { foo: 5, bar: "something"} { foo: -12, bar: "hehe" } ]; ??? the best way know like objs.sort(function(x,y){ var ix = arr.indexof(x), iy = arr.indexof(y); if(ix<iy) return -1; else if(ix==iy) return 0; else return 1; }); but i'm wondering if there's way more compact. you can refa

redhat - Apache 403 Forbidden error when configuring a directory outside of root directory -

Image
i'm trying config server use directory /home/imagenesdbd , can't work, have googled lot, , made every sample found, nothing working, add following httpd.conf file alias "/imagenesdbd" "/home/imagenesdbd" <directory "/home/imagenesdbd"> options followsymlinks allowoverride none order allow,deny allow </directory> the directory has 0777 permission setting the context of directories are i expecting url working http://mydomain/imagenesdbd and got following error 403 - don't have permission access /imagenesdbd/ on server. thanks help the type context of /home/imagenesdbd home_root_t . selinux allow type context httpd_sys_content_t . you should change type of security context , can done running $ sudo chcon -r -t httpd_sys_content_t /home/imagenesdbd here can found chcon manual chcon

css formating issue with html at top -

so i'm trying design webpage , trying footer stick bottom of page @ times. did manage trouble figured out error was. want know difference between doing this, body { background: red; margin:0; padding:0; height:100%; } #wrapper { min-height:100%; position:relative; } #header { background: black; padding:10px; } #content { background: green; padding-bottom:100px; /* height of footer element */ } #footer { background:#ffab62; width:100%; height:100px; position:absolute; bottom:0; left:0; } and doing this, html, body { background: red; margin:0; padding:0; height:100%; } #wrapper { min-height:100%; position:relative; } #header { background: black; padding:10px; } #content { background: green; padding-bottom:100px; /* height of footer element */ } #footer { background:#ffab62; width:100%; height:100px; position:absolute; bottom:0; left:0; } why pu

vb.net - How to pause loop while multithreading is alive -

i have 3 threads called inside loop. for integer = 0 dg.rows.count - 1 dim thread1 = new system.threading.thread(addressof processdata) dim thread2 = new system.threading.thread(addressof processdata2) dim thread3 = new system.threading.thread(addressof processdata3) if not thread1.isalive x1 = thread1.start() elseif not thread2.isalive x2 = thread2.start() elseif not thread3.isalive x3 = thread3.start() end if next how pause loop while threads alive? want is, if 1 of threads finishes continue loop , (i), pause loop again if there no available threads. because dg.rows items more 3. let framework handle you: use threadpool . first, create array hold thread status each item: dim doneevents(dg.rows.count) manualresetevent like x1 , x2 , x3 variables, needs accessible both main thread , processdata method. then modify processdata method accept object argument @ beginning , set resetevent @

ajax - In a user's Edit Info form, how do I include the name of the field(s) and user's input value(s) in a response from the model -

on yii2 project, in user's edit info form (inside modal): i'm figuring out fields changed using jquery .change() method, , i'm grabbing value jquery's .val() method. however, want less javascript , more yii's framework. i can see in yii debugger (after clicking ajax post request) yii smart enough know fields changed -- it's showing sql queries update fields changed. what need change in controller of action have yii include name of field changed -- including it's value -- in ajax response? (since goal update main view new values) public function actionupdatestudentinfo($id) { $model = \app\models\studentsupportstudentinfo::findone($id); if ($model === null) { throw new notfoundhttpexception('the requested page not exist.'); } $model->scenario = true ? "update-email" : "update-studentid"; if ($model->load(yii::$app->request->post()) && $model->save()) {

php - detecting hijacked code with call outs -

i have low traffic magento install , of sudden running slow. blocked ripe ip blocks using ip tables , site won't load after perform search using search box in magento. admin panel runs slow. trying make sure there wasn't malicious code injected. trying detect whether there call out server when blocked keeps site loading. possible detect , how so? is possible hijack magento install way?

excel - VBA code that concatenates a letter and variable to create a cell reference -

i have piece of code determines lowest row data in it. want write cell underneath row don't overwrite old data, i'm having trouble referencing cell. clarify, have code determines, example, 51st row lowest row contain data. need correct second piece of code writes cell below row: note: integer "highest" row number lowest on table contains data sh1.range(concatenate(",'b', (highest+1),")).value i tried sh1.range("b" & (highest+1) finally, checked several forums , hinted should use indirect create cell reference, haven't had luck that. correct way be? you're close, remove second ( line sh1.range("b" & (highest+1) so reads this: sh1.range("b" & highest + 1)

seo - Schema.org markup for listing of provided services -

Image
i trying improve seo local plumber website. using following elements in contact section: <div itemscope itemtype="http://schema.org/plumber"> <div itemprop="address" itemscope itemtype="http://schema.org/postaladdress"> <span itemprop="geo" itemscope itemtype="http://schema.org/geocoordinates"> i want list services provided. these shown in list , include: boiler services, installation, fix leaking taps etc. how markup these multiple services? you can add offercatalog of offer s provided service s: <div itemscope itemtype="http://schema.org/plumber"> <span itemprop="name">mr. plumber</span> <!-- other properties e.g. address --> <ul itemprop="hasoffercatalog" itemscope itemtype="http://schema.org/offercatalog"> <li itemprop="itemlistelement" itemscope itemtype="http://schema.org/offercata

A single Android layout xml file that handles slightly different portrait and landscape layouts? -

i if want different layout portrait , landscape, set different xml file each orientation. what if changes small, , don't want have maintain 2 sets of layout files every time design changes? there way in single layout xml file: if (portrait) ... else ... depends on changes... better new layout programatically can if yes if (getresources().getconfiguration().orientation == configuration.orientation_portrait) { //do code } else{ //do code }

regex - Split a string into pieces using java / a better code -

i have split string: 00016282000079116050 it has predefined chunks. should that: 00016 282 00 0079 116 050 i made code: string unformatted = string.valueof("00016282000079116050"); string str1 = unformatted.substring(0,5); string str2 = unformatted.substring(5,8); string str3 = unformatted.substring(8,10); string str4 = unformatted.substring(10,14); string str5 = unformatted.substring(14,17); string str6 = unformatted.substring(17,20); system.out.println(string.format("%s %s %s %s %s %s", str1, str2, str3, str4, str5, str6)); it works, need make code more presentable/prettier. something java 8 streams or regex should good. suggestions? you use regular expression compile pattern 6 groups, like string unformatted = "00016282000079116050"; // <-- no need string.valueof pattern p = pattern.compile("(\\d{5})(\\d{3})(\\d{2})(\\d{4})(\\d{3})(\\d{3})"); matcher m = p.matcher(unformatted); if (m.matches()) { system.o

JavaFX TriangleMesh rendering incorrectly -

i built obj javafx triangle mesh parser , imported monkey head sample model blender doesn't render correctly. seems have wallhack effect. link has obj i'm trying import video showing problem. link . code i'm using. if(tmp.startswith("v ")) { split = tmp.split(" "); verticies.add(float.parsefloat(split[1])); verticies.add(float.parsefloat(split[2])); verticies.add(float.parsefloat(split[3])); } else if(tmp.startswith("f ")) { split = tmp.split("f |/\\d*/\\d* *"); faces.add(integer.parseint(split[1]) - 1); faces.add(integer.parseint(split[2]) - 1); faces.add(integer.parseint(split[3]) - 1); if(split.length > 4) { faces.add(integer.parseint(split[3]) - 1); faces.add(integer.parseint(split[4]) - 1); faces.add(integer.parseint(split[1]) - 1); } } turns out solution really simple , had nothing obj code. scene constructor takes boolean parameter determine whet

javascript - Node.js Async Series not working in order -

i trying perform 2 loops in series, 1 before other using async node.js module. async.series([ insertskill,//first loop insertbehaviours//second loop ], function(err, results){ console.log(results);//print results }); this code in each function, have removed code better readability function insertskill(fncallback){ async.eachseries(object.keys(behaviours), function (askill, callback){ if (askill.indexof('skillid') > -1) { if (behaviours[askill] == null || behaviours[askill] == "") {} connection.get().query('select skill_id skills skill_id = ?', num, function (err, skillresults) { if (skilltitle != null || skilltitle != "") { connection.get().query('insert skills set ?', [skill], function (err, skillresults) { if (err) {} else { console.log("1");//print

javascript - what is wrong with this code in angular? -

in console error coming "getiddata not defined" wrong code. here deal service , getiddata function in service. $scope.edituserdetail = function edituserdetail(){ $scope.showeditview = !$scope.showeditview; $scope.showsubmitview = !$scope.showsubmitview; console.log(deal); deal.getiddata().then(function successcb(data){ $scope.editidoptionsdata=data; }); }; please check working example here: demo you forget return service object service. i.e write following code in service, return service; i.e angular.module('account').service('deal', function deal($http, accountconfiguration, $q, $log, httphelper) { var service = {}; var baseurl = account.app.url; service.getiddata = function(data, accountid, decisionmakerdetail) { var def = $q.defer(); var url = baseurl + '/api/accountsusers/' + accountid + '?role=' + decisionmakerdetail;

node.js - Hitting Maximum call stack exceeded in Lambda functions -

i have nodejs lambda function runs set of tests in newman (a js library of postman). tests run when lambda trying send message codepipeline using codepipeline.putjobsuccessresult, keeps throwing maximum call stack exceeded error. printed error stack doesn't seem long (i can see 6 lines printed). any how why stack trace exceeding , how debugged help. relevant exports.handler exports.handler = function(event, context) { var jobid = event["codepipeline.job"].id; console.log("triggering tests job "+ jobid); var putjobsuccess = function(message) { codepipeline.putjobsuccessresult({jobid: jobid}, (err, data) => { if (err) { context.fail(err); } else { context.succeed(message) } }); } var putjobfailure = function(message) { console.log("tests failed job: " + jobid); var params = { jobid: jobid, failure

javascript - unable to hide logout button after signout using ng-show in angularjs -

i have logout button this: <li class="dropdown" data-ng-if="username"> <a href class="dropdown-toggle clear" data-toggle="dropdown" data-ng-show="username"> </a> <!-- dropdown --> <ul class="dropdown-menu> <li ng-hide="fb_id"> <a ui-sref="app.changepassword">change password</a> </li> <li> <a ui-sref="app.changeprofilepic">change profile picture</a> </li> <li data-ng-show="username"> <a ui-sref="access.signout" data-ng-if="username">logout</a> </li> </ul> <!-- / dropdown --> </li> and in controller: $scope.login = function (user) { $scope.mypromise = authservice.login({ 'uid': user.email, 'password': user

Count up from date and display weeks and days only - PHP -

how can count date, may 7, 2016 , display number of weeks , days (5 weeks 1 day) date least amount of code? use this <?php $date = "may 07, 2011"; $date = strtotime($date); $week=5; $day=1; $days=(5*7)+1; $date = strtotime("+".$days." day", $date); echo date('m d, y', $date); ?>

.net - Removing White Space: C# -

i trying remove white space exists in string input . ultimate goal create infix evaluator, having issues parsing input expression. it seems me easy solution using regular expression function, namely regex.replace(...) here's have far.. infixexp = regex.replace(infixexp, "\\s+", string.empty); string[] substrings = regex.split(infixexp, "(\\()|(\\))|(-)|(\\+)|(\\*)|(/)"); assuming user inputs infix expression (2 + 3) * 4, expect break string array {(, 2, +, 3, ), *, 4} ; however, after debugging, getting following output: infixexp = "(2+3)*7" substrings = {"", (, 2, +, 3, ), "", *, 7} it appears white space being removed infix expression, splitting resulting string improper. could give me insight why? likewise, if have constructive criticism or suggestions, let me know! if match @ 1 end of string, empty match next it. likewise, if there 2 adjacent matches, string split on both of them, end empty string in

sql - Calculation of balance after each transaction -

i have table this: cust_id acc_no trans_id trans_type amount 1111 1001 10 credit 2000.0 1111 1001 11 credit 1000.0 1111 1001 12 debit 1000.0 2222 1002 13 credit 2000.0 2222 1002 14 debit 1000.0 i want hive query or sql query every transaction done customer balance should calculated so. i want output follows: cust_id acc_no trans_id trans_type amount balance 1111.0 1001.0 10.0 credit 2000.0 2000.0 1111.0 1001.0 11.0 credit 1000.0 3000.0 1111.0 1001.0 12.0 debit 1000.0 2000.0 2222.0 1002.0 13.0 credit 2000.0 2000.0 2222.0 1002.0 14.0 debit 1000.0 1000.0 i've tried select * (select cust_id, acc_no, trans_id, trans_type, amount, case when trim(trans_type) = 'credit' ball = trim(bal) + trim(amt) els

git - github Push permission denied over both SSH and HTTPS -

new git , github. author suggested in issue discussion make pull request. cloned repo with recommended https link on personal machine (not github repo) , committed edits. i'm trying generate pull request i'm not sure how. solutions i've found looking around haven't been helpful. below output of bash git commands. user@machinename odkwk52 /c/websites/github/repo (master) $ git status on branch master branch ahead of 'origin/master' 2 commits. (use "git push" publish local commits) nothing commit, working directory clean user@machinename odkwk52 /c/websites/github/repo (master) $ git remote -v origin ssh://git@github.com/repo.git (fetch) origin ssh://git@github.com/repo.git (push) user@machinename odkwk52 /c/websites/github/repo (master) $ ssh -t git@github.com permission denied (publickey). user@machinename odkwk52 /c/websites/github/repo (master) $ eval "$(ssh-agent -s)" agent pid 7180 user@machinename odkwk52 /c/websites/githu

javascript - Update position/transition from last value (guage chart / d3.js) -

i'm trying repurpose guage chart found here . have needle moving on submit, resets 0 before updating new position, i'd rather adjust position directly. when trying think of way it, figured need modifiy snippet of code handles reset; needle.prototype.moveto = function(perc) { var self, oldvalue = this.perc || 0; this.perc = perc; self = this; // reset pointer position this.el.transition().delay(100).ease('quad').duration(200).select('.needle').tween('reset-progress', function() { return function(percentofpercent) { var progress = (1 - percentofpercent) * oldvalue; repaintgauge(progress); return d3.select(this).attr('d', recalcpointerpos.call(self, progress)); }; }); this.el.transition().delay(300).ease('bounce').duration(1500).select('.needle').tween('progress', function() {

reactjs - React + Webpack bundling - if node_modules are excluded 'require is not defined' in browser -

Image
i'm learning react , i'm trying use webpack, i'm facing following issue: if use webpack config, node modules don't excluded , bundling process takes 20 second , bundle's size on 2mbs (see cli output below): const path = require('path'); const nodeexternals = require('webpack-node-externals'); module.exports = { entry: [ 'bootstrap-loader', './src/index.js', 'style!css!./src/style/style.css' ], output: { path: path.resolve(__dirname + 'build'), filename: 'bundle.js' }, module: { loaders: [ { test: /\.jsx?$/, loader: 'babel-loader' }, { test: /\.scss$/, loaders: [ 'style', 'css?modules&importloaders=2&localidentname=[name]__[local]__[hash:base64:5]', 'postcss', 'sass', ], }, { test: /\.woff2?(\?v=[0-9]\.[0-9]\.[0-9]

javascript - $.get() method JQuery reads nothing (html) -

goal: when click_div clicked, script should read file ( text.html ) own computer using $.get() method , , set html of div ( cont_div ) file's content. code: $(document).ready(function() { $('#click_div').click(function(){ var html_file_url = 'text.html'; $.get(html_file_url, function(data){ alert(data); $('#cont_div').html(text); }); }); }); problem: the content of cont_div keeps blank, after clicking click_div . put alert show content of method read, , displays blank dialog. further information: • file on same folder .js file, , index.html page file. • other javascript functions work well. question: given alert function displays nothing, still called, possibly doing wrong? i've tried many things, doesn't work. this should it /text.html <p>lorem ipsum dolor</p> /something.html <script type="text/javascript"> $(document)

excel vba - RUN time error 1004 , no data was selected to parse -

i have svg files in folder , have written vba code xml data svg files here code sub macro4() dim lines long dim letter string dim no string dim count integer dim integer dim xrow long dim xdirect$, xfname$, initialfoldr$ count = sheets.count if count > 1 = 1 sheets.count sheets(i).select on error goto loopexit if activesheet.name = "execute" elseif activesheet.name = "sheet1" else application.displayalerts = false activesheet.delete application.displayalerts = false = - 1 end if next end if loopexit: initialfoldr$ = "c:\" application.filedialog(msofiledialogfolderpicker) .initialfilename = application.defaultfilepath & "\" .title = "please select folder list files from" .initialfilename = initialfoldr$ .show if .selecteditems.count <> 0

c++ - Iteration speed and element size -

i have std::vector filled following structures: #define elementsize 8 struct element { int value; char size[elementsize - 4]; //1 char 1b in size - 4b int }; the size of structure depends on defined elementsize, makes array of chars of specified size in structure. i benchmarking average value of these structures in vector , love know reason why vector filled bigger structures in size takes longer iterate over. for example vector 1 000 000 8b structures takes 1,7ms , same test 128b structures 12,7ms. is big difference because of cache only? if so, explain why? or there other aspect can not see? the structure 16 times bigger, should take 16 times longer iterate through. mathematically 12,7/1,7 = 7,47 times more, matches mathematically. now imagine structure containing 128b elements structure containing 8b elements, same size. see 16 times larger?

php - replace page number using Regular Expression in Javascript -

i have url follow: http://example.com/category/news/page/2/ i need replace number comes @ end of url represents page number. if possible think is, want use regular expression in case domain changes, code still works. i using php ... could me proper regex? find answer: string.replace(/\/page\/[0-9]+/, '/page/' + pagenum); pagenum can variable replace page number

mediaelement - How to display embedded Closed Captions for HLS stream in Windows 10 UWP app? -

Image
i'm trying play hls stream in windows 10 uwp app . this stream contains embedded captions can turned on in vlc player or in edge browser when playing hls stream directly. is there way how show these embedded captions in uwp mediaelement well? i've tried using approach no textsources loaded or shown when using these steps: uri source = new uri("http://nasatv-lh.akamaihd.net/i/nasa_101@319270/master.m3u8"); adaptivemediasourcecreationresult result = await adaptivemediasource.createfromuriasync(source); if (result.status == adaptivemediasourcecreationstatus.success) { adaptivemediasource astream = result.mediasource; mediasource mediasource = mediasource.createfromadaptivemediasource(astream); var metadatatracks = mediasource.externaltimedmetadatatracks.toarray(); var textsources = mediasource.externaltimedtextsources.toarray(); // both arrays above empty when loading nasa tv stream mediaplaybackitem mediaelement = new mediaplayb

mysql - Perform angularjs operation inside value attribute of html input tag -

i want perform operation value attribute not working <input name="grand_total" type="text" class="form-control" value="@{{sum(saletemp)*discount1/100 | currency: "&#x9f3"}}" /> <input name="discount" type="text" class="form-control" id="add_payment" ng-model="discount1"/> second question if want send value p tag after html form submission, how can , how can retrieve value? want pass value @{{sum(saletemp)*discount1/100 | currency: "&#x9f3"}} controller , want store database. here code portion <div class="form-group"> <label for="grand_total" class="col-sm-4 control-label">discount</label> <div class="col-sm-8"> <p class="form-control-static" ><b>@{{sum(saletemp)*discount1/100 | currency: "&#x9f3"}}</b></p> &

java - How do I test a class that has private methods, fields or inner classes? -

how use junit test class has internal private methods, fields or nested classes? it seems bad change access modifier method able run test. if have of legacy application, , you're not allowed change visibility of methods, best way test private methods use reflection . internally we're using helpers get/set private , private static variables invoke private , private static methods. following patterns let pretty related private methods , fields. of course can't change private static final variables through reflection. method method = targetclass.getdeclaredmethod(methodname, argclasses); method.setaccessible(true); return method.invoke(targetobject, argobjects); and fields: field field = targetclass.getdeclaredfield(fieldname); field.setaccessible(true); field.set(object, value); notes: 1. targetclass.getdeclaredmethod(methodname, argclasses) lets private methods. same thing applies getdeclaredfield . 2. setaccessible(true) require

javascript - Alert if JSON Data is Empty - Code not working -

i want check if json data empty or not. if json empty, want alert orders not found . if not empty, want alert orders found . if user not logged in, there won't token in localstorage. 500 error when browser requests api url. want alert failed along failed status reason my dev sick, tried self. not going well. tried below code, not @ working. <script> $http.get("http://localhost.com/activeorders/?format=json",{ headers: {'authorization': 'token '+ localstorage.getitem("token")}}) .success(function(response) { if(response=="[]") { alert(" orders not found"); } else { alert("orders found"); } .error(function(response,status) { alert("failed");

algorithm - Bit swapping O(logN)? -

i've been told reversing bits of integer in divide-and-conquer fashion (i.e. first swapping every 2 consecutive bits, swapping 2-bit pairs, , on until result) o(logn), fail see how o(logn).. consider case when swapping byte (8 bit): first swap every 2 bits , perform 4 swaps, swap 2-bit pairs have 2 swaps , join in last swap. total: 7 swaps, log(n) have been 3. am right or missing something? you're counting else. if add "individual swaps", that's lot of swaps. whole point of technique (and many similar techniques) "phase", swaps in phase happen in constant number of steps. example step "swap adjacent bits": x = ((x & 0x55) << 1) | ((x & 0xaa) >> 1); .. or equivalent delta-swap formulation, looks no matter how many swaps it's doing (the constants change of course). so, that's constant number of steps right there. (cue complaining operations on n-bit integers not being single steps, here are , it

ListView with CursorAdapter is not refreshing even if I use swapCursor or changeCursor methods in Android -

i have 2 activities initial listview , fab , second 1 edittext, save , clear buttons. i call second 1 activity result enter values , click save button. list not refreshed its displaying first element , did following in first activity @override protected void onactivityresult(int requestcode, int resultcode, intent data) { super.onactivityresult(requestcode, resultcode, data); // check if request code same passed here 2 if(requestcode==3) { player = mhelper.getplayersbyteam(new_id); if(player!=null && player.getcount()>0) { playerdataadapter = new playeradapter(this, player); // assign adapter listview listplayers.setadapter(playerdataadapter); playerdataadapter.notifydatasetchanged(); playerdataadapter.swapcursor(mhelper.getplayersbyteam(new_id)); } } what doing wrong here? why listview not displaying refreshed data check database if retr

javascript - console.log and redirect in node.js doesn't work? -

i make application register , login, not working properly this users.js routers/users.js var express = require('express'); var router = express.router(); var passport = require('passport'); var localstrategy = require('passport-local').strategy; var multer = require('multer'); var upload = multer({dest: './uploads'}); var user = require('../models/user'); /* users listing. */ router.get('/', function(req, res, next) { res.send('respond resource'); }); router.get('/register', function(req, res, next) { res.render('register', { 'title': 'register' }); }); router.get('/login', function(req, res, next) { res.render('login', { 'title': 'login' }); }); router.post('/register', upload.single('profileimage'), function(req, res, next){ //get form values var name = req.body.name; var email = req.body.email; var user

Debug APK not signed correctly Android 2.1.1 [INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES] -

i have been coding on android since year now. kind of newbie. i upgraded android studio 1.3 2.1 , facing error msg everytime try test run app on device. 'installation failed since device has application same package different signature. in order proceed, have uninstall existing application. warning: uninstalling remove application data! do want uninstall existing application?' i tried unistalling app still everytime asks me it. tried run on device there says apk not signed correctly :( kindly highly appreciated have stuck on problem on week. you can sign apps release key while keeping debugging option - have add release key android studio (or specify on command line if signing apps there). in android studio, right click on app in project browser , open module settings. select app's module , click on 'signing' make sure release keystore listed. under 'build types', make sure debug target , release target share same signing config, ,

How can I change the defined API version of an Android app? -

i absolutly new in android development , have following problem trying build sample project have downloaded internet. when try build obtain following error message: error:cause: failed find target hash string 'android-18' in: c:\users\andrea\appdata\local\android\sdk <a href="install.android.platform">install missing platform(s) , sync project</a> so search online , found link: android studio - failed find target android-18 ok go tools > android > sdk manager , infact have installed android 6 corrisponding api level 23 not android 4.3 corrisponding api level 18 . so means? means have installed different version o android framework ?(is sdk considerable framework or what?) so, on android studio can install different version of sdk? i think api level have defined in way dowloaded application. how can specify application don't use api level 18 instead use installed api level 23 ? think not problem because have installed new

asp.net mvc - How to log source error in elmah mvc? -

Image
i want log source error in error page of asp.net mvc application in image. elmah log stack trace. is there config should set? how? elmah doesn't log this, since ui feature of yellow screen of death. information in source error, same in stack trace. can see, errorformatter used generate this.

layout inflater - Updating Android UI from custom view -

i'm new android development, , still having difficulties comprehending how framework works. try write simple game experience , i'd ask below. in main activity, have few textviews show various data game, , under have custom view called animatedview has canvas draw objects game itself. based on objects on canvas, i'd update textviews show e.g. number of object, level player at, etc. the problem is, though can textview object below code, when call textview.settext(...), nothing changes on ui. the below simplified version of real code, demonstrate problem: activity_main.xml <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" ... tools:context="com.danielsh.test.teststuff.mainactivity" android:orientation="vertical"> <textview android:layout_width="wrap_content" android:layout_height="wrap_content&quo

reactjs - URL not changing in React Routes -

i'm trying implement react-router in application. i've initialized router in index.js , works fine. doesn't change url in browser , throws error in console. warning: [react-router] `router` no longer defaults history prop hash history. please use `hashhistory` singleton instead. index.js import 'core-js/fn/object/assign'; import react 'react'; import reactdom 'react-dom'; import { router, route, browserhistory,indexroute } 'react-router'; // custom components import app './components/main'; import dashboard './components/containers/dashboard'; import settings './components/containers/settings'; import workspace './components/containers/workspace'; import main './components/main'; reactdom.render(( <router histrory={browserhistory}> <route path="/" component={main}> <indexroute component={dashboard}></indexroute> <route path="/wo

c# - How to convert textbox value ddmmyyyy to dd-mm-yyyy? -

i have textbox in project user enters date, ddmmyyyy . need convert dd-mm-yyyy format fetch particular data database. you can parse string datetime first , generate it's string representation that format. for example; var s = "11062016"; var dt = datetime.parseexact(s, "ddmmyyyy", cultureinfo.invariantculture); console.writeline(dt.tostring("dd-mm-yyyy", cultureinfo.invariantculture)); by way, assume wanna mm instead of mm since mm specifier minutes mm specifier months. on other hand, never told data wanna fetch but, not idea datetime values (if are) strings. use datetime values datetime data database (which of of rdms supports), not strings.

linux - insert symbol between numbers -

i have file in linux os containing random numbers: 1 22 333 4444 55555 666666 7777777 88888888 now, have 2 conditions: 1. remove last 3 digit every entry , put / in between rest. 2. numbers <=3, add/replace / symbol. command trying fulfilling 1st requirement is: sed -e 's|\(.\)|\1/|g;s|\(.*\)/\(.\/\)\{3\}|\1|g' desired out required: / / / 4 5/5 6/6/6 7/7/7/7 8/8/8/8/8 please help. something might work you: % sed 's/.\{1,3\}$//;s/./\/&/g;s/.//;s/^$/\//' file / / / 4 5/5 6/6/6 7/7/7/7 8/8/8/8/8 no smart moves here: s/.\{1,3\}$//; # remove last 3 character s/./\/&/g; # insert / before each character s/.//; # remove first character (it's /) s/^$/\// # insert slash on empty lines alternative solution gawk: awk -v fs='' -v ofs='/' '{if (nf > 3) nf=(nf-3); else $0 = ofs}1' file

c - How can Multiprocessing be achieved by Programming Languages? -

i trying develop simple operating system. till programs developed can run in single processor. when went through concept called multiprocessing systems of latest systems based, got lot of doubts. first, how can create program can run in multiprocessor systems. hardware oriented or programmer specific? second went through parallel programming languages can helpful in multiprocessing systems java 1 c not. how can os developed in c(windows) can achieve multiprocessing? thanks. you're right: typical c program single-processor. statements write in expected executed 1 after other, obeying loops , tests required. can call function in c says "don't execute function now: create new thread , execute that!" int maxplaces; int pidigits; void calculatepi() { // write code calculate pi maxplaces // update pidigits go } // calculatepi() int main() { maxplaces = 2000000000; // calculatepi(); // old code: don't this! instead, do... startthread

How can I make git log to show cherry-picked commits on the same line? -

if run "git log --graph --oneline --branches=* --date-order" on git repository 2 branches , 3 shared commits can this: * hash9 comment6 * hash8 comment5 * hash7 comment4 | * hash6 comment6 | * hash5 comment5 | * hash4 comment4 | * hash3 comment3 |/ * hash2 comment2 * hash1 comment1 is possible instead this?: * * hash9 hash6 comment6 * * hash8 hash5 comment5 * * hash7 hash4 comment4 | * hash3 comment3 |/ * hash2 comment2 * hash1 comment1 you have write own graph drawing program. graph drawing code in git log not clever. your graph drawing program need git cherry or (probably better) lower level cousin git patch-id . it whether compare commit messages. if do, commit a123456 copy of commit b987654 if message differs? if difference 1 of them says (cherry picked commit ...) , other not? id in string may not match either commit, if both cherry-picked (one -x , 1 without -x ) third commit; third commit may no longer in portion of graph drawing, or in r

php - How to orderBy a calculated column in Laravel Eloquent? -

i have products talbes has columns price1 , price2 , etc. want order table 1 - (price1 / price2) , select 10 records 11th row. how can achieve select *, 1 - (price1 / price2) discount products order discount in laravel eloquent ? currently i'm using accessor calculate discount , using sortby order entire product collection, means if need 10 reocrds, have select entire table first. have ~20k records, approach extremely slow (took ~10s on 1cpu , 0.5gb ram vps). i'm thinking calculate discount in query rather using accessor . know how in eloquent ? thanks.

lotus domino - Can I hide a subform in notes designer from specific set of users? -

can hide subform in notes designer restricted people using field in main form? i have field in main form has bunch of email id generated on computed display. want subform visible bunch of usernames. is possible? you can chose computed subform, in designer, first open form on menu bar go create>resource>insert subform>insert subform based on formula. then can use formula choose display subform or not.