id
stringlengths 5
27
| question
stringlengths 19
69.9k
| title
stringlengths 1
150
| tags
stringlengths 1
118
| accepted_answer
stringlengths 4
29.9k
⌀ |
---|---|---|---|---|
_softwareengineering.292044 | I'm writing a pretty simple TCP server/client application for the first time. It is a personal project for education, but I really like my applications to be extendable and to scale in case the code is good enough to use somewhere else.I am using Microsofts async TCP server/client as my starting pointhttps://msdn.microsoft.com/en-us/library/fx6588te(v=vs.110).aspxMy end goal is to be able to have some kind of ServerManager application that the client first connects to, and is then redirected based on that servers capacity.My question is: Do the clients get redirected to a different physical server, or does the ServerManager spawn another instance of TCPServer on the same machine and connect them there (not even sure how that would work)? | How to scale a C# server application | c#;server;tcp | null |
_unix.347540 | I am having touble understanding what server resource is causing lag in my Java game server. In the last patch of my game server, I updated my EC2 lamp server from apache2.2, php5.3, mysql5.5 to apache2.4, php7.0, mysql5.6. I also updated my game itself, to include many more instances of monsters that are looped though every game loop - among other things.Here is output from right when my game server starts up:Here is output from a few minutes later:And here is output from the next morning:As you can see in the images the cpu usage of my Java process levels off around 80% in the last screenshot, yet load avg goes to 1.20. I have even seen it go as high as 2.7 this morning. The cpu credits affect how much actual cpu juice my server has so it makes sense that the percentage goes up as my credits balance diminishes, but why at 80% does my server lag?On my Amazon EC2 metrics I see cpu at 10% (which confuses me even more):Right when I start up my server my mmorpg does not lag at all. Then as soon as my cpu credits are depleted it starts to lag. This makes me feel like it is cpu based, but when I see 10% and 80% I don't see why. Any help would be greatly appreciated. I am on a T2.micro instance, so it has 1 vCPU. If I go up to the next instance it nearly doubles in price, and stays at same vCPU of 1, but with more credits.Long story short, I want to understand fully what I going on as the 80% number is throwing me. I don't just want to throw money at the problem. | CPU and Load Average Conflict on EC2 server | cpu;top;amazon ec2;uptime;load average | You notice the large values of st? Those are stolen CPU cycles -- cycles you can't use, because you have completely almost -- or fully -- depleted your CPU credit balance.The usage is 10% is averaged over some time window, probably 5 minutes. If you watch the output from top, you should see that 100% minus stolen minus idle is approximately 10% over time.You essentially have no available CPU headroom at this point. A timing-critical workload would be expected to exhibit inconsistent responsiveness under these conditions.Your workload is too large for a t2.micro. If this were not the case, you'd always have a surplus of CPU credits... essentially, by definition. Unless you can do something to reduce the workload or improve the efficiency of your code, the current symptoms indicate the need for a larger instance class. |
_vi.7722 | I see a lot of questions on here where a user has a mapping which doesn't workand most of the time the reasons are pretty similar.I suggest to make this question a reference for this kind of questions, to give a complete procedure to debug a mapping. If a user as a problem witha mapping they could be redirected here to eliminate the most common issues.Of course there will still be particular cases which will require a dedicatedquestion and will not be addressed here. | How to debug a mapping? | key bindings | Your mapping doesn't do what it should do or behaves differently than expected, several steps are to follow to troubleshoot that:Check that the key is effectively mapped to what it should doVim provides a command :map. By default (when no argument is given) thecommand will show all the mappings currently created. Here is an example ofthe result of the command:As always the doc is your friend: :h map-listingYou can see in the first column the mode of the mapping (n for normal mode, v for visual mode, etc), the second column shows the keys mapped and thelast column what the keys are mapped to.Note that before the mapped actions some additional characters may appear, itis important to understand them:* indicates that it is not remappable (i.e. it is not a recursive mapping, see know when to use nore later in this answer)& indicates that only script-local mappings are remappable@ indicates a buffer-local mappingWhen asking for help about a mapping it is a good thing to add thisinformation since it can help other people to understand the behavior of your mapping.It is possible to restrict the prompt to a particular mode with the sister-commandsof :map, like :vmap, :nmap, :omap, etc.Now to restrict your search to the problematic mapping you can pass the keysequence you're debugging as parameter of the commands, like this::map j:map <Leader>m:map <F5>Note that the <Leader> key will be replaced by its actual value in the list.If the result of the command shows that your keys are correctly mapped, it probablymeans that the problem doesn't come from Vim but from your terminal or your desktopenvironment. See the part Check if your mapping is actually intercepted by VimIf the result of the command show that your keys are not correctly mapped see thefollowing part.Check what overrode your mappingAnother convenient use of the :map command is to combine it with verbose:This will prompt the last file which modified your mapping.For example see these two screen-shots: the first one is a mapping modified bymy .vimrc and the second a mapping created by a plugin:Now if you see that another script modified your mapping you'll have to see ifyou can remove it or modify its behavior. (Note that some plugins providesvariable to enable/disable their mappings, unfortunately not all of the pluginsdo that)If the last file which changed your mapping is your .vimrc, make sure there is no other line that also defines a mapping for the same key. The .vimrc file will happily override any mappings with the last one of its kind in the file.Check if your mapping is actually intercepted by VimSeveral situations may indicate that Vim doesn't intercept your key:The command :map show that your key is correctly mapped but pressing it does nothing.Your mapping works on gVim (GUI) but does nothing in terminal VimYour mapping works on a defined terminal emulator but not on anotherYour mapping works on a defined OS but not another one.It is probably caused by one of the two following things:Something intercepts the key before Vim: It can be different applications: your OS, your desktop environment, your terminal emulator, Tmux (if you use it)....To troubleshoot that, you should:Try to temporary remove your .tmux.conf if you use tmuxRefer to the doc of your terminal or of your desktop environment.You could also refer to sister-sites like super-user,Unix and Linux, askUbuntu, etc...If this is the problem, you then have two solutions: either you spend(a lot of) time to changethe behavior of the application which causes the problem or you findanother key combination to map which isn't intercepted by anotherapplication.Your terminal emulator can't handle the key combination you're trying to map: Terminal emulators are implemented differently and some of themare not able to handle some particular key combination. (The reason whythey can't is out of the scope of this question, see their doc or thesister-sites mentioned before for more details).In this case you don't have a lot of solutions: either you change your key for another one which is handled properly by your terminal or you change your terminal emulator.Check for the common pitfallsSome problems in mappings are pretty recurrent and mostly related to the vimscript syntax. If your mapping has an unexpected behavior remember to check the following points:Do not put a comment on the same line as your mapping, instead put the comment on the line above. Example:Don't do that:inoremap ii <esc> ii to go back into normal modeVim will consider the whitespaces, the and the comment as a part of the mapping which will result in an unexpected behavior.Instead do that: ii to go back into normal modeinoremap ii <esc>This is easier to read and won't mess your mapping.Do not pipe your commands with |. Example:Don't do that:nnoremap <Leader>x :w | !% python -m json.toolsVim will consider the pipe | as a command termination: When you source your .vimrc the mapping nnoremap <Leader>x :w will be created then the external command !% python -m json.tools will be executed.Instead do that:nnoremap <Leader>x :w <bar> !% python -m json.toolsSee an explanation about <bar>.Know when to use nore: always. LearnVimscriptTheHardWay explain it pretty clearly: never use map, nmap, vmap, etc... Always prefer the nore version: noremap, nnoremap, vnoremap, etc...Why? nore stands for non recursive mapping it means that the right hand side of the mapping will be considered as the built in feature even if you remmaped it. Example:Let's say you want to map > to delete a line and - to increment the indent of a line. If you don't use non recursive mappings you'll do that:(Do not do that it's for the example)nmap > ddnmap - >When you'll hit > your line will be deleted, that's good. But when you'll hit - your line will also be deleted instead of being indented. Why? Because Vim understood I received a hit on - which I should translate to > which I should in turn translate to dd.Instead do thatnnoremap > ddnnoremap - >This way Vim will translate - as > and will not try to do any other translation because of the nore.Edit note Always may be an exaggerated answer in some cases you'll need to use the recursive mapping form but it is not really common. To clarify, I'll quote @romainl from this answer:Use a recursive mapping only if you intend to use any other mapping in your mapping. Use non-recursive mappings if you don't.Remember that some key combinations are equivalent: Because of the hexadecimal codes that are produced some key combinationswill be interpreted by Vim as another key. For example <C-h> is equivalent to <backspace><C-j> as <enter>On French keyboards <M-a> is the same as and the same goes with all the<m- mappings. As @LucHermitte pointed out in the comment that is aproblem with plugins using this type of mappings like vim-latex.<C-S-a> is equivalent to<C-a>. Mapping Ctrl+upper caseletter separately from Ctrl+lower case letter is not possible cause of theway the terminals send ASCII codes.When your mapping seems to affect another key try to use another lhs combination, if that solves the problem inspect which hexadecimal codesare sent to Vim.Check that your leader is correctly defined: If your mappings involving <leader> doesn't work and you changed your leader with the command mapleader, check that the definition of your leader is done before the definition of the mappings. Otherwise, Vim will try to create mappings with a key which is not the one you think. Also if you want to use the space bar as your leader (which is pretty current) make sure that you used the correct notation: let mapleader = \<Space>Your mapping still doesn't work?If you went through all the steps of this answer and your mapping still doesn't work like you want, you'll probably want to ask for help on this site.To help people to help you remember to provide some crucial information like:The command you used to define your mapping.What you are expecting your mapping to do.A precise description of the problem:It doesn't work won't be really helpful to people who will try to help you. You should precise if the mapping doesn't do anything or how it behaves differently than what you was expecting.Also indicate that you actually followed the steps described here and the results you get with :map and :verbose mapAll of this will save you and the users of the site a lot of time.A useful command: :unmapSometimes it can be useful to reset a mapping without quitting Vim to help debugging its behavior.To do so you can use the command :unmap <key> which will remove the mappingassigned to <key> for Normal, Visual and Operating-pending modes. :iunmap will remove mappings for Insert mode. For other modes see :help :unmap.ReferencesAn excellent introduction to mapping: learnvimscriptthehardway (And a lot of other aspects of Vim)The doc: :h mapping,:h :mapSection 20 of Vim's FAQ is about mapping and contains interesting questions: And a bonus: A question about best practices to find which keys to use in your mappingHelp improving this questionIf you know of another good way to debug a mapping don't hesitate to make anotheranswer or to edit this one to improve it. |
_scicomp.25196 | I am implementing higher order derivatives for FEM. Example, to solve a Poisson problem, biharmonic or triharmonic PDE one needs first, second or third order derivatives respectively. As usually done in FEM, there is a mapping from a reference element to a physical element e.g. $F : \hat{K} \rightarrow K$ with the associated coordinates $(\hat{x}, \hat{y})$ and $(x,y).$ If we assume a linear affine map on a quadrilateral mesh, then for a function $u,$ the derivative is easily computed and given by $\nabla u = J^{-T} \nabla \hat{u}.$ Now, my aim is to compute $\nabla^2 u, \nabla^3 u,...$ possibly $\nabla^n u.$I will appreciate any ideas on how to compute these derivatives. | implementing higher order derivatives for finite element | finite element | You appear to have pretty much answered your own question.Changing notation slightly to use $\bf x$ for physical coordinates and $\bf \xi$ for the reference coordinate (because I have a nasty habit of leaving tildes off variables where I shouldn't) you have in component form that $\frac{\partial}{\partial x_{i}}u\left(\bf{x}\right)=\sum_{j}\frac{\partial\xi_{j}}{\partial x_{i}}\frac{\partial}{\partial\xi_{j}}u\left(\bf{\xi}\right)$so using the definition $\frac{\partial^2 f}{\partial x_i^2} := \frac{\partial}{\partial x_i}\frac{\partial f}{\partial x_i}$we get$\frac{\partial^2 u}{\partial x_i^2} = \frac{\partial}{\partial x_i}\frac{\partial u}{\partial x_i} = \frac{\partial}{\partial x_i} \frac{\partial}{\partial x_{i}}u\left(\bf{x}\right)= \frac{\partial}{\partial x_i} \sum_{j}\frac{\partial\xi_{j}}{\partial x_{i}}\frac{\partial}{\partial\xi_{j}}u\left(\bf{\xi}\right) = \sum_k \frac{\partial\xi_{k}}{\partial x_{i}}\frac{\partial}{\partial\xi_{k}}\sum_{j}\frac{\partial\xi_{j}}{\partial x_{i}}\frac{\partial}{\partial\xi_{j}}u\left(\bf{\xi}\right)$.Assuming your mapping is linear, we can take the derivative through the summation and write$\frac{\partial^2 u}{\partial x_i^2} = \sum_{j,k} \frac{\partial\xi_{k}}{\partial x_{i}}\frac{\partial\xi_{j}}{\partial x_{i}}\frac{\partial^2 }{\partial \xi_k \partial\xi_{j}}u\left(\bf{\xi}\right)$.Hopefully you see the connection to what you're already doing with first derivatives. |
_softwareengineering.7629 | What coding standards do you think are important for .NET / C# projects? This could be anything from dealing with curly braces and spacing and pedantry like that. Or it could be more fundamental questions such as what namespaces in the .NET Framework to avoid, best practices with config files, etc.Try to avoid creating a post that is simply the corollary to another. For example, it would be fine to have one post focusing on curly braces. We don't need two to support one style vs. the other. The idea is not to vote for your pet standard, but rather to flesh out what should be thought about when creating standards. | Recommended .NET / C# coding standards? | c#;.net;coding standards | Here is the official Microsoft Guide on coding standards for the .NET framework Version 4.0.If you want the older version for 1.1, try here.I don't necessarily follow this to a 'T', as they say. However, when in doubt, this is the best place to start to be consistent with the current .NET framework, which makes it easier on everyone, no matter if they're new to your particular project or not. |
_unix.127327 | I just installed a fresh Waldorf (Crunchbang, Debian Wheezy-based) on a computer which has no Internet access. Previously on a Xubuntu 10.04 VM, what I did when I needed some software was:go to packages.ubuntu.com;find the relevant packages and their dependencies, download the .deb's;run dpkg-scanpackages <download dir> /dev/null | gzip -9c > Packages.gzrun apt-get update (<download dir> figures in my /etc/apt/sources.list, i.e. there is an entry which looks like deb file:<download dir> ./);run apt-get install <top-package>;if there were any unmet dependencies, (i.e. package downloaded from packages.ubuntu.com is too recent and depends on a newer version of some package already present on my system), go to launchpad.net, and find an older version of the package;resume installation.Now with Debian Wheezy, I can find the .deb on packages.debian.org just fine, but problems start when those packages need newer versions of already installed packages. I cannot find an equivalent to launchpad.net for Debian...I guess since Ubuntu is Debian-based I could still find the old .deb's I need on launchpad.net, but I'm starting to think that maybe I'm doing something wrong. Is that the case? What should actually be done to install packages on a computer which has no Internet access?For example, I'm trying to install openjdk-6-jre. Going down the dependency tree I found I also need tzdata-java and libnss3-1d, but I can't install those with the .deb found on packages.debian.org, because apt-get chokes on the versions:tzdata-java : Depends: tzdata (= 2014a-0wheezy1) but 2013b-2 is installed.libnss3-1d : Depends: libnss3 (= 2:3.14.5-1) but 2:3.14.3-1 is installed.(In before just compile from the source) | Manage local package repository | apt;dependencies | In the end, I found two solutions. A simple, risky one, or a second one which should be as simple and less risky (not sure, have not tried it).Many thanks to the folks from the Crunchbang community for helping me on this.Risky solutionSimply download the newer Wheezy packages from pakages.debian.org, add them to local dir;Run apt-get upgrade: apt recognizes the downloaded packages as being newer, no questions asked;Run apt-get install <top-package>.Now the problem with that, I guess, is that the upgraded packages themselves could depend on upgraded versions of other packages on the system, which means that the list of stuff to download could get arbitrarily long. In my case, just downloading libnss3 and tzdata was enough.Less risky solutionUse apt-offline. On the disconnected computer, this software builds a signature which represents the dependencies to fetch; on a second computer with access to the Internet, use the signature to actually download the dependencies, transfer back to the first computer, install.I haven't actually tried this solution, which is why the description above might seem fuzzy (the people from Crunchbang posted links to adequate documentation if anyone is interested). |
_codereview.114289 | I am trying to build a food search app. I am using Angular and Spring. I am currently using the yelp API, but it's done on the Java side.I think what I have achieved is really bad design. It works, but the data is not always updated correctly.For Java, I created two methods and one string variable:private String response;@RequestMapping(value = /searchRestaurant, method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)public void searchRestaurantWithYelp(@RequestBody String jsonData) { //here i process the json string and pass the values to yelp function, // then yelp sends the respond as a json string, i assigned the value // to the response variable. response = queryYelp();}As you can see, this post request receive a json string from client side, and pass the string to the yelp java API I created. The yelp respond is a json string, and I assign it to the response variable.I also created a GET method, which simply returns the response, which contains the data yelp returned. I want to immediately return this data to the client/browser, with angular.@RequestMapping(value = restaurantResult, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)public String returnRestaurantSearchResultWithYelp() { return response;}Now for my JS/angular side of code:function HomeCtrl($scope, $http) { $scope.term = ; $scope.location = ; $scope.submitSearch = function () { var data = { term: $scope.term, location: $scope.location }; //end data var res = $http.post('/searchRestaurant', data); $http.get('/restaurantResult'). success(function (data) { $scope.response = data; }); } } I wrapped a $http.get inside the $http.post. This function first sends data, which invoke my Java post method, then retrieves the data right after. I am binding the json data with angular so my app is single page. And with angular two way data binding the {{response}} contains the yelp response and will display instantly to the user.My simplified HTML: <input type=text ng-model=term/> <input type=text ng-model=location/> <button ng-click=submitSearch()>Search</button> {{response}}It works, sort of. But I feel there is a better way to do it.The issue: The {{response}} sometimes cannot be updated instantly. For instance, I search burger king, the response will show me the address, location, etc. Then I type McDonalds, the response still shows the info of Burger King. I have to refresh the browser to get the latest and correct response.I was wondering what the issue is causing the response not update instantly? Is it because of browser cache?In terms of the my project build design, what part I did wrong? Is there a better way to handle this type of request? | Handling Java instant Ajax request/respond with Angular | java;javascript;angular.js;spring | I type McDonalds, the response still shows the info of Burger King. I have to refresh the browser to get the latest and correct response.The request is being made before the previous post completes.In your Angular, you need to chain your $http actionsfunction HomeCtrl($scope, $http) { $scope.term = ; $scope.location = ; $scope.submitSearch = function () { var data = { term: $scope.term, location: $scope.location }; //end data var res = $http.post('/searchRestaurant', data); //chain from the post res.then ( function() { return $http.get('/restaurantResult'). }).then ( function(result) { $scope.response = result.data; return data; }).catch ( function(error) { //log error throw error; }); //return for further chaining return res; } } By chaining your actions, you guarantee that the previous action completes before starting the next.Notice that the .then method returns data differently than the .success method.Also I avoid the .success and .error methods for two reasons: They ignore return values and they are deprecated. For more information on tbe deprecation of .success and .error, see the AngularJS $http Service API Reference -- deprecation notice.For more information on chaining see AngularJS $q Service API Reference - chaining promises.UPDATETo answer you questions about the differences between .then and .catch methods and the deprecated .success and .error methods. The $http service .then method returns a response object to its resolve callback.// Simple GET request example:$http({ method: 'GET', url: '/someUrl'}).then(function resolveCallback(response) { // this callback will be called asynchronously // when the response is available }, function catchCallback(response) { // called asynchronously if an error occurs // or server returns response with an error status. });The response object has these properties:data {string|Object} The response body transformed with the transform functions.status {number} HTTP status code of the response.headers {function([headerName])} Header getter function.config {Object} The configuration object that was used to generate the request.statusText {string} HTTP status text of the response.--- AngularJS $http Service API Reference -- general usageDeprecated: The $http service .success method spreads out the response object.// Simple GET request example :$http.get('/someUrl'). success(function(data, status, headers, config) { // this callback will be called asynchronously // when the response is available }). error(function(data, status, headers, config) { // called asynchronously if an error occurs // or server returns response with an error status. });As I said before, avoid these method for two reasons: they ignore return values and they are deprecated.The rule of thumb for functional programming is always return something. By ignoring return values, .success and .error break that rule. What makes promises powerful is returning and chaining. |
_codereview.100928 | Is there any way I can simplify this re-sizable solution? It seems too difficult and messy to me.Working example$.ui.plugin.add(resizable, alsoResizeReverse, { start: function (event, ui) { var self = $(this).data(resizable), o = self.options; var _store = function (exp) { $(exp).each(function () { $(this).data(resizable-alsoresize-reverse, { width: parseInt($(this).width(), 10), height: parseInt($(this).height(), 10), left: parseInt($(this).css('left'), 10), top: parseInt($(this).css('top'), 10) }); }); }; if (typeof (o.alsoResizeReverse) == 'object' && !o.alsoResizeReverse.parentNode) { if (o.alsoResizeReverse.length) { o.alsoResize = o.alsoResizeReverse[0]; _store(o.alsoResizeReverse); } else { $.each(o.alsoResizeReverse, function (exp, c) { _store(exp); }); } } else { _store(o.alsoResizeReverse); } }, resize: function (event, ui) { var self = $(this).data(resizable), o = self.options, os = self.originalSize, op = self.originalPosition; var delta = { height: (self.size.height - os.height) || 0, width: (self.size.width - os.width) || 0, top: (self.position.top - op.top) || 0, left: (self.position.left - op.left) || 0 }, _alsoResizeReverse = function (exp, c) { $(exp).each(function () { var el = $(this), start = $(this).data(resizable-alsoresize-reverse), style = {}, css = c && c.length ? c : ['width', 'height', 'top', 'left']; $.each(css || ['width', 'height', 'top', 'left'], function (i, prop) { var sum = (start[prop] || 0) - (delta[prop] || 0); if (sum && sum >= 0) style[prop] = sum || null; }); //Opera fixing relative position if (/relative/.test(el.css('position')) && $.browser.opera) { self._revertToRelativePosition = true; el.css({ position: 'absolute', top: 'auto', left: 'auto' }); } el.css(style); }); }; if (typeof (o.alsoResizeReverse) == 'object' && !o.alsoResizeReverse.nodeType) { $.each(o.alsoResizeReverse, function (exp, c) { _alsoResizeReverse(exp, c); }); } else { _alsoResizeReverse(o.alsoResizeReverse); } }, stop: function (event, ui) { var self = $(this).data(resizable); //Opera fixing relative position if (self._revertToRelativePosition && $.browser.opera) { self._revertToRelativePosition = false; el.css({ position: 'relative' }); } $(this).removeData(resizable-alsoresize-reverse); }});$(function () { $(#resizable).resizable({ alsoResizeReverse: .myframe });});#resizable, .myframe { border:1px solid black; padding:10px; margin-bottom:20px; width:50%; height: 150px}<script src=https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js></script><link href=http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.0/themes/base/jquery-ui.css rel=stylesheet/><script src=https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js></script><div id=resizable>This is the resizable content...</div><div class=myframe>This must resize in reverse direction...</div> | jQuery resizable plugin | javascript;jquery;html;plugin;jquery ui | null |
_unix.241688 | A few years ago pidgin worked fine, but now I can't find one IM client that connects on Facebook. | Is there a Facebook IM client for Mint (or Ubuntu)? | ubuntu;linux mint;pidgin;facebook | You can use any XMPP client AFAIK(Facebook IM is XMPP based).There is also an option of using non offical facebook messenger desktop version.http://messengerfordesktop.com/Can also try: Empathy, Kopete or Emesene.EDIT: Pidgin works fine with facebook, make sure you have package: purple-facebook |
_unix.25919 | I am running Angstrm on my BeagleBoard-xm. I want to use a webcam (I have Microsoft LifeCam Cinema and Logitech C310). I installed v4l-utils, libv4l-dev and kernel-module-uvcvideo with opkg. But the webcams don't appear in the /dev folder. cheese can't find them too.Here is the output of dmesg:[ 8925.347137] usb 2-2.4.3: new high speed USB device using ehci-omap and address 8[ 8925.489044] usb 2-2.4.3: New USB device found, idVendor=045e, idProduct=075d[ 8925.496490] usb 2-2.4.3: New USB device strings: Mfr=1, Product=2, SerialNumber=0[ 8925.504333] usb 2-2.4.3: Product: Microsoft LifeCam Cinema(TM)[ 8925.510528] usb 2-2.4.3: Manufacturer: Microsoft[ 8926.635742] 8:3:1: cannot get freq at ep 0x82and here is the output of lsusb:# lsusbBus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hubBus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hubBus 002 Device 002: ID 0424:9514 Standard Microsystems Corp. Bus 002 Device 003: ID 0424:ec00 Standard Microsystems Corp. Bus 002 Device 004: ID 05e3:0608 Genesys Logic, Inc. USB-2.0 4-Port HUBBus 002 Device 005: ID 04d9:1603 Holtek Semiconductor, Inc. Bus 002 Device 006: ID 045e:0040 Microsoft Corp. Wheel Mouse OpticalBus 002 Device 008: ID 045e:075d Microsoft Corp.uvcvideo kernel module seems to be in the right folder:# locate uvcvideo.ko/lib/modules/2.6.32/kernel/drivers/media/video/uvc/uvcvideo.ko# uname -aLinux beagleboard 2.6.32 #3 PREEMPT Tue Jul 26 10:56:56 CEST 2011 armv7l unknownlsmodoutput is:# lsmodModule Size Used byipv6 249063 10But I don't see uvcvideo module in the lsmod output. Should I do something else to load the module? Or should I install a specific driver? | Webcam on Angstrm | linux;drivers;video;kernel modules;camera | null |
_softwareengineering.191013 | What is a good strategy to label software requirements in an SRS?Typically outline numbering is employed on headers - but these will renumber if a new heading is inserted in the document. To me it seems like a good idea to aim for a more stable designation for each software requirement. This should make it easier to reference a particular requirement even in the face of an updated SRS.What are your experiences on this? | How to label software requirements? | requirements;requirements management | null |
_codereview.88578 | This program takes a command line argument of how many times you would like to encrypt plain text. After you compile the program, input a message you would like to have coded. I'm new to C and curious about how to make this program more efficient./**caesar.c****Encrypts user supplied messages according to a user supplied encryption key **/#include <stdio.h>#include <cs50.h>#include <stdlib.h>#include <string.h>#include <ctype.h>int main(int argc, string argv[]){ if (argc != '\0' && argc == 2 ) { //converting string input to integers int f= atoi(argv[1]); //getting string command from user string a = GetString(); for(int i = 0, j = strlen(a); i < j; i++) { if ( isalpha (a[i])) { if (isupper(a[i])) { //converting capitalized chars char acap = (a[i] - 65); int ccap = (acap+f)%26; //final capitalized chars loop char ecap = ccap + 65; printf(%c, ecap); } else if (islower(a[i])) { //converting small chars char asma = (a[i] - 97); int csma = (asma+f)%26; //final small chars loop char esma = csma + 97; printf(%c, esma); } } else { printf(%c, a[i]); } } printf(%c, esma); return 0;} else { return 1;}} | Caesar Cipher encryption/decryption | c;caesar cipher | This is unnecessarily complicated: if (argc != '\0' && argc == 2 ) This is exactly the same thing but simpler: if (argc == 2) Instead of the hard-coded ASCII code 65 of A, you could use 'A' to make the code easier to read. So instead of this://converting capitalized charschar acap = (a[i] - 65);int ccap = (acap+f)%26;//final capitalized chars loopchar ecap = ccap + 65;printf(%c, ecap);You can write like this://converting capitalized charschar acap = (a[i] - 'A');int ccap = (acap + f) % 26;//final capitalized chars loopchar ecap = ccap + 'A';printf(%c, ecap);I also added spaces around operators in (acap+f)%26 to make it more readable, which is a good practice.The same goes for the number 97, it's better to use 'a' instead.The code for handling upper case and lower case letters is practically the same, except for the constant 'A' and 'a'.Avoid such code duplication, repetition and copy-paste coding as much as possible.Extract the common logic to a helper function,and reuse it by passing 'A' and 'a' as parameter.Use more descriptive variable names.f, acap, ccap, ecap are really not intuitive,and your code could become much more readable if you gave these better names.@Edward made an excellent remark in comments that I'm just going to quote verbatim:It's worth noting that both original and suggested changes assume a character encoding with a contiguous encoding for the alphabet. This is not actually guaranteed by the C standard. For example, EBCDIC systems are admittedly rare but not yet extinct. |
_unix.71063 | This question may seem trivial at first sight, but it has certain implications and I'm wondering what is the recommended path to take here.Assume the following scenario: a server system. The default boot gets kicked off from a partition on the first hard drive which hosts the /boot volume and the GRUB2 code. The / volume is on an md device (RAID1, in case it matters) and GRUB2 is aware of that. Everything works fine and is nice and dandy.Now: another system is to be set up in parallel for rescue purposes, in case something happens to the md. The rescue shell isn't exactly too helpful, but having a full-fledged Ubuntu installation gives you a lot more power, I reckon. So the idea would be to clone the configuration - largely - which is kept under version control using etckeeper from the default system to the rescue system in a cron job and cherry pick some pieces such as the sshd host keys and /etc/network/interfaces to make sure the rescue system would end up booting into a remotely accessible state resembling that of the default system (possibly locked down to only allow root logins instead - but I think I know how to take care of those parts).How can these two installations share the same /boot volume? It makes sense to do it, because the existing one is on the first hard disk and so will the rescue system be. However, assuming updates and eventually pruning kernels from the default system, this would leave the rescue system in an unbootable state. How can I prevent this and recycle the /boot volume for both installations? | Sharing /boot between two Ubuntu 12.04 Server installations? | ubuntu;boot;dual boot | null |
_softwareengineering.193723 | I am interested in hearing some guidelines as to what feedback is or is not appropriate for a code review. My team has a very unstructured review process and I am trying to suggest some ways to improve it. I am no expert so I hope to hear from you experts out there!Should code review comments be limited to actual problems with the code?Are criticisms about other LOC in the file appropriate even if those lines are not being modified? i.e., criticism of pre-existing code?What about suggestions of different ways to solve the same problem? Should I suggest a new way only when a case can be made for it being better? How do I draw the line between contributing ideas but not sounding like a know-it-all?In matters which are purely a difference of opinion, who should get the 'final say'? The author, the person who knows the code base the best, the person with the highest title or someone else?Any other advice for ensuring the code reviews serve their purpose without unnecessarily blocking the developer's progress?Please, if you could, provide reasoning along with any answers. It will help this junior developer be able to really understand the best way to approach a code review. | What feedback is or is not appropriate for a code review? | code quality;code reviews | null |
_codereview.64268 | I am currently handling some setup of an object on a background thread (I am using a concurrent queue within the following initWithDocumentFileURL method):+ (TWReaderDocument *)initWithDocumentFileURL:(NSURL *)url withLoadingCompletionBlock:(loadingCompletionBlock)completionBlock{ __block NSError *error;TWReaderDocument * twDoc = [[TWReaderDocument alloc] init];twDoc.status = ReaderDocCreated;twDoc.doc = [ReaderDocument withDocumentFilePath:[url path] withURL:url withLoadingCompletionBLock:^(NSError *_error) { if (_error) { _error = error; twDoc.status = ReaderDocReady; } else twDoc.status = ReaderDocFailed;}];//completionBlock(error);return twDoc;}Header@property (nonatomic, assign, readonly) TWReaderDocumentStatus status;Implementation- (TWReaderDocumentStatus) status { __block TWReaderDocumentStatus readStatus; dispatch_sync([ReaderDocument concurrentLoadingQueue], ^{ readStatus = _status; }); return readStatus;}If I would like to access the status property on the main thread do I need to take any precaution or there is nothing to take care of as I am just reading the property on the main thread? | Reading a property on a main thread that is set on a background thread | multithreading;objective c | null |
_unix.122483 | I have 3 input files all having the same number of lines. I have come up with a movie example to make the question look interesting. file1.txt -- Essentially contains the actor names. 1234|jacknicholson|actor5678|jacknicholson|director4321|christianbale|actorfile2.txt -- Contains the movies of the actors.1234|oneflewovercuckoosnest^asgoodasitgets5678|theshining4321|batmanbegins^darkknightfile3.txt -- Residence of the actors.1234|california5678|hollywoodstudios4321|losangelesI am splitting the first input file based on the condition that if names are equal, I need to apply some algorithm. The command is as below. awk -F '|' 'NR>1 && $2 != prev {print } {prev=$2; print}' file1.txtThe above command will make my first file (file1.txt) as,1234|jacknicholson|actor5678|jacknicholson|director4321|christianbale|actorI need to introduce the space at the same position in the remaining 2 files too so that I can apply my algorithm. One approach that comes to my mind is, store the position of spaces in the file1.txt in an array and then when I encounter that position in the remaining 2 files, introduce the spaces. | introduce line break at the same position based on another file | awk;perl | To introduce a blank line in a file at the same position as changes in actors in file1.txt, try:$ awk -F '|' '{save=$0; getline<file1.txt} NR>1 && $2!=prev {print } {prev=$2; print save}' file2.txt1234|oneflewovercuckoosnest^asgoodasitgets5678|theshining4321|batmanbegins^darkknightThe above works quite a bit like your code except that it is extended to read two files at the same time. It reads from file2.txt and saves the line in the variable save. If then reads from file.txt, and using the same logic as your code, determines if the actor changes and, if so, prints a line break. It then prints the line it received from file2.txt. |
_unix.130727 | I've been playing around with obnam these last few days, and although it looks very promising and seems to offer basically everything I ever wanted in a backup tool, I am pretty disappointed in its performance. In fact, it's so slow, I'm suspecting that obnam is not even at fault here, but something in my environment is causing it.So I'm mainly wondering, if anyone else is using obnam or knows its internals well enough to maybe identify the problem.From what I could tell so far, obnam seems to fork an individual gpg process for each file that is backed up. Judging from htop, strace, and iostat, the speed of an initial backup is mostly bounded by the constant forking, while the CPU and the drives (no networking is involved) are mostly idling below 20% utilization.My backup amounts to about 500.000 files with 170 GiB of data in total. So for each backup run, gpg is forked 500.000 times. I'm actually not even surprised that this takes almost an entire day for the initial run and over three hours for another run with most files unchanged. But is this really the performance obnam users should expect? For comparison: an incremental run of rsnapshot (same data, same machine, same drives) takes about four minutes. Granted, there is no encryption involved, but this shouldn't be that significant.So, to ask plainly: Is everyone else's machine not able to run gpg (encrypting a small chunk of data) more than 50 times per second either, ultimately making obnam an almost unusably slow tool? Or is it just me?(FWIW, my machine is a Core i5-2500 with 8G of RAM and SSD drives, running Gentoo. Backup is done onto an HDD, but I couldn't observe any difference to backing up to the SSD, since it's not I/O-bound.) | What is the expected performance of obnam? Or: why is it so slow? | backup;performance | null |
_unix.33155 | My desktop system is:$ uname -aLinux xmachine 3.0.0-13-generic #22-Ubuntu SMP Wed Nov 2 13:25:36 UTC 2011 i686 i686 i386 GNU/LinuxBy running ps a | grep getty, I get this output: 900 tty4 Ss+ 0:00 /sbin/getty -8 38400 tty4 906 tty5 Ss+ 0:00 /sbin/getty -8 38400 tty5 915 tty2 Ss+ 0:00 /sbin/getty -8 38400 tty2 917 tty3 Ss+ 0:00 /sbin/getty -8 38400 tty3 923 tty6 Ss+ 0:00 /sbin/getty -8 38400 tty6 1280 tty1 Ss+ 0:00 /sbin/getty -8 38400 tty1 5412 pts/1 S+ 0:00 grep --color=auto gettyI think ttyX processes is for input/ouput devices but I am not quite sure. Based on this I am wondering that why there are 6 ttyX processes running? I have only one input devices(keyboard) actually. | why there are six getty processes running on my desktop? | linux;terminal;console | This shows because one getty process is running on each virtual console (VC) between tty1 and tty6. You can access them by changing your active virtual console using Alt-F1 through Alt-F6 (Ctrl-Alt-F1 and Ctrl-Alt-F6 respectively if you are currently within X).For more information on what a TTY is, see this question, and for information on virtual consoles, see this Wikipedia article. |
_scicomp.25230 | So I'm working with a rather complicated dynamical system. Instead of writing it all out. It's probably easier if you just clone my git repository.git clone https://gitlab.com/mdornfe1/vortex_acousticThe dynamics of the system is encoded in the function flow inside vortex_acoustic.py. If I integrate the system from rest I find oscillations for certain values of the parameters. The system is 13 dimensional, but here is a plot of the first variable vs. timeSo it seems like the system is approaching a limit cycle attractor. From my understanding of dynamical systems there should be an unstable fixed point inside that limit cycle. I want to try to calculate it so I can analyze its stability. My idea is that the fixed point should be close to the mean of the oscillating quantities, so I use that as a starting value for a numerical root solver. Here's the code for finding the fixed point, but you can also just run stack_exchange.py.import pickle, numpy as np, matplotlib.pyplot as pltimport vortex_acoustic as vafrom scipy import optimizefrom constants import *T = 5000dt = 0.05tn_transients = int(0.9 * T / dt)def calc_fixed_point(seed, params): return optimize.fsolve(va.flow_star, seed, params)def calc_closest_fixed_point(y, params): seed = np.mean(y[tn_transients:, :], 0) seed[Nq+1:2*Nq+1] = 0 y_star = calc_fixed_point(seed, params) return y_star, seedy = np.load('simulation.npy')with open('params.p', 'r') as f: params = pickle.load(f)plt.plot(y[:,0])y_star, seed = calc_closest_fixed_point(y, params)The function calc_closest_fixed_point takes the output of the simulation and the params passed to the simulation. It calculates the mean of the fluctuating quantities after the transients has died out. It sets the derivatives to 0 and uses that quantity seed as a starting point for fsolve. The function calc_fixed_point then finds the fixed point of the system y_star. I thought this approach would show that seed and y_star are very close to each other. But for this example I'm seeing they're quite different. Furthermore the actual value isn't inside the limit cycle.print(seed)>>>array([ 0.18307736, -0.11207637, 0.00382286, 0. , 0. , -0.02016129, 0.08881281, -0.07852504, 0.07439292, 0.0109214 , -0.00894938, -0.02896082, 0.00833759])print(y_star)>>>array([ 1.06466138e+00, -6.65605305e-01, 2.15920825e-02, -5.18569988e-25, 1.44087666e-24, 7.55288134e-03, 5.17875853e-01, -4.41152924e-01, 4.72080951e-01, 4.86813549e-02, -6.04678149e-02, -1.42533599e-01, 5.90028044e-02])Also seed is pretty obviously not a fixed point. If you calculate the function flow at seed the derivatives are pretty far from 0.va.flow(seed,0,*params)>>>array([-0.00543102, 0. , 0. , -0.00113827, -0.00042674, -0.00973662, -0.00775962, 0.01449168, 0.01369892, 0.00331889, 0.00502761, -0.00026469, -0.00076228])Anyone know what's going? I'm correct in assuming there is a fixed point inside the limit cycle right? | Calculating fixed point inside limit cycle | roots;fixed point | null |
_unix.42332 | I did a search for java with babushka, and got the following results:Name | Source | Runs | | Command---------------------+------------------------------------------------------+---------+------+--------------------------------------------java.managed | git://github.com/all4miller/babushka-deps.git | 1 ever | 100% | babushka all4miller:java.managedjava.managed | git://github.com/benhoskings/babushka-deps.git | 2 ever | 50% | babushka benhoskings:java.managedjava environment | git://github.com/compactcode/babushka-deps.git | 4 ever | 75% | babushka compactcode:'java environment'java dev environment | git://github.com/compactcode/babushka-deps.git | 21 ever | 14% | babushka compactcode:'java dev environment'java.environment | git://github.com/compactcode/babushka-deps.git | 1 ever | 100% | babushka compactcode:java.environmentjava.managed | git://github.com/compactcode/babushka-deps.git | 1 ever | 0% | babushka compactcode:java.managedjava | git://github.com/cheef/babushka-deps.git | 1 ever | 100% | babushka cheef:javajava | http://chris-berkhouts-macbook-pro-2.local:9292/.git | 4 ever | 25% | java-6-sun | https://github.com/cheef/babushka-deps.git | 2 ever | 0% | babushka cheef:java-6-sunjava.managed looks the most promising, because I trust benhoskings more than the others. But what does the .managed mean? | What does .managed mean in a babushka package name? | package management | It's just his convention for indicating the template type the dep was based on.managed means that dependency was defined with the managed template.From http://ben.hoskings.net/2010-08-01-design-and-dsl-changes-in-babushka-v0.6 (emphasis mine):That's all cleaned up now. Just as sources have been unified, deps are always defined with the dep top-level method now, whether they use a template or not. Instead of saying gem 'hpricot', you say either dep 'hpricot', :template => 'gem', or dep 'hpricot.gem'. These two styles produce the same dep---the choice is there to allow you to include the template type in the dep's name.Earlier in the same article, he explains that the original name for the managed template was pkg, which was causing confusion for his Mac users who assumed it meant they were for Mac installer packages: The pkg template was renamed to managed because it looked like it handled OS X installer packages.Unfortunately, that leads to confusion in the dep list: I'm guessing you wouldn't have asked what the package suffix name meant if it was called java.pkg. :-) |
_unix.232392 | Plasma shell is not logging in anymore. I've created a new user and it seems to work fine with this user.I've tried to delete the cache folder the config and also the file in /var/tmp/kdecache-user with no luck. Is there some other files or something else that I need to do to fix this? | Plasma shell not logging in | login;plasma;kde5 | null |
_softwareengineering.322430 | I am promoted to team lead position in my organization. Previously I was working as senior software developer or senior software engineer. Now company want to build their own product which is a website. Requirements and technologies selection are established as well. They want to hire team for this project. Senior software engineerJunior software engineerWeb Designer (UI)Database AdminSEO ExpertI have given task to decide which team member should selected first. What I think Database Admin should hired first.Please share your ideas so I should make my first decision accurately.Thank you | How to select a team for a new website development project | project management;planning;team building | null |
_unix.88454 | Does anyone know how do I list existing alias for a certain Unix/Linux user on Debian?For example I have an Unix/Linux user 1001 and want to know which alias for login it has? | How to list existing alias for a certain linux user? | login;alias | null |
_unix.268676 | The following packages have been kept back: click click-dev gir1.2-click-0.4 libclick-0.4-0 0BUTIt's clear that all of these packages are either on hold somewhere, or are in some kind of conflict, or would cause conflict. I don't understand why or where. They are neither Locked in Synaptic, nor Held back by apt or aptitude.I am curious as to why these packages are held back? I cannot get past this with apt-get dist-upgrade, or with apt-get --with-new-pkgs upgrade.I am on Linux Mint 17.3.apt-cache policy click click-dev gir1.2-click-0.4 libclick-0.4-0:click: Installed: 0.4.42+16.04.20151229-0~467~ubuntu14.04.1 Candidate: 0.4.43+16.04.20160203-0~606~ubuntu14.04.1 Version table: 0.4.43+16.04.20160203-0~606~ubuntu14.04.1 0 500 http://ppa.launchpad.net/ubuntu-sdk-team/ppa/ubuntu/ trusty/main amd64 Packages *** 0.4.42+16.04.20151229-0~467~ubuntu14.04.1 0 100 /var/lib/dpkg/status 0.4.21.1ubuntu0.2 0 500 http://mirror.vutbr.cz/ubuntu/archive/ trusty-updates/main amd64 Packages 500 http://security.ubuntu.com/ubuntu/ trusty-security/main amd64 Packages 0.4.21.1 0 500 http://mirror.vutbr.cz/ubuntu/archive/ trusty/main amd64 Packagesclick-dev: Installed: 0.4.42+16.04.20151229-0~467~ubuntu14.04.1 Candidate: 0.4.43+16.04.20160203-0~606~ubuntu14.04.1 Version table: 0.4.43+16.04.20160203-0~606~ubuntu14.04.1 0 500 http://ppa.launchpad.net/ubuntu-sdk-team/ppa/ubuntu/ trusty/main amd64 Packages *** 0.4.42+16.04.20151229-0~467~ubuntu14.04.1 0 100 /var/lib/dpkg/status 0.4.21.1ubuntu0.2 0 500 http://mirror.vutbr.cz/ubuntu/archive/ trusty-updates/main amd64 Packages 500 http://security.ubuntu.com/ubuntu/ trusty-security/main amd64 Packages 0.4.21.1 0 500 http://mirror.vutbr.cz/ubuntu/archive/ trusty/main amd64 Packagesgir1.2-click-0.4: Installed: 0.4.42+16.04.20151229-0~467~ubuntu14.04.1 Candidate: 0.4.43+16.04.20160203-0~606~ubuntu14.04.1 Version table: 0.4.43+16.04.20160203-0~606~ubuntu14.04.1 0 500 http://ppa.launchpad.net/ubuntu-sdk-team/ppa/ubuntu/ trusty/main amd64 Packages *** 0.4.42+16.04.20151229-0~467~ubuntu14.04.1 0 100 /var/lib/dpkg/status 0.4.21.1ubuntu0.2 0 500 http://mirror.vutbr.cz/ubuntu/archive/ trusty-updates/main amd64 Packages 500 http://security.ubuntu.com/ubuntu/ trusty-security/main amd64 Packages 0.4.21.1 0 500 http://mirror.vutbr.cz/ubuntu/archive/ trusty/main amd64 Packageslibclick-0.4-0: Installed: 0.4.42+16.04.20151229-0~467~ubuntu14.04.1 Candidate: 0.4.43+16.04.20160203-0~606~ubuntu14.04.1 Version table: 0.4.43+16.04.20160203-0~606~ubuntu14.04.1 0 500 http://ppa.launchpad.net/ubuntu-sdk-team/ppa/ubuntu/ trusty/main amd64 Packages *** 0.4.42+16.04.20151229-0~467~ubuntu14.04.1 0 100 /var/lib/dpkg/status 0.4.21.1ubuntu0.2 0 500 http://mirror.vutbr.cz/ubuntu/archive/ trusty-updates/main amd64 Packages 500 http://security.ubuntu.com/ubuntu/ trusty-security/main amd64 Packages 0.4.21.1 0 500 http://mirror.vutbr.cz/ubuntu/archive/ trusty/main amd64 PackagesDEBUG:apt-get -o Debug::pkgProblemResolver=true install click click-dev gir1.2-click-0.4 libclick-0.4-0Reading package lists... DoneBuilding dependency tree Reading state information... DoneStarting pkgProblemResolver with broken count: 0Starting 2 pkgProblemResolver with broken count: 0DoneThe following extra packages will be installed: python3-click-packageSuggested packages: ubuntu-app-launch-tools upstart-app-launch-toolsRecommended packages: debootstrapThe following packages will be REMOVED: python3-clickThe following NEW packages will be installed: python3-click-packageThe following packages will be upgraded: click click-dev gir1.2-click-0.4 libclick-0.4-04 upgraded, 1 newly installed, 1 to remove and 0 not upgraded.Need to get 146 kB of archives.After this operation, 1,024 B of additional disk space will be used.Do you want to continue? [Y/n] REPRODUCTION of the PROBLEM:apt-get dist-upgradeReading package lists... DoneBuilding dependency tree Reading state information... DoneCalculating upgrade... DoneThe following packages have been kept back: click click-dev gir1.2-click-0.4 libclick-0.4-00 upgraded, 0 newly installed, 0 to remove and 4 not upgraded.AFTER FIX:apt-get install click click-dev gir1.2-click-0.4 libclick-0.4-0Reading package lists... DoneBuilding dependency tree Reading state information... Doneclick-dev is already the newest version.click-dev set to manually installed.click is already the newest version.libclick-0.4-0 is already the newest version.libclick-0.4-0 set to manually installed.gir1.2-click-0.4 is already the newest version.gir1.2-click-0.4 set to manually installed.0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded. | The following packages have been kept back | debian;apt;aptitude;synaptic | According to the poster, the following command worksapt-get -o Debug::pkgProblemResolver=true install click click-dev gir1.2-click-0.4 libclick-0.4-0and gives the resultReading package lists... DoneBuilding dependency tree Reading state information... DoneStarting pkgProblemResolver with broken count: 0Starting 2 pkgProblemResolver with broken count: 0DoneThe following extra packages will be installed: python3-click-packageSuggested packages: ubuntu-app-launch-tools upstart-app-launch-toolsRecommended packages: debootstrapThe following packages will be REMOVED: python3-clickThe following NEW packages will be installed: python3-click-packageThe following packages will be upgraded: click click-dev gir1.2-click-0.4 libclick-0.4-04 upgraded, 1 newly installed, 1 to remove and 0 not upgraded.Need to get 146 kB of archives.After this operation, 1,024 B of additional disk space will be used.Do you want to continue? [Y/n]So, no problem showed up when running an explicit apt-get install.I asked the poster to run it without the debug flag to see whether it gave the same results, but apparently he had already run the debug version. |
_opensource.120 | Recognized graphic designers usually charge a fee for their work, but what if this project isn't expecting any funds and is expected to run purely off the community?How would I attract a graphic designer (or designers) to create logos, web site graphics and other artistic/graphical works? | How do I recruit a graphic designer to help on a project with no funding involved? | project management;community | Visibly crediting their work on the site/product could be seen by some as payments through advertising.Some graphics design crowdsourcing sites might accept a volunteer/for free project category. Contributors would be interested to contribute to such projects to increase their visible portfolios, exposure, reputation and ultimately their chances of participating/winning in paid projects. |
_webapps.29802 | I need to make google docs evoke the row number for a cell reference by pointing to another cell. Allow me to explain:I have a form with different cells that point to another sheet (Sheet1!). All the cells always point to a cell of a similar row number; only the column changes.For example, the Name field points to Sheet1!C2, Address points to Sheet1!D2, Phone Number points to Sheet1!E2.I want to have a single cell where I can type the row number, so that if I were to type in 5 in such cell, it will automatically make the previous fields point to C5, D5, E5Is there a way of doing this? I am trying to avoid having to go into each cell and manually change the 2 to a 5 or any other number. | Cell row reference coming from another cell in Google Docs | google drive;google spreadsheets | null |
_vi.9585 | I have lines like the following ones (actually function prototypes)void ()word ( word, another word, one_more word, ..., hello, ... )one argument ( only )I want to match each single argument and enclose it between < and >.Before wasting time with the replacement string, I'm trying to devise the proper search pattern. The following command:%s/\(( \|, \)\(.\{-}\)\( )\|,\)/\1<\2>\3/gonly matches and replace odd-position arguments. | Substitute words enclosed between comma or open-parenthesis and comma or closed parenthesis | regular expression;substitute;delimiter matching | It's because your matching groups have overlap! Exept for zero-width pattern items, every charachter in your string will be consumed in the matching. so here you can use \zs and \ze to confine your match::%s/\%(( \|, \)\zs\(.\{-}\)\ze\%( )\|,\)/<\1>/gHere i also changed the first and third captuting groups to non-capturing as we don't need to capture them.for a complete list of zero-width pattern items, see: :h pattern-overview |
_webapps.107388 | In Google Sheets:In column B, I want to display a certain word on each line, based on the value of column A. B2 gets it value from A2, B3 gets it value from A3 etc.range: 1500 triggers the word low1501-1950 triggers the word medium1951 triggers the word high.How do I solve this? | How to get particular words to appear based on a number in another column | google spreadsheets;formulas | null |
_codereview.98514 | I've created some custom code that will capture how long a user spent viewing a picture. The timer will stop when the user clicks or escapes from the fancybox view. Is there an alternate way for me to implement this functionality without using the counterStop setInterval() variable?The specific reason why I added another setInterval() was so that I could quickly stop the first the counterIncrease variable. If the user clicked too fast and reopened the fancyBox, the timer would stack on itself and increment faster than the intended 1 second.Also, as this was a refinement of a previous implementation of this exact functionality (lines of code was significantly reduced/refined), please point out, edit and critque any methods that you would have done differently, so long as the result is the same.Credit and source of proof of concept goes to creator of thisFiddle - ime Vidas.HTML: <div id=fullBrochure> <div id=thumbWrapper> <a href=http://www.alexldixon.com/images/alexdixon.jpg class=fancybox target=_blank><span class=innerText>Front Cover</span><div id=frontCover><img src=http://www.alexldixon.com/images/alexdixon.jpg /></div><span class=Zoom>ZOOM</span></a> </div> <div id=thumbWrapper> <a href=http://www.alexldixon.com/images/face.png class=fancybox target=_blank><span class=innerText>Inside (fully opened)</span> <div id=frontCover><img src=http://www.alexldixon.com/images/face.png /></div><span class=Zoom>ZOOM</span> </a> </div> <div id=thumbWrapper> <a href=http://www.alexldixon.com/images/face2.png class=fancybox target=_blank><span class=innerText>Inside Flap</span> <div id=frontCover><img src=http://www.alexldixon.com/images/face2.png /></div><span class=Zoom>ZOOM</span> </a> </div> <div id=thumbWrapper> <a href=http://www.alexldixon.com/images/face3.png class=fancybox target=_blank><span class=innerText>Back Cover</span> <div id=frontCover><img src=http://www.alexldixon.com/images/face3.png /></div><span class=Zoom>ZOOM</span> </a> </div> </div><table summary= class=mrQuestionTable style=display: inline-block;> <tbody> <tr> <td id=Cell.0.0 class=mrGridCategoryText style= text-Align: Left; vertical-align: Middle; background-color: #D8D8D8; width: 250px; border-color: black; border-width: 1px; border-left-style: Solid; border-right-style: Solid; border-top-style: Solid; border-bottom-style: Solid;> <span class=mrQuestionText style=font-size: 8pt;>Front Cover:</span></td> <td id=Cell.1.0 style= text-Align: Center; vertical-align: Middle; background-color: #D8D8D8; width: 120px; border-color: black; border-width: 1px; border-left-style: Solid; border-right-style: Solid; border-top-style: Solid; border-bottom-style: Solid;> <span style=><input type=text name=_QPQ3_QAD__LP_Q__01_QQ3__Timer id= _Q1_Q0_Q0 class=mrEdit autocomplete=on style= maxlength=10 value= /></span><span style=><input type=checkbox name= _QPQ3_QAD__LP_Q__01_QQ3__Timer_XNo__Ans id=_Q1_Q0_Q0_X0 class=mrMultiple style= value=No__Ans /> <label for=_Q1_Q0_Q0_X0><span class= mrMultipleText style= font-size: 8pt; text-Align: Center; vertical-align: Bottom; width: 120px; border-color: black; border-style: Solid; border-width: 1px;> No Answer</span></label></span></td> </tr> <tr> <td id=Cell.0.1 class=mrGridCategoryText style= text-Align: Left; vertical-align: Middle; background-color: #F8F8F8; width: 250px; border-color: black; border-width: 1px; border-left-style: Solid; border-right-style: Solid; border-top-style: Solid; border-bottom-style: Solid;> <span class=mrQuestionText style= font-size: 8pt;>Inside (fully opened):</span></td> <td id=Cell.1.1 style= text-Align: Center; vertical-align: Middle; background-color: #F8F8F8; width: 120px; border-color: black; border-width: 1px; border-left-style: Solid; border-right-style: Solid; border-top-style: Solid; border-bottom-style: Solid;> <span style=><input type=text name=_QPQ3_QAD__LP_Q__02_QQ3__Timer id= _Q1_Q1_Q0 class=mrEdit autocomplete=on style= maxlength=10 value= /></span><span style=><input type=checkbox name= _QPQ3_QAD__LP_Q__02_QQ3__Timer_XNo__Ans id=_Q1_Q1_Q0_X0 class=mrMultiple style= value=No__Ans /> <label for=_Q1_Q1_Q0_X0><span class= mrMultipleText style= font-size: 8pt; text-Align: Left; vertical-align: Middle; background-color: #F8F8F8; width: 250px; border-color: black; border-width: 1px; border-left-style: Solid; border-right-style: Solid; border-top-style: Solid; border-bottom-style: Solid;> No Answer</span></label></span></td> </tr> <tr> <td id=Cell.0.2 class=mrGridCategoryText style= text-Align: Left; vertical-align: Middle; background-color: #D8D8D8; width: 250px; border-color: black; border-width: 1px; border-left-style: Solid; border-right-style: Solid; border-top-style: Solid; border-bottom-style: Solid;> <span class=mrQuestionText style= font-size: 8pt;>Inside flap:</span></td> <td id=Cell.1.2 style= text-Align: Center; vertical-align: Middle; background-color: #D8D8D8; width: 120px; border-color: black; border-width: 1px; border-left-style: Solid; border-right-style: Solid; border-top-style: Solid; border-bottom-style: Solid;> <span style=><input type=text name=_QPQ3_QAD__LP_Q__03_QQ3__Timer id= _Q1_Q2_Q0 class=mrEdit autocomplete=on style= maxlength=10 value= /></span><span style=><input type=checkbox name= _QPQ3_QAD__LP_Q__03_QQ3__Timer_XNo__Ans id=_Q1_Q2_Q0_X0 class=mrMultiple style= value=No__Ans /> <label for=_Q1_Q2_Q0_X0><span class= mrMultipleText style= font-size: 8pt; text-Align: Center; vertical-align: Bottom; width: 120px; border-color: black; border-style: Solid; border-width: 1px;> No Answer</span></label></span></td> </tr> <tr> <td id=Cell.0.3 class=mrGridCategoryText style= text-Align: Left; vertical-align: Middle; background-color: #F8F8F8; width: 250px; border-color: black; border-width: 1px; border-left-style: Solid; border-right-style: Solid; border-top-style: Solid; border-bottom-style: Solid;> <span class=mrQuestionText style= font-size: 8pt;>Back cover:</span></td> <td id=Cell.1.3 style= text-Align: Center; vertical-align: Middle; background-color: #F8F8F8; width: 120px; border-color: black; border-width: 1px; border-left-style: Solid; border-right-style: Solid; border-top-style: Solid; border-bottom-style: Solid;> <span style=><input type=text name=_QPQ3_QAD__LP_Q__04_QQ3__Timer id= _Q1_Q3_Q0 class=mrEdit autocomplete=on style= maxlength=10 value= /></span><span style=><input type=checkbox name= _QPQ3_QAD__LP_Q__04_QQ3__Timer_XNo__Ans id=_Q1_Q3_Q0_X0 class=mrMultiple style= value=No__Ans /> <label for=_Q1_Q3_Q0_X0><span class= mrMultipleText style= font-size: 8pt; text-Align: Left; vertical-align: Middle; background-color: #F8F8F8; width: 250px; border-color: black; border-width: 1px; border-left-style: Solid; border-right-style: Solid; border-top-style: Solid; border-bottom-style: Solid;> No Answer</span></label></span></td> </tr> </tbody> </table>JavaScript: $(.fancybox).fancybox({ openEffect : 'none', closeEffect : 'none', openSpeed : '0', closeSpeed : '0', arrows: false, mouseWheel: false }); if(jQuery('div#IsInternetExplorer').length > 0) { jQuery('.innerText, .Zoom, a.innerText, a.Zoom, span.innerText, span.Zoom, #thumbWrapper, #frontCover, #insideOpen, #insideFlap, #backCover').css(cursor, all-scroll); } //Start a timer on click for each of the 4 images. var TimerBox = jQuery('input[type=text]'), currentWrapper = $('div#fullBrochure > div#thumbWrapper'), timeArray = [1, 1, 1, 1]; TimerBox.addClass('Timers'); currentWrapper.find('a').attr(tabIndex, -1); currentWrapper.keydown(function (z) { if (z.which == 13 || event.keyCode == 13) { z.preventDefault(); } }); function targetDiv(currentTimer) { var $currentTimer = $(currentTimer); $currentTimer.addClass('selected').siblings().removeClass('selected'); } currentWrapper.on('click', function (c) { targetDiv(this); var $adIndex = $(this).index(), $timerIndex = TimerBox.filter(':eq(' + $adIndex + ')'); if($(this).hasClass('selected')) { var counterIncrease = setInterval(function() { $timerIndex.val(timeArray[$adIndex]++); $timerIndex.addClass('counting'); }, 1000); var counterStop = setInterval(function() { if($('div.selected').length === 0) { clearInterval(counterIncrease); clearInterval(counterStop); } else { $('div.fancybox-overlay:eq(0), a.fancybox-close:eq(0)').on('mouseup', function () { currentWrapper.removeClass('selected'); $timerIndex.removeClass('counting'); }); $(document).keydown(function(esc){ var code = esc.keyCode ? esc.keyCode : esc.which; if(code === 27) { currentWrapper.removeClass('selected'); $timerIndex.removeClass('counting'); } }); } }, 100); } });Working Example | Capture time spent viewing media | javascript;jquery;html;css;fancybox | For most of your code, you use the $ sign for jQuery, like here:$(.fancybox).fancybox({...});However, there are two places where you do not use the $. Instead, you use the name jQuery. Here is one of the spots:if(jQuery('div#IsInternetExplorer').length > 0)Why did you switch? You should be consistent with which function you use, as it is good practice.You are inconsistent with your brace types:if(jQuery('div#IsInternetExplorer').length > 0){ // <======= ...} // <=========but here you do:function targetDiv(currentTimer) { // <====== ... } // <==============Generally, the style for JavaScript is to go with the second version. However, both work equally as well, but you should choose one and stick with that one.You have a few magic numbers in your code, especially around the areas where you are checking key codes:if (z.which == 13 || event.keyCode == 13) {and:if(code === 27) {What do these numbers mean? Don't make the person who is reading your code (or yourself, possibly in the future) have to do some google searches (or tests) to find out what these numbers mean; create constants.At the top of your code, create a constant variable for each magic number like this:var CONSTANT_NAME = magic_number;Then, when you need to use that number again, just use the variable.Another inconsistency:$('div.fancybox-overlay:eq(0), a.fancybox-close:eq(0)').on('mouseup', ...);and:$(document).keydown(...);Why are you setting an event in the first one using $.on, but in the second using that event's specific method? Again, you need to be consistent in your code.I see why you need to have something to stop the counter as soon as the user is done viewing the image/video. However, I don't see why you needed to do that at an interval.Let's break down what you are doing in this interval:If the user is no longer watching the video, stop the intervals.If the user is still watching the video, set event listeners for when the user presses a button.There are a few problems with this: why are you setting the event listeners every single time the interval loops? There is absolutely nothing changing in the event listeners' functions.A better way to go about this would be to set the event listeners outside of any interval. Don't worry; they will still run just fine when the event fires.Now let's take this one step farther: both these events fire when someone is attempting to exit out of viewing and image/video.My question is why are you using an interval to check if the user has exited the image/video, only then to stop the timer? Why don't you just stop the timer when the user exists the image/video?Add this line to the appropriate spot in both of these functions:clearInterval(counterIncrease);Now that the second interval has been basically stripped down to nothing, you can completely get rid of this (hooray!).var counterIncrease = setInterval(function() { $timerIndex.val(timeArray[$adIndex]++); $timerIndex.addClass('counting'); }, 1000);Why are you addClassing $timerIndex every second? Once it's counting, it's counting and you don't need to say that every single second; you need only to specify it once, and then to remove it when it is no longer counting.Remove this line and put it above the interval:$timerIndex.addClass('counting');You are inconsistent with your indentation. Some places you have a space of indentation, and others you have 4 spaces / 1 tab. Choose one. (Preferably 4 spaces or 1 tab). |
_unix.224262 | I want to append a string to the beginning of second line of my text file, for example:123should become:1423Any idea about how to go about with this thing? | Append a string to the beginning of second line using unix | text processing | null |
_softwareengineering.209896 | I have a controller in my mvc4 web application in which there is an action that needs to call another function. What happens in that function i.e. the return value is not important for my action. How i can call that function and never wait for it to be executed?I think it can be done by async but my point is not to use resources, just call the function and never wait for it what ever happens.Please give me some advise. | call a function and never wait for it in C# | c#;.net;asp.net;asp.net mvc | private void Demo(){ // Do something, given that the result doesn't matter.}public void Do(){ Task.Factory.StartNew(this.Demo); // The following line will be executed without waiting for the result. DoSomethingElse();}Note that starting a method without caring about the result or about exceptions it can throw is risky.If an exception is thrown in a Task, it will be hidden until you:Observe the Result,Wait() for the task, or:The GC calls the finalizer on the Task.You can handle yourself 1. and 2. shortly after you call the method, or you can attach a continuation with myTask.OnComplete(myErrorHandler, TaskContinuationOptions.OnlyOnFaulted) to be run when the original task throws an exception. 3. will crash your process; don't do that. |
_unix.373949 | I've just installed the openSUSE tumbleweed Snapshot 20170625 and want to configure Windows Domain login on console. I've successfully added the machine to the domain but when I try to login with domain\user I get login incorrect and in the journal it says User not known to the underlying authentication moduleI've done this successfully on the 13.1 release... what have I forgot? | Login with Active Directory not working | opensuse;authentication;active directory | null |
_unix.116914 | I've installed Linux Mint 16 on a netbook that I'm trying to pump more life into. I'm currently stuck with configuring the wireless as the computer uses a USB wireless adapter (rt5370 from Ralink) due to its own wireless interface being hard blocked (the fn key is broken).The connection is protected by WPA.I installed the Linux driver, and I'm able to scan for networks nearby. However, when I try to:$ wpa_supplicant -B -i ra0 -DWext -c /etc/wpa_supplicant.confI get:ra0: Unsupported driver 'wext'I've tried different drivers, and none of them work. I've also tried finding out what driver the wireless adapter uses (in theory it should be rt5370sta which is what I installed) to no avail. Tried lsusb, lspci -k, and lsmod; but none of them list the driver I need to be using.Does anyone know whether I'm asking the right question or if the problem lies somewhere else? I was confident this was it as iwlist ra0 does work, and /etc/wpa_supplicant.conf is configured as per the instructions over here: https://www.linux.com/learn/tutorials/374514-control-wireless-on-the-linux-desktop-with-these-toolsI tried wifi-radar, which gets stuck on the same issue (ends up completely unresponsive and I have to reboot computer in order to start it up again; killing the process doesn't work).The computer has no internet access, but I can use Keryx to update or install packages.Any help with figuring this out in order to get the internet working is very much appreciated! | What driver is being used by a wireless usb adapter? | ubuntu;linux mint;drivers;wifi | Don't use Ralinks drivers as they are unneccesary.The RT5370 uses the uses the rt2800usb drivers on the kernel side, and the nl80211 drivers on the wireless side of things.If you start afresh or if you remove Ralink's drivers, when you plug in the RT5370 you should get a wlan0 interface already.If you use wpa_supplicant, specify the driver nl80211 when you're starting it, and it should work sweet.To specify the driver with wpa_supplicant, use the -Dnl80211 command line switch. |
_codereview.48288 | I'm trying to improve my understanding of recursive and iterativeprocesses. I've started with SICP, but have branched off to try andfind a few exercises when I started having difficulty. Currently I'vebeen looking at a series of posts on the subject by TomMoertel.Tom's codedefines a node object for binary search trees and a search function:class BSTNode(object): Binary search tree node. def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def __repr__(self): return '(%s, %r, %r)' % (self.val, self.left, self.right)def find_val_or_next_smallest(bst, x): Get the greatest value <= x in a binary search tree. Returns None if no such value can be found. if bst is None: return None elif bst.val == x: return x elif bst.val > x: return find_val_or_next_smallest(bst.left, x) else: right_best = find_val_or_next_smallest(bst.right, x) if right_best is None: return bst.val return right_bestThe exercise asks us to transform the search function into aniterative process and gives a generalprocedurefor doing so: refactor all recursive calls into tail calls usingaccumulators and then create a loop structure.I've refactored the else clause in the search function into: else: return work(find_val4(bst.right, x), bst)def work(child_node, parent_node): if child_node is None: return parent_node.val return child_nodeBut I've been having trouble figuring out how to move the logic donein the 'work' function into an accumulator. Any advice, hints, or waysto think about this would be totally appreciated. | Understand recursion | python;recursion;iteration | Ahhhh. Okay.That the issue here is that if the process takes a right branch at node Foo, it needs to store a reference to Foo in the event that it fails to find a child node which is less-than or equal. That reference effectively lives in the stack-calls which occur in inside the calls to the work function. There can be an arbitrary number of these calls, so we need an internal, private stack:def find_val_iterative(parent_node, x): right_branch = [] def _inner(parent_node, x): if parent_node is None: if right_branch: return right_branch.pop().val return None elif parent_node.val == x: return x elif parent_node.val > x: return _inner(parent_node.left, x) else: right_branch.append(parent_node) return _inner(parent_node.right, x) return _inner(parent_node, x) |
_unix.81371 | I'm not able to see (or access) my WiFi in Ubuntu. tharcisyo@tssd:~$ iwlist scaneth0 Interface doesn't support scanning.lo Interface doesn't support scanning.wlan0 Failed to read scan data : Network is down. | Problem with wifi in Ubuntu | ubuntu;wifi | null |
_unix.384056 | My ubuntu VM does not run cron jobs with a TTY (not even when I log in and run the command from the user's env).Because of this, cron can't run tmux or screen, preventing programs (specifically rtorrent in this case) to be run in the background in a simple and attachable way.What is the best approach to running a program like rtorrent on boot while making it easy to attach, detach, and kill the process from any terminal?I assume just running the equivalent of rtorrent & should do it, but this is not as convenient as screen/tmux. | What is the best way to attach to a cron program without TTY | cron;tmux;gnu screen;tty | If you use the -d option with tmux new, it won't attach to or require a tty. From man tmux:new-session [-AdDEP] [-c start-directory] [-F format] [-n window-name] [-s session-name] [-t group-name] [-x width] [-y height] [shell-command] (alias: new)Create a new session with name session-name.The new session is attached to the current terminal unless -d is given. [...]For example:tmux new -d -s rtorrent rtorrentThat creates a new tmux session called rtorrent and runs rtorrent inside it.You will probably need to configure ~/.tmux.conf, and run a script to start rtorrent (rather just the bare rtorrent command) in order to setup the run environment correctly.The user who owns the cron job can attach to the session at any time with:tmux attach -t rtorrentThe equivalent for Screen isscreen -d -m -S rtorrent rtorrentfrom the cron job and screen -S rtorrent -rd to attach later. |
_softwareengineering.245274 | I would like to define several names for the same type and have the compiler distinguish between them.My motivation is that different int variables could represent very different units, and I would like the compiler to catch errors in units.typedef int Speed does not generate any warnings, when assigning to Speed from int. One possible solution is using an enum. Furthermore, the enum hack does not let me specify the underlying representation e.g. uint8_t.Is what I am trying to do a bad practice? How do I achieve it in C++? Edit:Grim. I tied using enum Speed {};. error: invalid conversion from 'int' to 'Speed' [-fpermissive] error: no match for 'operator+=' in 'a += b'Those are just a couple of errors I encountered. Enums can't be the right way.I will think about structs, and if in my case some members and predefined operators can actually make the rest of the code cleaner.Hmm, here is quite some research, to the point of making my question a duplicate. | How to define different names for the same type and have the compiler check them? | c++11;type safety | null |
_unix.350063 | I've got a file called dispositivos.dat in wich I have all the information related to devices directly connected to certain cisco equipment, depending on the equipment, the file changes, those are examples of this file: Example_1:Device ID: CIVIL_3702-01IP address: 148.000.000.140Interface: FastEthernet0/47Port ID (outgoing port): GigabitEthernet0Device ID: SEP0c1167231e23IP address: 148.000.000.149Interface: FastEthernet0/16Port ID (outgoing port): Port 1Device ID: SEP0c116722f331IP address: 148.000.000.162Device ID: SEP0c116722f197IP address: 148.000.000.155Interface: FastEthernet0/8Port ID (outgoing port): Port 1Device ID: Barragan_3750IP address: 148.000.000.129Interface: GigabitEthernet0/1Port ID (outgoing port): GigabitEthernet1/0/11SN: OPC13020953 Example_2: Device ID: BIOTERIOIP address: 148.000.00.189Interface: GigabitEthernet1/0/6Port ID (outgoing port): GigabitEthernet0/1SN: P7K08UQ Device ID: N7K-LAN(JAF1651ANDL)IP address: 148.000.0.192Interface: GigabitEthernet1/0/1Port ID (outgoing port): Ethernet7/23SN: H006K022 Device ID: LAB_PESADOIP address: 148.000.000.130Interface: GigabitEthernet1/0/11Port ID (outgoing port): GigabitEthernet0/1SN: FNS174002FT Device ID: Arquitectura_SalonesIP address: 148.000.000.61Interface: GigabitEthernet1/0/9Port ID (outgoing port): GigabitEthernet0/49SN: FNS14420533 Device ID: CIVIL_253IP address: 148.000.000.253Interface: GigabitEthernet1/0/4Port ID (outgoing port): GigabitEthernet1/0/52SN: H006K021 I'm using awk to create a csv file with this info, but as you can see I don't always have all the information, I'm specifically interested in SN (serial number) that is my primary key in my DB, the awk code I have is this:awk ' BEGIN { RS = \n\n FS = \n OFS = , print sn,device_id,ip_address } { for(i=1; i<=NF; i++) { split($i, a, :); k[a[1]] = a[2] } print k[SN], k[Device ID], k[IP address] }' Example.dat > Example.csvIt works fine for Example_2 because every device has SN:sn,device_id,ip_address P7K08UQ , BIOTERIO, 148.000.00.189 H006K022 , N7K-LAN(JAF1651ANDL), 148.000.0.192 FNS174002FT , LAB_PESADO, 148.000.000.130 FNS14420533 , Arquitectura_Salones, 148.000.000.61 H006K021 , CIVIL_253, 148.000.000.253 H006K083 , Arquitectura, 148.000.000.253 H006K032 , ING_CIVIL, 148.000.000.251 FNS16361SG0 , ING_CIVIL_DIR, 148.000.0.188 H006K040 , Ingenieria_Posgrado, 148.000.000.253 00000MTC1444080Z, Biblio_Barragan, 148.000.000.61 FNS11190FLE , Electronica_Edif_3, 148.000.000.253 FDO1129Z9ZJ,Barragan_3750,148.000.0.199But in Example_1 I get this output:sn,device_id,ip_address, CIVIL_3702-01, 148.000.000.140, SEP0c1167231e23, 148.000.000.149, SEP0c116722f331, 148.000.000.162, SEP0c116722f197, 148.000.000.155 OPC13020953 , Barragan_3750, 148.000.000.129FCQ1622X1GH,LAB_PESADO,148.000.000.130In Example_1 I need an output like this:sn,device_id,ip_address OPC13020953 , Barragan_3750, 148.000.000.129 FCQ1622X1GH ,LAB_PESADO,148.000.000.130I need to avoid those devices without SN, I need the awk code to work in any case.Could you help me?Thanks in advance | awk check condition and print just when it's true | shell script;awk;csv | A nonempty string is true, so you can just check k[SN] for truthiness. Also, I would suggest clearing the whole of k at the beginning or end of the loop to avoid values from the previous item bleeding through.So, replace the print line with something like:if (k[SN]) { print k[SN], k[Device ID], k[IP address]}delete k; |
_unix.333595 | In order to overcome a number of issues arising from nginx I decided to switch it off and activate apache instead on Plesk. Yet when I did it no php script seems to run and I get Service Temporarily Unavailable whatever page I call as you may see at this page.What other operation need I do to have it fully working? | php not working after having activated Apache instead of nginx on plesk | centos;apache httpd;nginx;plesk | null |
_computerscience.5181 | How are fluid simulations handled in Computer Graphics? For a novice, there are hardly any novice friendly tutorials explaining how particles or fluids can be simulated.Things like smoke, crown splashes and fog are they animated by artists as opposed to physically based simulations? If there are any worthwhile resources that you could recommend please do! :) | How are fluid simulations handled in Computer Graphics? | animation;pbr;simulation;fluid sim | null |
_unix.232601 | I am trying to extract the values of the %user,%nice etc from the output of the sar command.Command : sar -P ALL 1 1Output of this :Linux 2.6.32-358.el6.x86_64 (ftizsldapp009.ftiz.cummins.com) 09/28/2015 _x86_64_ (4 CPU)02:49:40 PM CPU %user %nice %system %iowait %steal %idle02:49:41 PM all 3.01 0.00 2.51 0.00 0.00 94.4902:49:41 PM 0 1.98 0.00 3.96 0.00 0.00 94.0602:49:41 PM 1 6.00 0.00 4.00 0.00 0.00 90.0002:49:41 PM 2 2.00 0.00 1.00 0.00 0.00 97.0002:49:41 PM 3 1.98 0.00 2.97 0.00 0.00 95.05Average: CPU %user %nice %system %iowait %steal %idleAverage: all 3.01 0.00 2.51 0.00 0.00 94.49Average: 0 1.98 0.00 3.96 0.00 0.00 94.06Average: 1 6.00 0.00 4.00 0.00 0.00 90.00Average: 2 2.00 0.00 1.00 0.00 0.00 97.00Average: 3 1.98 0.00 2.97 0.00 0.00 95.05I have written following string to get the values but this doesn't seen to work. My Command :sar -P ALL 1 1 | awk '{cpu=$3; pctUser=$4; pctNice=$5; pctSystem=$6; pctIowait=$7; pctIdle=$NF}' '{printf %-3s %9s %9s %9s %9s %9s\n, cpu, pctUser, pctNice, pctSystem, pctIowait, pctIdle}'Kindly advise, if you see any error in my command or if you can write/advise me on writing this.Thanks | Need help in writing awk to extract cpu utilization from sar command | awk;cpu usage;sar | null |
_hardwarecs.6500 | Definition of processor: A CPU that has to be attached to a motherboard. May or may not have integrated graphics. Does not contain other computer parts such as memory (other than parts crucial to the functioning of a modern processor such as registers and cache), sensors, connectors (other than the socket), etc.Definition of individually: Is not contained as part of a mandatory bundle. Is not a part of a system on a chip or other similar constructs.Definition of can be purchased by the average joe: Does not require a corporate contract. Does not require a phone call to the company. Does not require a bunch of hoops to be jumped through. Can be bought at a quantity of 1.Companies that are included in x86: Intel, AMD, and other minor x86 manufacturers. (Even though other architectures by Intel such as IA32, etc. are completely different from x86, I am not interested in them)Other preferable things: Motherboards, Memory, and all of the other components required to make a working personal computer (luxuries excluded) to be available.This question was asked out of curiosity, but it may have practical applications as I am a very casual hobby operating system developer looking to dabble in non-x86 architectures.I find it hard to believe that x86 is the only computer architecture that you can actually purchase individual components for and build a personal computer. If that is the case, that is really a shame =(Further clarification: I am looking for a socketed CPU | Is there a non-x86 processor that can be purchased by the average joe individually? | processor;processor architecture | I am not aware of any non-x86 consumer-level CPUs, ie. ones where you can simply purchase and slot together all the parts for a computer.Various ARM CPUs can be purchased individually, and OpenCores has some CPU designs that can be loaded up on an FPGA, but these aren't end-user-friendly: they require sufficient electrical-engineering skills to design a mainboard for connecting the CPU to things like memory or a video controller, or at least the assembly skills to build someone else's design.The only non-x86 CPUs I'm aware of that were ever even remotely available to consumers in build-your-own-computer form were the DEC Alpha (discontinued in 2001) and the PowerPC (you could cobble together something from Apple spare parts until about 2005). |
_unix.381342 | I'm trying to make sound from my phone show up as a pulseaudio input so that I can play music through my computer's speakers using bluetooth A2DP. I'm using arch linux with bluez 5.45.There are tons of guides about this on the web, but they all seem out of date. In particular, with bluez 5.45 (and bluez-utils 5.45 and bluez-tools 0.2) there is no file /etc/bluetooth/audio.conf anymore. hcitool and sdptool do not exist any more. There is no longer an org.bluez.AudioSource interface I can call on hci devices over dbus. Some web pages suggest things should just work now, but I certainly don't see any sources or sinks after pairing my phone (a Pixel) with my computer.What does work: I am able to pair my phone from bluetoothctl and ping it with l2ping. I placed my user in the lp group and edited /etc/dbus-1/system.d/bluetooth.conf so I have all possible bluetooth permissions. pacmd list-modules shows that I have loaded module-bluetooth-policy, module-bluetooth-discover, and module-bluez5-discover. On my phone's bluetooth menu, my computer shows up as used for Media audio (don't know if that's right or not).However, pacmd list-sources doesn't list anything about bluetooth, and there's not a hint of bluetooth anything under pavucontrol. | Bluetooth A2DP pulseaudio source to play sound from phone to linux with bluez 5.45 | linux;pulseaudio;bluetooth | Well, I spent hours working on this and for some reason was unable to connect to my phone. However, I then tried on a different computer, and simply typing connect xx:xx:xx:xx:xx:xx in the bluetoothctl shell was enough to connect and get audio working. Then I went back to the first computer, ran remove xx:xx:xx:xx:xx:xx and re-paired, and then it worked.The one thing I did differently was to be playing music while pairing and connecting in the cases that worked, while in the first case I tried connecting before sending audio.So basically to summarize for other people who are trying to get bluetooth working on arch, these are the steps:pacman --needed -S pulseaudio-bluetooth bluez-utils bluez-tools rfkillsystemctl enable bluetoothsystemctl start bluetoothrfkill unblock wifigpasswd -a `logname` lpThen as yourself run pulseaudio -k, log out, and log in again to get into the lp group (which provides bluetooth access).Now play music from your phone's built-in speaker and place your phone in pairing mode.Finally, once again as root run bluetoothctl, and from within the utility run the following commands:power onscan onpair xx:xx:xx:xx:xx:xx[confirm pin]scan offconnect xx:xx:xx:xx:xx:xxtrust xx:xx:xx:xx:xx:xxAt this point if things are working the phone will stop playing through its speaker, and you will see a new input under the pavucontrol application.Note, the trust command is necessary if you want your phone to connect automatically when it is in range, without you needing to run a copy of bt-agent to authorize the phone's access to your sound. Otherwise, you will need to initiate all connections from your computer, either with the connect command in bluetoothctl, or with a command like this:dbus-send --system --type=method_call --dest=org.bluez \ /org/bluez/hci0/dev_xx_xx_xx_xx_xx_xx org.bluez.Device1.Connect |
_codereview.8881 | I'm a rather novice programmer who recently came up with a solution that works for my project, however I'm always looking for ways to improve my code. So essentially, I have a settings form that pop's up and I was looking for a way to put it next to my main form but not covering it nor appearing partially off of the screen the main form is on. I came up with this but it's not very dynamic because it only checks 4 different locations and if none of them work it uses the default, which is center screen.Here is what I have:private void Place_Form(Form formToPlaceNextTo, Form formToPlace) { Point alignRightTop = new Point(m_parent.Location.X + m_parent.Width, m_parent.Location.Y); Point alignRightBottom = new Point(m_parent.Location.X + m_parent.Width, (m_parent.Location.Y + m_parent.Height) - this.Height); Point alignLeftTop = new Point(m_parent.Location.X - this.Width, m_parent.Location.Y); Point alignLeftBottom = new Point(m_parent.Location.X - this.Width, (m_parent.Location.Y + m_parent.Height) - this.Height); if (Screen.FromControl(formToPlace).WorkingArea.Contains(new Rectangle(alignRightTop.X, alignRightTop.Y, this.Width, this.Height))) { this.Location = alignRightTop; return; } if (Screen.FromControl(formToPlace).WorkingArea.Contains(new Rectangle(alignRightBottom.X, alignRightBottom.Y, this.Width, this.Height))) { this.Location = alignRightBottom; return; } if (Screen.FromControl(formToPlace).WorkingArea.Contains(new Rectangle(alignLeftTop.X, alignLeftTop.Y, this.Width, this.Height))) { this.Location = alignLeftTop; return; } if (Screen.FromControl(formToPlace).WorkingArea.Contains(new Rectangle(alignLeftBottom.X, alignLeftBottom.Y, this.Width, this.Height))) { this.Location = alignLeftBottom; return; } }Any suggestions or preferred coding techniques?Addendum#1: I agree that it's easier and probably more preferred to let the framework decide where to put forms, however this settings form changes the visual look of the main form and the default position of the settings form is almost directly on top of the main form. This poses a problem in regards to user friendliness (in my eyes). | Is there a more elegant way of arranging my forms? | c#;winforms | My bad, I think see now what you wanted. I just did not feel like reading your logic fully (too many details). After I did read it, I saw that you got the details right. All you needed was to stick your points into a list or enumerate over them, as in this example. This way, if you feel like adding more options - you can. Let me know if this works, so that I can delete the other answer.private void Place_Form(Form formToPlaceNextTo, Form formToPlace){ foreach (Point pointToTry in EnumerateFormPlacement(formToPlaceNextTo, formToPlace)) { var rectToTry = new Rectangle(pointToTry.X, pointToTry.Y, formToPlace.Width, formtoPlace.Height); if (Screen.FromControl(formToPlace).WorkingArea.Contains(rectToTry)) { formToPlace.Location = pointToTry; return; } } // Else no match, hence default location.}private IEnumerable<Point> EnumerateFormPlacement(Form formToPlaceNextTo, Form formToPlace){ Point alignRightTop = new Point( formToPlaceNextTo.Location.X + formToPlaceNextTo.Width, formToPlaceNextTo.Location.Y); yield return alignRightTop; Point alignRightBottom = new Point( formToPlaceNextTo.Location.X + formToPlaceNextTo.Width, (formToPlaceNextTo.Location.Y + formToPlaceNextTo.Height) - formToPlace.Height); yield return alignRightBottom; Point alignLeftTop = new Point( formToPlaceNextTo.Location.X - formToPlace.Width, formToPlaceNextTo.Location.Y); yield return alignLeftTop; Point alignLeftBottom = new Point( formToPlaceNextTo.Location.X - formToPlace.Width, (formToPlaceNextTo.Location.Y + formToPlaceNextTo.Height) - formToPlace.Height); yield return alignLeftBottom;} |
_unix.227653 | With the command of df, I can get something like:Filesystem 1K-blocks Used Available Use% Mounted on/dev/root 197844228 15578648 180242500 8% /devtmpfs 4101368 0 4101368 0% /devtmpfs 820648 292 820356 1% /runtmpfs 5120 0 5120 0% /run/locktmpfs 1693720 4 1693716 1% /run/shmWhat if I just want to keep the 180242500 number recorded of / and store it in a file (like disk-space-available.txt)If I use df >> disk-space-available.txt it will store all the content while I just want the raw number in that file.For example if there is something like this then it's working:df -OUTPUT=raw-available-number180242500What can I do? | How do I get / available space with df and output it to a log file? | shell | You can filter easily with awk, checking if the last field equal /, then print the corresponding 4th field:df | awk '$NF == / { print $4 }' >> outputor:df / | awk 'NR == 2 { print $4 }' >> output |
_unix.273335 | I have a scenario where a tomcat user-defined configuration is stored in a file called tomcat.env.In catalina.sh we are sourcing the values as below:. $CATALINA_BASE/bin/setenv.shBut as the configuration is present in a different file I tried adding:#!/bin/shif [ -f ./envvars/tomcat.env ]; then . ./envvars/tomcat.envfiBut the values from the tomcat.env file do not get sourced into the shell running the catalina.sh script. So the custom configurations are not getting set.Any idea why this is happening ? or is my understanding of source not right ?folder structure--bin (contains)-------- catalina.sh-------- setenv.sh-------- envvars (contains)-------------------- tomcat.envthe script is executed from a interactive parent script which inturn invokes catalina.sh and within catalina.sh setenv.sh is sourced which internally sources tomcat.env. | Unable to source file | bash;shell script | null |
_unix.49987 | Does ls have a way to show negated conditions like all files which are not a symlink? I use the latter a lot in a project directory but other negations would be useful as well.For now, my research has only lead to creating an alias to something like:find . -maxdepth 1 ! -type l | sort # (...)but obviously this way I don't get the colouring of ls, the column formatting, etc...I am on Bash v3 on OS X 10.8.2 and Bash v4 on Pangolin sometimes. | ls everything that is _not_ a symlink | bash;ls | Instead of piping it to sort, use ls.find . -maxdepth 1 \! -type l -exec ls -d {} +find . -maxdepth 1 \! -type l | xargs ls -dIf you used the zsh shell you could use their non-portable glob extensions:ls -d *(^@) |
_unix.11023 | Imagine you were working on a system and someone accidentally deleted the ls command (/bin/ls). How could you get a list of the files in the current directory? Try it.I tried many methods and also searched on the Internet but nothing. I want to ask beside ls command what command can we use to list out all the files. | Linux - command to list files (except ls) | shell;ls | null |
_codereview.66686 | Implementation: IEnumerable<BigInteger> Fibs(){ BigInteger a = 0; BigInteger b = 1; while(true) { b = a + (a = b); yield return a; }}Usage:void Main(){ // take first 100 fib numbers var fibs = Fibs().Take(100);}How can I improve this? | Calculating Fibonnaci sequence lazily | c#;fibonacci sequence;generator;lazy | null |
_cstheory.38648 | Recently in this beautiful paper, https://arxiv.org/pdf/1705.02397.pdf it has been shown that there is an explicit $Th \circ Th$ function with sign-rank scaling exponentially in dimension. I wanted to get some context for this,Before this paper was there no other function known in the $Th \circ Th$ or $Th \circ Maj = Maj \circ Th$ or in any other $TC^d$ class with such high sign-rank? What other functions do we know of which have a high sign-rank? I can see it to be known for only a handful of examples like the Minsky-Pappert function, a depth $3$ $AC^0$ generalization of it (in a Razborov-Sherstov paper) and another in a Bun-Thaler paper and Inner-Product-Mod-2. Are there others? (If yes, then can you kindly link to references to their proof?) The page 4 and 5 of this paper give some intuition about what makes a Boolean function have a sign-rank. It would be great to know if others have more insights to add to this discussion. Are there maybe any folklore thumb-rules which help judge if a function has a high sign-rank? | About Boolean functions with a high sign-rank | circuit complexity;linear algebra;boolean functions;circuit families;boolean matrix | null |
_webmaster.6661 | Do you know any research paper about spatial data mining algorithms to retrieve trends about local business services (such as google places.. etc)let's say most rated restaurants this week.. etc ?I need scientific material about it.thanks | Spatial data mining algorithms about local business web services? | web services;map | That is a really specific question - your best bet would be to inquire directly with people who specialize in spatial data mining and possibly with companies which provide local business/restaurant data to see what's out there.(Note that sites like Yelp and Google Places have API's which might come in handy if you plan to conduct any original research) |
_scicomp.3227 | I have encountered the following system of differential equations in lagrangian mechanics. Can you suggest a numerical method, with relevant links and references on how can I solve it, and the implementation in C (if possible) Also, is there a shorter implementation on Matlab or Mathematica?\begin{align*}mx \dot y^2 + mg\cos(y) - Mg - (m+M)\,\ddot x &= 0 \\g\sin(y) + 2\dot x\dot y + x \,\ddot y &= 0\end{align*}where $\dot x$ or $\dot y$ are time derivatives, and the double dots indicate a 2nd derivative wrt time. | Solving two coupled non-linear second order differential equations numerically | numerics;matlab;mathematica | null |
_cs.13088 | Consider we have a finite set $S$ with $n$ distinct elements. We want to find a subset $\{a_1, a_2, \dotsc, a_k\}\subseteq S$ ($k\ll n$) such that a function $f(a_1,a_2,\dotsc,a_k)$ is maximized. Consider $f$ to be a symmetric function that takes $k$ arguments.More specifically, we are given $n = 120$ items, each item being associated with three positive numbers $(A_i, B_i,C_i)$, and we want to choose $k=12$ items within this set such that$$ \frac{\sum_{k=1}^{12} A_{i_k} \times \left\lceil\frac{\sum_{k=1}^{12} B_{i_k}}{10000}\right\rceil}{\sum_{k=1}^{12} C_{i_k}} $$is maximal.If we solve it by exhaustive search it requires $\binom{120}{12} \approx 10^{16}$ operations. Is there faster method to this problem? Approximate solution is also fine. | Subset optimization problem | algorithms;optimization;approximation | null |
_softwareengineering.210620 | I already read some post about the why use embedded script language but I want to ask when to use it.I have implemented an Objective-C / Javascript binding framework which allow me to write Javascript to use any Objective-C classes and methods. I found it very useful for debugging purpose because I can check / modify the internal state of my app at runtime. But I also found I still prefer to write ObjC code instead of JS code when building my app for some reasons:Code completion. If I want to call some UIKit method froom JS, I often have to check the document for its name compare to just type first few letters and let Xcode complete it for me in ObjC.All the benefit of static typed language. ObjC is static typed and dynamic typed language so compiler can do lots type checking for me when possible.Performance?C binding to JS not ready yet (this required to parse header and generate code to expose C function, enum, struct, etc)More natural to write ObjC when dealing with ObjC methods. (e.g. in JS write code like view.setEdit_animated(true, true) compare to ObjC [view setEdit:YES animated:YES]But I feel I should write more JS code so I can take the benefit scripting language (e.g. replace methods with bug fixes at runtime)I am not sure which part of my app should be written in JS and which part should be written in ObjC. Any advice?Also any design pattern can be used for embedded script language? | When to use embedded script language? | design patterns;javascript;objective c;scripting | There are two main benefits of scripting in my opinion:it is usually fasterand it is usually fasterThe first faster is for JIT compilation and underlying C interpreters that most languages have and the second one is for not needing to recompile your code.Scripting should be used whenever you want to quickly change behavior without the need of recompilation. So you probably want to script the user interface and just tell it how to connect to the binary code. Writing GUIs in statically typed languages is most likely hard and complex. Most scripting languages are also useful when you want to do things like events or implement simple behavior in certain parts of your application.The benefit of splitting it is, that you get a program core that is compiled once, and a number of script files that maybe make up your application behavior. So actually there is a third advantage to it: Scripting is usually faster. This time in terms of application development. You just adapt a script file and run your program again, or even change scripts at runtime and the immediately see the results.One field where applications in native binaries are really faster than scripts is when it comes to hardware interaction and OS calls. Since scripting usually is intended to be cross-platform, you are likely to have to use the native libraries for applications. Scripting languages would have to wrap them, applying a performance penalty. And also Interpreters have their own threading model and garbage collection. If you need control over these facilities, choose native binaries. |
_reverseengineering.6592 | I'm working on a certain executable to which I add additional binary files from time to time.A few hours ago, I added an additional binary file to the idb I was working on like this:The additional binary file is about 60k in size.When I next pressed ctrl+W, it took a long while for IDA to save, and then I noticed the .idb file grew to 16GB in size. It couldn't have been more than a few megabytes before that.I tried editing the sections and deleting the one I just added and re-saving but it doesn't seem to change anything.I have no backup.What can I do at this point?edit:I forgot to mention, when I try to close and tell IDA to collect garbage, it still saves 16GB worth of idb file. Telling it to deflate the database causes the resulting idb file to be 16 -MB- but when I open it again it inflates to 16GB. Specifically, the .id1 file is the heavy one. | .idb file suddenly grew to 16GB in size | ida | null |
_softwareengineering.251242 | For example I have a server [c#] and 4 clients. When the first client sends a request to the server I want to push a notification to the other 3 clients that they should send a request to the server with some required data. After I receive requests from all clients I want to send the same response to all of them.What is the best way/pattern to implement something like this? | Server should accumulate several requests and to retrurn response for all | c#;wcf;client server | null |
_cstheory.36838 | Given a $k>0$ and a graph $G(V,E)$ with known independence number $\sqrt{|V|}\leq\alpha(G)\leq\alpha\sqrt{|V|}$ and chromatic number $\frac1\beta\sqrt{|V|}\leq\chi(G)\leq\sqrt{|V|}$ for some fixed $\alpha,\beta\geq2$ and given an optimum vertex coloring is it $\mathsf{NP}$-complete to decide if clique number $\omega(G)>k$? | Deciding $\omega(G)>k$ when $\alpha(G)$ and $\chi(G)$ have bounds and are known | graph algorithms;np complete;graph colouring;clique;independent set | null |
_softwareengineering.167687 | I have some experience writing small tools in Haskell and I find it very intuitive to use, especially for writing filters (using interact) that process their standard input and pipe it to standard output.Recently I tried to use one such filter on a file that was about 10 times larger than usual and I got a Stack space overflow error.After doing some reading (e.g. here and here) I have identified two guidelines to save stack space (experienced Haskellers, please correct me if I write something that is not correct):Avoid recursive function calls that are not tail-recursive (this is valid for all functional languages that support tail-call optimization).Introduce seq to force early evaluation of sub-expressions so that expressions do not grow too large before they are reduced (this is specific to Haskell, or at least to languages using lazy evaluation).After introducing five or six seq calls in my code my tool runs smoothly again (also on the larger data). However, I find the original code was a bit more readable.Since I am not an experienced Haskell programmer I wanted to ask if introducing seq in this way is a common practice, and how often one will normally see seq in Haskell production code. Or are there any techniques that allow to avoid using seq too often and still use little stack space? | How often is seq used in Haskell production code? | programming practices;haskell;stackoverflow | Unfortunately there are cases when one has to use seq in order to get a efficient/well working program for large data. So in many cases, you cannot do without it in production code. You can find more information in Real World Haskell, Chapter 25. Profiling and optimization.However, there are possibilities how to avoid using seq directly. This can make code cleaner and more robust. Some ideas:Use conduit, pipes or iteratees instead of interact. Lazy IO is known to have problems with managing resources (not just memory) and iteratees are designed exactly to overcome this. (I'd suggest to avoid lazy IO alltogether no matter how large your data is - see The problem with lazy I/O.)Instead of using seq directly use (or design your own) combinators such as foldl' or foldr' or strict versions of libraries (such as Data.Map.Strict or Control.Monad.State.Strict) that are designed for strict computations.Use BangPatterns extension. It allows to replace seq with strict pattern matching. Declaring strict constructor fields could be also useful in some cases.It's also possible to use Strategies for forcing evaluation. Strategies library is mostly aimed at parallel computations, but has methods for forcing a value to WHNF (rseq) or full NF (rdeepseq) as well. There are many utility methods for working with collections, combining strategies etc. |
_softwareengineering.42895 | It seems that off-by-one errors are one of the most (if not the most) common programming errors (see https://softwareengineering.stackexchange.com/questions/109/what-are-common-mistakes-in-coding, and conventional wisdom).What is the reason these are so common, is it something to do with how the human brain works?What can we do to prevent falling prey to the off by one errors? | Why are off by one errors so common and what can we do to prevent them? | coding;bug | It sort of is something to do with how the human brain works. We're wired to be good enough for tasks that don't usually require engineering-grade precision. There's a reason why the cases we have the most trouble dealing with are called edge cases.Probably the best way to avoid off-by-one errors is encapsulation. For example, instead of using a for loop that iterates a collection by index (from 0 to count - 1), use a for-each style loop with all the logic of where to stop built into the enumerator. That way you only have to get the bounds right once, when writing the enumerator, instead of every time you loop over the collection. |
_softwareengineering.279231 | I developed a genetic algorithm in java 8 taking advantage of its reasonably free parallelism opportunities with Streams. As you are likely aware, running the epochs takes its time for even a test problem of generating the phrase to be or not to be, that is the question with char genes. I have managed to parallelize all the operations except two, that have become significant bottlenecks: speciation (determining the compatibility of a chromosome with others so they can be put into the appropriate species or create new ones) and the calculation of how many offspring a species should have.I doubt I'll ever be able to parallelize speciation, as it involves iterating through all the chromosomes while creating new species if necessary that the next chromosome should have access to; too many concurrent modifications of lists. I get the feeling that the species offspring calculation could be parallelized, but I can't figure out how. I think it's a reduction operation, but it needs to carry over the fractional part of divisions so they can be added when necessary. This accumulation should be available to each species and each chromosome. I suspect the solution might involve creating a complex class that implements IntConsumer, but I'm not bright enough to figure out. The code is below. Any ideas? private Map<ID, Integer> createMapWithTheExpectedOffspringNumberForEachSpecies() { final Map<ID, Integer> mapWithTheExpectedOffspringNumberForEachSpecies = new ConcurrentHashMap<ID, Integer>(); final double averageOfFitnesses = this.calculateAverageOfFitnesses(); double skim = 0.0; for (final ISpecies<T> species : this.collectionOfSpecies.get()) { int offspringThisSpeciesShouldHave = 0; for (final IChromosome<T> chromosome : species.getChromosomes().get()) { int offspringThisChromosomeShouldHave = 0; final double fitnessOfThisChromosome = this .retrieveFitnessForChromosome(chromosome); final int floorOfChromosomesExpectedOffspring = (int) Math.floor(this.expectedAmountOfChildrenForChromosome(averageOfFitnesses, fitnessOfThisChromosome)); final double fractionalPartOfChromosomesExpectedOffspring = this.expectedAmountOfChildrenForChromosome(averageOfFitnesses, fitnessOfThisChromosome) % 1.0; offspringThisChromosomeShouldHave += floorOfChromosomesExpectedOffspring; skim += fractionalPartOfChromosomesExpectedOffspring; if (skim > 1.0) { final double skimIntPart = Math.floor(skim); offspringThisChromosomeShouldHave += skimIntPart; skim -= skimIntPart; } offspringThisSpeciesShouldHave += offspringThisChromosomeShouldHave; } mapWithTheExpectedOffspringNumberForEachSpecies.put( species.getID(), offspringThisSpeciesShouldHave); } return mapWithTheExpectedOffspringNumberForEachSpecies;} | Can't figure out how to parallelize the calculation of the amount of offspring expected for species in genetic algorithm | java;algorithms;artificial intelligence;parallelism;java8 | null |
_cs.19736 | I'm totally new to DFA's and automaton in general -- this is the first week or two of class that I've actually seen this -- and I'm curious as to a pattern to match the following: Match the set of all strings on the alphabet {a, b} that have at least one b and exactly 2 a's I've tried to construct a DFA to represent this structure, but I have no idea how to form a structure to count for something and match for one. Can someone help? Okay, so. Here's what I got and I think it's the right answer. | DFA for exactly two of a and one or more of b | automata;finite automata | If you're stuck on problems like this, it often helps to try to construct a regular expression first. Note that it's perfectly acceptable to make it the union of overlapping REs.The RE $b^* a b^* a b^*$ accepts strings with exactly two $a$'s, but doesn't take into account that there must be a $b$. A $b$ could be in any of the $b^*$ parts, so this RE accepts the language:$$(b b^*) a b^* a b^* \cup b^* a (b b^*) a b^* \cup b^* a b^* a (b b^*)$$Did that help? |
_softwareengineering.292109 | We have a third party supplied application with a button that enables the opening of another application showing related data when pressed (these applications are made by completely different companies). However, the application with the button does nothing more than the equivalent of clicking a url with a query string of parameters and so initiates the default behaviour of widows in response which is to open a web browser pointing to the url (the url can be whatever we want).The application we want to open in response is not a web application; it is just a standard windows desktop application.The solution we have at current for this is to create a small self-hosted service using WebServiceHost in .Net framework 4.0 and to host this service in a windows form application, but without a form and instead display an icon in the tray when it is running (which will be all the time). When the service is effectively called into it closes the browser web page that had been opened in response to the url and opens the desktop application populating the fields with the parameters supplied in the query string.This all seems to work as required but it does not seem a very conventional way of doing things, in fact it would not be possible without WebServiceHost because it is the only thing we have that can respond to the url. We use a WebHttpBinding. We have looked at other things such as IPC, etc. but they all require IIS to be running on the user machines and that is not company policy. Ideally I would like to use a Windows service for hosting rather than a tray application but WebServiceHost does not seem to work (respond) in that context.What does anyone think of this rather unconventional way of doing things? Are they any security risks associated with hosting a service like this? Is there a better way of doing it?The code involved is little more than:webServiceHost = new WebServiceHost(typeof(Services.MyService), new Uri(http://localhost:8001/));webServiceHost.AddServiceEndpoint(typeof(Contracts.IMyService), new WebHttpBinding(), /WindowsHost/MyService/); webServiceHost.Open();(it might be necessary to add an empty WebHttpBehaviour)and then just a url like below will call into the service and initiate the method in the service (open notepad in this example). http://localhost:8001/WindowsHost/MyService/OpenNotePadpublic void OpenNotePad(){ Process.Start(notepad.exe);} | Is using a self-hosted service a viable option for launching applications from a url? | c#;.net;wcf | null |
_unix.264237 | I would like to execute a script as a normal user and execute a command that shuts off apache (which needs a root password). I was wondering if is possible to run the script with sudo but it executes some of the commands with an specific user and executes a specific command as a root.How can I achieve this? | How can I execute a script as root, execute some commands in it as a specific user and just one command as root | bash;scripting;sudo | sudo -u <username> <command> |
_webmaster.68913 | The title explains most of my question. The OS is linux (Lubuntu). The servers are Apache2 (PHP5), MySQL 5.6 and FTP (Samba). | How to block all hacking? | php;apache2;mysql;linux;ftp | You can prevent hacking to an extent however, nothing is perfect and there are always flaws in any system. Asking a question with such little detail prevents a comprehensive insightful answer. It's advisable to read up and practice Linux and PHP security concepts. However it's impossible to make your website hackproof, you can make it hack-resistant though. Secure the core, code your application securely and it might not be a bad idea to invest in a firewall on the network, server and web application layers. |
_vi.8431 | I have the following vimscript: it contains a vimscript function which executes a python code thanks to python << EOF:function! Test(myArgument)python << EOFdef test(myArgument): print My argument + myArgumenttest(foo)EOFendfunctionHow can I use the argument of the vimscript function a:myArgument and pass it as argument to my python function (instead of foo)? | How to use the argument of a vimscript function in an inner python function? | vimscript;vimscript python | You can use the vim package inside python, you should be able to gain access to vim:function! Test(myArgument) python << EOFimport vimdef test(myArgument): print My argument + myArgumenttest(vim.eval('a:myArgument'))EOFendfunctionYou can read about the python integration at :h python and about this particular feature at :h python-eval. |
_softwareengineering.275195 | I have a MessageHandler class which receives and validates messages before determining which components in the architecture they should be delegated to so they can be processed. This involves calling functions with different names and possibly different signatures on classes in different components.What is the best way to implement the delegation?The diagram below shows two possible approaches.Option 1 - each component that must process messages exposes an interface, which is realised by a Facade. For each message, the MessageHandler calls the appropriate operation on the interface and the facade delegates it to the appropriate class internally.Option 2 - for each message, the MessageHandler calls the appropriate operation directly in the relevant component. Weighing up the advantages/disadvantages of each:Option 2 means polluting the message handler with a handle of each class in every component that will process a message. It also makes it harder to test the message handler in isolation. Doesn't seem right.Option 1 - seems like a better approach. The message handler depends on an interface rather than concrete classes, which also makes it easier to test. I'm wondering if option 1 a good approach? Or is there a better way to achieve what I want? | Delegating work and programming to component interfaces | design patterns;interfaces;architectural patterns;component;delegation | null |
_cstheory.12653 | What is best known approximation ratio for the following problem :Given n points in d dimensions , what is the minimum number of axis parallel lines needed to cover them . A line is said to cover a point , if the point lies on the line . | Approximation ratio for covering n points in d dimensions | cg.comp geom;approximation algorithms;set cover | null |
_unix.203473 | I found some inconsistent behavior of $BASHPID as below:# On Mac Yosemiteecho $BASH_VERSION ${BASH_VERSINFO[5]} $BASHPID# => 3.2.57(1)-release x86_64-apple-darwin14# On Ubuntuecho $BASH_VERSION ${BASH_VERSINFO[5]} $BASHPID# => 4.3.11(1)-release x86_64-pc-linux-gnu 29134The $BASHPID is not present for Mac OSX, is it not safe to use it to write portable script? | Portability of $BASHPID | bash | The builtin variable $BASHPID was introduced in bash version 4.0.See the file NEWS in the bash source code: 397 ------------------------------------------------------------------------------- 398 This is a terse description of the new features added to bash-4.0 since 399 the release of bash-3.2. As always, the manual page (doc/bash.1) is 400 the place to look for complete descriptions. 401 402 1. New Features in Bash 403 ... 410 c. There is a new variable, $BASHPID, which always returns the process id of 411 the current shell. |
_codereview.83161 | I'm teaching myself data structures and would really appreciate some feedback on my stack implementation.A couple of things I'm not sure if I should be doing:creation of the array and pointer using newstyle // Implement 3 stacks with one array #include <iostream>class SingleArrayStacks{ private: int stack_size; int *array; int *pointers; int get_top_position(int stack_num){ return (stack_num * stack_num) + pointers[stack_num]; } public: SingleArrayStacks (int array_size = 100, int num_stacks = 3) { array = new int[array_size]; pointers = new int[num_stacks]; stack_size = array_size / num_stacks; std::fill_n(pointers, num_stacks, -1); } ~SingleArrayStacks (){ delete[] array; delete[] pointers; } void print_stack (int stack_num) const { std::cout << Current stack state: ; for (int i = 0; i < sizeof(array); i++) { std::cout << array[i]; } std::cout << std::endl; } bool is_empty(int stack_num) const { return pointer[stack_num] == -1; } void push (int stack_num, int val) { if (pointers[stack_num] > stack_size) { throw std::runtime_error(Stack is full); } else { array[get_top_position(stack_num) + 1] = val; pointers[stack_num]++; } } int pop(int stack_num){ if (is_empty(stack_num) { throw std::runtime_error(Stack is empty); } else { int val = array[get_top_position(stack_num)]; array[get_top_position(stack_num)] = NULL; pointers[stack_num]--; return val; } } int top(int stack_num){ if (is_empty(stack_num) { throw std::runtime_error(Stack is empty); } else { return array[get_top_position(stack_num)]; } }}; | 3-stack implementation with a single array | c++;stack | Compiler errors:You code did not compile under Clang! It would not compiler anywhere for that matter, as it has a few syntax errors:In method is_empty(), pointer is not declared. It should be pointers (plural).In both pop() and top() methods, this line is broken:if (is_empty(stack_num) {// ^-------- Missing a `)` here!Compiler warnings:Always compile with warnings turned on and set them to the highest level practical.If you have the habit of ignoring warnings, try compiling with warnings as errors (-Werror for Clang and GCC) to force yourself into fixing them.That said, your code only produced one warning, after the errors above where fixed:array[get_top_position(stack_num)] = NULL;// ^^^^--------- implicit conversion of NULL constant to 'int'NULL is not the same as int. In fact, an implementation is free to define NULL to whatever, so don't assume it will be convertible to an integer on all compilers/platforms.Code review:Now if I get the idea behind your code, you intend to have a single array with several stacksharing this array. Your implementation doesn't seem to be doing that correctly. I could not test it thoroughly, but the helper array pointers, which doesn't store pointers by the way, seems questionable. The method get_top_position() also seems a bit contrived to me. print_stack() is broken, so I couldn't print the stacks to validate the state of the structure.I would suggest that you attempt to simplify this by storing actual pointers (or indexes) to the sub-array inside the main array. Then you won't need any additional offset calculation once pushing/poping. You also have the advantage that all stacks share the same size. main array of ints: +--+--+--+--+--+--+--+--+--+--+--+--+---- | | | | | | | | | | | | | ... +--+--+--+--+--+--+--+--+--+--+--+--+---- | | | | V V V V +-----------+-----------+-----------+---- | stack 0 | stack 1 | stack 2 | ... +-----------+-----------+-----------+---- | | | | V V V Vpointer[0] pointer[1] pointer[2] pointer[N] ...Overall code improvements:sizeof misuse: This is not doing what you expect:for (int i = 0; i < sizeof(array); i++) {sizeof is a compile-time operator, so it cannot infer the size of dynamically allocated arrays, only arrays in which the size is known at compile-time (e.g.: char buf[128]) can have the size inferred with sizeof. You must keep a member variable with the size of the stacks and another with the main array's.top() only inspect data, so it should also be a const method.Simplify if-else logic where it is not needed. Example:if (is_empty(stack_num)) { throw std::runtime_error(Stack is empty);} else { return array[get_top_position(stack_num)];}No need to keep the if-else when both paths will exit the function.if (is_empty(stack_num)) { throw std::runtime_error(Stack is empty);}return array[get_top_position(stack_num)];Instead of hardcoding cout in print_stack(), you could take the output parameter as an std::ostream &. However, such function is asking to become an output stream operator.Manual memory management (with new/delete) is a dated practiced in C++. Even for custom containers, the use of smart pointers is strongly advised. I would replace the raw pointers by at least a std::unique_ptr or even better a std::vector. |
_vi.9795 | Let's say I'd like to indent the current line 4 times. (Not 4 spaces, 4 indent commands). As far as I can tell, the shortest way to do this is>>...(Indent once, repeat three times) This seems really inefficient to me. I'd rather do something like this:4>>But instead of repeatedly indenting the current line, this indents the next 4 lines 1 time. In my mind, this is a total waste, because if the count before the operator was indent level, and the count after is for a repeated motion, this doesn't lose any ability. If I wanted to indent the next four lines one time, I could just do>4>or even >3jIf the first count were to work this way, you could even do a command like this:2>4>And this would mean Two times, indent the following four lines. Instead it means One time, indent eight lines.Can I configure vim to behave this way? | Can I make the indent commands take an additional count that doesn't affect the motion? | key bindings;indentation | null |
_hardwarecs.1035 | Current setup, kind of outdated - was built in 2009, except graphics card and a chassis:chassis: Corsair 650Dmobo: Asus P5Q DeluxeCPU: Intel Core2Quad 3GHz @4GHzgfx: Radeon R9 290psu: Corsair 750Wmem: 16GBI want to keep chassis and gfx card for a new setup. Looking for a CPU recommendation (no AMD please) which will be better from current one and will allow future upgrade. Computer mainly used for work (web dev, Photoshop, some android coding with unity), casual gaming (Battlefield 4, Battlefront Star Wars (new one), Evolve, etc), music (mp3, Spotify - mostly when doing my work) and movies watching from streaming services (HBO Go, STARZ Go, Plex, Netflix, etc)Price range something around $250 | CPU recommendation for new casual gaming setup | gaming;processor | I reccomend the Intel i5 4690k.It costs $240 USD, and is significantly more powerful than your current CPU. It has 4 cores, (no hyperthreading) with a base-clock of 3.5 GHz, but is unlocked and could be OC'ed to 3.9 GHz. 6 MB of cache, and the TDP is 88W (which I believe is actually lower than your current CPU).It meets or exceeds the system requirements of every game you listed.BF4 recommends any quadcore intel CPU.Star Wars battlefront recommends an i5 6600, which has nearly identical specs, except for the lower base clock speed.Evolve recommends an i7 920, which has twice the number of threads, but a significantly lower clock speed (2.66 GHz). I'm not sure how well Evolve utilizes the extra multi-threading capabilities, but it's probably safe to assume it will run well. (At least, as well as it can run. It's still very buggy from what I have heard).Given that all of these games are far more CPU-intensive, it should also easily handle Photoshop, unity, music streaming, movies and browsing. |
_unix.260514 | I have version 2.5 of Git on Ubuntu:$ git --versiongit version 2.5.0but Git is at version 2.7.1 now. The Git website says to doapt-get install gitto install it. But I tried both sudo apt-get install git and sudo apt-get upgrade git and it is still version 2.5. How do I upgrade it to the latest version? | How to install the latest version of Git on Ubuntu? | ubuntu;git | null |
_codereview.3780 | I guess I might use delegates. But I'm not certain if I can apply for it. Sorry if the code is a mess. I'm a beginner and am still learning. For that reason, I need a little of help to improve this code. It's not finished.I'm creating a Math quiz system. And there are many questions as you will be able to see in it, they're so different and I have a difficult moment to create the classes. private int[] Generate_Fraction(int li1, int ls1, int li2, int ls2) { int numerator = randomizer.Next(li1, ls1); int denominator = randomizer.Next(li2, ls2); int[] fraction = new int[2]; fraction[0] = numerator; fraction[1] = denominator; return fraction; } // Decimals private double[] GeneratePattern5(double[][] limits) { double[] decimals = new double[limits.Length]; for (int i = 0; i < limits.Length; i++) { bool flag; double decTemp; do { flag = false; decTemp = GetDoubleBetween(limits[i][0], limits[i][1], (int)limits[i][2]); if (Exists(decimals, decTemp, i)) { flag = true; } } while (flag); decimals[i] = decTemp; } return decimals; } // Fractions like: 6/60 private int[][] GeneratePattern7(int[][] arrayLimits) { int[][] fractions = new int[arrayLimits.Length][]; for (int i = 0; i < arrayLimits.Length; i++) { bool flag; int[] fracTemp = new int[2]; do { flag = false; fracTemp = Generate_Fraction(arrayLimits[i][0], arrayLimits[i][1], arrayLimits[i][2], arrayLimits[i][3]); fracTemp[1] *= fracTemp[0]; if (Exists(fractions, fracTemp, i)) { flag = true; } } while (flag); fractions[i] = fracTemp; } return fractions; } | Can I improve this code using delegates? | c#;beginner;wpf | null |
_unix.243265 | For a socket file likes this: # ls -alti socket14112 srw------- 1 root root 0 Nov 15 20:03 socket# cat socketcat: socket: No such device or addressSince cat command is useless here, is there any method to get more info about the socket file? Such as which port it is listening on? etc. | How to get more info about socket file? | linux;filesystems;socket | A socket is a file for processes to exchange data. You can see more data about it using the netstat, lsof, and fuser commands.From Wikipedia : https://en.wikipedia.org/wiki/Unix_domain_socketA Unix domain socket or IPC socket (inter-process communication socket) is a data communications endpoint for exchanging data between processes executing on the same host operating system. Like named pipes, Unix domain sockets support transmission of a reliable stream of bytes (SOCK_STREAM, compare to TCP). |
_unix.227780 | Sometimes I'm noticing my bandwidth being all consumed although I'm not doing anything consuming, so I fire up nethogs on my wireless interface and I notice an apt process running without me starting it, and without for example using cron, and although I'm using Linux since about 6 years I never noticed it does anything without me asking to, so what have I done wrong?uname -a3.16.0-4-amd64 #1 SMP Debian 3.16.7-ckt11-1 (2015-05-24) x86_64 GNU/LinuxEdit: I googled the exact process path and found this same question as mine on ubuntu but the answers don't explain why it's working autonomously on my machine! | apt working unexpectedly on debian 8 | debian;apt;bandwidth | null |
_unix.280993 | I would like to make a script, which allows user to input some text and it will output the same text with number of lines.Example:Input:Hi Jack,how are you?Output:0001: Hi Jack,0002: how are you? | Script - numberlines | scripting | A simple solution with read:I=0; while read -r; do ((I++)); echo $I: $REPLY; done< test.txt;where you can change test.txt to your script argument.If you don't want to use bash variable REPLY:I=0; while read -r LINE; do ((I++)); echo $I: $LINE; done< test.txt;or something else instead of 'LINE' |
_softwareengineering.323784 | I am working on a complex widget with a preferences object tree with 50-100 objects and 3-5 properties in each object. Each property is watched by Angular and controls how some aspects of the data are displayed.The user can directly change each preference via inputs in the widget and I want to save the preference tree when changed.The Angular way to do this is to $watch(preferences, <save function>, true), but the documentation does warn:This therefore means that watching complex objects will have adverse memory and performance implications.The alternative is to add event handlers to each of the input that alters the preference object, which is quite error prone.If the preferences are very infrequently changed, would the performance penalty of the deep watch be significant enough to justify implementing the alternative? | AngularJS: cost of deep watching infrequently changed object trees | javascript;performance;angularjs | null |
_softwareengineering.279985 | Is it possible for a developer to lose rights to work on a self-created, open-source-licensed project after an outside company, developer, or organization copyrights (or takes some other legal action regarding) the same project?I haven't heard of this happening, but it seems entirely possible that someone could independently develop a project and then have the rights to continue working on said project (or an idea/language/technology) taken away...For example, when a project like Minecraft (but open-source-licensed, in this case,) is developed, and is later bought by a company like Microsoft, does this mean that Microsoft can say that Mojang (or Notch, for that matter,) no longer has rights to work on further Minecraft development?Another example would be Oracle who bought the open-source MySQL database.In other words, are copyrights still necessary for intellectual property alongside open source licensing? | Open Source Licensing and Intellectual Property Rights | licensing;open source;copyright;intellectual property | Minecraft is actually an invalid example, as it was a proprietary commercial project. If Microsoft purchases the IP rights to the project, and does not keep the Mojang developers on, then it's no different from any other proprietary project: you don't own the rights to what you work on, under work made for hire doctrine.Having said that, for an actual open-source project, things are different. When source code is released under a license, the genie can't be put back into the bottle. There's a legal doctrine known as promissory estoppel which, in layman's terms, says that but you promised! is actually a valid legal argument, and so when someone publishes source code and says here you go, community, use this as an open-source project, they can't take that back.One of the most dramatic examples of this is the Firebird database. A long time ago, Borland decided to release the source code to their InterBase RDBMS, but then, for whatever reason, they quickly had a change of heart. But because the code had already been published, they couldn't take that back, and a development community continued to work on the InterBase source under the new name Firebird. Today, Firebird and InterBase are two similar but distinct products, both still under active development, one by the open-source community and the other as a commercial project run by Embarcadero, who bought the rights from Borland.(Standard disclaimer: I am not a lawyer. This is not legal advice. This is just stuff I've picked up based on common sense and experience.) |
_codereview.83088 | The purpose of the code is to see if a form element would get data from internal react components and it did. It was also to see how clean I could make an autocomplete component.The autocomplete has 4 states and I use bind excessively (is this bad?). I also added a function updateSpecificState, because I found it inconvenient that React has no method to let you change a specific property in the state.app.js:React.render( <Rendrform method=post />, document.getElementById('content'));rendrform.js: (don't worry about the name, I confused rendr and react)var Rendrform = React.createClass({ onSubmit: function(event) { console.log('I would ajax this:', $(event.target).serialize()); event.preventDefault(); }, render: function() { var types = [ {title: 'blog', id: 11,}, {title: 'comment', id: 22,}, {title: 'todo', id: 33,}, ]; var mappingTo = function(option) { return option.id; }; var mappingFrom = function(option) { return option.title; }; return ( <form method={this.props.method} target=index.html onSubmit={this.onSubmit}> <input type=text name=author placeholder=Enter Author /> <Autocomplete options={types} mappingTo={mappingTo} mappingFrom={mappingFrom} name=type /> <textarea name=body></textarea><br /> <input type=submit value=Post /> </form> ); }});autocomplete.js://TODO: by default options would be an array of strings,with no mapping//TODO: the user can define mappingTo and/or mappingFrom, which both can either be a string or a function. String would be the keyvar Autocomplete = React.createClass({ //Feels like this should be a native function... updateSpecificState: function(object, key, value) { object[key] = value; this.setState(object); console.log('Current State: ', this.state); console.log('Current State.value: ', this.state.value); }, getInitialState: function() { return { display: 'none', filteredOptions: this.props.options, value: null, faceValue: '', }; }, setValue: function(option) { this.updateSpecificState(this.state, 'value', this.props.mappingTo(option)); this.updateSpecificState(this.state, 'faceValue', this.props.mappingFrom(option)); }, /* TODO: make a toggle mixin for events or something... */ onFocus: function() { this.updateSpecificState(this.state, 'display', 'block'); }, blurTimer: false, onBlur: function() { //otherwise the blur happens bfore the click event this.blurTimer = window.setTimeout(function() { this.updateSpecificState(this.state, 'display', 'none'); if(!this.state.value) this.updateSpecificState(this.state, 'faceValue', ''); }.bind(this), 200); }, onClick: function(event) { this.setValue(this.props.options[event.target.dataset.index]); window.clearTimeout(this.blurTimer); this.updateSpecificState(this.state, 'display', 'none'); }, onChange: function(event) { this.updateSpecificState(this.state, 'faceValue', event.target.value); this.updateSpecificState(this.state, 'filteredOptions', this.props.options.filter(function(option) { return option.title.indexOf(this.state.faceValue) != -1; }.bind(this))); //Note: If performance is an issue, then I could return here if the above filter returns more than 1. var exactOptionMatches = this.props.options.filter(function(option) { return option.title === this.state.faceValue; }.bind(this)); if(exactOptionMatches.length >= 1) this.setValue(exactOptionMatches[0]); else this.updateSpecificState(this.state, 'value', null); }, render: function() { var faceValue = this.state.faceValue; return ( <div> <input type=text onFocus={this.onFocus} onBlur={this.onBlur} onChange={this.onChange} value={faceValue} /> <input type=hidden name={this.props.name} value={this.state.value} /> <div className=autocomplete-items style={{display: this.state.display}}> {this.state.filteredOptions.map(function(option, i) { return <div data-index={i} onClick={this.onClick}>{this.props.mappingFrom(option)}</div>; }.bind(this))} </div> </div> ); },}); | Potentially excessive state and use of bind | javascript;react.js | null |
_codereview.167579 | I wrote this script that downloads an RSS feed and converts it to HTML. One of my only concerns is my variable naming because I suck at naming things.# -*- coding: utf-8 -*-Simple RSS to HTML converter.__version__ = 0.0.2__author__ = Ricky L Wilsonfrom bs4 import BeautifulSoupfrom feedparser import parse as parse_feedTEMPLATE = u<h2 class='title'>{title}</h2><a class='link' href='{link}'>{title}</a><span class='description'>{summary}</span>def entry_to_html(**kwargs): Formats feedparser entry. return TEMPLATE.format(**kwargs).encode('utf-8')def convert_feed(url): Main loop. html_fragments = [entry_to_html(**entry) for entry in parse_feed(url).entries] return BeautifulSoup(\n.join(html_fragments), 'lxml').prettify()def save_file(url, filename): Saves data to disc. with open(filename, 'w') as file_object: file_object.write(convert_feed(url).encode('utf-8'))if __name__ == '__main__': save_file('http://stackoverflow.com/feeds', 'index.html') with open('index.html') as fobj: print fobj.read() | RSS to HTML script - version two | python;html;parsing;rss | null |
_unix.38593 | My inspiration for asking this is this other question on Ask Ubuntu.One reason I am asking is that I am just curious. I would like to know more about this for whatever value it might have in the future. But I would also like to know so that I have a procedure I can ask a user to perform when I am wondering WTF might be up with them and their system. ;-)Initially I wondered if this information might be detected and reported by a tool such as (or similar to) dmidecode. But what would happen when a UEFI BIOS is simulating a pre-UEFI BIOS?I expect this question will only become more interesting as time passes. It appears that the companies behind each of the major operating systems will insist on implementing EFI support by doing the same thing only different. <sigh/> | Is there a command or method (other than RTFM) to determine if a system has a UEFI BIOS? | x86;system information;bios;uefi | A system can have a UEFI firmware and still boot OS in legacy BIOS mode. In that situation there is no way for the booted OS to determine if the hardware is actually capable of UEFI, because BIOS isn't forward compatible with UEFI.You can still look at firmware interface if anything is related to UEFI, but that is vendor specific and inconsistent. So there is also no definite answer from that side.The canonical method to prove your x86(_64) kernel is booted from UEFI: $ dmesg | grep 'EFI v' [ 0.000000] efi: EFI v2.31 by EDK IIThe kernel will print such message at the main entry point of EFI boot. The kernel is booted with UEFI if and only if such message exists.Other informative stuff: $ dmesg | grep 'efi: mem' [ 0.000000] efi: mem00: type=7, attr=0xf, range=[0x0000000000000000-0x00000000000a0000) (0MB) ...This is the memory map passed from EFI firmware to the kernel. $ ls -F /sys/firmware/efi efivars/ systab vars/These are kernel ABI's related to EFI. efivars (3.8+) and vars are kernel ABI to the EFI NVRAM so you can change boot options with them.But lack of these clues does not prove the system is BIOS only.Empirically, recent laptops all have UEFI firmware. Latest servers are migrating to UEFI firmware.Edit:The author of rEFInd has a more thorough explanation. Steps are the same.Also, Firmware Test Suite from Ubuntu might detect whether your UEFI firmware has a compatibility feature for legacy BIOS. Although it doesn't solve the problem of detecting UEFI capable firmware booting in BIOS mode. |
_softwareengineering.257169 | I'm wondering how to write the if statement in the following block in a better way. It's supposed to operate when $a is 14, 22, 30 and for all following values at intervals of 8, up to some limit. The current way is obviously not good since the action must be performed each time that periodic pattern is fulfilled, and this would require many, many OR operators.if($a == 14 || $a == 22 || $a == 30 || $a == 38 || $a == 46... until some number){ do something...} | Ifology - how to write this statement better? | conditions | if($a % 8 == 6 && $a >= 14 && a <= some_number)In general, if you want periodicity, think modulus. |
_unix.120357 | After some research, I was wondering if it was possible to define a TTL by interface as I can the Hop Limit definition in ipv6.To change the TTL in IPv4, I can change the file /proc/sys/net/ipv4/ip_default_ttl But this changes TTL for all interfaces.However in IPv6, you can put a different hop limit value for each interfaces /proc/sys/net/ipv6/conf/eth*/hop_limitSo do I miss something? or there is no way to configure a different TTL for each interface ? | Define specific TTL for each interfaces | ipv6;interface;ipv4 | If that entry does not exist for ipv4, it's probably not supported.But have you tried to modify TTL values with iptables? See if the TTL target helps |
_unix.147619 | I wanted to tail the last 100 lines of a file to the same file, but the commandtail -n 100 file > file doesn't work, I assume because the stdout gets written to the file 'live', before everything was read from the original file.Is there some way to pipe the output to something, that then keeps it until all 100 lines are there, and then outputs it to the file? Or just another way to shorten the file in this way? | Command line 'buffer' | bash;files;stdout | sponge from moreutils is good for this. It will:soak up standard input and write to a fileYou use it like this:tail -n 100 file | sponge fileto get exactly the effect you want. |
_codereview.122201 | This is my implementation of MinHeap in Java.public class MinHeap { int[] heap; int pos; int size; public MinHeap(){ this.size = 2; heap = new int[size]; this.pos = 0; } private void minHeapify(int index){ int child = index; int parent = child/2; while(heap[parent] > heap[child] && parent > 0){ int temp = heap[parent]; heap[parent] = heap[child]; heap[child] = temp; child = parent; parent = child/2; } } public void add(int item){ if(pos == heap.length) resize(); heap[pos++] = item; minHeapify(pos-1); } public void delete(int item){ boolean found = false; int start = 0; for(int i = 0; i< heap.length; i++){ if(heap[i] == item){ found = true; start = i; break; } } if(found == false) throw new IllegalStateException(Item doesn't exist.); pos--; for(int i= start; i< pos; i++){ heap[i]= heap[i+1]; } for(int i=pos; i > 0; i--){ minHeapify(i); } } public int min(){ return heap[1]; } private void resize(){ size = size*2; int[] curr = new int[size]; for(int i=0; i< heap.length; i++){ curr[i] = heap[i]; } heap = curr; } }Invite comments and suggestions to improve. | Array-based MinHeap implementation in Java | java;heap | null |
_codereview.119504 | I am trying to grab the URL query of the URL which is in the browser's address bar, then append it at the end of the other URL and echo it to the browser.So, if I visit my script at:http://script.com/script.php?a=x&b=zand the other URL is:http://google.com/?c=v&d=uthen the browser will display:http://google.com?a=x&b=z&c=v&d=uThis code is quite slow. How can I improve this? function parse_me($from, &$to) { // $to = array(); $from = urldecode($from); $from = urldecode($from); foreach (explode('&', $from) as $part) { $part = explode('=', $part); if ($key = array_shift($part)) { $to[$key] = implode('', $part); } } // print_r($to);}function add_qsrt_to_url($url) { $other_query_string = arrayGet($_SERVER, 'QUERY_STRING', ''); $url_parsed = parse_url($url); $new_qs_parsed = array(); if (isset($url_parsed['query'])) { // parse_str($url_parsed['query'], $new_qs_parsed); parse_me($url_parsed['query'], $new_qs_parsed); } $other_qs_parsed = array(); // parse_str($other_query_string, $other_qs_parsed); parse_me($other_query_string, $other_qs_parsed); // print_r($other_qs_parsed); $final_query_string_array = array_merge($new_qs_parsed, $other_qs_parsed); // var_dump($final_query_string_array); $final_query_string = http_build_query($final_query_string_array); $new_url = $url_parsed['scheme'] . '://' . $url_parsed['host']; if (isset($url_parsed['path'])) { $new_url = $new_url . $url_parsed['path']; } if ($final_query_string) { $new_url = $new_url . '?' . $final_query_string; } return $new_url;}function arrayGet($array, $key, $default = NULL) { return isset($array[$key]) ? $array[$key] : $default;} | Parsing URL query and appending it at end of the other URL | php;url | null |
_webmaster.29823 | Possible Duplicate:How to find web hosting that meets my requirements? So I recently found out to my dismay that my domain name registrar does not even support sub domains?!Hence I need to get a new one quick.I am faced with a problem where by my company has just signed up to an (legit) bulk email provider.I want to:have a domain abc.com which host a website and also has MX records set up to route email as well.I also want to set up a sub domain news.abc.com and re-point the whole name server for this sub domain to the bulk email provider.A couple of the well known domain registrars do not provide this service.Does anyone have any recommendations of flexible domain companies? Note I am not a sys-admin more a web dev so would prefer not to have to manually edit zone files!Thanks | Domain registrar that will allow separate sub domain NS record | domains;subdomain;domain registration | null |
_softwareengineering.157236 | It occurs to me that there's not a heck of a lot of difference between$>python module.pyAnd:$>javac module.java$>java module.classThe former compiles to an intermediate language (python bytecode) and executes the program. The latter breaks the steps up, first compiling to the intermediate language (jvm bytecode) and then executing on another line. In fact I can rewrite the python to break out the two steps, as in this SO question.It seems people make a big deal about the stark difference between compiled and interpreted languages. It seems the lines are entirely blured. Other popular interpreted languages havi similar features. Php compiles to its own opcodes which can be cached or stored for later use. Perl also is compiled to something.So... is there really any difference between these popular interpreted languages and popular compiled languages that compile to VMs? Perhaps in one case the VMs are typically more memory resident whereas with the interpreted languages they typically have their runtimes spun up? Yet this seems like it could be easily changed. Yet there still seems to be something of a difference. If they are more-or-less the same, then why is it that the performance of Java/C# seems to approach C++ while the interpreted languages are still an order of magnitude off? If its all truly bytecodes running in a VM, and all really the same, why the big difference in performance? | Whats the difference between an interpreted language and one compiled to a VM? | programming languages;language design;compiler;interpreters | null |
_unix.345340 | Ive been trying to install Deco-IDE on Ubuntu 16.04 linux through this hack I found on github but I keep getting an error seen in the image below after the lines:cd ../../Desktopnpm installI included a screenshot of the entire script bellowI tried to manually install ngrok but still I get the same error.Could somebody please tell me what I'm doing wrong? | Trouble installing Deco-IDE on Ubuntu 16.04 - .sh file keeps throwing a postscript ngrok error | ubuntu;error handling | null |
_unix.31166 | I just re-installed Firefox, but the thumbnail is not showing in the dock applications folder. The icon DOES show both in dock and in finder.I have tried to re-install Firefox again but without success.Any advice? | Icon not showing in applications on OSX | osx;application | This is a result of one of OS X's security features.This icon is shown to tell you that the program is potentially unsafe because you haven't opened it yet and it was downloaded from the Internet.The first time you open the app, you'll see a security dialog that says, App Name is an application which was downloaded from the Internet. Are you sure you want to open it?Once you click Open on that dialog, the app will open and the icon will change to the app's normal icon.Usually, you shouldn't need to restart or anything like that.Since it's appearing on the Finder but not in the Dock, you can force the Dock to refresh its icons by relaunching it: open Activity Monitor, find the Dock process, and click Quit Process.Mostly copied from my answer on Ask Different |
_unix.155255 | I did a full upgrade on my Debian system (jessie/sid).Unfortunately there is now a 30 second gap on the bootup and I really don't know where it comes from and where I have to look to find it. I looked at /var/log/dmesg and found some lines that could be interesting. Notice the gap between 27.280227 and 56.835253.[ 27.261104] [drm] Initialized i915 1.6.0 20080730 for 0000:00:02.0 on minor 0[ 27.280207] cfg80211: World regulatory domain updated:[ 27.280213] cfg80211: (start_freq - end_freq @ bandwidth), (max_antenna_gain, max_eirp)[ 27.280216] cfg80211: (2402000 KHz - 2472000 KHz @ 40000 KHz), (N/A, 2000 mBm)[ 27.280218] cfg80211: (2457000 KHz - 2482000 KHz @ 40000 KHz), (N/A, 2000 mBm)[ 27.280220] cfg80211: (2474000 KHz - 2494000 KHz @ 20000 KHz), (N/A, 2000 mBm)[ 27.280223] cfg80211: (5170000 KHz - 5250000 KHz @ 80000 KHz), (N/A, 2000 mBm)[ 27.280225] cfg80211: (5735000 KHz - 5835000 KHz @ 80000 KHz), (N/A, 2000 mBm)[ 27.280227] cfg80211: (57240000 KHz - 63720000 KHz @ 2160000 KHz), (N/A, 0 mBm)[ 27.843406] [drm] Enabling RC6 states: RC6 on, RC6p off, RC6pp off[ 56.835253] EXT4-fs (dm-1): re-mounted. Opts: (null)[ 57.068560] EXT4-fs (dm-1): re-mounted. Opts: errors=remount-ro[ 57.615554] lp: driver loaded but no devices found[ 57.661815] ppdev: user-space parallel port driver[ 57.855124] fuse init (API version 7.22)[ 58.123866] Adding 4886524k swap on /dev/mapper/encrypted-swap. Priority:-1 extents:1 across:4886524k[ 58.327537] EXT4-fs (sda4): mounted filesystem with ordered data mode. Opts: (null)[ 59.137990] RPC: Registered named UNIX socket transport module.[ 59.137996] RPC: Registered udp transport module.[ 59.137998] RPC: Registered tcp transport module.[ 59.138000] RPC: Registered tcp NFSv4.1 backchannel transport module.Searching for [drm] Enabling RC6 states: RC6 on, RC6p off, RC6pp off points to some graphical bugs. Since I have sometimes problems with my graphiccards (switchable graphic card) this could be a reason.00:02.0 VGA compatible controller: Intel Corporation 2nd Generation Core Processor Family Integrated Graphics Controller (rev 09) (prog-if 00 [VGA controller])Subsystem: Dell Device 04cdFlags: bus master, fast devsel, latency 0, IRQ 52Memory at f6400000 (64-bit, non-prefetchable) [size=4M]Memory at d0000000 (64-bit, prefetchable) [size=256M]I/O ports at f000 [size=64]Expansion ROM at <unassigned> [disabled]Capabilities: [90] MSI: Enable+ Count=1/1 Maskable- 64bit-Capabilities: [d0] Power Management version 2Capabilities: [a4] PCI Advanced FeaturesKernel driver in use: i91501:00.0 VGA compatible controller: Advanced Micro Devices, Inc. [AMD/ATI] Whistler [Radeon HD 6630M/6650M/6750M/7670M/7690M] (prog-if 00 [VGA controller])Subsystem: Dell Radeon HD 6630MFlags: bus master, fast devsel, latency 0, IRQ 53Memory at e0000000 (64-bit, prefetchable) [size=256M]Memory at f7b20000 (64-bit, non-prefetchable) [size=128K]I/O ports at e000 [size=256]Expansion ROM at f7b00000 [disabled] [size=128K]Capabilities: [50] Power Management version 3Capabilities: [58] Express Legacy Endpoint, MSI 00Capabilities: [a0] MSI: Enable+ Count=1/1 Maskable- 64bit+Capabilities: [100] Vendor Specific Information: ID=0001 Rev=1 Len=010 <?>Capabilities: [150] Advanced Error ReportingKernel driver in use: fglrx_pciAs I said, I have no clue where to look at and what to search for. I'm also happy for some keywords that might help.I hope I provided the information you need. If not it would be nice if you also can tell me which command I have to execute to get the output you want, since I'm still not very familiar with the 'deeper system'.Thank you very much,rocco | 30 second gap in boot process | debian;boot;graphics | If you don't use systemd, it could be Debian bug 754987 in udev, since it involves a 30-second delay.The consequence of this bug in my dmesg log file:[ 19.809738] input: HP WMI hotkeys as /devices/virtual/input/input14[ 25.107974] WARNING! power/level is deprecated; use power/control instead[ 50.739902] Adding 19800076k swap on /dev/sda5. Priority:-1 extents:1 across:19800076k FS[ 50.780205] EXT4-fs (sda1): re-mounted. Opts: (null)[ 51.259666] EXT4-fs (sda1): re-mounted. Opts: errors=remount-ro[ 52.346718] lp: driver loaded but no devices found[ 52.469463] loop: module loaded[ 52.491077] smsc47b397: found SMSC SCH5317 (base address 0x0480, revision 1)[ 52.538276] fuse init (API version 7.23)It looks similar to yours. |
_webapps.8376 | I was looking for restaurants in my home town and I found one that closed some years ago (in fact it changed its name and now it is completely different). Is there any way to notify this to Google? | How to remove a location from Google Maps? | google maps | You can report the error to Google from the marker on the map.After you search for a place, click the appropriate marker. The info window appears.Click Edit > Report a problem.Select the issue that pertains to this place and add any comments you have.Click Report a problem. Google will investigate the place you have reported.Taken from this help articleUPDATEIt appears that you can't report it then. I've had a look around but there doesn't seem to be a simple Report here link.This is from a help article that can be found hereIf the Edit or Report a problem link is greyed out or doesnt exist, this means that youre not able to tell us about these issues just yet. Dont worry, were working hard to make this available in all countries! |
_unix.349939 | I am developing a Debian 8 system that has two network interfaces (one ethernet and one 3G modem) and is supposed to have two simultaneous connections to an MQTT broker i.e. there should be a connection via both interfaces. The language I am using is Python and the MQTT client is Paho.Supplying Paho's connect-method with argument called bind_address should do extacly what I want. I would just create two instances of Paho and give them the IP addresses of my two interfaces.The problem is that only one of them gets connected.I have tried pinging the broker IP specifying the interface explicitly (ping -I ifname a.b.c.d) and that works with both interfaces. Also, giving the two instances of Paho the same IP, the one of ethernet, works.At this point, my guess is that this problem is related to routing, but that's an area I am not very familiar with. How can I fix this?Output of ip addr as requested:1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 scope host lo valid_lft forever preferred_lft forever inet6 ::1/128 scope host valid_lft forever preferred_lft forever2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000 link/ether 00:04:25:18:e9:a9 brd ff:ff:ff:ff:ff:ff inet 82.195.211.80/23 brd 82.195.211.255 scope global eth0 valid_lft forever preferred_lft forever inet6 fe80::204:25ff:fe18:e9a9/64 scope link valid_lft forever preferred_lft forever3: sit0@NONE: <NOARP,UP,LOWER_UP> mtu 1480 qdisc noqueue state UNKNOWN group default link/sit 0.0.0.0 brd 0.0.0.0 inet6 ::127.0.0.1/96 scope host valid_lft forever preferred_lft forever4: wwan0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UNKNOWN group default qlen 1000 link/ether 0a:71:b0:b9:ca:39 brd ff:ff:ff:ff:ff:ff inet 10.36.124.58/30 brd 10.36.124.59 scope global wwan0 valid_lft forever preferred_lft forever inet6 fe80::871:b0ff:feb9:ca39/64 scope link valid_lft forever preferred_lft foreverOutput of ip route as requested:default via 82.195.210.1 dev eth0 metric 202default via 10.36.124.57 dev wwan0 metric 204default via 82.195.210.1 dev eth0 proto static metric 102410.36.124.56/30 dev wwan0 proto kernel scope link src 10.36.124.58 metric 20410.36.124.58 via 127.0.0.1 dev lo metric 20482.195.210.0/23 dev eth0 proto kernel scope link src 82.195.211.80 metric 20282.195.211.80 via 127.0.0.1 dev lo metric 202 | Connecting to same IP via two network interfaces at the same time | debian;routing;network interface | Simple source policy routing would probably solve your problem. Create a new routing table called mobile with an arbitrary unused number (100 here; this is optional, you could just use the number instead):echo 100 mobile >> /etc/iproute2/rt_tablesSet this table to route towards your 3G gateway:ip route add default via 10.36.124.57 dev wwan0 table mobileip route flush cacheFinally, add the rule for your 3G source address to use the newly setup mobile table:ip rule add from 10.36.124.58 table mobileI took the interface name (wwan0) and the addresses from your question. The interface name can be reasonably expected to stay stable (at least until you attach another 3G modem to your computer), but the local and gateway address may change on every connection. You'll probably want to script this setup. |
_webmaster.58256 | When displaying multiple products that are basically the same, let's call them Product A with different sizes, 30, 40 and 50, I choose to create only one page per product and avoid duplicates, since the size would really be the only difference.So in this page, I'm displaying the different product codes based on their size, ie: A30, A40 and A50.On a different page, for example, where Product B is listed, I would like to display related products, in this case, Product A (only a list with sizes and codes, no pictures). I can either display Product A by itself (which I don't want to, since a Product B30 would fit a product A30, for example), or display Product A30, A40 and A50.Using schema.org, itemprop=url, I would like to link to this product's page.The question here is, product A30, A40 and A50 are all listed in the same URL. Would linking these 3 products to the same URL pose a problem? | Schema.org product variations with same url. Problem? | microdata | If Product A is an accessory or spare part for Product B, this shouldn't be a problem since you're using the isAccessoryOrSparePartFor property, which is:A pointer to another product (or multiple products) for which this product is an accessory or spare part.It's natural to list accessories on the same page as the corresponding product, and provide a link to another page for more details on them. And as previously covered here, several products can be listed on a single page.This is akin to having a page for a printer (Product B), and then listing various printer cartridges (Product A) there as accessories, which point to a cartridges page that contains content like pictures of the cartridges, compatibility, specs, etc... It's doubtful that a search engine would view this as a form of manipulation or otherwise since you're indicating the accessory/product relationship, and this type of structuring is common. |
_cstheory.12824 | I am looking for a book on advanced data structures that goes beyond what is covered in standard textbooks like Cormen, Leiserson, Rivest, and Stein's Introduction to Algorithms.A book that can be used for teaching a graduate level course on advanced data structures like Erik Demaine and Andr Schulz's Advanced Data Structures course at MIT. An encyclopedic handbook of data structures would be even nicer. | Handbook of advanced data structures | soft question;ds.data structures;survey;books | null |
_unix.115222 | Is it possible to find out the sizes of data types (int, float, double, ...) on a Linux system, without writing a C program? Would the results for C same as for C++, and other programming languages in the same Linux system? | Possible to find out the sizes of data types (int, float, double, ...) on a system, without writing a C program? | c | null |
_unix.67845 | I have this keybinding in .vimrc:map + :put=''<cr>map - ddI find it really useful for fast layout and source file cleaning with + and -.But using :put=<cr> adds a line after the current cursor line, whereas dd removes a line at the current cursor.I'd rather have my + keybinding insert a line rather than add it after. What command should I try ? | Adding a line in vim adds it at the line after the cursor, I would like to insert | vim | Edit: Reading it again I gather I misunderstood. But, what about:-putIt inserts line above current.Edit:As do: put!To insert at mark (m[a-z]) one can say 'aput=xx, 'bput=xx etc. |
_softwareengineering.257469 | I'll do my best to describe the problem, but I'm still very new to several concepts that I think this problem requires to be solved (namely interfaces and threads). I should preface this by saying that I'm obviously not a Comp Sci major (as you'll see). I've learned as I've built my App, therefore my theory is terrible.My App works as follows: I have a Workout object which is contained in an Activity, which also contains a few UI Fragments. The UI Fragments accept input from the user, Then call methods in the Activity, which then manipulate the object. After the user finishes inputting their details, the Workout object (Which is a HashMap), gets serialized and passed to the next Activity via Bundle, then deserialized. This generally loses the order in which the user adds exercises to the Workout Object, which is important to maintain. Using LinkedHashMap doesn't work either, as it is bugged when it comes to serialization (It deserializes as a normal HashMap, verified with Eclipse debugger). This whole process happens again when the user wants to save the Workout, as the Workout gets Bundled once again and passed to a Fragment. In other words, the Object is stored, manipulated, and accessed, in the same place as where I handle user input events. This strikes me as terrible practice. Here's what I think I should do:Have one Fragment, which contains the Workout Object and runs in the background. It would also be accessible by every Activity which requires the Workout Object, and would communicate with the Fragments and activities via Interface, as follows: [Background Fragment] / \ / \ (Activity 1) (Activity 2) / \ / \ [UI Frag] [UI Frag] [UI Frag] [UI Frag]This solves the issue of having to pass the Workout object around like the only Joint at a Ziggi Marley concert, and the only time it will need to be serialized is when onSaveInstanceState() is called, if I'm not mistaken. This strikes me as better practice.Does this sound like a reasonable approach for the Data flow of my App?Although every extra detail you can give me will save me a lot of time, a Yes or No followed by a brief Why would definitely help.This is more of a bonus question, as I'm fully willing to sort this out through the brute force method, (try things until something works), but:Given Android's penchant for killing background processes, what implementation would work best for maintaining and manipulating the proposed Background Fragment?I have a hunch that having this Fragment running on a separate thread might be a good idea, but I know very little about them as of yet. Again, this Fragment needs to be accessible by more than one Activity, pretty much at any time. | Android, using a Fragment to hold/edit complex object, accesible from any Activity | android;multithreading;interfaces;object | null |
_cs.65796 | All papers with the subject of total functional programming make use of some kind of static type checking to ensure totality. This make sense considering hoy easily is to make a language Turing-complete. The question is: Is there any untyped/dynamically-typed formalism that ensures total functions?EditIn other words, there exist any formalism that only allows to construct total functions, with the impossibility of construction of partial functions, so there is no need of a filtering stage like a type checker or a termination analysis? | Total functional programming language without an static type checker | functional programming | null |
_unix.213060 | I am currently working on an embedded Linux system. For it to be similar to our other products I need to have it start a shell in a specified directory on boot, accessible using the serial port.For that I have this line in the inittab-script:::respawn:-/bin/shThis is working so far, only that the shell starts up with a pwd of /, instead of /mnt/flash.The only way I can come up with is to have it not start /bin/sh but instead a script like that:#!/bin/shcd /mnt/flash/bin/shIs there a way to do that in-line in the inittab without a second script?Edit: I need this to be a login script. This is what the - before the /bin/sh signifies. If I just run ::respawn:/bin/sh -c cd /mnt/flash;exec /bin/sh it does change the folder as expected, but I don't get a login shell which causes other problems.If I run it with ::respawn:-/bin/sh -c cd /mnt/flash;exec /bin/sh I get this error:/bin/sh: exec: line 1: -/bin/sh: not found | Start sh in a specified directory from inittab | shell;busybox;sysvinit;ash | You could give the shell some arguments, so that it starts slightly differently. eg./bin/sh -c cd /mnt/flash;exec /bin/shStarting with -c which will execute commands in following string.First command is the directory change, followed by exec which will start a new shell (in the same process) which is now starting in your desired directory. Update:If busybox shell is being used, there is a problem starting a login shell since busybox does not accept the -l option. Use the dot . command to source commands from your profile(s) before you do the exec eg/bin/sh -c cd /mnt/flash;. /etc/profile;exec /bin/sh |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.