id
stringlengths
5
27
question
stringlengths
19
69.9k
title
stringlengths
1
150
tags
stringlengths
1
118
accepted_answer
stringlengths
4
29.9k
_webapps.50249
Does anyone know if there's any way to change your username on theRPF.com? I first signed in with Facebook, which auto-created a user for me, based off my Facebook identity, but I really would prefer my username on RPF be a different handle. I've tried emailing/tweeting/facebooking the RPF, but I got no response, not even an automated one. Any help would be appreciated. I'm hoping I don't have to delete my account and recreate to do this, because I've already made a couple posts on RPF.
Can I change my username on theRPF?
username
null
_reverseengineering.11286
Assuming the following lines of code: MOV DWORD PTR FS:[0],EAX CALL someRoutine MOV EAX,DWORD PTR DS:[EAX+4] CMP DWORD PTR DS:[EAX+1204],0 JE placeInCode XOR EAX,EAXMy goal is to change [someRoutine] in such a way that the JE is always taken - I specifically don't want to tamper with the code outside [someRoutine]. So just think of [someRoutine] as a set of instructions that you can freely change and adapt. I can't seem to understand how to solve this equation. If there was no MOV instruction after the call, I guess I could just go to the address [EAX+1204] and fill it with 0. But like this, there seem to be too many unknown dependencies. Any advice?
Is this code equation solvable?
disassembly
Have someRoutine perform the following actions (in C below for example purposes) --DWORD* p = (DWORD*)malloc(8);p[0] = 0;p[1] = (SIZE_T)p - 1204;return p;Obviously this is a memory-leak since the allocated memory never gets free()'d, so you wouldn't want to use this approach if someRoutine gets called often. However it's not feasible to offer a better recommendation without us knowing the memory layout of the actual program.Edit: Updated based on @tathanhdinh's suggestion.
_unix.119463
I have created a script to read 15 pcap files from a folder and merge then into one file using mergecap command. I want the merged file to have the creation time same as the first file of the 15 files and the last modified time same as the last 15th file. W.R.T Changing a file's Date Created and Last Modified attributes to another file'sI have got how to modify the file times, but this will change all file times to that of the first file. touch -m command needs to be used here , but I cant see how to save the last modified time from the last file and put this to to the merged file.
Updating last modified time of a file
shell;files;touch
The simplest : you could use :touch -r Referencefile THEFILE to give THEFILE the same time as Referencefileso:rm -f Referencefileecho > Referencefile #to set the creation time#...do your captures here, then concatenate into THEFILE ....echo >> Referencefile #to set the modification timetouch -r Referencefile THEFILEBut if you prefer to have a more flexible way:To have a reliable way to get the time of a file in a portable format, not depending on if the file last changed within 6 months, etc: tar cf - file | tar tvf -so you could do this to get a time suitable for touch:gettouchdate () { tar cf - $1 | tar tvf - | tr ':' ' ' \ | awk '{mm=sprintf(%02d,(match(JanFebMarAprMayJunJulAugSepOctNovDec,$5)+2)/3) ; print $10 mm $6 $7 $8 $9 ;}'}#firstdate=$(gettouchdate /path/to/FIRSTFILE)lastdate=$(gettouchdate /path/to/LASTFILE)touch -r /path/to/FIRSTFILE THEFILEtouch -m $lastdate THEFILE
_opensource.2822
A repository owner on GitHub transferred me ownership of a project he abandoned some time ago. I noticed the year in the license file is outdated (2014), and the original author's name is still included.The license is MIT, but I know I can't reattribute the work to myself. Should I:Keep the year updated and continue crediting him, even if I'm now the one maintaining the codebase?Leave the license as-is?Ask for permission to modify the license?All things considered, the author's probably not that hung-up on this matter, but I am and I'd prefer to know what the recommended procedure for transferal of ownership is... I didn't, after all, pen the original code...EDIT: Just to confirm, I've read the question regarding forking an MIT-licensed project. This is different, because it's not forking somebody else's work, it's having it handed over to you in its entirety.
How should a codebase's original author be credited after they've transferred ownership of it?
attribution;ownership
Based on the exchange you've had with the previous repository maintainer, the previous maintainer never transfer ownership of his copyright. This situation is virtually identical (from a copyright and licensing perspective) to forking someone else's freely-licensed repository without coordinating directly with them. The original owner holds copyright on the original code, and you have permission to make your own modifications, which will be under your own copyright.The only difference here appears to be that the Github repository has been mechanically transferred from being listed under the previous owner's account to being listed under your account. This by itself appears to have no copyright transfer implications. It is merely an easy way for the previous maintainer to signal, I don't care about updating this project anymore, but this guy does. Having the repo listed under your account doesn't mean anything in copyright terms -- the license text always allowed you to copy the code and post a new copy under your own Github account, which is nearly identical to what has happened here.Unless the previous maintainer has explicitly authorized a transfer of title making you the new copyright owner, you do not have the right to remove the copyright notice. If you would like to do so (and if you would like the unambiguous ability to completely re-license the entire work in the future) you should ask for the maintainer to completely relinquish copyright to you, which he may or may not wish to do.Assuming you have participated in a transfer of title and you are now the new copyright owner of the entire work, then, yes, you can remove the copyright notice. this is trivial to see, because the previous copyright holder no longer has any legal standing to take legal action against you, since only the current copyright holder (who is now you) can take legal action against misuse of a work. This hardly seems like a polite thing to do (versus simply adding your own copyright notice as an addition to his), it appears to be a legally valid thing to do, assuming you own the copyright on everything.Note that outside of the U.S., some jurisdictions have moral rights that can never be surrendered, and those moral right may include the right to be acknowledged as an author of a work. It's possible that removing an old copyright notice may run afoul of this moral right in certain jurisdictions, but I'm not sure.
_cstheory.20369
I'm studying how, given:an input from the user ( like a click of the mouse or the input from a key )a well defined data structure that represent the graphical layout inside a window ( a tree/graph like structure for now )I could possibly create what is generally called as a G/UI toolkit, which means that I should be able to create a responsive UI and a mapping between the input from the user and the functionality given to the UI itself.I found absolutely no paper, no technical explanation, no articles, about both the data structure and the algorithms used to perform this kind of mapping, and I'm wondering if someone could help me with this.I found some sparse reference to some tree-like data structure like kd-tree or quadtree that are used to subdivide the 2D space in the window and so when the signal will be fired, the coordinates generated by the signal, the click of a mouse, will be injected in the tree to find the corresponding widget to activate.This approach feels really old and I don't think it will scale that well.I also found some reference to what is called the third generation of rasterizers and UIs which seems to be based on linear algebra/vectors and sounds really nice because it's highly scalable and simple to reason about, the problem is I can't see any implementation or algorithms or data structures.Someone can point me in the right direction ?
What are the algorithms and the data structures for GUIs and input management?
graph algorithms;data streams
I'll first restate your question, and then try to answer it. As I understand it, the question you are trying to answer is, if I have a scene graph/widget tree, and I get an event, how can I figure out how to dispatch that event to the appropriate subnodes of the tree?The answer is that the data structures you have outlined are not sufficient by themselves to do the job; you need a bit more information. The primitive events the OS produces tell you the positions of the mouse, and the scene graph gives you a logical decomposition of the structure of the GUI. Therefore, you need some additional data structures to translate between the widget tree and what it looks like geometrically. The simplest case is when every widget is an axis-aligned rectangle. What you do then is:Every widget node stores its position and shape. In addition to the widget tree, you keep a separate doubly-linked list storing all of the clickable widgets in their z-order, so that the widget which is visually on top is at the head of the list. You also keep track of the current mouse position (you have to do this anyway, because the OS only gives you relative position changes). When an event occurs, what you do is:When an event occurs you iterate through the z-order list, doing a simple hit test for the bounding box of each widget. The first time the hit test succeeds, you know where the event occurred, and can do event dispatch. With fancier graphics geometry (say with vector graphics), each widget will store a data structure representing the shape, and your hit test gets more complicated to match. The things to Google for: collision detection or hit detection. spatial indices -- often these data structures are variants of quadtrees and the like. It really does work pretty well, even though the geometric data can be quite large, because user events are generally relatively infrequent.
_cs.14022
When it comes to the design of algorithms, one often employs the following techniques:Dynamic ProgrammingThe Greedy-StrategyDivide-and-ConquerWhile for the first two methods, there are well-known theoretical foundations, namely the Bellman Optimality Principle and matroid (resp. greedoid) theory, I could not find such a general framework for algorithms based on D&C. Firstly, I am aware of something that we (or rather, the prof) introduced in a functional programming class, called an algorithmic skeleton, that arose in the context of combinators. As an example hereof, we gave such a skeleton for D&C algorithms as follows: Definition: Let $A,S$ be non-empty sets. We call the elements of $S$ solutions, and the elements of $P:=\mathfrak{P}(A)$ (that is, the subsets of $A$) are referred to as problems.Then, a D&C-skeleton is a 4-tuple $(P_\beta, \beta, \mathcal{D}, \mathcal{C})$, where: $P_\beta$ is a predicate over the set of problems and we say that a problem $p$ is basic iff $P_\beta(p)$ holds.$\beta$ is a mapping $P_\beta \rightarrow S$ that assigns a solution to each basic problem. $\mathcal{D}$ is a mapping $P \rightarrow \mathfrak{P}(P)$ that divides each problem into a set of subproblems.$\mathcal{C}$ is a mapping $P\times \mathfrak{P}(S) \rightarrow S$ that joins the solutions (depending on kind of a pivot problem) of the subproblems to produce a solution. Then, for a given skeleton $s=(P_\beta, \beta, \mathcal{D}, \mathcal{C})$ and a problem $p$, the following generic function $f_s: P\rightarrow S$ computes a solution (in the formal sense) for $p$:$f_s(p)= \left\{ \begin{array}{l l} \beta(p) & \quad \text{if $p$ is basic}\\ \mathcal{C}(p,f(\mathcal{D}(p))) & \quad \text{otherwise} \end{array} \right.$where in the second line we use the notation $f(X) := \{f(x) : x\in X\}$ for subsets $X$ of the codomain of a mapping $f$.However, we did not further examine the underlying, structural properties of problems that can be formulated this way (as I said, it was a functional programming class and this was only a small example). Unfortunately, I could not find further reference on this very approach. Hence I don't think the above definitions are quite standard. If someone recognizes what I have stated above, I would be glad about related articles.Secondly, for the greedy strategy we have the famous result that a problem is correctly solved by the general greedy algorithm if and only if its solutions constitute a weighted matroid. Are there similar results for D&C-algorithms (not necessarily based on the method outlined above)?
Theoretical foundations of Divide and Conquer
algorithms;reference request;divide and conquer
A formal treatment (somewhat resembling the model proposed in the question) of the subject using what is called pseudo-morphisms (that is, functions that are almost morphisms, with some pre- and post-computation done), as well as considerations of complexity analysis and parallel implementation of such algorithms are given in:An algebraic model for divide-and-conquer and its parallelism by Zhijing G. Mou and Paul Hudak (in The Journal of Supercomputing , Volume 2, Issue 3, pp. 257-278, November 1988)
_softwareengineering.214734
I am fairly new in product development and I am trying to work over a product. The problem that I have realized is that people draw diagrams and charts showing different modules and layers.But as I am working alone (I am my own team) I got a bit confused about the interaction I am facing in the development within the programs and I am wondering whether developing a product in modules is real or not?Maybe I am not a great programmer, but I see no boundaries when data start to travel from frontend to backend.
Is programming in layers real?
design;web development;layers;product
null
_unix.40495
Possible Duplicate:Linux for low-end hardware and internet browsing My dad has a rather old computer that's just sitting there that I want to repurpose. Now I know could probably get a Pentium 4 very cheap but where's the fun in that? What I'm after is something that's simple to use that will run on a Pentium II or III (I can't remember) with 4GB of HDD space and probably about 512MB of RAM.What can I install on this to make it work?
Linux for a writer, running on a Pentium II
linux;small distribution;word processing
Have a quick read of this techradar article.Classic distribution for old machines: Damn Small Linux.Look at Markdown/LaTeX for nice formatting of documents, but very low memory consumption whilst writing.
_webapps.54347
Suppose you pay $5 every month for 100GB and you fill it with stuff. What happens if you don't pay after a while? Will Google hold your stuff hostage until you pay or will they erase it?
What happens when you no longer pay for your Google storage?
gmail;google;google drive
null
_softwareengineering.115029
I'm developing a multi-tier application. We separate our project into three logical layers: client, service and data access. However, almost all methods in the service layer don't do anything except returning table/view from DAL to the client and then the client continues processing data. More than 50% of the returned data is bigger than it really needs to be. For example the client needs a username and an email-address but the service layer returns way more data. This is the coding standard in my team. I tried to change this by shaping classes that return what the client really needs but they wanted me to change it back after I had done it.I'm curious what are the pros and cons of doing things that way?
What are the pros and cons of directly exposing a Table/View entity class to the client?
coding style;coding standards
null
_webmaster.50323
In the Google Analytics ecommerce tracing script you must provide for every item and SKU code. I have this code for every product I'm selling and up until now I have always provided it in the _addItem method.But when reviewing that data in the ecommerce module of Google Analytics, I have no real, no readable data about my SKU sales. I know what product has been sold, due to the product name I provide. But when clicking through to the SKU-level, I know nothing more, since all I can see there are SKU codes.Is it possible and wise to replace the SKU code with the following template?product-name colour-name size-nameThis way, it should still be a unique field, but more readable afterwards.
sku code as description in Google Analytics
google analytics;javascript
null
_computergraphics.1888
I'm trying to figure out how to properly implement flat shading for meshes containing non-planar polygons (using OpenGL/GLSL). The aim is to obtain something similar to the result Blender gives (all polygons below are non-planar):To provide a bit of context the non-planar polygons (e.g. quads, pentagons, ...) are either present in the mesh I load or appear as a result of applying a subdivision scheme (such as Catmull-Clark) to the mesh.In case of a triangle mesh, I'm aware of the following approaches to implement flat shading Compute the cross product of dFdx and dFdy in the fragment shaderUse the geometry shader to compute the triangle normal by taking the cross product of two sides of the triangleWhen using glDrawElements, use the flat interpolation qualifier (which basically uses the normal associated with the provoking vertex for all fragments)When using glDrawArrays, most vertices (usually all of them) are copied to the GPU multiple times. Therefore, a different normal can be used each timeFor a mesh containing non-planar polygons the first three options don't yield the result I'm after. In my implementation (using the Qt framework) I use GL_TRIANGLE_FAN:The fourth option could work, but isn't very elegant I'd like to use either glDrawElements or glDrawMultiElements. One other option would be to use glDrawElements while looping over the faces one by one (instead of invoking it once using glPrimitiveRestartIndex). In that case, one could upload a uniform normal for each face. However, this does not seem very efficient. Any other ideas?
Flat shading for non-planar polygons
opengl;shader;glsl
null
_webmaster.1031
What do you do if one of the users of your website announces that he will commit suicide?
How do you handle Suicide Threats?
moderation;community management
You should handle it just like any other threat to someone's life. A person threatening suicide, or to kill someone else, is still threatening to kill someone. The only sensible thing to do is try and report it.If you have the visitor's information, you may be able to get in touch with a local police department. This might be difficult if the visitor is from another country. If not, you have the FBI, etc, even if they tell you that there's nothing they or you can do.If the person followed through, at least you tried to report it, furthermore, nobody can say you failed to report it, though I hate to bring up public perception in such a topic.
_scicomp.19471
I am currently working on 2D interpolation and I am using cubic splines. In 1D given N points one would use N+2 splines and would have to apply additional constraints in order to achieve a square system. For example requiring that the interpolant, S, second derivative is equal to zero ,Sxx = 0, at the end points (Natural Spline conditions) I was wondering how one would extend this to 2D? I believe it should be something like Sxx = Syy = 0 at the edge of your domain but I am not sure (if so I believe we would still be missing some equations). Any help would be appreciated.I will provide an example in 2D: Consider the points 1:1:10 in the x component and 1:1:10 in the y component, thus N points in each direction. For cubic splines one need N+2 splines in each direction. In 1D interpolation we can add the constraint that the second derivative should be zero to arrive at (N+2) equations for (N+2) unknowns.Thus to extend to 2D I will take the tensor product of these points I will have a 10x10 grid (100 pairs of points) and the tensor product of 12 splines in each direction (144 splines). Since I am using these for interpolation then I can retrieve 100 equations by setting up an equation for each point in my grid. I can retrieve an additional 40 equations by asking that S_{xx} = S_{yy} = 0 at the boundaries. 10 at $(x_0,y)$, $(x_N,y)$, $(x,y_0)$, $(x,y_N)$ Thus I would be missing 4 equations. This is where my confusion lies.
Natural spline conditions for 2D cubic splines
image processing
null
_webapps.41060
Is it possible to search videos on http://google.com with different parameters like size in MB, GB or resolution or file type etc. Just like we have for Images.Is it possible to apply some query parameters to do this?
Searching google videos of a particular size
google search;video
This is exactly what you need.You can access advanced search on YouTube by clicking the Filter link below your search result videos. There, you can filter results by:Type of results, such as Videos, Channels, or PlaylistsUpload dateSubject categoryVideo lengthVideo qualityFeatures, such as Closed captions, Partner videos, or RentalsYou can also sort your results by:RelevanceUpload dateView countRatingYou can close the options box by clicking Filter again after making your selections.You might also be looking for Google Videos (Not YouTube). You can perform advanced searches for Google Videos.
_vi.2006
Occasionally, my pinky will graze the ' key while reaching for enter, resulting in :w'<Enter>.I've tried:cabbrev w' :wcabbrev w\' :wcabbrev w' :wNone of them work. Is there a way to alias :w' to :w?I also use cmdwin (:help cmdwin + nnoremap : :<C-F>) instead of the normal command-line, so bonus points if it works there too.
Is there a way to alias `:w'` to `:w`, to avoid creating files named '?
command line;save;key bindings
As Peter Rincker points out, cmaps can expand in other places as well, so a cnoreabbrev would be better:cnoreabbrev w' wOr, the safest, again thanks to Peter:cnoreabbrev <expr> w' getcmdtype() == : && getcmdline() == w' ? w : w'By explicitly checking if the command line contains only w', unwanted expansions in situations can be avoided.You can use a cmap:cmap w' wYou'd still have to press Enter, but an accidental ' should be ignored now.If you're using cmdwin, a inoremap set by autocmd might be useful:autocmd CmdwinEnter * inoremap w' wautocmd CmdwinLeave * iunmap w'
_softwareengineering.145947
I work on some iphone/android apps and the data stored on a centralized server pattern seem fairly common.So far, I have done one app like this, doing everything myself at a low level without using many libraries:MySQL databasePHP/HTML web forms allowing the app manager to enter/update content with some validationPHP scripts turning the SQL data into downloadable XML filesApp code (java/objective-c) to download the XML files, parse them and turn them in some proper objects then displayed in the app UIAs you can imagine, that is very tedious and boring and there is lots of duplicated stuff.Also, it was interesting to do it once that way to understand how it works but Im sure some libraries do it much better that my own php/java/obj-c code.Now, I will have to work on something similar and Im looking for some sort of API/service that will do most of this work for me but still allow me to alter/customize what I need to (e.g.: web form validation so that the app manager doesnt break the integrity of the database, e.g.: plugging with my own classes).So Im looking for the best generic solution that cover all the steps above plus the case when the app can insert/update data as well (download and upload). (Note the library shouldnt have a licence that prevents me from selling the app)Lets say I have to build an app about cars, I want to store the car data in an online SQL database with some HTML forms allowing the app manager to add more cars (but only allowing him to enter validated data). I want the app user to be able to download the cars and insert new one in the online SQL database from his phone.What library/API would you recommend? What service would save me the most time while still allowing flexibility?
Client/Server App Best online data storage/administration/communication library?
database;android;iphone;libraries;server
Django's admin interface for the CRUD admin website, an RPC-like mechanism for communicating with a server-side API from the clients, probably there are decent libraries to export Django methods over XMLRPC (something like http://pypi.python.org/pypi/django-xmlrpc)
_unix.288787
I want to compile QSyncthingTray (https://github.com/sieren/QSyncthingTray) on my notebook running arch linux x86.I've set $QTDIR to /home/user/.qt/5.5/gcc/as well as $CMAKE_PREFIX_PATHI've even set $Qt5WebEngineWidgets_DIR to/home/user/.qt/5.5/gcc/lib/cmake/Qt5WebEngineWidgetsThe directory exists and the required files are in there.Cmake still errorsCMake Warning at /usr/lib/cmake/Qt5Core/Qt5CoreMacros.cmake:326 (find_package):Could not find a package configuration file provided byQt5WebEngineWidgets with any of the following names:Qt5WebEngineWidgetsConfig.cmakeqt5webenginewidgets-config.cmakeAdd the installation prefix of Qt5WebEngineWidgets to CMAKE_PREFIX_PATH or set Qt5WebEngineWidgets_DIR to a directory containing one of the above files. If Qt5WebEngineWidgets provides a separate development package or SDK, be sure it has been installed.Call Stack (most recent call first):CMakeLists.txt:127 (qt5_use_modules)CMake Error at /usr/lib/cmake/Qt5Core/Qt5CoreMacros.cmake:328 (message):Can not use WebEngineWidgets module which has not yet been found.Call Stack (most recent call first):CMakeLists.txt:127 (qt5_use_modules)
Cmake cannot find module Qt5WebEngineWidgets
arch linux;cmake
null
_unix.196939
I'm scanning one of my systems with Clamav like this:$ clamscan -r -i --remove --max-filesize=4000M --max-scansize=4000M \ --exclude=/proc --exclude=/sys --exclude=/dev --bytecode-timeout=190000It just found a virus in my download directory:/home/user/Downloads/jdk-8u31-linux-x64.tar.gz: Java.Exploit.CVE_2013_2472 FOUND/home/user/Downloads/jdk-8u31-linux-x64.tar.gz: Removed.What is the damage from this kind of malware?I downloaded this file from the official Oracle site, so I can't understand how it could be infected. Did someone manipulate this file before it entered my system and I installed some kind of malware on my Fedora?I removed the Java in question from my system and activated openjdk from the repository.Information from Oracle:Excerpt:CVE-2013-2472 Vulnerability in the Java Runtime Environment component of Oracle Java SE (subcomponent: 2D). Supported versions that are affected are 7 Update 21 and before, 6 Update 45 and before and 5.0 Update 45 and before. Easily exploitable vulnerability allows successful unauthenticated network attacks via multiple protocols. Successful attack of this vulnerability can result in unauthorized Operating System takeover including arbitrary code execution.Note: Applies to client deployment of Java only. This vulnerability can be exploited only through sandboxed Java Web Start applications and sandboxed Java applets.CVSS Base Score 10.0 (Confidentiality, Integrity and Availability impacts). CVSS V2 Vector: (AV:N/AC:L/Au:N/C:C/I:C/A:C). (legend) [Advisory]What are the procedures here, is this a Linux virus? Note result in unauthorized Operating System takeover.EDIT #1Here are the scan results:/home/user/Downloads/jdk-8u31-linux-x64.tar.gz: Java.Exploit.CVE_2013_2472 FOUND /home/user/Downloads/jdk-8u31-linux-x64.tar.gz: Removed./usr/share/nmap/scripts/irc-unrealircd-backdoor.nse: Unix.Trojan.MSShellcode-21 FOUND/usr/share/nmap/scripts/irc-unrealircd-backdoor.nse: Removed.----------- SCAN SUMMARY -----------Known viruses: 3791398Engine version: 0.98.6Scanned directories: 103265Scanned files: 746031Infected files: 2Total errors: 18624Data scanned: 330294.49 MBData read: 367850.33 MB (ratio 0.90:1)Time: 33458.657 sec (557 m 38 s)17 April 2015ClamAV is saying that there were two infections, according to @dhag this is not the case and one is an exploit/vulnerability in Java.... I am curious as to why frequently the scan is removing scripts from the nmap directory. I suspect that that's not malware but has to do with something about the capability of the script.
Exploit FOUND with clamav on Fedora 21 in Oracle's java
fedora;security;malware;jdk;clamav
I think that the message Java.Exploit.CVE_2013_2472 FOUND means thatthis installer is for a version of Java affected with the security bugyou posted the description of.If so, it's not a virus at all, just some piece of legit-but-dangeroussoftware. I would say the message from ClamAV is a bit confusing, andthe action of deleting the affected file may not be the most sensible,but that's open to debate.
_webapps.70827
I shared a map on Maps Engine with anybody to edit. However, when I open the link without signing in to my Google account, I am not able to edit the map. Is it possible to collaborate without requiring signin?Sharing settings:
Collaborate on Google Maps without signing in (Maps Engine)
google maps
null
_softwareengineering.237476
I know the basics of the model driven architecture: it is all about model the system which I want to create and create the core code afterwards. I used CORBA a while ago. First thing that I needed to do was to create an abstract interface (some kind of model of the system I want to build) and generate core code later.But I have a different question: is model driven architecture a broad approach or not? I mean, let's say, that I have the language (modelling language) in which I want to model EXISTING system (opposite to the system I want to CREATE), and then analyze the model of the created system and different facts about that modeled abstraction.In this case, can the process I described above be considered the model driven architecture approach? I mean, I have the model, but this is the model of the existing system, not the system to be created.
Model Driven Architecture Approach in programming / modelling
architecture;modeling;model
null
_cs.7
When placing geometric objects in a quadtree (or octree), you can place objects that are larger than a single node in a few ways:Placing the object's reference in every leaf for which it is containedPlacing the object's reference in the deepest node for which it is fully containedBoth #1 and #2For example:In this image, you could either place the circle in all four of the leaf nodes (method #1) or in just the root node (method #2) or both (method #3).For the purposes of querying the quadtree, which method is more commonplace and why?
Which method is preferred for storing large geometric objects in a quadtree?
graphics;data structures;computational geometry
null
_unix.141080
I have a laptop running Oracle Solaris and Gentoo Linux.First I installed Gentoo Linux. I used GPT partitioning scheme. In order to boot Gentoo Linux I have GRUB 2.Then I installed Solaris 11.1. Now GRUB from Solaris overwrote the GRUB from Gentoo Linux and it didn't detect it and so currently I have only Solaris in the boot menu.What I would like to do is to modify Solaris' GRUB configuration in order to do a dual boot by chainloading, since Solaris' GRUB does not support ext2 file system.Unfortunately Solaris documentation about GRUB, which is here, does not give an example about Linux - it's Windows only.So I created /rpool/boot/grub/custom.cfg:root@solaris:/rpool/boot/grub# cat custom.cfgmenuitem Gentoo { insmod gpt_part insmod chain set root=(hd0,ext2) chainload --force +1}and then rebooted.When GRUB started, I saw only Solaris menu.Do I have to run some additional commands on Gentoo Linux, in order for the GRUB configuration to take effect?On Solaris, I didn't see anything like this in the docs.What am I missing? At least the menuitem Gentoo should be visible in the GRUB.GRUB configuration /rpool/boot/grub/grub.cfg:igor@solaris:~/Broadcom$ cat /rpool/boot/grub/grub.cfg## DO NOT EDIT THIS FILE## It is automatically generated by grub-mkconfig using templates# from /usr/lib/grub2/bios/etc/grub.d and settings from /usr/lib/grub2/bios/etc/default/grub#### BEGIN /usr/lib/grub2/bios/etc/grub.d/00_header ###if [ -s $prefix/grubenv ]; then load_envfiset default=0if [ ${prev_saved_entry} ]; then set saved_entry=${prev_saved_entry} save_env saved_entry set prev_saved_entry= save_env prev_saved_entry set boot_once=truefifunction savedefault { if [ -z ${boot_once} ]; then saved_entry=${chosen} save_env saved_entry fi}function load_video { insmod vbe}if loadfont /@/boot/grub/unicode.pf2 ; then set gfxmode=1024x768x32;1024x768x16;800x600x16;640x480x16;640x480x15;640x480x32 load_video insmod gfxterm set locale_dir=($root)${prefix}/locale set lang=en_US insmod gettextfiterminal_output gfxterminsmod part_gptinsmod zfsset root=''if [ x$feature_platform_search_hint = xy ]; then search --no-floppy --fs-uuid --set=root e71191bc1127be5celse search --no-floppy --fs-uuid --set=root e71191bc1127be5cfiinsmod gfxmenuloadfont ($root)//@/boot/grub/themes/solaris/liber18.pf2loadfont ($root)//@/boot/grub/themes/solaris/univers16.pf2loadfont ($root)//@/boot/grub/themes/solaris/univers20.pf2insmod jpeginsmod pngset theme=($root)//@/boot/grub/themes/solaris/theme.txtset timeout=30### END /usr/lib/grub2/bios/etc/grub.d/00_header ###### BEGIN /usr/lib/grub2/bios/etc/grub.d/10_solaris ###menuentry Oracle Solaris 11.1 { insmod part_msdos insmod part_sunpc insmod part_gpt insmod zfs search --no-floppy --fs-uuid --set=root e71191bc1127be5c zfs-bootfs /ROOT/solaris/@/ zfs_bootfs set kern=/platform/i86pc/kernel/amd64/unix echo -n Loading ${root}/ROOT/solaris/@$kern: $multiboot /ROOT/solaris/@/$kern $kern -B console=graphics -B $zfs_bootfs set gfxpayload=1024x768x32;1024x768x16;800x600x16;640x480x16;640x480x15;640x480x32 insmod gzio echo -n Loading ${root}/ROOT/solaris/@/platform/i86pc/amd64/boot_archive: $module /ROOT/solaris/@/platform/i86pc/amd64/boot_archive}if [ $target = i386_pc ]; then search --no-floppy --fs-uuid --set=root_rpool e71191bc1127be5c if [ -s ($root_rpool)/@/boot/grub/menu.lst ]; then submenu Legacy GRUB Menu (from root pool rpool) ($root_rpool)/@/boot/grub/menu.lst { extract_legacy_entries_source $2 } fifi### END /usr/lib/grub2/bios/etc/grub.d/10_solaris ###### BEGIN /usr/lib/grub2/bios/etc/grub.d/41_custom ###if [ -f $prefix/custom.cfg ]; then source $prefix/custom.cfg;fi### END /usr/lib/grub2/bios/etc/grub.d/41_custom ###
Dual boot Solaris and Linux
linux;solaris;grub2;dual boot
null
_softwareengineering.63250
I consider myself a high level software developer. I enjoy reading a lot, and it's helped me over the course of my career. I think I am doing well.Right now, I spend a lot of time learning new things. I don't suck when it comes to writing code right now, but I'm about to start a family, and I regularly see many seniors with 14-15 years of experience whobecause they cut back on learning new thingsnow suck at programming. They were inspiring figures at some point of time, but they are not anymore.You might argue that basics never change, but it does appear to make a difference when you are coding on Delphi for 10 years and suddenly everyone is using the .NET framework. It's true that an experienced developer will take less time when learning a new framework, but it still does demand time and effort.How does a software developer manage the demands of the job while still being able to concentrate on things that necessarily take you out of the job, like starting a family?
How do you cope with the dynamic nature of high-level software development?
self improvement;career development
Something you said stood out: I regularly see many seniors with an experience of 14-15 years... they now suck at programming. That's a pretty broad brush stroke you are using to paint people with experience. I'd like to point out a couple things to consider:Younger/less experienced practitioners love to point out how their seniors fail to do X or Y, when they fail to understand that experience has shown that those were bad ideas. Yet each new generation of practitioners seems to want to repeat those mistakes. That phenomenon is common to all professions, not just programming.Not all people who have been working a number of years are experienced, mature, or good. It takes effort to become better. A lot of effort put in when you are younger builds a good body of experience from which you can draw on later.Perhaps the people you are referring to were never good. It's just as possible that they are looking at you thinking, why do you insist on doing things the hard way?It is true, however, that as you start a family you have much less time to keep up with new toys. You actually have less time as your kids get older than you do when they are younger. Toys don't make you a better programmer. Neither do tools. What makes you good is the ability to break down problems and build a working solution. What makes you great is the ability to teach others to be good. That's where experience starts to shine.
_unix.366987
I am confused with groups in Linux. Considering that user1 is in both groups user1 and user2 (and vice versa):user1> id user1uid=1000(user1) gid=1000(user1) groups=1000(user1),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),50(staff),113(lpadmin),130(sambashare),131(vboxusers),1001(user2)user1> id user2uid=1001(user2) gid=1001(user2) groups=1001(user2),0(root),1000(user1)I do not understand why user1 cannot edit a -rwxrw-r-- file owned by the user2 and group user2:user1>ls -l hey.xml-rwxrw-r-- 1 user2 user2 8385 May 24 11:39 hey.xmluser1>echo fails >> hey.xml bash: hey.xml: Permission deniedbut it works when I change the group:user1> sudo chgrp user1 hey.xml user1> echo works >> hey.xml Once this question is hopefully answered, what can I do to always allow user1 to read-write files in that user2 group?Thanks
Automatically allow user1 in group1 to edit file with owner user2 and group user2
users;group
If you add a user to a group, the new membership will not take effect immediately. The easiest way to ensure this is current is to have the user whose group membership has been changed log out and back in again. Once done, the user should be able to access files as expected.
_unix.2109
I'm using apache2 and postgres running on Ubuntu Server 10.04.I have removed the startup scripts for both of these apps and I'm using supervisor to monitor and control them. The problem I have run into is that both of these need directories in /var/run (with the correct permissions for the users they run under) for pid files. How do I create these during startup as they need to be created as root and then chown'd to the correct user?EditIt seems the best way to so this is to creat the directories with custom init scripts. As I have no shell scripting skills at all how do I go about this?
Create directory in /var/run/ at startup
ubuntu;permissions;init script
In reply to this comment:There are currently no startup scripts for the servcies. The supervisor daemon is started by the init.d scripts and then the other services are started by this service, which should not run as root.If your supervisor is started from init.d script, then just create another init.d script with the preferences to be run before the supervisor starts ( how you achieve this is totally dependent on your flavor of **IX ).In its start method create needed directories with required permissions.In its stop method tear those directories down.
_unix.257546
Hi I would like to block one user on all of the linux machines (Debian Wheezy) from being able to surf the internet, chat and email. However they are using linux based Rip stations for large format printers so they need to be able to access everything on the local network. They do not, however need to access any thing outside of the local network.
Block Internet access, but not network access for a user
networking;firewall
null
_codereview.103910
It has been bugging me for a while that while I understand how the basics of Brainfuck works, I can't get a firm grasp on the advanced features of the language. So I started to re-evaluate what I know about the language from the ground up.Brainfuck's memory consists of a tape of cells. Every cell can be modified by pointing the pointer at it and incrementing or decrementing it's value.The most basic operators are +, - and .. These operators will respectively increment, decrement and print the data at the current cell. The print operator will take the current value and put the corresponding ASCII character on screen.To print a basic sentence:Hello, World!I've written the following:++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++. Increment to 'H' and print+++++++++++++++++++++++++++++. Increment to 'e' and print+++++++. Increment to 'l' and print. Value is already at 'l' so just print+++. Increment to 'o' and print-------------------------------------------------------------------. Decrement to comma and print------------. Decrement to ' ' and print+++++++++++++++++++++++++++++++++++++++++++++++++++++++. Increment to 'W' and print++++++++++++++++++++++++. Increment to 'o' and print+++. Increment to 'r' and print------. Decrement to 'l' and print--------. Decrement to 'd' and print-------------------------------------------------------------------. Decrement to '!' and printWriting Brainfuck in this style to print a sentence is pretty straightforward. Iterate over the sentence and do the following per character:Calculate the difference between the current character and the previousWrite either as many + or - as the difference between characters. + if current character is higher than previous character, - if lower than previous characterWrite . to print current characterThe result as seen above isn't as bad as it looks. It's very memory efficient since all operations are made on the same cell. But speed is also important. Unfortunately I do not know how to properly time Brainfuck executions (yet).I'm fairly sure this is not the 'best'/'idiomatic' way of writing this. I know Brainfuck supports a while construction which seems like a good idea here, but I haven't found the most obvious implementation yet. I've seen Simon's method, but I'm not at that level yet.As usual I don't care about the length of the code (Brainfuck isn't JavaScript after all), but I'm definitely repeating myself an awful lot.How bad is my current implementation? Pointers as to how to gradually improve this to the more standard style of Brainfuck (using loops instead of repetition) are welcome.
Hello, Brainfuck
beginner;brainfuck
Brainfuck MultiplicationElaborating a bit more about 200_success' multiplication, and the shorter, less readable version, using similar ideas, but with more cell reuse:The ASCII values of what you want to write is, as 200_success mentioned:72 101 108 108 111 44 32 87 111 114 108 100 33So these are the numbers we want to generate. Let's start by sorting them:32 33 44 72 87 100 101 108 108 108 111 111 114GroupingHere we notice that we can separate the numbers into different groups. How to do that is a bit opinion-based, but I would chose a 30-50 group, a 70-90 group and a 100+ group, which leaves us with these groups:32 33 4472 87100 101 108 108 108 111 111 114The idea now is to use multiplication to get three numbers, it is important to remember what number in each group we want to write first. Looking back at our list of ASCII values sorted by the order they appear, we see that we want 72, 101, and 44.Using a bit of mathematics, we know that \$72 = 7 * 10 + 2\$, \$44 = 4 * 10 + 4\$ and \$101 = 10 * 10 + 1\$.Generating the numbersTo generate these numbers in BF we will do the typical BF construct:a++++[-b++++a]a and b means go to cell a/b. The number of + signs to use varies with what number you want to generate. As we want to generate three different numbers, we can do this all at once with something like this:a++++[-b+c++d+++a]The [...] construct in BF means while the current cell is not zero, this is the only conditional and looping construct that BF supports, and in reality it is the only thing you actually need. You just need to know how to use it.As we already start on cell a, we can write our construct like this:++++[->+>++>+++<<<]This will generate 4 * 1, 4 * 2 and 4 * 3, respectively. Adjusting the number of + signs leave us with:+++++ +++++ [-> ++++ > +++++ ++ > +++++ +++++ <<<]That is, 10 * 4, 10 * 7 and 10 * 10.So now we can use these values to write our string. The values we have are 40, 70 and 100, so we will go to the different cells and change their values slightly up and down to get and print the numbers we want.+++++ +++++ [-> ++++ > +++++ ++ > +++++ +++++ <<<]>>++.>+.+++++ ++..+++.<<++++.----- ----- --.>+++++ +++++ +++++.>.+++.----- -.----- ---.<<+.Comments and formattingNow we clean up the formatting and add a bit of comments:+++++ +++++ [- 10 times >++++ 10 * 4 = 40 >+++++ ++ 10 * 7 = 70 >+++++ +++++ 10 * 10 = 100 <<<] 40 70 100>>++. 40 72 100 print 'H'>+.+++++ ++..+++. 40 72 111 print 'ello'<<++++.----- ----- --. 32 72 111 print comma and space>+++++ +++++ +++++. 32 87 111 print 'W'>.+++.----- -.----- ---. 32 87 100 print 'orld'<<+. 33 87 100 print '!'Brainfuck doesn't have any guidelines (that I know of) about indentation, formatting and comments, so how you do those parts is entirely up to you.Personally, when writing Brainfuck, I find it extremely important to keep track of the values of the memory tape, which is why I prefer adding comments about what the values of the memory tape are. Then if you want to edit anything you can more easily change what you want to change by reading your comments about the values of the memory tape.PerformanceIt's very memory efficient since all operations are made on the same cell. But speed is also important. Unfortunately I do not know how to properly time Brainfuck executions (yet).The most reasonable way to time Brainfuck executions is to count the number of instructions being performed at runtime.I added a feature to my Brainfuck Interpreter to allow me to easily count this.I also used a certain Brainfuck Developer IDE that includes a Text generator tool to generate BF code for your string, this tool produced the following code:>++++++++[<+++++++++>-]<.>++++[<+++++++>-]<+.+++++++..+++.>++++++[<----------->-]<-.------------.>+++++[<+++++++++++>-]<.>++++[<++++++>-]<.+++.------.--------.>++++++[<----------->-]<-.Here is an overview of the number of instructions being performed at run-time in the different versions:$$\newcommand{smallm}[0]{\overset{n\ \gg\ m}{\longrightarrow}}\begin{array}{|l|c|c|} \hline \\ & \textrm{Your code} & \textrm{200_success A} & \textrm{200_success B} & \textrm{My code} & \textrm{bfdev tool} \\ \hline \\ \textrm{Next} & 0 & 99 & 69 & 35 & 39 \\ \hline \\ \textrm{Previous} & 0 & 90 & 64 & 34 & 39 \\ \hline \\ \textrm{Print} & 13 & 13 & 13 & 13 & 13 \\ \hline \\ \textrm{Add} & 193 & 709 & 466 & 256 & 226 \\ \hline \\ \textrm{Subtract} & 160 & 21 & 22 & 36 & 193 \\ \hline \\ \textrm{Start While} & 0 & 1 & 1 & 1 & 6 \\ \hline \\ \textrm{End While} & 0 & 10 & 10 & 10 & 33 \\ \hline \\ \textrm{Total} & 366 & 943 & 645 & 385 & 549 \\ \hline\end{array}$$And here is an overview of the source code length of the different versions:Your code : 366200_success A : 151200_success B : 123My code : 124bfdev generated: 185As you can see, using loops doesn't normally improve performance. The reason for this is that instead of using only one cell, loops uses more. There is no faster way to go from 0 to 100 than to write + 100 times. Using loops does however reduce code length.I suggest that you try to aim for a combination of less code and few instructions at runtime. If you are concerned with performance, you shouldn't use Brainfuck in the first place ;)Another small improvementThe order of the tape values does matter a little bit. I realized that the order you wanted to go to the cells was 70 100 40 70 100 40, but my BF program kept the cells in the order 40 70 100. So by reordering the cells slightly, I saved 2 run-time instructions and reduced source code length by 2! (Yay!)My updated code: (383 run-time instructions, source code length 122)+++++ +++++ [- 10 times >+++++ ++ 10 * 7 = 70 >+++++ +++++ 10 * 10 = 100 >++++ 10 * 4 = 40 <<<] 70 100 40>++. 40 72 100 print 'H'>+.+++++ ++..+++. 40 72 111 print 'ello'>++++.----- ----- --. 32 72 111 print comma and space<<+++++ +++++ +++++. 32 87 111 print 'W'>.+++.----- -.----- ---. 32 87 100 print 'orld'>+. 33 87 100 print '!'
_cs.16221
Problem Statement:Suppose we have a thousands of words and we need to maintain these words in a data structure in such a way that we should be able to find all anagrams for a given string.I tried to achieve this with O(1) complexity.I am looking for a algorithm to implement above scenario. I implemented this problem with below algo, but I feel that we can improve its complexity. Any suggestion will be helpful.Algorithm:Here is trick to utilise hash code, we can also use character histogram.Step 1:Create an array of prime numbers. int primes[] = {2, 3, 5, 7, ...}; We are using prime number to avoid false collisions.Step 2:Create a method to calculate hash code of a word\string. int getHashCode(String str){ int hash = 31; for(i =0 to length of str){ hash = hash*primes['a' - str.charAt[i]]; } return hash; }Step 3: Now store all words in a HashMap.void loadDictionary(String[] words){ for( word from words for i = 0 to length of words) { int hash = getHashCode(word); List<String> anagrams = dictionary.get(hash); if(anagrams ! = null){ anagrams.add(word); } else List<String> newAnagrams = new ArrayList<String>(); newAnagrams.add(word); dictionary.put(hash, newAnagrams); } }}Step 4: Now here is the approach to find anagrams: int findNumberOfAnagrams(String str){ List<String> anagrams = dictionary.get(getHashCode(str)); return anagrams.size(); }
Algorithm to write a dictionary using thousands of words to find all anagrams for a given string with O(1) complexity
algorithms;complexity theory;time complexity;strings
You may get some inspiration from the articles The world's fastest scrabble program by Andrew W. Appel and A Faster Scrabble Move GenerationAlgorithm by Steven A. Gordon.Both algorithms rely on a clever use of finite automata.See also this question on Stackoverflow.
_cs.10002
Functional programming employs persistent data structures and immutable objects. My question is why is it crucial to have such data structures here? I want to understand at a low level what would happen if the data structure is not persistent? Would the program crash more often?
Why do we use persistent data structures in functional programming?
data structures;functional programming;programming paradigms;persistent data structure
When you work with immutable data objects, functions have the property that every time you call them with the same inputs, they produce the same outputs. This makes it easier to conceptualize computations and get them right. It also makes them easier to test.That is just a start. Since mathematics has long worked with functions, there are plenty of reasoning techniques that we can borrow from mathematics, and use them for rigorous reasoning about programs. The most important advantage from my point of view is that the type systems for functional programs are well-developed. So, if you make a mistake somewhere, the chances are very high that it will show up as a type mismatch. So, typed functional programs tend to be a lot more reliable than imperative programs.When you work with mutable data objects, in contrast, you first have the cognitive load of remembering and managing the multiple states that the object goes through during a computation. You have to take care to do things in the right order, making sure that all the properties you need for a particular step are satisfied at that point. It is easy to make mistakes, and the type systems are not powerful enough to catch those mistakes.Mathematics never worked with mutable data objects. So, there are no reasoning techniques we can borrow from them. There are plenty of our own techniques developed in Computer Science, especially Floyd-Hoare Logic. However, these are more challenging to master than standard mathematical techniques, most students can't handle them, and so they rarely get taught.For a quick overview of how the two paradigms differ, you might consult the first few handouts of my lecture notes on Principles of Programming Languages.
_softwareengineering.161911
Would this be considered dependency injection, or delegation or object collaboration?https://gist.github.com/3428071
Would this be considered dependency injection?
design patterns;object oriented
The ors in your question make it sound like those three things are mutually exclusive.This is a form of dependency injection, albeit a non-conventional form of it. In the end, you are injecting Logger_model into User_model, so it is injection of a dependency. It is also true to say that Logger_model is a collaborator in this instance. And it is also true that User_model delegates logging to Logging_model.So, basically, it's all of the above.
_codereview.80671
I have only been coding C# for a short time and I can't say I'm an expert but I am rather enjoying it. I wondered if you could see any way I could improve my code.using System;using System.Net;using System.Net.Sockets;namespace Reality.Network{ /// <summary> /// Callback to be invoked upon accepting a new connection. /// </summary> /// <param name=Socket>Incoming socket connection</param> public delegate void OnNewConnectionCallback(Socket Socket); /// <summary> /// Reality simple asynchronous TCP listener. /// </summary> public class SnowTcpListener : IDisposable // Snow prefix to avoid conflicts with System.Net.TcpListener { private Socket mSocket; private OnNewConnectionCallback mCallback; public SnowTcpListener(IPEndPoint LocalEndpoint, int Backlog, OnNewConnectionCallback Callback) { mCallback = Callback; mSocket = new Socket(LocalEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); mSocket.Bind(LocalEndpoint); mSocket.Listen(Backlog); BeginAccept(); } public void Dispose() { if (mSocket != null) { mSocket.Dispose(); mSocket = null; } } private void BeginAccept() { try { mSocket.BeginAccept(OnAccept, null); } catch (Exception) { } } private void OnAccept(IAsyncResult Result) { try { Socket ResultSocket = (Socket)mSocket.EndAccept(Result); mCallback.Invoke(ResultSocket); } catch (Exception) { } BeginAccept(); } }}
Custom TcpListener
c#;tcp
null
_softwareengineering.338611
Thanks to some great replies in a previous question, I think I now have a better understanding of GAs, but am still confused on a couple of points. I'll start with one here.I've been reading around about how a GA algorithm works, and have seen what appear to be conflicting opinions as to what you do at each generation:Some articles seem to say you pick the two best chromosomes and mate them, using the crossover and mutation rates to produce an offspring. You then replace the chromosome with the lowest fitness with the offspring. That only changes one chromosome per generation, which I would have thought makes for a very slow change overall, and so a slow approach to a solution. Why not do this for (say) the best 50% of the chromosomes, and replace the worst 50% at each generation? I've not seen this suggested.The other approach I've seen is to pick two chromosomes using some stochastic process, such as a roulette wheel, mate them to produce an offspring, then repeat until you have generated a whole new population. You then throw away the last generation entirely, and replace it with the new population. Whilst this will obvious produce more change per generation than the previous method, it has the (apparent) disadvantage of throwing away the best chromosomes from the previous generation. Granted, we hope that the offspring may be better, but they might not, and even if they are overall, you still throw away what could be even better chromosomes.Sorry if this is a dumb question, but I haven't seen a clear explanation of this part of the algorithm, and I'm not sure how it's supposed to be done. I wrote my very first GA code last night, which didn't do badly, but didn't perform as well as I'd hoped, and I'm wondering if I am doing this part wrongly.Thanks for any help you can give.Edit: Following some of the comments and replies, here is more information about the problem I'm trying to solve. Being really new at this, I've started with the simplest problem I could find, that of finding a string of all 1s. I fix the string length, say 20, and the fitness of any chromosome will be the number of 1s divided by 20.My first definition of performance was how close it got to the right solution. Given the easy nature of this problem, I know that the right solution is just a string of twenty 1s.I had a a further play, and found that by increasing the number of chromosomes helped for strings of length up to about 30, but once I got above that, it never really got past a fitness of about 0.8, ie sixteen 1s in the string.Don't know if that helps. From the comments, it sounds like I just have to keep playing (shame!).Edit2: Following all the excellent comments, but specifically Delioth's explanation, I tried keeping the 50% of the current population with the highest fitness, and replacing the poorer 50% with new chromosomes bred by roulette wheel selection from the current population. The results were pretty dramatic, with the GA finding the correct solution in around 200 generations, even when I increased the string length significantly. This compares with it not finding it after 10,000 generations before!I tried playing with the ratio of current chromosomes kept, but found that as long as I kept away from extremes either way, it didn't make a lot of difference.Thanks to everyone for the help. This has been a great learning experience. I have more questions, so will be back!
How do we produce the next generation?
genetic algorithms
Genetic algorithms are one of those pieces in CS where it's less science and more art, and very dependent on the requirements. You get to try some things, adjust it a bit and see how that turns out, and eventually come to your own consensus.As a rule, there are 4 things you can do in various combinations to create a new generation:Mating, which usually produces two children (xxxxx + yyyyy => xxyyy + yyxxx or various other possible splits)Mutation, changing one thing out of a chromosome and pushing it forward (xxxxx=>xxxyx)New blood, where we generate an entirely new chromosome in the new generationI don't recall the name, but forwarding a chromosome unchanged into the next generation is an option as well.In a typical genetic algorithm, you generally use all of these- but it's usually also entirely random. We like to use some sort of biased selection to get our generations improving, but if we take the top ones and decide to just keep those the algorithm will tend to stagnate- as an example, assume we have 10 copies of xxxyzz in a gene pool of 20. If we keep the top 50% as-is and mate and mutate to create 8 more, we have a whole pool of xxxyzz with two new bloods and aren't making any progress, since 90% of our chromosomes are the same (or one bit off of the same).As such, a typical genetic algorithm assumes each generation is entirely new, even though some of the members are the same as the previous generation. We try to keep the number of kept members to a minimum, since a few copies of a decent solution can very easily overwhelm a population if there are too many being kept, which leads to stagnation (and once you hit sufficient stagnation, every generation isn't helping you much since you're relying on either a lucky new blood or a good incremental improvement).In a case where there are several very different/distinct 'correct' solutions (final chromosomes), you may need to have a high rate of entirely new chromosomes. In a case where you know the general structure of the result, you may not want any new blood- you may just want incremental changes on the chromosomes you've got (since new blood could at that point give you an entirely nonfunctional answer)- but you may keep new blood in the algorithm and it might do better.
_unix.194583
Can anyone help to remove the line in file based on delimeter(Comma), Incase if line contain less number of columns or Bad records , Need to delete those.Input File:a,b,c,da,b,d,fc,da,v,b,hd,e,v,nIn the above file if the delimeter is less than 4 than i have to delete the line from the file.Output File :a,b,c,da,b,d,fa,v,b,hd,e,v,nThe below command gives me number of delimeter in a line , How can i delete if that not equal to 4,egrep -iv '' file.csv | awk -F',' '{print NF}' Thanks.
How to remove line based on Delimeter in perl / Shell?
shell;sed;awk;perl
With perl:$ perl -F, -i.bak -ane 'print if @F > 3' fileWith perl > 5.20, you can use -F without -a and -n (-F implies -a and -a implies -n).Or you can use sed:$ sed -i.bak -e '/\([^,]*,\)\{3,\}/!d' file
_unix.11871
A lot of the time I edit a file with nano, try to save and get a permission error because I forgot to run it as sudo. Is there some quick way I can become sudo without having to re-open and re-edit the file?
Is it possible to save as sudo from nano after you've forgotten to run as sudo?
command line;sudo;nano
No, you can't give a running program permissions that it doesn't have when it starts, that would be the security hole known as 'privilege escalation'.Two things you can do:Save to a temporary file in /tmp or wherever, close the editor, then dump the contents of temp file into the file you were editing. sudo cp $TMPFILE $FILE. Note that it is not recomended to use mv for this because of the change in file ownership and permissions it is likely to cause, you just want to replace the file content not the file placeholder itself. Background the editor with Ctrl+z, change the file ownership or permissions so you can write to it, then use fg to get back to the editor and save. Don't forget to fix the permissions! Some editors are actually able to do this by launching a new process with different permissions and passing the data off to that process for saving. See for example this related question for other solutions in advanced editors that allow writing the file buffer to a process pipe. Nano does not have the ability to launch a new process or pass data to other processes, so it's left out of this party.
_softwareengineering.28272
I saw the recent post about the person questioning his boss's solution (I believe my solution is better than my boss, so should I ignore him?) and decided to ask something similar but not as clashing as it sounded in the above link.To put it simply and more conceptually:We have a web app that does phone billing for many different clients. The thing is, the person that started the project didn't consider that there are only 9999 possible phone extensions in our design (a bit naive, I know). We have come across a point where different clients's users will have to share the same extension number. In the DB level, the extension number is fixed as unique and the Extensions table has a foreign key to Users. The easiest solution as we saw was to remove this unique constraint and allow extension numbers to be duplicated because we can still check and validate to see which Client the User belongs to. However, the person that oversees my work believed it would cause future problems if we simply allowed for duplication. He suggested I create an intermediary table that links two tables together, namely UserProfile (which has a foreign key to User and Client) and the Extension table. Since my way seemed easier to do, I created a branch of the project to test if it works fine, which it does.Then I started implementing the other way and came across some complications, system-wide modifications, but I still think it's doable. The person that oversees my work is a sys admin that does some programming. I'm the full-time programmer, though without much experience (still young ;) ). It would be cool if I had some outside perspective on my dilemma?Thanks a lot guys.
Two possible solutions to a problem, DB design
database design
This is a bit of an abstract answer, but I would go with the design that most closely models the business. In your case, it seems like in reality, you do have situations where people share extensions, because you are modeling many distinct phone systems. Therefore I would drop the unique constraint. This means that extension is no longer a natural key for a person, but I don't really see that as a problem.
_codereview.144520
The problem here , requires me to find the best possible combination of values in an array which is nearest to 0 and are adjacent to each other , here is an little excerpt from it,The government of Siruseri has just commissioned one of the longest and most modern railway routes in the world. This route runs the entire length of Siruseri and passes through many of the big cities and a large number of small towns and villages in Siruseri.The railway stations along this route have all been constructed keeping in mind the comfort of the travellers. Every station has big parking lots, comfortable waiting rooms and plenty of space for eateries. The railway authorities would like to contract out the catering services of these eateries.The Siruseri Economic Survey has done a through feasibility study of the different stations and documented the expected profits (or losses) for the eateries in all the railway stations on this route. The authorities would like to ensure that every station is catered to. To prevent caterers from bidding only for profitable stations, the authorities have decided to give out catering contracts for contiguous segments of stations.The minister in charge realises that one of the bidders is his bitter adversary and he has decided to hand out as useless a segment as possible to him. On the other hand, he does not want to be seen to be blatantly unfair by handing out a large loss-making section to the adversary. Instead he wants to find the largest segment whose sum is closest to 0, so that his adversary spends all his time running a large number of canteens and makes either a small loss or a small profit or, even better, nothing at all!In other words, if the profits/losses at the stations are p1, p2, ..., pN the minister would like to handover a sequence i, i+1, ..., j such that the absolute value of pi + pi+1 + ... + pj is minimized. If there is more than one sequence with this minimum absolute value then he would like to hand over the longest one.For example, suppose there are 8 stations along the line and their profitability is as follows:Station 1 2 3 4 5 6 7 8 Expected Profits -20 90 -30 -20 80 -70 -60 125 If the adversary is awarded the section 1 through 4, he will make a net profit of 20. On the other hand if he is given stations 6, 7 and 8, he will make loss of 5 rupees. This is the best possible value.My first approach was to make an 2d array and calculate the sums by , first adding up the number adjacent to current index the use that to add with the next adjacent number and calculate the whole matrix which eventually can give me the number nearest to 0 and their position , but due to huge number of stations , the code gave runtime errors.Hence changed to a simple solution where you dont have to save each and every result and also break the loop when the output is the minimum possible value that is 0.The code ran fine with a couple of time limit exceeded cases , but the most astonishing fact is it landed up with 4 wrong answers , the TLE's were expected but wrong answers? I then tested against the test cases , yes couple of them takes a lot of time about 5-6s , but no wrong answers (the set of vertices were different but the question says I can print any set of vertices given the output is minimum) , so probably its a bug in the server.Here is my code:#include <iostream>#include <vector>#include <cmath>#include <climits>int main(){ int n; std::ios_base::sync_with_stdio(false); std::cin>>n; std::vector<int>profit(n); for(int i=0;i<n;i++){ std::cin >> profit[i]; } int min = INT_MAX ; int sVertex,eVertex; for(int i=1;i<n;i++){ int prevCost = profit[i] + profit[i-1]; if(std::abs(prevCost) < std::abs(min)){ min = prevCost; sVertex = i; eVertex = i; } for(int j=i+1;j<n;j++){ int prof = prevCost + profit[j]; if(std::abs(prof) < std::abs(min)){ min = prof; sVertex = i; eVertex = j; if(min == 0){ std::cout << min << std::endl; std::cout << sVertex << << eVertex+1 << std::endl; return 0; } } prevCost = prof; } } std::cout << min << std::endl; std::cout << sVertex << << eVertex+1 << std::endl; return 0;}Anyone having a better approach for this problem?Here are the testcases.
Code for calculating best possible combination in an array
c++;algorithm;programming challenge;time limit exceeded;dynamic programming
Bug #1The main bug that is probably causing your incorrect answers is due to your misreading of the problem. The problem says that if two or more segments have the same score, then you need to return the longest segment. Then, if there are multiple segments of the same score and length, you can return any of these segments.Currently, your code only finds the first segment with the lowest score. You could trivially modify your program to also record the best segment length and use it as a tiebreaker when you find a new segment of the same score.Possible Bug #2Depending on the problem intention, it could be a bug that your program does not consider segments of length 0 (i.e. a segment containing just one station). Your program currently only considers segments with a minimum of 2 stations. Thus, given the input 1 2 3 4 5, your program would find the segment 1 2 instead of the segment 1 1. Of course, if 0 length segments are not allowed, then your program is fine.Possible Bug #3Depending on the input, you may be overflowing your integer variables when you do things like:int prof = prevCost + profit[j];If this addition overflows past MAX_INT, then prof will turn negative when it actually should be a large positive value. For example, if prevCost and profit[j] were both 0x7fffffff, then the addition will result in the value 0xfffffffe which should be over 4 billion, but when treated as a signed int is -2.Better algorithm@PeterTaylor already demonstrated an \$O(n \log n)\$ solution that is probably the simplest to understand. I had come up with another \$O(n \log n)\$ algorithm that works in a similar way. Both are based on the fact that \$S(j) - S(i)\$ gives you the profit of a segment.Create a std::map, which will use running sums (sum[i]) as keys and indices (i) as values. Note that std::map has guaranteed logarithmic insertion and find time, because it uses some form of a a balanced binary tree implementation.Loop i from 0..n, keeping a running sum of profit[0..i].Search the map for the closest match to the current sum. If this closest match is better than the previous best match (by both score and by segment length), then record it as the new best match.If sum does not exist in the map, insert it. If it already exists, do not insert it because the earlier index with the same sum will give a longer segment so we can throw away the current index. Then go back to step #2.Sample implementation using std::map#include <iostream>#include <cmath>#include <climits>#include <map>int main(){ int n; std::ios_base::sync_with_stdio(false); std::map<int, int> sumMap; int sum = 0; int bestScore = INT_MAX; int bestLen = 0; int bestStart = 0; int bestEnd = 0; std::cin >> n; // Need to add a sum of 0 with index -1 so that we can find sequences // starting at the first station. sumMap[0] = -1; for (int i=0;i<n;i++) { bool alreadyExists = false; int profit; std::map<int, int>::iterator it; // Maintain running sum of profit[0..i] std::cin >> profit; sum += profit; // Search map for closest match to sum. Need to search twice. for (int loop = 0; loop < 2; loop++) { if (loop == 0) { // On the first loop, find the closest match >= sum, if // there is one. Use lower_bound() to find this. it = sumMap.lower_bound(sum); if (it == sumMap.end()) continue; } else { // On the second loop, find the closest match < sum. We can // find this by just decrementing the previous lower_bound. if (it == sumMap.begin()) break; it--; } // Replace the best match if this match is better. int prevSum = it->first; int score = std::abs(sum - prevSum); int len = i - it->second; if (score < bestScore || (score == bestScore && len > bestLen)) { bestScore = score; bestLen = len; bestStart = it->second; bestEnd = i; } if (score == 0) alreadyExists = true; } // Add sum to map, if it doesn't already exist. if (!alreadyExists) sumMap[sum] = i; } std::cout << bestScore << std::endl; std::cout << bestStart+2 << << bestEnd+1 << std::endl; return 0;}Sample implementation using sortOut of curiosity, I wrote a solution using @PeterTaylor's algorithm that used a sort. You can decide whether you think this one is easier to understand than the one using a map. There is one tricky part here where if there are multiple answers all with score 0, you need to handle that specially in order to find the longest segment with score 0.#include <iostream>#include <cmath>#include <climits>#include <vector>#include <algorithm>int main(){ int n; std::ios_base::sync_with_stdio(false); std::vector<std::pair<int, int> > sums; int sum = 0; int bestScore = INT_MAX; int bestLen = 0; int bestStart = 0; int bestEnd = 0; std::pair<int, int> sumPair; std::cin >> n; // Need to add a sum of 0 with index -1 so that we can find sequences // starting at the first station. sumPair.first = 0; sumPair.second = -1; sums.push_back(sumPair); // Create vector of sums. for (int i=0;i<n;i++) { int profit; std::cin >> profit; sum += profit; sumPair.first = sum; sumPair.second = i; sums.push_back(sumPair); } // Sort vector by sum, then by element index. std::sort(sums.begin(), sums.end()); // Iterate through vector looking for smallest sum distance between // adjacent entries. There is a special case for distance 0 where we // need to find the max length segment. std::vector<std::pair<int, int> >::iterator it = sums.begin(); int prevSum = it->first; int prevIndex = it->second; for (it++; it != sums.end(); it++) { int sum = it->first; int index = it->second; int score = std::abs(sum - prevSum); int len = std::abs(index - prevIndex); if (score < bestScore || (score == bestScore && len > bestLen)) { bestScore = score; bestLen = len; bestStart = prevIndex; bestEnd = index; } if (score != 0) prevIndex = index; prevSum = sum; } // Swap start and end if necessary. if (bestStart > bestEnd) { int tmp = bestStart; bestStart = bestEnd; bestEnd = tmp; } std::cout << bestScore << std::endl; std::cout << bestStart+2 << << bestEnd+1 << std::endl; return 0;}Defeating the bug(s) in the serverAfter examining the input and output files used by the server, I have come to the following conclusions:The server uses 32-bit integers and does not account for overflow. That is to say, some of the input files create segments with sums that overflow a 32-bit integer. But if you correctly solve the problem using 64-bit integers, the correct answers are marked wrong by the server. So you are expected to overflow your 32-bit integers and get the wrong answer.After accounting for the 32-bit issue, the server clearly has the wrong answer for input sets 1 and 8. For input set 1, you can find the answer of 6 18 19 by visual inspection, because the segment between stations 18 and 19 adds up to 6. The server expects the answer -48 6 8. Input set 8 should have answer 1 39396 47087 but the server expects answer -3 1021 21224.My guess is that whoever solved the problem to create the correct answers used a buggy program to do it. The trick now is to recreate the same bug to get the same correct answers. I was able to submit a program that passed all tests by adding some code to the map implementation.As you recall, the map implementation first checks the map for a sum >= target, then checks the map for a sum < target. The first check essentially finds a zero or negative profit answer. The second check finds a positive profit answer. Since the two mistaken answers both missed a correct positive profit answer, I put in some code that sometimes causes the second check to be skipped. This seemed to make the code match the buggy program code. Here is my submission that was accepted:#include <iostream>#include <cmath>#include <climits>#include <map>int main(){ int n; // std::ios_base::sync_with_stdio(false); std::map<int, int> sumMap; int sum = 0; int bestScore = INT_MAX; int bestDiff = INT_MAX; int bestLen = 0; int bestStart = 0; int bestEnd = 0; std::cin >> n; // Need to add a sum of 0 with index -1 so that we can find sequences // starting at the first station. sumMap[0] = -1; for (int i=0;i<n;i++) { bool alreadyExists = false; int profit; std::map<int, int>::iterator it; // Maintain running sum of profit[0..i] std::cin >> profit; sum += profit; // Search map for closest match to sum. Need to search twice. for (int loop = 0; loop < 2; loop++) { if (loop == 0) { // On the first loop, find the closest match >= sum, if // there is one. Use lower_bound() to find this. it = sumMap.lower_bound(sum); if (it == sumMap.end()) continue; } else { // On the second loop, find the closest match < sum. We can // find this by just decrementing the previous lower_bound. if (it == sumMap.begin()) break; it--; // This block here is purely for the sake of skipping // a positive profit answer to match the server bug. { int len = i - it->second; if (len > 1 && len < bestLen) break; } } // Replace the best match if this match is better. int prevSum = it->first; int score = std::abs(sum - prevSum); int len = i - it->second; if (score < bestScore || (score == bestScore && len > bestLen)) { bestScore = score; bestDiff = sum - prevSum; bestLen = len; bestStart = it->second; bestEnd = i; } if (score == 0) alreadyExists = true; } // Add sum to map, if it doesn't already exist. if (!alreadyExists) sumMap[sum] = i; } std::cout << bestDiff << std::endl; std::cout << bestStart+2 << << bestEnd+1 << std::endl; return 0;}
_unix.16501
I have about 15 instances of screen running on my linux server. They are each running processes I need to monitor. I had to close terminal (hence the reason I launched screen).Is there a way to reopen all 15 instances of Screen in different tabs without having to open a new tab, login to the server, print all the available screens to resume, and then type in the id for each screen session?
How to resume multiple instances of Screen from command line with minimal steps?
command line;terminal;osx;gnu screen
This python script just did the job for me. I made three screen sessions and this fires up three xterms with the sessions reattached in each. It's a bit ugly but it works.#! /usr/bin/env python import osif __name__ == '__main__': tempfile = '//tmp//screenList' # capture allthescreenIds os.system('screen -ls | grep Det | cut -d . -f 1 > ' + tempfile) f = open(tempfile, 'r') screenIds = f.readlines() f.close() screenIds = [x.lstrip() for x in screenIds] for eachId in screenIds: cmdLine = 'xterm -e screen -r ' + eachId.strip() + ' &' os.system(cmdLine)
_codereview.80545
I wrote a RomanNumeral class in C#. Please pull it to pieces:class RomanNumeral{ public RomanNumeral(string num) { AsRoman = num; AsArabic = RomanNumeralToArabic(num); if (AsArabic == -1) { throw new ArgumentException(); } } public RomanNumeral(int num) { AsRoman = ArabicNumeralToRoman(num); AsArabic = num; if (AsRoman == ) { throw new ArgumentException(); } } private string ArabicNumeralToRoman(int num) { string val = ; while (num >= 1000) { val += M; num -= 1000; } if (num >= 900) { val += CM; num -= 900; } while (num >= 500) { val += D; num -= 500; } if (num >= 400) { val += CD; num -= 400; } while (num >= 100) { val += C; num -= 100; } if (num >= 90) { val += XC; num -= (0; } while (num >= 50) { val += L; num -= 50; } if (num >= 40) { val += XL; num -= 40; } while (num >= 10) { val += X; num -= 10; } if (num >= 9) { val += IX; num -= 9; } while (num >= 5) { val += V; num -= 5; } if (num >= 4) { val += IV; num -= 4; } while (num >= 1) { val += I; num -= 1; } return val; } private int RomanNumeralToArabic(string num) { int val = -1; for (int i = 0; i < num.Length; i++) { switch (num[i]) { case 'M': val += 1000; break; case 'D': val += 500; break; case 'C': if (i != num.Length - 1) { switch (num[i + 1]) { case 'M': case 'D': val -= 100; break; default: val += 100; break; } } else { val += 100; } break; case 'L': val += 50; break; case 'X': if (i != num.Length - 1) { switch (num[i + 1]) { case 'M': case 'D': return -1; case 'L': case 'C': val -= 10; break; default: val += 10; break; } } else { val += 10; } break; case 'V': val += 5; break; case 'I': if (i != num.Length - 1) { switch (num[i + 1]) { case 'X': case 'V': val -= 1; break; case 'I': val += 1; break; default: return -1; } } else { val += 1; } break; default: return -1; } } return val; } public string AsRoman { get; private set; } public int AsArabic { get; private set; }}I really hate that humongous switch in RomanNumeralToArabic. Should that be a if/else if/else series, or is there a better way to do it entirely?
Roman Numerals - the good, the bad, and the ugly
c#;roman numerals
It is probably worth exploring other algorithms, if you wish to optimize for speed or brevity. Or just to explore the possibilities.Another interesting algorithm that I've seen used is first to normalize the roman numerals to a form which excludes their subtractive use: so, a string replace of CM CD XC XL IX IV to their equivalents DCCCC CCCC LXXXX XXXX VIIII IIII.Then you have a far easier job, since you can just assign a value to each letter and count how many of that letter there is in the string.Even better, all letters of a type will all be grouped together, and sorted largest to smallest, so you can loop over them until they change.Pseudocode:result = 0;replace CM DCCCCreplace CD CCCCreplace XC LXXXXreplace XL XXXXreplace IX VIIIIreplace IV IIIIread nextChar;while (nextChar == 'I') { result += 1; read nextChar; }while (nextChar == 'V') { result += 5; read nextChar; }while (nextChar == 'X') { result += 10; read nextChar; }while (nextChar == 'L') { result += 50; read nextChar; }while (nextChar == 'C') { result += 100; read nextChar; }while (nextchar == 'D') { result += 500; read nextChar; }while (nextChar == 'M') { result += 1000; read nextChar; }Best case, this still requires two passes, but it's kinda delightful in my head.Another algorithm is to work right-to-left, adding or subtracting each entry from a running total, which you can unroll to get the fastest roman numeral parsing algorithm I know of (1 read, 1 cmp, 1 add or subtract per char, plus overhead of 6 cmps per string)read prevChar;while (prevChar == 'I') { result += 1; read prevChar;}while (prevChar == 'V') { result += 5; read prevChar; if (prevChar == 'I') { result -= 1; read prevChar; }}... repeat above block 5 more times replacing values for X, L, C, D, M.
_cstheory.2834
Does anyone know of a set of problems that vary uniformly and span one of the interesting hierarchies of complexity and computability? By interesting, I mean, for example, the Polynomial Hierarchy, the Arithmetic Hierarchy, or the Analytic Hierarchy. Or maybe (N)P, (N)EXP, 2(N)EXP, $\ldots$More concretely: You can give a uniform set of problems that characterize the Arithmetic Hierarchy: $0, 0', \overline{0'}, 0'', \overline{0''},\ldots$. But these aren't always the most useful for reducing to actual problems. On the other hand, the book by Harel, Kozen and Tiuryn has a set of varying tiling problems that are NP, $\Pi^0_1$, $\Sigma^0_2$ and $\Sigma^1_1$ complete. The problems are useful for showing reductions, but it isn't entirely clear if they generalize uniformly to cover the other levels of the hierarchies they sit in.Does anyone know of such a set of concrete, uniform problems that span a hierarchy?EDIT: Just for clarification, I know that the 3 hierarchies I give above all have standard definitions in terms of alternating quantifier strength. That's not what I'm looking for. I'm looking for something different, like a game on a graph or a puzzle played with tilings.
Uniform hierarchy of problems that span complexity and computational hierarchies
cc.complexity theory;computability
null
_cstheory.7247
We can think of Kolmogorov complexity of a string $x$ as the length of the shortest program $P$ and input $y$ such that $x = P(y)$. Usually these programs are drawn from some Turing-complete set (like $P$ might be the description of a Turing machine, or it could be a program in LISP or C). Even when we look at resource-bounded Kolmogorov complexity, we still look at Turing machines but with some bounds on their runtime or space usage. One of the consequences of this, is that the complexity of a string is undecidable. This seems like an awkward feature.What happens if we use non-Turing complete models of computation to define Kolmogorov complexity?If we pick a restrictive enough model (say our model can only implement the identity), then the complexity of a string becomes decidable, although we also lose the invariance theorem. Is it possible to have a model strong enough to have complexity equal (upto a constant offset, or even a multiplicative factor) to the Turing-complete model, but weak enough to still allow the complexity of a string to be decidable? Is there a standard name for Kolmogorov complexity with non-Turing complete models of computation? Where could I read more about this?
Kolmogorov complexity with weak description languages
reference request;computability;kolmogorov complexity
Let's assume there exists some decidable complexity $D(s)$ differs from Kolmogorov complexity $K(s)$ by shift, by factor or, more generally, by any decidable monotonic unbounded numerical function $f(n)$ such that $K(s) > f(D(s))$.As $D(s)$ is decidable, it is possible to choose (effectively) a sequence of strings $s_n$ such that $f(D(s_n))> \mathrm{vff}(n)$ where $\mathrm{vff}$ is some very very fast growing function such as $\exp(\exp(\exp(n)))$. Suppose that we have $K(s_n) > \mathrm{vff}(n)$, i.e. Kolmogorov complexity of string $s(n)$ grows fast with $n$. But index $n$ also identifies the string $s(n)$ and, therefore, may be treated as upper bound of $K(s_n)$ (with some const shift). Any number $n$ needs only $\log(n)$ bits to represent it, and this contradicts with fast growing of complexity of $K(s_n)$. Thus for any decidable monotonic unbounded numerical function $f$, there exists strings $s$ such that $K(s) \not> f(D(s))$.
_webapps.19088
I generally search for images using Google Image Search and after any search, I select the minimum size as 640x480 from the left pane of the page. Is there any way to set a minimum size for Google Image Search by default? I looked at my search options in my Google account but couldn't find anything related.
Search Google Images for minimum 640x480 size by default
google image search
There doesn't seem to be any way to save Google Image search preferences, even when logged in to Google, which is a bit strange. I would have thought this would be something that a lot of people would use.Anyway, you could probably create a little piece of JavaScript and add to your toolbar as a bookmarklet to do this.Something like this would work:javascript:(function() { var searchTerm = prompt(Enter search term:,);searchTerm = escape(searchTerm);var url = http://www.google.com/search?q= + searchTerm + &tbm=isch&hl=en&cr=&safe=images&orq=dog&tbs=isz:lt,islt:vga&biw=1280&bih=;window.location.href = url;})();
_webapps.65379
How can I get a list of an Instagram account media (photos and videos)?Can I do this without programming?
List of Instagram Media
instagram
null
_scicomp.23433
I have the geometry file attached, and I would like to generate a coarse structured mesh over that body with gmsh.If I generate the .msh file, it includes both mesh and geometry points (attached). Do it is possible to force gmsh to write down only mesh points (in other words, what I can see if I toggle off geometry visibility)?fusoliera.geo:https://www.dropbox.com/s/p37eeiyilag3m34/fusoliera.geo?dl=0fusoliera.msh:https://www.dropbox.com/s/1fhrgtqvmx52w1c/fusoliera.msh?dl=0
Gmsh coarse mesh from finer one
mesh generation;gmsh
null
_unix.229091
I like uGet multi-thread downloader in Linux. I use it with Flashgot addon in Firefox. But I miss the following feature: when it is minimized to tray, the only way I can make it visible is by right clicking the tray icon and than selecting from a long list the option 'Show window'. Ideally, it should be showing by left or middle clicking the tray icon, but it doesn't. I have tested this in different Linux desktops.Can I make a shortcut for show window feature? UPDATE:This is desktop-specific. In KDE the menu is triggered with right-click, in Xfce with left-click (tested in Mint).I can confirm that the intended feature is already active at least in some desktops. For example, in Fluxbox (Manjaro).
Show uGet downloader window with click on tray-icon or shortcut
kde;keyboard shortcuts;xfce
null
_codereview.161891
I am working on C++ code which builds matrices (3D and 4D) using dynamic arrays.I am using arrays instead of std::vector; as in the future, I might extend this code to some kind of multithreading or parallel process (e.g. CUDA).In my code, I often initialize and define the source matrix in main.cpp.Then I have a function (sometimes it may belong to a class) which inputs the matrix along with other variable and I need to return the modified matrix. Which is subsequently used in main.This is what I usually work with in my code: #include <iostream> #include <stdio.h> #include <stdlib.h> using namespace std; float ***matFunc ( ***mat3D, int n); int main() { // define dimensions of the matrix int M , N, S = 3; //define and initialize the matrix float ***myMat = new float **[M]; for (int i = 0; i< M; i++ ) { myMat[i] = new float *[N]; for ( int j = 0; j < N; j++ ) { myMat[i][j] = new float [S]; for (int k = 0; k < S; k++ ) { myMat[i][j[k] = someValue obtained or calculated } } } // here I call my member function to perform addition // This is also used if I have more than one matrices float ***newMat = matFunc( myMat, int n ); //returns modified matrix //deleting the original myMat for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { delete[]myMat[i][j]; } delete[] myMat[i]; } delete[]myMat; return 0; } //function definition for matFunc float***matFunc(float ***mat, int n ){ int p, q, r; int M, N, S = 3; float ***modifiedMat = new float **[M]; for ( p = 0, p < M; p++ ) { modifiedMat[p] = new float *[N]; for ( q = 0; q < n; q++ ) { modifiedmat[p][q] = new float [S]; for (r =0; r < S; r++ ) { modifiedMat[p][q][r] = mat[p][q][r] * do something } } } return modifiedMat; }As you can observe, I am always defining and initializing new matrices with help of dynamic arrays. This becomes more troublesome if matrix dimensions are to be increased. I use dynamic arrays due to their faster operations as compared to vectors. But I think there might be some memory management issues with code. As I have observed it consumes more RAM and sometimes my IDE/compiler will complain lack of index or space for integer type.Could you please suggest how I can improve on this code?
Memory management for matrices built with dynamic arrays
c++;array;memory management
null
_cs.33671
I was told this question may be better received here.Prove that the probability that an insertion into a cuckoo hash table probes $t$ array locations is $O(\frac{1}{2^{t/2}})$. Keep in mind that there are two tables, each with size $s \ge 2n$, where $n$ is the number of elements in the set.I'm trying to use induction, but I don't know if this is the best method to go about proving this.The worst case to probe $1$ array location would be when all $n$ element are stored in the first table, and we get probability $\frac{n}{2n} = \frac{1}{2} = O(\frac{1}{\sqrt{2}})$ for insertion.The worst case to probe $2$ array locations would be when all $n$ elements are stored in the first table, we hit the first table, and we succeed in the second table. This has the same probability as it does to probe $1$ array location.However, I don't know how to continue the analysis. For example, what's the worst case probability to probe $4$ array locations? The question statement implies that the worst case is $O(\frac{1}4)$, but how do we achieve this result? If the first and second tables each have $\frac{1}4$ of their array locations occupied, then the worst case to probe $4$ elements would be hitting in the first table, hitting in the second table, hitting in the first table again, then finally inserting into the second table $\Rightarrow \frac{1}4\cdot\frac{1}4\cdot\frac{1}{4}\cdot\frac{3}4 = \frac{3}{256} \not = \frac{1}4$.Does anyone have a clearer way of thinking about this problem?
Probability of probing $t$ locations in a Cuckoo hash is $O(\frac{1}{2^{t/2}})$ locations in the worst case
algorithms;algorithm analysis;data structures;hash tables
Basically, you just write down everything that is necessary to have $t$ evictions and then use the universality of your hash functions to bound the probability.Assume you want to insert $x$ and your hash functions are $f,g$. Then if you have $t$ probes if $f(x)$ is occupied that is $$\begin{align}\mathbb{P}[t=1]& =\sum_{y \neq x} \mathbb{P}[f(x)=f(y)]\\&\le n \cdot 1/s \le 1/2.\end{align}$$since your hash function are $(1,k)$-universal (I assume).Now for $t=2$, the place of $f(x)$ have to be occupied by some element $y$ (that is $f(x)=f(y)$), and the alternative for $y$ is blocked by some other element $z$ (that is $g(y)=g(z)$). Summing up over all possible values for $y$ and $z$ gives $$\begin{align}\mathbb{P}[t=2]& =\sum_{y,z \neq x} \mathbb{P}[f(x)=f(y) \text { and } g(y)=g(z) ]]\\&\le n^2 \cdot 1/s^2 \le 1/4. \end{align}$$The summands of the sum are bounded by $1/s^2$ due to the universality of the hash functions, and you have less than $n^2$ summands. I think from here you can continue by yourself.
_webapps.58317
Sometimes, while editing the contents of a cell, using the arrow keys will not move the cursor but instead inserts the address to an adjacent cell. Here is an example of this problem with a screenshot: I go into an empty cell and enter =SUMIF( and then decide I want to use a normal SUM instead of a SUMIF so I hit the left arrow key once to move the cursor back, but this enters the address of the cell to the left.It doesn't always happen, so I wonder if there are conditions which cause it to occur which can be avoided. Is there a meta key which ensure the arrows can be used for navigation? Or can this functionality be disabled entirely?
How to avoid selecting a cell address when using the arrow keys while editing a cell
google spreadsheets
Short answerGoogle Sheets doesn't have meta-keys that disable cell navigation and referencing during the edition of a formula and this behaviour can't be disabled. WorkaroundsAdd ) before pressing the left arrow key.i.e. if you write =SUMIF(, press ) so you have =SUMIF(). Now press the left arrow key.Press Backspace instead of the left arrow key.ReferencesKeyboard shortcuts for Google Sheets - Docs editors Help
_unix.303824
I have successfully installed CentOS7 as a guest on VirtualBox for mac. I have also installed a Tomcat 7 as shown in the picture below and I can successfully access http://localhost:8080 from Firefox within the CentOS virtual machine. However, I am not able to access http://localhost:8080 outside the centOS virtual machine (i.e. I am not able to access the website from my host Yosemite web browsers like Safari or Firefox). Here are my centOS7 network settings from within Virtual Box: With the above network settings, I am able to connect to the internet within the CentOS virtual machine. But I can't connect to the host machine.
Why can't my host machine connect to my virtual guest machine via HTTP protocol?
centos;virtualbox;macintosh
null
_unix.287913
I was trying to make a linux server become a radius client. So I downloaded pam_radius. By following the steps from this website : openacs.org/doc/install-pam-radius.html and by following these steps : cd /usr/local/srcwget ftp://ftp.freeradius.org/pub/radius/pam_radius-1.3.16.tartar xvf pam_radius-1.3.16cd pam_radiusmakecp pam_radius_auth.so /lib/securityI thought I could install it but I got stuck at make I get this error message:[root@zabbix pam_radius-1.4.0]# makecc -Wall -fPIC -c src/pam_radius_auth.c -o pam_radius_auth.omake: cc: Command not foundmake: *** [pam_radius_auth.o] Error 127I googled this error message and someone said they installed pam-devel. But I get the same message even after installation of pam-devel. What can I do?
cc: Command not found when compiling a PAM module on Centos
centos;compiling;radius
Your error message is:make: cc: Command not foundwhich tells you that you are missing the C compiler. As @GAD3R suggests, installing the Development Tools group will correct this. You probably also need the pam-devel package.But, that said: there's really no reason to build pam_radius yourself, as it already exists in EPEL (Extra Packages for Enterprise Linux). Find instructions for configuring it here, and then just sudo yum install pam_radius.
_cogsci.12684
We learn facts in life from books or from experience, and we remember them. If later we ascertain a new fact about the same subject or phenomenon that contradicts the first impression, we can't erase that first fact, but we keep both facts with the ability to distinguish between them clearly, in consciousness.For example Pluto used to be the 9th planet however is no longer.But if in a dream one tells someone tha Pluto is in fact the 9th planet, does this mean that there is inconsistency between the id, ego and superego?Can we link this to slips of the tongue/mind or silly mistakes to which we later feel oh I still knew it, I did that mistake
Interpretation of facts in dream
dreams;long term memory;psychoanalysis;episodic memory
null
_unix.47972
I have to admit, I really really hate apt-listchanges. If I'm going to do a huge dist-upgrade, I want to just leave the computer there for a few hours. The asker of this serverfault question had a similar goal in mind, bu after implementing all of the suggestions in that post, I was still hit by apt-listchanges.Why is it so difficult to achieve non-interactivity with apt, an otherwise excellent program, given that the Unix philosophy aspires to it?I am hoping the changes I made to /etc/apt/listchanges.conf will help, but I want suggestions as to how to reliably do upgrades without any interaction whatsoever.[apt]frontend=noneemail_address=rootconfirm=0save_seen=/var/lib/apt/listchanges.dbwhich=newsThis is the command I used wasDEBIAN_FRONTEND=noninteractive \apt-get \-o Dpkg::Options::=--force-confnew \--force-yes \-fuy \dist-upgradeI also added the following lines to /etc/dpkg/dpkg.cfgforce-confoldforce-confdef
disable apt-listchanges (and other interactive stuff) during upgrades (reliably)
apt;upgrade
As you found and set in your config, apt-listchanges should not prompt if you set the frontend to none. You can also set the environment variable APT_LISTCHANGES_FRONTEND=none to achieve the same thing.It sounds like what you really want to do is use the unattended-upgrades package. It handles everything for you: disabling apt-listchanges, setting the frontend to noninteractive, checking for and avoiding conffile prompts, etc. If nothing else, the contents of the Python script /usr/bin/unattended-upgrades should answer your questions about how it does its magic.
_unix.3172
I would like to know What is the exact meaning of primary partitions? Why it is named so? and why it is restricted to 4?What is meant by extended partitions? Why it is named so? and what is the possible number of extended partitions in the hard disk?What is mean by logical partitions? Why it is named so? How it is calculated?What are the advantages of these software partitioning?Is it it possible to install OS(Linux/windows) in all partitions ? If no, why?
Meaning of hard disk drive software partitions?
partition
Hard drives have a built-in partition table on the MBR. Due to the structure of that table the drive is limited to four partitions. These are called primary partitions. You can have more partitions by creating virtual ( called logical ) partitions on one of the four primary partitions. There is a limit of 24 logical partitions.The partition you choose to split into logical partitions is called the extended partition, and as far I understand you can have only one.The advantage to logical partitions is quite simply that you can have more than 4 partitions on a disk.You should be able to install any OS on all of the partitions.See this page for more detailsIn the current IBM PC architecture, there is a partition table in the drive's Master Boot Record (section of the hard dirve that contains the commands necessary to start the operating system), or MBR, that lists information about the partitions on the hard drive. This partition table is then further split into 4 partition table entries, with each entries corresponding to a partition. Due to this it is only possible to have four partitions. These 4 partitions are typically known as primary partitions. To overcome this restriction, system developers decided to add a new type of partition called the extended partition. By replacing one of the four primary partitions with an extended partition, you can then make an additional 24 logical partitions within the extended one.
_unix.317335
I am trying to get internet connection in my raspberry pi 3 (Raspbian) with a GSM (SIM900a) module, connecting it to RXD/TXD Serial ports (/dev/ttyS0), I already got an ip address and DNSs, but I can't even ping any host, so I think it must be a routing problem, but I'm too newbie at low-level networking things to get the proper configuration by myself. I already have tried a lot of possible configs and didn't get it to work.I think that what I am missing may be an iptables rule... something with POSTROUTING MASQUERADE? I don't know...ppp output in /var/log/messages:Oct 18 22:09:35 NULL chat[1277]: abort on (BUSY)Oct 18 22:09:35 NULL chat[1277]: abort on (NO CARRIER)Oct 18 22:09:35 NULL chat[1277]: abort on (VOICE)Oct 18 22:09:35 NULL chat[1277]: abort on (NO DIALTONE)Oct 18 22:09:35 NULL chat[1277]: abort on (NO DIAL TONE)Oct 18 22:09:35 NULL chat[1277]: abort on (NO ANSWER)Oct 18 22:09:35 NULL chat[1277]: abort on (DELAYED)Oct 18 22:09:35 NULL chat[1277]: report (CONNECT)Oct 18 22:09:35 NULL chat[1277]: timeout set to 6 secondsOct 18 22:09:35 NULL chat[1277]: send (ATQ0^M)Oct 18 22:09:35 NULL chat[1277]: expect (OK)Oct 18 22:09:35 NULL chat[1277]: ATQ0^M^MOct 18 22:09:35 NULL chat[1277]: OKOct 18 22:09:35 NULL chat[1277]: -- got itOct 18 22:09:35 NULL chat[1277]: send (ATZ^M)Oct 18 22:09:35 NULL chat[1277]: timeout set to 3 secondsOct 18 22:09:35 NULL chat[1277]: expect (OK)Oct 18 22:09:35 NULL chat[1277]: ^MOct 18 22:09:35 NULL chat[1277]: ATZ^M^MOct 18 22:09:35 NULL chat[1277]: OKOct 18 22:09:35 NULL chat[1277]: -- got itOct 18 22:09:35 NULL chat[1277]: send (AT+CPIN=5503^M)Oct 18 22:09:35 NULL chat[1277]: expect (OKd)Oct 18 22:09:35 NULL chat[1277]: ^MOct 18 22:09:35 NULL chat[1277]: AT+CPIN=5503^M^MOct 18 22:09:35 NULL chat[1277]: ERROR^MOct 18 22:09:38 NULL chat[1277]: alarmOct 18 22:09:38 NULL chat[1277]: send (AT^M)Oct 18 22:09:38 NULL chat[1277]: expect (OK)Oct 18 22:09:38 NULL chat[1277]: AT^M^MOct 18 22:09:38 NULL chat[1277]: OKOct 18 22:09:38 NULL chat[1277]: -- got itOct 18 22:09:38 NULL chat[1277]: send (ATI^M)Oct 18 22:09:38 NULL chat[1277]: expect (OK)Oct 18 22:09:38 NULL chat[1277]: ^MOct 18 22:09:38 NULL chat[1277]: ATI^M^MOct 18 22:09:38 NULL chat[1277]: SIM900 R11.0^MOct 18 22:09:38 NULL chat[1277]: ^MOct 18 22:09:38 NULL chat[1277]: OKOct 18 22:09:38 NULL chat[1277]: -- got itOct 18 22:09:38 NULL chat[1277]: send (ATZ^M)Oct 18 22:09:38 NULL chat[1277]: expect (OK)Oct 18 22:09:38 NULL chat[1277]: ^MOct 18 22:09:38 NULL chat[1277]: ATZ^M^MOct 18 22:09:38 NULL chat[1277]: OKOct 18 22:09:38 NULL chat[1277]: -- got itOct 18 22:09:38 NULL chat[1277]: send (ATQ0 V1 E1 S0=0 &C1 &D2 +FCLASS=0^M)Oct 18 22:09:39 NULL chat[1277]: expect (OK)Oct 18 22:09:39 NULL chat[1277]: ^MOct 18 22:09:39 NULL chat[1277]: ATQ0 V1 E1 S0=0 &C1 &D2 +FCLASS=0^M^MOct 18 22:09:39 NULL chat[1277]: OKOct 18 22:09:39 NULL chat[1277]: -- got itOct 18 22:09:39 NULL chat[1277]: send (AT^M)Oct 18 22:09:39 NULL chat[1277]: expect (OK)Oct 18 22:09:39 NULL chat[1277]: ^MOct 18 22:09:39 NULL chat[1277]: AT^M^MOct 18 22:09:39 NULL chat[1277]: OKOct 18 22:09:39 NULL chat[1277]: -- got itOct 18 22:09:39 NULL chat[1277]: send (AT+CGDCONT=1,IP,lowi.private.omv.es^M)Oct 18 22:09:39 NULL chat[1277]: expect (OK)Oct 18 22:09:39 NULL chat[1277]: ^MOct 18 22:09:39 NULL chat[1277]: AT+CGDCONT=1,IP,lowi.private.omv.es^M^MOct 18 22:09:39 NULL chat[1277]: OKOct 18 22:09:39 NULL chat[1277]: -- got itOct 18 22:09:39 NULL chat[1277]: send (ATDT*99***1#^M)Oct 18 22:09:39 NULL chat[1277]: timeout set to 30 secondsOct 18 22:09:39 NULL chat[1277]: expect (CONNECT)Oct 18 22:09:39 NULL chat[1277]: ^MOct 18 22:09:39 NULL chat[1277]: ATDT*99***1#^M^MOct 18 22:09:39 NULL chat[1277]: CONNECTOct 18 22:09:39 NULL chat[1277]: -- got itOct 18 22:09:39 NULL chat[1277]: send (^M)Oct 18 22:09:39 NULL pppd[1270]: Script /usr/sbin/chat -v -t15 -f /etc/ppp/chatscripts/mobile-modem.chat finished (pid 1276), status = 0x0Oct 18 22:09:39 NULL pppd[1270]: Serial connection established.Oct 18 22:09:39 NULL pppd[1270]: using channel 1Oct 18 22:09:39 NULL pppd[1270]: Using interface ppp0Oct 18 22:09:39 NULL pppd[1270]: Connect: ppp0 <--> /dev/ttyS0Oct 18 22:09:40 NULL pppd[1270]: sent [LCP ConfReq id=0x1 <asyncmap 0x0> <magic0x16c75854> <pcomp> <accomp>]Oct 18 22:09:41 NULL pppd[1270]: rcvd [LCP ConfReq id=0x1 <asyncmap 0xa0000> <auth pap>]Oct 18 22:09:41 NULL pppd[1270]: sent [LCP ConfAck id=0x1 <asyncmap 0xa0000> <auth pap>]Oct 18 22:09:41 NULL pppd[1270]: rcvd [LCP ConfRej id=0x1 <magic 0x16c75854> <pcomp> <accomp>]Oct 18 22:09:41 NULL pppd[1270]: sent [LCP ConfReq id=0x2 <asyncmap 0x0>]Oct 18 22:09:41 NULL pppd[1270]: rcvd [LCP ConfAck id=0x2 <asyncmap 0x0>]Oct 18 22:09:41 NULL pppd[1270]: sent [LCP EchoReq id=0x0 magic=0x0]Oct 18 22:09:41 NULL pppd[1270]: sent [PAP AuthReq id=0x1 user=NULL password=<hidden>]Oct 18 22:09:41 NULL pppd[1270]: rcvd [LCP EchoRep id=0x0 magic=0x0]Oct 18 22:09:41 NULL pppd[1270]: rcvd [PAP AuthAck id=0x1 Login OK]Oct 18 22:09:41 NULL pppd[1270]: Remote message: Login OKOct 18 22:09:41 NULL pppd[1270]: PAP authentication succeededOct 18 22:09:41 NULL pppd[1270]: sent [CCP ConfReq id=0x1 <deflate 15> <deflate(old#) 15> <bsd v1 15>]Oct 18 22:09:41 NULL pppd[1270]: sent [IPCP ConfReq id=0x1 <addr 0.0.0.0> <ms-dns1 0.0.0.0> <ms-dns2 0.0.0.0>]Oct 18 22:09:41 NULL pppd[1270]: rcvd [LCP ProtRej id=0x2 80 fd 01 01 00 0f 1a 04 78 00 18 04 78 00 15 03 2f]Oct 18 22:09:41 NULL pppd[1270]: Protocol-Reject for 'Compression Control Protocol' (0x80fd) receivedOct 18 22:09:44 NULL pppd[1270]: sent [IPCP ConfReq id=0x1 <addr 0.0.0.0> <ms-dns1 0.0.0.0> <ms-dns2 0.0.0.0>]Oct 18 22:09:44 NULL pppd[1270]: rcvd [IPCP ConfReq id=0x1 <addr 192.200.1.21>]Oct 18 22:09:44 NULL pppd[1270]: sent [IPCP ConfAck id=0x1 <addr 192.200.1.21>]Oct 18 22:09:44 NULL pppd[1270]: rcvd [IPCP ConfNak id=0x1 <addr 10.242.68.43> <ms-dns1 195.219.66.42> <ms-dns2 87.119.194.34>]Oct 18 22:09:44 NULL pppd[1270]: sent [IPCP ConfReq id=0x2 <addr 10.242.68.43> <ms-dns1 195.219.66.42> <ms-dns2 87.119.194.34>]Oct 18 22:09:44 NULL pppd[1270]: rcvd [IPCP ConfAck id=0x2 <addr 10.242.68.43> <ms-dns1 195.219.66.42> <ms-dns2 87.119.194.34>]Oct 18 22:09:44 NULL pppd[1270]: not replacing default route to wlan0 [192.168.1.1]Oct 18 22:09:44 NULL pppd[1270]: local IP address 10.242.68.43Oct 18 22:09:44 NULL pppd[1270]: remote IP address 192.200.1.21Oct 18 22:09:44 NULL pppd[1270]: primary DNS address 195.219.66.42Oct 18 22:09:44 NULL pppd[1270]: secondary DNS address 87.119.194.34Oct 18 22:09:44 NULL pppd[1270]: Script /etc/ppp/ip-up started (pid 1286)Oct 18 22:09:44 NULL pppd[1270]: Script /etc/ppp/ip-up finished (pid 1286), status = 0x0ifconfig output:pi@NULL:~ $ ifconfigeth0 Link encap:Ethernet HWaddr b8:27:eb:34:7a:5e inet6 addr: fe80::e8a7:c560:2f66:73a2/64 Scope:Link UP BROADCAST MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)lo Link encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 inet6 addr: ::1/128 Scope:Host UP LOOPBACK RUNNING MTU:65536 Metric:1 RX packets:200 errors:0 dropped:0 overruns:0 frame:0 TX packets:200 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1 RX bytes:16656 (16.2 KiB) TX bytes:16656 (16.2 KiB)ppp0 Link encap:Point-to-Point Protocol inet addr:10.242.68.43 P-t-P:192.200.1.21 Mask:255.255.255.255 UP POINTOPOINT RUNNING NOARP MULTICAST MTU:1500 Metric:1 RX packets:3 errors:0 dropped:0 overruns:0 frame:0 TX packets:5 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:3 RX bytes:54 (54.0 B) TX bytes:91 (91.0 B)wlan0 Link encap:Ethernet HWaddr b8:27:eb:61:2f:0b inet addr:192.168.1.5 Bcast:192.168.1.255 Mask:255.255.255.0 inet6 addr: fe80::509e:723a:2fb:453/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:7937 errors:0 dropped:759 overruns:0 frame:0 TX packets:1040 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:1477582 (1.4 MiB) TX bytes:199477 (194.8 KiB)PD: I've set my hostname to NULL, which may be confused at some points of the log, I'm sorry
Internet connection over GSM module + PPP
internet;route;ppp;interface;gsm
null
_webmaster.23993
Possible Duplicate:Why should we use tags like p, span, hx tags when we can use CSS instead? Do you think that is actual difference between, as example<h1><span class=aaa>Hello!</span>,<span class=bbb>welcome</span>to my<span class=ccc>fantastic</span>website!</h1>and the simplest possible one<h1>Hello! welcome to my fantastic website!</h1>?thank you in advanceHAPPY NEW YEAR
complex heading tags: should I avoid them?
html;seo;tags
From an SEO perspective, it doesn't matter too much. There's some speculation that, in general, a high content-to-markup ratio is better for SEO. But I've seen no real evidence for this. This often repeated statement is probably generalized from the fact that high quality pages generally have lots of content, and pages with lots of content will have a high content-to-markup ratio.It's also possible that this popular conception originated from the days when major search engines only indexed the first X bytes from your page. While this may still be the case to an extent, the limit is generally high enough that for all practical purposes, it's a non-issue (if it is, then you're either a corner case or you're doing it wrong). Anyway, see John Mueller's comments on the issue here.That said, you rarely see the style of markup you propose because:A heading is a heading. Headings are short labels for a section of content, and there's rarely any need to specially style different parts of it. That isn't to say that there's never a circumstance where it might be required/appropriate, however, just that in generally it's not needed.Semantic markup dictates that your markup should be structured according to the smeantics of the content. Again, a heading is a heading. There usually aren't complex semantics involved. So it's likely someone using that style of markup is violation the separation of presentation and content, and the classnames aaa, bbb, and cccare probably presentational descriptions (e.g. grey1, grey2, grey3, or big, small, underlined, etc.), in which case it's no different than using <b>, <ul> or <i> really.Lastly, manually inserting such tags into each heading is going to be very time consuming for little to no reward. I suppose if they're arbitrarily inserted, then that process can be automated, but what would be the point?So there are plenty of reasons not to do it, but SEO isn't one of them. It's not likely to add any semantic information to the document, so the search engine will just strip out the tags and treat it as Hello! welcome to my fantastic website! in either case.Edit:As you mentioned, for semantic information there is some overlap in functionality between HTML5 microdata and using classnames as per microformats. You just have to decide which is more appropriate in a particular scenario based on features, markup length, support, and difficulty in implementing each.Here's an example from Google's Webmaster Tools help of how you can convey the same semantic information about a recipe using microdata, microformats, or RDFa.
_unix.323638
I'm running Linux Mint 18 Cinnamon on my Asus X555LA, which also has Windows 10 installed on another partition (the backlight works perfectly in Windows).However in Linux Mint: there's already an issue with Fn+F5/F6 not changing the backlight intensity. The various fixes I've tried (but haven't worked) include:adding a 20-intel.conf file into the /usr/share/X11 folder.added acpi_osi= to the /etc/default/grubRunning acpi_listen and pressing Fn+F5/F6 shows no output.Installing xbacklight and running xbacklight -set $percentageUntil about two days ago I could skirt this issue by using the brightness slider in the UI, however even this no longer works and the screen brightness is stuck at 100%.I am at a loss and no longer know what to do.
Backlight slider no longer works in Linux Mint
linux mint;acpi;asus;backlight
null
_cs.78101
Recently, I encountered terminologies such as primitive recursion and recursion combinator. One of the sources is here link I googled and read some, but missing the points of them. I know that recursion occurs when a function appears within its definition. While $\lambda$-calculus cannot express such recursive definitions directly, it can use combinators to implement recursion.So, what are Structural recursion, primitive recursion, recursion combinator and recursion principles? how each related to others?Hoping someone could explain these clearly, so I can go in the right direction. now I am struggling to figure out their points.Thanks in advance!
what are Structural recursion, primitive recursion, recursion combinator and recursion principles?
recursion;primitive recursion;variable binding
The recursion combinator you mention seems to be the recursor associated to an inductive (or recursive) data type. In the paper this seems to be the type describing the syntax of lambda terms. Here, I'll take lists as a simpler recursive type.Note that the lists of naturals type can be intuitively described as the least type admitting these constructors:$$\begin{array}{l}nil : list \\cons : nat \to list \to list\end{array}$$Recursive types as the one above have an associated induction principle. For instance, if we wanted to prove a property on all lists $p(l)$, it would suffice to prove the base case $p(nil)$, andthe inductive case $p(l) \implies p(cons\ n\ l)$ for any $n,l$.If we had more constructors, we would have move base or inductive cases, accordingly.Similarly, we can define a function $f : list \to A$ by induction. That is to define $f(l)$ on all lists, all we have to do is to definewhat is the result in base case, i.e. $f(nil) = a : A$provided we already defined $f(l)$, we need to define $f(cons\ n\ l)$ for all $n,l$.Note that step 2 amount to define a function $g : nat\to A \to A$, which takes $n:nat$ and $f(l):A$ and produces $g(n)(f(l)) = f(cons\ n\ l)$.We can generalize this by crafting a combinator that given $a,g$ produces $f$ defined as above. This is called the (primitive) recursor.$$\begin{array}{l}rec : A \times (nat \to A \to A) \to (list \to A) \\rec(a,g)(nil) = a \\rec(a,g)(cons\ n\ l) = g(n)(rec(a,g)(l))\end{array}$$Usually this is called fold_right or foldr in functional programming languages.Note how, roughly, $a$ replaces $nil$, and $g$ replaces $cons$. Indeed, in the general case, the recursor takes one argument for each constructor of the recursively defined type at hand.If you have a general fixed point combinator like Church's $Y$, you can easily encode the above. However, in many type theories, you don't have that luxury, since $Y$ causes the inconsistency of the related logic. Instead, for any recursive type you define, you get a restricted version of $Y$ which is the recursor: each type has its own recursion combinator. This ensures the termination of the calculus, which is important to ensure the consistency of the logic.
_unix.127857
On my friend's computer when Skype is launched either via terminal or GUI the current user is forced to log out of the system. Purging and reinstalling Skype did not work and we are using the same version of Ubuntu, that is 12.04.4 LTS 32-bit, and both our installed Skype programs are of the same version, namely 4.2.0.11. What may be the cause behind this and how can this behaviour of Skype avoided? Is it a bug or something related with installed programs etc. ? Any help is appreciated.EDIT:The log files are as follows and my friend also stated that when he tried to have a look at these files in Emacs he got kicked out of the system again:skype-err.logskype: Fatal IO error 11 (Resource temporarily unavailable) on X server :0..xsession-errorsWarning: Only changing the first 12 of 24 buttons.(gnome-settings-daemon:6738): power-plugin-WARNING **: gnome-session is not availableBackend : gconfIntegration : trueProfile : unityAdding pluginsInitializing core options...doneInitializing composite options...doneInitializing opengl options...doneInitializing decor options...doneInitializing mousepoll options...doneInitializing gnomecompat options...doneInitializing grid options...doneInitializing snap options...doneInitializing resize options...doneInitializing move options...doneInitializing unitymtgrabhandles options...doneInitializing place options...doneInitializing vpswitch options...done** Message: applet now removed from the notification areaInitializing wall options...doneI/O warning : failed to load external entity /home/jack/.compiz/session/102004b2d250ec54c7139932580828939400000066890035Initializing session options...doneInitializing animation options...doneInitializing workarounds options...donecompiz (expo) - Warn: failed to bind image to textureInitializing expo options...doneInitializing ezoom options...doneInitializing staticswitcher options...done** Message: using fallback from indicator to GtkStatusIconInitializing fade options...doneInitializing scale options...done(compiz:6756): GConf-CRITICAL **: gconf_client_add_dir: assertion `gconf_valid_key (dirname, NULL)' failedNautilus-Share-Message: Called net usershare info but it failed: 'net usershare' returned error 255: net usershare: cannot open usershare directory /var/lib/sa$Please ask your system administrator to enable user sharing.Initializing unityshell options...doneSetting Update main_menu_keySetting Update run_keySetting Update run_command_terminal_keySetting Update icon_size** Message: moving back from GtkStatusIcon to indicator** (zeitgeist-datahub:7185): WARNING **: zeitgeist-datahub.vala:227: Unable to get name org.gnome.zeitgeist.datahub on the bus![7193:7193:0506/003710:ERROR:nss_util.cc(853)] After loading Root Certs, loaded==false: NSS error code: -8018** (nautilus:6770): WARNING **: Error calling current_status: Method current_status with signature on interface com.ubuntuone.SyncDaemon.Status doesn't ex$** (nautilus:6770): CRITICAL **: syncdaemon_status_info_get_online: assertion `SYNCDAEMON_IS_STATUS_INFO (sinfo)' failedNo bp log location saved, using default.[000:000] Cpu: 6.37.2, x4, 2267Mhz, 3887MB[000:000] Computer model: Not available[000:003] Warning(clientchannel.cc:472): 0xb8304550: Unreadable or no port file. Could not initiate GoogleTalkPlugin connection[000:003] 0xb8304550: SendConnectStatus: Connect Status:[ f-connect, { error : -1, step : 0 }][000:004] Warning(clientchannel.cc:445): 0xb8304550: Could not initiate GoogleTalkPlugin connection[000:004] 0xb8304550: GoogleTalkPlugin not running. Starting new process...[000:004] Starting Flute[000:004] Warning(pluginutils.cc:268): Failed to get GoogleTalkPlugin path. Trying default.[000:006] Started GoogleTalkPlugin, path=/opt/google/talkplugin/GoogleTalkPlugin[000:006] 0xb8304550: SendConnectStatus: Connect Status:[ f-connect, { error : -1, step : 0 }][000:004] Warning(clientchannel.cc:445): 0xb8304550: Could not initiate GoogleTalkPlugin connection[000:004] 0xb8304550: GoogleTalkPlugin not running. Starting new process...[000:004] Starting Flute[000:004] Warning(pluginutils.cc:268): Failed to get GoogleTalkPlugin path. Trying default.[000:006] Started GoogleTalkPlugin, path=/opt/google/talkplugin/GoogleTalkPlugin[000:006] 0xb8304550: SendConnectStatus: Connect Status:[ f-connect, { step : 2 }][000:006] 0xb8304550: Waiting for GoogleTalkPlugin to start...[001:108] 0xb8304550: Attempting to connect to GoogleTalkPlugin...[001:108] Read port file, port=55429[001:108] 0xb8304550: SendConnectStatus: Connect Status:[ f-connect, { step : 0 }][001:109] 0xb8302d20: sending cookie Z2CZ//Bddv3VJWxk[001:109] 0xb8304550: SendConnectStatus: Connect Status:[ f-connect, { step : 1 }][001:110] 0xb8304550: Initiated connection to GoogleTalkPlugin[001:209] 0xb8304550: SendConnectStatus: Connect Status:[ f-connect, { step : 3 }][001:232] 0xb8304550: Socket connection established[001:232] 0xb8304550: ScheduleOnlineCheck: Online check in 5000ms[001:236] 0xb8304550: C->F: [comment,BC state change: 2 to 3. Error? 0][001:254] 0xb8304550: C->F: [comment,BC state change: 3 to 4. Error? 0][001:309] 0xb8302d20: Got cookie response, socket is authorized[001:309] 0xb8304550: AUTHORIZED; socket handshake complete[001:349] 0xb8304550: C->F: [mf,2,{appName:googlemail,buildLabel:gmail_fe_140429.00_p4,buildCl:65973900,compileMode:OPTIMIZED,LOCALE=tr,estima$[001:353] 0xb8304550: F->C: [fs,{pr:a}][001:417] 0xb8304550: F->C: [mf,mf5.3,5.3.1.0,2,{audioCodecs:[[103,ISAC,1,0,16000],[111,opus,2,64000,48000],[104,ISAC,1,0,32000],[109,CELT,1,6400$[001:435] 0xb8304550: C->F: [getdevicestate][001:441] 0xb8304550: F->C: [getdevicestate,15,0,[__default_device,Built-in Audio Analog Stereo],0,[__default_device,High Definition Audio Control$[001:589] 0xb8304550: C->F: [jec,[[96,H264-SVC,320,200,30]],{num_threads:-1,cpu_profile:1}][001:631] 0xb8304550: C->F: [jf,[[stun.l.google.com,19302],[alt3.stun.l.google.com,19302],[alt2.stun.l.google.com,19302],[alt4.stun.l.google.com,19302],[alt1.stun.l.google.com,19302]],[CAESGwoSamFja2FyYXpAZ21haWwuY29tEN+V0YDdKBoQzrz8rti0zAEr12uU4bzj5g\u003d\u003d,[relay.google.com,19305,19305,443]][001:634] 0xb8304550: C->F: [jec,[[96,H264-SVC,640,400,30]],{num_threads:-1,cpu_profile:31}][006:260] 0xb8304550: HandleOnlineCheck: Starting check[006:260] 0xb8304550: HandleOnlineCheck: OK; current state: 3As far as I am concerned X is the culprit. I would like to hear you feedback and suggestions for possible remedies. Thanks
Getting logged out of user account upon execution of a program
ubuntu;login;skype;32bit
null
_webapps.99190
I've filtered my Gmail inbox before in all possible ways, but only recently I've had a lively group conversation that got flooded by a single sender. I have tried different things only to find that filters are applied to entire conversation and not matched messages only.I want to keep all the messages for the record, but I really need to move that sender's posts out of the conversation in order to maintain readability, while keeping the conversation going.Is that possible in Gmail web at all?
How to exclude a sender from conversation in Gmail?
gmail
null
_cogsci.8331
If a person intentionally thinks quickly would this affect how much glucose the brain consumes? Or would it not be very significant?
Does the brain burn more calories when thinking quickly?
brain development
null
_vi.1873
I've noticed while editing along a line in a .txt file in insert mode the cursor will move to the start of the line following a write using key sequence:<esc>:wI'd like to change this behavior such that the cursor will stay in position following a :write. Is this possible? I don't need the cursor to remain in insert mode, I'd just like it to maintain its last position following a write.I am using gVim 7.4 on windows. My .vimrc is very basic, I don't believe any of my settings interfere with this behavior. I have also removed sourcing of mswin.vim and example.vim from my .vimrc (as bundled with the official vim.org windows installer).After reading the comments below I looked at the issue again and realized the cursor only slides to the far left after a write on lines which are entirely made up of trailing white space. In other words, the cursor only slides to the far left upon esc-:w when the line is a hanging indent with no other characters besides spaces. The .vimrc is handling indent behaviors with these settings: set tabstop=4set softtabstop=4set shiftwidth=4set expandtabset autoindent So, a new line created below an indented line will contain 4 trailing white spaces as the first 4 spaces of the line (which I want to keep). Upon the 'esc' key press the cursor slides to the far left of the buffer. Is there a way to retain cursor position upon hitting 'esc' to return to normal mode, on a line made up of trailing white spaces (as indentation)?
Why does the cursor move to the start of the line after ?
cursor movement;save
Looking at the documentation for autoindent has an answer as to why and how to work around it. :help 'autoindent':Copy indent from current line when starting a new line (typing <CR> in Insert mode or when using the o or O command). If you do not type anything on the new line except <BS> or CTRL-D and then type <Esc>, CTRL-O or <CR>, the indent is deleted again. Moving the cursor to another line has the same effect, unless the 'I' flag is included in 'cpoptions'.In other words, if you want it to not lose the indent, type something and then backspace it before hitting Esc, and the leading space will remain.Alternatively, if you just want to be back at the indent-level when you go back into insert mode and are using 'cindent' as well, use Shift-S instead of i, which will clear the (already empty) line, and start at the appropriate indentation level. This is not as general a solution as the one above, but I prefer this when I'm writing C code, so that my files don't actually get saved with white-space only lines.
_softwareengineering.329316
Suppose you have a very simple CRUD where you are just storing a simple tuple-like type of data, but its natural primary key is cumbersome for the user to remember (very long, difficult to write, etc.). Further, suppose I want to let users refer to the records using a handle such as an autoincremented integer value (which will then act as the primary key, but is surrogate, rather than natural).They create the records without specifying the handle, but, when they request a list of all records, I want to give them the records with the handle attached to them, so that they can later easily refer to them.If, in my application, the record is represented as a simple value object, (which is its own DTO), which is created and passed to the database gateway, and returned from the database gateway... how could I properly do the returning of the handle as well?I don't want to return a different object (something like a record decorated with the handle) when reading from the database,because I believe the handle is just a presentation detail demanded by the requirements of this specific user interface, and may be useless for different user interfaces. Sticking the handle to the existing record object makes no sense because it is not really part of the data type.One thing I could do is have the presentation separately ask for the handle of each record. That would mean two trips to the database but at least it would be clear that the handle is not part of the record.But I'm positive there must be a better way. Any ideas?For exampleA very simple book catalog. The data is Book, which is represented by tuples of the form (author, title, year). We suppose (author, title) is a natural primary key (in all rigor, this may not be the case but just take this as an assumption of the system). I only have an UI, which is a command-line interface to my system. Here, requiring the users to refer to books by providing the natural primary key (author, title) is cumbersome, hence I decide to link each record to a dumb autoincremented integer which would act as a surrogate primary key. That way, users of the command-line interface can refer to records by their associated integer handle. This link may be implemented as a sparate association table mapping natural PKs to surrogate PKs.The whole implementation of the system consists of a data type, which may be a tuple/struct/hash/custom plain old object, and a single CRUD repository where I can persist these objects, and read them by their natural primary key. I don't want to return an object which also has a 'handle' member containing its associated surrogate primary key because that data has nothing to do with the rest of the data and is there just as a requirement of the particular UI. So I'd propose having a method on the repository (or a different repository altogether) which gives me handles of records, providing the natural primary key. With this, this specific UI would use the repository (or those two repositories) to first retrieve the record and then retrieve the handle, in two steps.
How to avoid mixing surrogate key with the rest of the data
design;object oriented;architecture;sql;surrogate keys
null
_unix.155056
My OS is Scientific Linux 32 bit. I can only find plugins for 64bit. Is there a plugin for 32bit?
Bluejeans on 32bit Scientific Linux
scientific linux;plugin
null
_webmaster.14041
Is there a way to do previews for audio files in the base, Magento Community Edition? I see the place to put the sample files under Downloadable information section on my product. I attached an .MP3 as the sample, in this case, and it won't play. If alternatively, I try to download the file locally and then play it, instead of the 400K+ file, I just get a 4K file of garbled nothing, and it doesn't seem to work.
Previews for audio e-commerce site
magento;audio
The behavior you've described sounds as though it may be an issue with Magento (in which case you may want to inquire at the Magento user forum or file a bug report).Whether or not Magento supports native MP3 sample streaming, your site's users can play the sample MP3 files in the audio player of their choice (without an embedded Flash player or reliance on HTML5) if you create M3U files which point to the respective URLs of the uploaded samples.For example, if you have a sample file named test.mp3, you would want to upload that file to a location like http://example.com/samples/test.mp3 and create an M3U file which references that URL:#EXTM3U#EXTINF:-1,http://example.com/samples/test.mp3http://example.com/samples/test.mp3Users who download the M3U file will be prompted (if they have a compatible audio player installed) to open the M3U file and stream the http://example.com/samples/test.mp3 sample in their audio player.
_unix.385005
When I'm trying to update my Manjaro, I'm getting this. How can I fix it?
libglvnd causes an error when updating Manjaro
linux;manjaro;software updates
This is what helped me.sudo pacman -S mhwd mesa libglvnd lib32-mesa lib32-libglvnd --forcesudo pacman -Syu
_unix.9053
On Ubuntu 10.10, xdg-open fails to open the file and give me the error:No application is registered as handling this fileBut xdg-mime query defaut ... succeeds for the mime type. Why?Here is my process:Added a new mime type application/vnd.xx by xdg-mime install mytype.xml. Then xdg-mime query filetype <file name> shows that the new mime type is recognized.I wrote my desktop entry file my-app.desktop like this:[Desktop Entry]Name=xxxComment=xxxIcon=Exec=/usr/bin/my-app %UTerminal=falseType=ApplicationCategories=Utility;MimeType=application/vnd.xx;I copied this desktop file to ~/Desktop. After I re-login, I saw the shortcut on the desktop and xdg-mime query defualt application/vnd.xx printed out this desktop file. But, xdg-open <file name> fails with the error:No application is registered as handling this fileI've installed nautilus. Do I miss something? How do I fix this?
Why does xdg-open fail although xdg-mime query defaut succeeds on Ubuntu 10.10?
linux;ubuntu
I don't know off the top of my head if this is the cause of your problem, but in general application *.desktop files need to be in specific places to be fully recognized. Try moving your my-app.desktop to ~/.local/share/applications/my-app.desktop (create that directory first if needed: mkdir -p ~/.local/share/applications). If you used a full pathname to the *.desktop file, change it to just the basename; I don't think pathnames work as expected there.
_vi.11623
I use netrw :Lexplore as my file browser and I also use vim sessions. However, whenever I open a session file, :Lexplore is closed and I have to re-open.Is there a way to keep netrw :Lexplore open on session save / restore?
How could I preserve netrw :Lexplore in Vim sessions?
netrw;sessions
null
_unix.86201
When I log into Webmin, with the Ubuntu administrative user frank, I cannot see most of the administrative options:frank is shown as the Administration username in Webmin.I accidentally removed the frank user from the sudo group, last week.My VSP provider added the frank account back to the sudo group.# Allow members of group sudo to execute any command%sudo ALL=(ALL:ALL) ALLIt appears that Webmin is not recognizing that frank is back in the sudo group. How do I get Webmin to show all the administrative options for frank?
Webmin administrative panel options are missing
sudo;webmin
null
_unix.306474
I have an up-to-date version of the kernel in my install, 3.10.0-327.28.3, as installed by yum update.When I boot into rescue mode, and run uname -r, the version is very old, 3.10.0.10.something.Is there a way to install a newer rescue kernel? I notice with this rescue kernel version, I can't start networking, something about device errors. I'm assuming it is because this kernel is old compared to what it normally runs.CentOS 7.2
How to update the version of the kernel used in rescue mode?
centos;kernel;rescue
null
_softwareengineering.219584
I've written a special indexOf function for a list of unsorted unique values.I can search for one or multiple (unsorted) values, passed as array/list, and the function will return me an array/list of indices (possibly empty).Based on the following circumstances:I know that the values i'm searching for are in the listI don't care about the order in which the indices are returnedUniquenessI'm doing the following:Walk through the list (of size n)Compare the values with all values in the search-listIf there's a match break, add to results, break out of the loop and remove the found value from the search-list (so it's smaller on the next item)If there are no more values left to search for, break out of the list-traversal.I'd like to know how to analyse this algorithm, and specifically what the worst-case runtime is. (I guess if I'm searching for all values contained in the list.)Source in JavaScript:function multipleIndexOf(search, arr) { var searchArr = search.slice(0); var result = []; /* loop through array */ for (var i = 0, l = arr.length; i < l; i++) { /* loop through search values */ for (var i2 = 0, l2 = searchArr.length; i2 < l2; i2++) { /* if a search value matches... */ if (arr[i] == searchArr[i2]) { /* add to result */ result.push(i); /* remove from array */ searchArr.splice(i2, 1); /* continue search with next */ break; } } if (searchArr.length == 0) { break; } } return result;}
How to calculate the worst-case runtime of this search-algorithm
javascript;algorithms;search;algorithm analysis
You're going through each item in one collection for each item in another, that's O(N * M) where n and m are the sizes of each collection. The short circuiting doesn't affect the big O representation, as it is measuring the worst case, in which you never exit early. And even in the average case, the short circuiting cuts the time in half. O(N * M / 2) is equivalent to O(N * M).
_datascience.5565
Is it possible to learn the weights for a logistic regression classifier using EM (Expectation Maximization)algorithm? Is there any instance reference?
Using EM (Expectation Maximization) algorithm for Training Logistic Regression
machine learning;classification;statistics;logistic regression;expectation maximization
null
_unix.8975
First of all: I'm just a beginning Linux-User ;-)I've set up a server with OpenVZ support. I wrote a backup script that's dumping the vz containers from time to time. But some containers are not backed up due to insufficient disk space. So I ran df -h which gives me this:Filesystem Size Used Avail Use% Mounted on240f0d7c-195b-461b-87e3-0d0dfc33c3d4 5.0G 4.4G 362M 93% /tmpfs 2.0G 0 2.0G 0% /lib/init/rwudev 10M 660K 9.4M 7% /devtmpfs 2.0G 4.0K 2.0G 1% /dev/shm/dev/sda3 270G 32G 225G 13% /vz/dev/sda4 184G 188M 174G 1% /srvSo it seems the problem is the root partition (?) which has only 362M available. As /srv has 174G which is may too much I want to give some disk space from there to root. Can someone explain how I can do this and maybe explain it a little bit. I don't really know much about this mounting/partioning on Linux (yet).Thanks!
Need help with re-partitioning
linux;mount;disk usage
The simplest soulution is to create a backup of /srv. This is only 188MB it should fit in /srv.tar.tar cvf /srv.tar.bz2 --auto-compress /srvThen delete the sda4 partition and create 2 others. You can use cfdisk /dev/sda or any other partitioning software.sda4 extended partition (you can only have 4 otherwise)sda5 for /srvsda6 for the backupsCreate filesystems on sda5 and sda6 mount sda5 to /srv and restore the backup.mke2fs -j /dev/sda5 # For ext3 filesystemsmke2fs -j /dev/sda6 # use mkfs.<fsname> for any othermount /dev/sda5 /srvcd /srvtar xvf /srv.tar.bz2 --preserve-permissionsMount /sda6 to the directory where you want the backups stored. For example:mount /dev/sda6 /var/lib/backupsDon't forget to modify /etc/fstab. Add the new backups filesystem and change the device for /srv./dev/sda5 /srv ext3 defaults 0 0/dev/sda6 /var/lib/backups ext3 defaults 0 0In the future it would be a good idea to use LVM. That makes this sort of problems easier.
_codereview.64188
I need to write a factory of generic converters to produce converters from/to MongoDB objects to/from Java objects. Here is my implementation, it doesn't look good enough to me, so I would like to see your advice.public static <T> Converter<T> getConverter(final Class<T> clazz) { return new Converter<T>() { public DBObject convert(T t) { if (clazz == Manager.class) { BasicDBObject dbObject = new BasicDBObject(); dbObject.append(age, ((Manager) t).getAge()); dbObject.append(id, ((Manager) t).getId()); return dbObject; } throw new IllegalArgumentException(Unsuported Object Type + clazz); } public T convert(DBObject o) { if (clazz == Manager.class) { int age= Integer.valueOf((String) o.get(age)); int id= Integer.valueOf((String) o.get(id)); Manager t = new Manager(id, age); return (T) t; } throw new IllegalArgumentException(Unsuported Object Type + clazz); } };}
Best way to write generic factory in Java
java;generics;factory method
When you see yourself going and editing the same function again and again to extend its functionality then thats a code smell. The problem is that whenever you add a type you have to add an if condition to your converter. So the conversion could be the class responsibility. in Java 8 you can use Suppliers for that and if you don't have Java 8 then Guava is your friend Supplier<DBObject> convertToDBObject(){ // java 8 code Supplier<DBObject> supplier = ()-> { BasicDBObject dbObject = new BasicDBObject(); dbObject.append(age, this.getAge()); dbObject.append(id, this.getId()); return dbObject; } return supplier; }Or implement Guava suppliers anonymously if you running java 6 or 7.You can add an interface for convertable things that your classes can implement.interface DBObjectConvertable{ Supplier<DBObject> convertToDBObject();}and by doing so your types will be responsible for converting to DBObject in their own ways. The code smell in your code is adding ifs to the factory.Suppliers are factories but in a declarative way, so instead of returning converted object immediately, I will return you a function that knows how to convert to MongoDB objects.
_webmaster.17649
I am trying to create a filter for all of my Analytics websites. I am wondering if it is currently possible to do this. Basically one filter to rule them all!thanks!
Global Analytics Filter for all accounts
google;analytics
For the sake of clarity, the word profile refers to a specific tracking ID (example: UA-123456-1) and account refers to a set of tracking ID's (example: UA-123456-1 through UA-123456-n).The Filter Manager allows you to apply a filter to an entire account (and all related profiles), however, if you have access to multiple accounts and you want to automate filter creation, you will need to wait* until Google provides access to create filters through the Management API.(* Related discussion thread: Filters?)
_unix.128213
Linux uses a virtual memory system where all of the addresses are virtual addresses and not physical addresses. These virtual addresses are converted into physical addresses by the processor. To make this translation easier, virtual and physical memory are divided into pages. Each of these pages is given a unique number; the page frame number. Some page sizes can be 2 KB, 4 KB, etc. But how is this page size number determined? Is it influenced by the size of the architecture? For example, a 32-bit bus will have 4 GB address space.
how is page size determined in virtual address space?
linux;kernel;memory;hardware
You can find out a system's default page size by querying its configuration via the getconf command:$ getconf PAGE_SIZE4096or $ getconf PAGESIZE4096NOTE: The above units are typically in bytes, so the 4096 equates to 4096 bytes or 4kB.This is hardwired in the Linux kernel's source here:Example$ more /usr/src/kernels/3.13.9-100.fc19.x86_64/include/asm-generic/page.h....../* PAGE_SHIFT determines the page size */#define PAGE_SHIFT 12#ifdef __ASSEMBLY__#define PAGE_SIZE (1 << PAGE_SHIFT)#else#define PAGE_SIZE (1UL << PAGE_SHIFT)#endif#define PAGE_MASK (~(PAGE_SIZE-1))How does shifting give you 4096?When you shift bits, you're performing a binary multiplication by 2. So in effect a shifting of bits to the left (1 << PAGE_SHIFT) is doing the multiplication of 2^12 = 4096.$ echo 2^12 | bc4096
_unix.28454
I have written a bash script for use on my ubuntu box. Now I would like to prevent running this script under my own user and only able to run it as root (sudo).Is there a possibility to force this. Can I somehow let my script ask for root permissions if I run it under my own username?
How do I force the user to become root
bash;permissions
I have a standard function I use in bash for this very purpose:# Check if we're root and re-execute if we're not.rootcheck () { if [ $(id -u) != 0 ] then sudo $0 $@ # Modified as suggested below. exit $? fi}There's probably more elegant ways (I wrote this AGES ago!), but this works fine for me.
_cs.28388
PreambleI can't understand what are the advantages and disadvantages of microcoded processor architecture and hardcoded one.Basically what I understood is that a microcode architecture divides an istruction in more microinstructions. I didn't found much documentation written in a simple way (too much complicated) so I'm asking you: what are the advantages and disadvantages of each one?Due to the large amount of aspect of this subject, I'll recap the question into three main aspects:Question (architectural point of view)A microcoded architecture should semplify the design of each instruction, it means that it's do much more difficoult to design a full hard coded processor?Or maybe hardcoded archtecture is suitable for microcontrollers or smaller design?Question (performance point of view)Wikipedia (not the most reliable source, I know) says that a microcoded architecture is a little slower than an hardcoded one. It also says that microinstruction are used to build complex instruction, but these are not commonly used because programmers prefer high level languages, and compilers prefer using simpler but faster instruction.From this point of view, is still necessary to design microcoded processor?Question (functional point of view)If microcoded archtectures help the creation of complex instruction (= easier assembly development?), hardcoded ones help programmers in any way during their work? This seems a stupid question but I think it's not.Looking at this site of assembly game programmers (I hope I can post that link, FAQ says to share your research), one guy says that HuC6280 processor has the best instruction set because:Fav[ourite]: HuC6280. Basically a 65CS02 set (Rockwell's added instructions). Optimizing is soo much fun. There are some super crazy optimizations for this style chip out there. I know people will fight to the death (or possibly argue) that it's not RISC, but it definitely had some precusor ideas of RISC. A very small, simple, but fast instruction set (hard coded, not microcoded), a large set of 128 16bit address registers (also halved as 256 8bit data registers). The immediate operand instructions are very fast and lend themselves perfectly for self modifying code. The downside is the small logical address range of the PC. All optimizations have to be made local and very specific. Look up tables (LUTs) need to be organized accordingly (and interleaved for 16bit and wider data elements). One thing I never understood is why they never implemented immediate operand opcodes as 1 cycle instead of 2, since the chip would perform a fetch cycle while operating an ALU operation on other opcodes. Same for implied instructions (flag changing).He seems to be very excited about that architecture. One point to hardcoded design?However, I found that HuC6280 is an 8bit processor, it is much much simplier than modern ones. It means that hardcoded would be preferrable if its design wasn't so hard? EDIT: He also quote self modifying code, which is not commonly used today (due to high level programming maybe) but for assembly programmer is quite an important feature. ExamplesI know that this is an hard question, explanation might be long. If you (guy with much more experience than me) want to answer, may you add some example of hardcoded architecture? It would be much appreciated. Both modern and deprecated are okAnd thanks for reading all this poem
Advantages and disadvantages of microcoded vs hardcoded architectures
computer architecture
The distinction between microcoded and hardcoded multi-cycle control units is a relatively small implementation detail. The distinction was more important in the 1950s when people were inventing new implementation techniques for state machines. In modern processor design there are much more important implementation distinctions, like how much pipelining and instruction overlap you are going to try to achieve, whether you are going to speculatively execute instructions, and whether you are going to try to schedule instructions out-of-order.That said, here's the distinction: We divide the design into datapath and control. Here's the picture of the MIC-1 from Tanenbaum's Computer Organization book. (The image is by Suyog.karnawat, from Wikimedia commons.) Everything in the design is the datapath except the box in the upper right hand side that says Instruction decoder and control logic.The Insruction decoder and control logic box is a finite state machine. The datapath in this example is very simple, with only a single bus, so even an instruction to add two registers and put the result in a third register takes multiple cycles (each of which corresponds to a state in the state machine.)Each instruction goes through the following steps/states (each of which takes a cycle)move the PC (Program Counter) to the MAR (Memory Address Register)assert the controls to perform a load from the memory buseventually the memory will return the requested data (which corresponds to the next instruction) and put it in the MDR (Memory Data Register)move the instruction from the MDR to the IR (Instruction Register). At this point the instruction gets decoded and we figure out what to do with it. In this case it's an add operation so we know we need to:move Ra to the X registerput Rb on the bus (so that it will go to the B input of the ALU) assert the ALU control lines and Mux select appropriately to do an add operation, the result of which will get saved in register YMove Y to the Rc register, and then every non-branch instruction ends by incrementing the program counter:Put the PC on the bus, set up the ALU to increment (Select the MUX to put constant 1 on the A input and set up the ALU to Add) so that PC+1 will get saved in the Y registerMove the Y register back to PCSo 9 state transitions to perform a simple add instruction.So the Instruction decoder and control logic is a finite state machine with inputs from the IR register, outputs are the control signals, and there must be some flip-flops inside to represent the state of the state machine. But there are lots and lots of ways to implement a state machine.$\lceil \log_2 N \rceil$ flip-flops (where $N$ is the number of states) and a lot of combinational logic (to calculate the control signals and next state).$N$ flip-flops with one-hot encoding and a bunch of combinational logic (usually less than with option A, but a lot.)Somewhere between $\lceil \log_2 N \rceil$ and $N$ flip-flops with some combinational logic of intermediate complexity.And the combinational logic for the control signals and next state functions can be implemented any number of ways:As NAND gates reduced (using Quine-McCluskey, or whatever) to sum-of-products form.As NAND gates reduced to some relatively efficient multiple-level circuit. (This is probably what people think they mean when they talk about hardwired control.)A design using Multiplexers for the combinational logicA design using Programmable logic arrays (although I don't know if you can even buy these anymore.)A design where the combinational logic is implemented with a ROM. (This is probably what people think they mean when they talk about microcoded control.) The ROM might be a EEPROM so that it is somewhat easier to modify if you find a bug.ROMs can get really huge if you're not careful. For example a ROM-based design would almost always use $\lceil \log_2 N \rceil$ flip-flops, because making the state wider also makes it sparser, which is sometimes good for gates but not for ROMs. Also, you would only use the opcode bits as part of the address to the ROM, not the register specifiers and such.Finally with ROMs you might choose to make the microcode word wide (the microcode word produces the entire set of bits for the control signals) or narrow (the microcode word chooses one of a smaller number of possible control signal combinations and then there's a second ROM that translates from that smaller number to the actual required control signals.So the distinction between hardcoded and microcoded is only one very small decision that needs to be made among hundreds of design decisions. And it's certainly not the most important one. (For example, you could choose to put a second bus on the datapath, which would enable you to perform some instructions with a lot less cycles.)
_softwareengineering.161711
I am a Jr. ASP.NET/C# Developer and I have been working with a Company for the past 9 months. I have been appointed to try and develop their Legacy System (built in Visual FoxPro) in ASP.NET/C#.I am the only developer working on this project and it's a bit overwhelming, but I complete the tasks assigned to me within a reasonable time frame using Google, SO and other forums as references.My senior developer is a FoxPro developer and has very little knowledge of .NET. I do not get any sort of help from my Senior developer. I am working completely on my own.By working as a solo developer I have learnt quite a few things and feel like I am moving forward. However as I am working alone I feel that there are so many things that I might have missed out on having not worked in a team.I feel I need someone who can just guide me on do's and the don'ts. I feel the need to have a mentor who can help me with the many questions that I cannot ask on SO or earch on Google.Questions:Is it normal to feel this way or I am just not doing enough?How important is mentoring for a junior developer?How important is it for a Jr. Developer to work in a team?
Is it must for a junior Programmer to have a mentor?
junior programmer;mentor
null
_unix.302368
My team shares a user account via a non-user shell on a few systems for reasons beyond our control. We all move our passphrase protected private keys to the share'd users ~/.ssh directory. We normally login and open an ssh-agent session then ssh-add our passphrase protected keys like below. None of us like this workflow and we're trying to make it easier.Is there a way we can automatically be prompted for our passphrase when we open the shared user's shell?sudo -u shared /bin/bash# new shell openseval `ssh-agent -s`ssh-add ~/.ssh/my_username_rsa# enter passphrase and continue...
Automatically login to an ssh-agent session in a non-user shell
shell;ssh agent
null
_cs.12664
I have a a few fundamental doubts in recursive enumerability and countability and below, I have written what I understand them to be with proofs. But there are contradictions at the end. What is wrong with the statements/proofs i have made?Countability (C=Countable): A set $X$ is C when a bijection exists between the set of natural numbers and the set $X$Recursive Enumerability (RE= Recursively Enumerable): Say set $S'$ is a subset of another set $S$. When there exists a turing machine with alphabet $A$ (where $S$ is a subset of $A^*$) which halts if the input to it belongs to the set $S'$ and does not halt if the input belongs to $S-S'$ then I say that the set $S'$ is recursively enumerable (given the fact that inputs comes only from the set $S$ and not from $A^*-S$ hence the latter will not concern us.) I have referred to the book Elements of the theory of Computation by Papadimitrou for this definition, though the introduction of an alphabet A is my own addition to make things more firmNow I will prove 2 statements:if a set $X$ is RE then it is Cif a set $X$ is C then it is REHence proving 3. RE iff C I will prove 2 first.I can write a Turing Machine $M$ which when asked to check if an element $x$ belongs to $X$ or not will follow the algorithm:There exists a mapping from the set of natural numbers to $X$ call it $f$. $M$ can search for $x$ (like a linear search algorithm running on $X$) starting from $f(1)$ going to $f(2)$... and it keeps going till it finds $x$. By this method, $M$ terminates iff $x$ belongs to $X$.The behaviour above proves that $X$ is RENow I prove 1- Given a Turing Machine $M$ exists which halts iff $x$ belongs to $X$I can construct a bijective map from the set of naturals to $X$ as follows: To map $x$ (given it belongs to $X$) , we run it as input against $M$. I take the concatenation of all configurations (Configuration=tape head position+tape content+state) of $M$ which it goes through from the starting of a computation to the end and decode that string as a natural number. It will be unique.Hence 1. is proven and so is 3.But then I find certain resources on the internet which tell me that enumerability and recursive enumerability are different things. How is it possible? Furthermore- We know that the power set of a countably infinite set is uncountably infinite. If $X$ was countably infinite, it would be RE (see 2.). Now we know that the subset of a set which is C is also C. Hence all subsets of $X$ would be C hence they would be RE. Now there would be an uncountable number of RE sets. Now for each RE set, we can write a turing machine (with appropriate halting behaviour) which can be encoded as a natural number implying that the set of all RE sets must be C. This contradicts the conclusion of the previous paragraph.Where exactly am I wrong?Thankyou in advance!
Where am I wrong?: countability and recursive enumerability
computability;turing machines;uncountability
Your algorithm for recursively enumerating any given set doesn't work since the bijection between a countable set $X$ and the natural numbers can be arbitrarily complicated. For example, consider the following set $X$:$$ X = \{ P : \text{the program coded by $P$ doesn't halt on the empty string as input} \}. $$The set $X$ is countable: there are only countably many programs. However, there is no computable bijection between $X$ and the natural numbers, since otherwise RE=coRE (as your argument shows; $X$ is coRE-complete).Here is a more tangible example of a countable set for which there is no computable bijection:$$ Y = \{ 2P : \text{program $P$ halts on the empty string} \} \cup \{ 2P+1 : \text{program $P$ doesn't halt on the empty string} \}. $$If there was a computable bijection between $Y$ and the natural numbers, then you could solve the halting problem (how?).
_unix.211733
Does anyone know if it is possible to restrict execution of commands via dot slash notation for a directory?The environment is bash on Linux.For example, I have a directory /usr/local/app/bin. In /usr/local/app/bin is a command called foo. For some users I am creating an alias during login for foo that redirects foo elsewhere.I don't want those users to be able to run foo directly by cd'ing to /usr/local/app/bin and running:$ ./fooThese users need to be able to run other commands in /usr/local/app/bin but it doesn't matter if they are prevented from running these other commands via ./.In the end, my goal is to restrict certain users from executing foo interactively when logging on interactively.For example (roughly), in .bashrc:if [ -z $PS1 ]; then:elsealias foo=echo access denied!fiThis works except users can run foo directly using ./ from /usr/local/app/binThe file needs to be executable, but only when the full path is used. I'm hoping someone knows a clever way to accomplish this
How prevent users from running commands via dot slash for a directory?
linux;bash;command
null
_webapps.19634
When I play some Youtube videos the thinking wheel remains in the centre of the video still thinking even though the video is loaded and playing properly. In some videos everything is normal. What is causing this? I did update Flash yesterday.Win 7 64-bit.
Thinking icon remains turning on Youtube video after the video is playing. What's the fix?
youtube
null
_codereview.155697
I have wrote a PHP template code to replace placeholders based on the value provided within the placeholder. For example the content may have placeholders like {ITEM-100} {ITEM-110} and I want to replace them with a text made by the details fetched from db with item_id=100 or item_id=110. The code below id working fine, and I would like to get suggestions to improve the performance of the code. Thanks in advance.$content = 'Here is the item list {ITEM-100} {ITEM-110} {ITEM-200}'; if(preg_match_all('/{ITEM-.*?}/', $content, $matches)){ foreach($matches[0] as $v) { $value = trim($v, '{}'); $val_chunk = explode('-', $value); if(isset($val_chunk[1])){ $item_card = get_item_card($val_chunk[1]); $content = str_replace($v, $item_card, $content); } } }echo $content;
Replace template based on placeholder values
php;parsing
The best way to improve the performance of this code is probably by using the preg_replace_callback()-function. This function allows you to search for a regex in a string, and call a function for every match. This function then returns the replacement. This avoids running multiple str_replace() operations over the string, which can be costly for large strings.Secondly, we can use a capture group in the regex to avoid the use of explode(). I.e. by changing the regex from /{ITEM-.*?}/ to /{ITEM-(.*?)}/ we can ensure that we get the matched item identifier directly.Applying those two modifications, we would end up with something like:$content = 'Here is the item list {ITEM-100} {ITEM-110} {ITEM-200}'; function get_replacement($matches) { $value = $matches[1]; // Index 1 is the first capture group, which contains our item number. return get_item_card($value);}$content = preg_replace_callback('/{ITEM-(.*?)}/', 'get_replacement', $content);echo $content;
_softwareengineering.301034
To keep it simpler for any client of my class, I have put a sequence of private method calls within one public method.The client then calls this method and all the methods within run to complete the action. E.g: public void DoRejection(string comments, string rejectionType) { GetPartstoReject(); UpdateRejectedPartsStatus(rejectionType); RemoveInitiatingRejectionPart(); ClearRejectedPartsData(); CreateNewOpenPart(); SaveRejectionComments(rejectionType, comments); }The downside I can see to this is it is harder to unit test as each private method won't be tested in isolation (following the best practice of only unit testing public methods).How can this be better designed to enhance testability but still make it simple for a client to call?
How to structure a chain of method calls
c#;unit testing
null
_unix.381886
I have a bunch of Windows programs on my Gallium OS installation (an Xubuntu-based linux distribution designed for Chromebooks) running on PlayOnLinux. When I have an internet connection the programs launch like normal. When I don't have internet connection the programs don't launch at all! Why this happens?Log of foobar2000 : https://pastebin.com/3U0HcpJS
Can't launch apps without internet connection - PlayOnLinux
playonlinux
null
_codereview.112109
I have written a wrapper for Java's Iterator class using Java 7, which is designed to only iterate items that match a certain filter.When the filter is null, all items should be iterated.Filter.javapublic interface Filter<T> { boolean apply(T type);}FilteredIterator.javaimport java.util.Iterator;public class FilteredIterator<E> implements Iterator<E> { private Iterator<E> iterator; private Filter<E> filter; private E iteratorNext; private boolean iteratorHasNext; public FilteredIterator(Iterator<E> iterator, Filter<E> filter) { this.iterator = iterator; this.filter = filter; findNextValid(); } private void findNextValid() { iteratorHasNext = iterator.hasNext(); while (iterator.hasNext()) { iteratorNext = iterator.next(); if (filter == null || filter.apply(iteratorNext)) { iteratorHasNext = true; break; } } } @Override public boolean hasNext() { return iteratorHasNext; } @Override public E next() { E nextValue = iteratorNext; findNextValid(); return nextValue; } @Override public void remove() { iterator.remove(); }}Is there anything I can improve on here? I'm not all that fond of findNextValid's implementation but I don't know what I can do to improve it.
Filtered Iterator
java;iterator;iteration
CorrectnessYou can't support remove() because your iterator must always be at least one step behind the iterator being wrapped. DesignYou twist the code to make a null filter equal to a filter that accepts everything. Don't do that. Write a filter that accepts everything and use that instead.Your class should be final. It's not designed to be extended.You really need to document the Filter#apply(). That's not an intuitive method name. I'd rather see something like #accept(). When I apply a filter, I expect to pass in a collection and get back a filtered collection. You're asking the filter if a specific element is acceptable. That naming would also be more consistent with the JDK classes named XXXFilter, which use the accept name.EDIT: I'm not a big fan of using null to indicate a default behavior. If they don't have to specify a filter, give them another constructor that doesn't ask for one. It can chain to the two-arg filter with a new Accept All filter. If they call a constructor asking for a filter and don't give one, I'd throw an NPE back at them.EDIT: You can/should also move the Accept All filter to its own top-level class and make it public. You need it anyway .. may as well let clients specify it directly. ImplementationYou don't need iteratorHasNext at all. Just keep the next value. If there is none, set it to null. Your hasNext() implementation can check for null and return correctly.With all these changes, your code might look more like:public final class FilteredIterator<E> implements Iterator<E> { private final Iterator<E> iterator; private final Filter<E> filter; private boolean hasNext = true; private E next; public FilteredIterator(final Iterator<E> iterator, final Filter<E> filter) { this.iterator = iterator; Objects.requireNonNull(iterator); if (filter == null) { this.filter = new AcceptAllFilter<E>(); } else { this.filter = filter; } this.findNext(); } @Override public boolean hasNext() { return this.next != null; } @Override public E next() { E returnValue = this.next; this.findNext(); return returnValue; } @Override public void remove() { throw new UnsupportedOperationException(); } private void findNext() { while (this.iterator.hasNext()) { this.next = iterator.next(); if (this.filter.accept(this.next)) { return; } } this.next = null; this.hasNext = false; } private static final class AcceptAllFilter<T> implements Filter<T> { public boolean accept(final T type) { return true; } }}
_codereview.173469
I attempted this sample question from the Australia Infomatics Competition. TL;DR - Each line of input contains two numbers, representing a pair of knights that will fight and thus cannot be invited to the same meeting. The output needs to be the number representing maximum number of knights that could be invited to a meeting. Exact Words:InputYour program should read from the file arthin.txt.The first line of input will contain N, the number of knights. The second line of input will contain P, the number of pairs of duel-prone knights.Each of the following P lines will contain two space-separated integers a and b, representing two knights who cannot be invited to the same meeting. It is guaranteed that a b and that the same pair will not appear twice in the input. Knights are labelled from 1 to N.OutputYour program should write to the file arthout.txt. It should output a single integer: the maximum number of knights that can be invited to the first meeting without any chance of a duel occurring at either the first or second meeting. Here is my current code (in python 2.6.6 as per the comp's requirements):list_id = {}with open(arthin.txt,r) as Input: for i,line in enumerate(Input): if i > 2: a,b = [int(each) for each in line.split()] #if list_id[a] != None and list_id[b] != None: if list_id[a] == True: list_id[b] = False elif list_id[a] == False: list_id[b] = True elif list_id[b] == True: list_id[a] = False elif list_id[b] == False: list_id[a] = True else: list_id[a] = True list_id[b] = False elif i == 2: a,b = sorted([int(each) for each in line.split()]) list_id[a] = True list_id[b] = False elif i == 0: Knight_no = int(line) #list_id #True = 1st meeting, false = second meeting for x in xrange(1,Knight_no+1): list_id[x] = Nonefirst_meeting = set(k for k,v in list_id.items() if v == True)second_meeting = set(k for k,v in list_id.items() if v == False)pascifist_knights = set(k for k,v in list_id.items() if v == None)longest_set = max(len(first_meeting),len(second_meeting))if len(first_meeting) == longest_set: first_meeting = first_meeting.union(pascifist_knights) fileOutput = open(arthout.txt, w) fileOutput.write(str(len(first_meeting))) fileOutput.close()else: second_meeting = second_meeting.union(pascifist_knights) #print second_meeting fileOutput = open(arthout.txt, w) fileOutput.write(str(len(second_meeting))) fileOutput.close()The code seems to be mostly broken - it works for the sample input and some cases I made up, but I think that there are still many flaws in the method. I would be really appreciative if someone could point me in the right direction to get more cases right.
AIO Programming Challenge 2012- King Arthur II - How many non-conflicting people can we fit?
programming challenge
null
_cs.16586
For the following function (not in particular coding style or programming languange)f (N, y) // y is an integer such that 0 <= y < N{ x = rand (N) // rand (N) returns a random integer x satisfying 0 <= x < N if (y == rand (N)) return else f (N, y)}I need to find best, worst and average cases using O-notation. So my assumption is that the linex = rand (N)does nothing particular but in each recursion it takes O(1) (correct me if my assumption is wrong).Now, the best case is quite obvious - rand() will give y or O(1).The thing that I have stuck in are the worst and average cases. In the worst case it will just go into infinite iteration, but what is the complexity for a function that does not halt? And what is the average case? My assumption about the average case is that it will go through all N integers and then find y.
Best, worst and average cases for a function that uses random number generator
algorithm analysis
null
_unix.333351
I have a PowerWalker VI 850 LCD ups connected to a Raspberry Pi Model B+ via USB. I have been trying to use NUT to monitor it, with lots of problems. First, it seems that the protocol detection wasn't working right, and I've since specified protocol = mustek and that seems to have partially stabilized it--now every time I start the nut-driver service it actually connects.However, another quirk is that for some reason the USB device keeps changing (e.g. from /dev/bus/usb/001/005 at boot to 006 or 007) without warning or apparent cause. I tried to work around this by adding a SYMLINK parameter to my udev rule:ACTION==add, \SUBSYSTEM==usb, \ATTR{idVendor}==0665, ATTR{idProduct}==5161, \SYMLINK+=powerwalkerups \MODE=0660, GROUP=nutWhich makes sure /dev/powerwalkerups always points to the right bus device. But--it seems, at least--whenever the USB device magically changes, the nut-driver loses it connection and I get the wonderful data stale message. Just, now whenever I restart it, it will actually connect up properly with a good protocol and works. But I have to manually systemctl restart nut-driver.Is there an automatic way to make NUT try restarting the driver if the data goes stale? Or can someone recommend a watchdog type process that will do this for me? Since the service doesn't actually stop, systemd doesn't see the service as failed. How can I try to restart the service at least once to see if that resolves connectivity?(Or, any idea how to stop it from disconnecting in the first place?)UPDATEUptime on my NUT host is now 5 days and the USB device has wiggled all the way up from 005 to 012. So, I'm running Icinga2 on another host, and I'm going to look into making it restart the service...but that requires SSH access from the Icinga host to the NUT host :-P. Better ideas?
Restart nut-driver when data stale, usb device keeps changing
usb;raspberry pi;ups;nut
Figured something out... since my problem was connected to the USB device changing, and I already had a udev rule above, I added a RUN statement to it like so:ACTION==add, \ SUBSYSTEM==usb, \ ATTR{idVendor}==0665, ATTR{idProduct}==5161, \ SYMLINK+=powerwalkerups, \ MODE=0660, GROUP=nut, \ RUN+=/bin/systemctl restart nut-driverThis restarts nut-driver not when the data goes stale but when the USB device gets reconnected (or whatever you call what it's doing). This seems to have solved the problem.
_codereview.36935
Question: Is having a master class bad practice? I am making a simple pong game, but I'm writing the code as if I were making for something that might be for something more complicated I want to create in the future. Also, am I not doing it in a good manner? What I am doing: I have a class, in this case engine, which basically holds everything and runs all of its referenced objects logic inside of its own functions. All of the other objects are then linked to each other by holding the data of the world or engine object and use it as a linker to other objects that it can interact with. NOTE: The sfml media library was used with this project.note: if you need the ball definitions i'll post them#include <SFML/Graphics.hpp>#include <vector>#include <iostream>#include <stdlib.h>class paddle;class ball;class enemy;class player;class engine{ ball *gameBall; enemy *enemyPaddle; player *playerPaddle; Clock gameClock; RenderWindow &refWindow; int gameSpeed; Event windowEvent; void eventDraw(); void eventUpdate(); void handleWindow();public: engine( RenderWindow &rendy); ~engine(); bool start(); Vector2f getWindowSize(); void drawPart(Drawable &art); Time getGameClock(){ return gameClock.getElapsedTime(); }};class ball{private: CircleShape myShape; engine& world; int radius; Color color; Vector2f position, velocity; short signed int dirX, dirY; short signed int getDirection(); void wallBounce();public: ball( engine& gameEngine); void draw(); CircleShape getCircle(){ return myShape; } void pop(); void update();};int main(){ RenderWindow window(VideoMode(640, 480), Pong); engine gameEngine( window ); return (int)gameEngine.start();}// Class Prototyes // Engine engine::engine(RenderWindow &rendy):refWindow(rendy){ gameBall = new ball(*this); enemyPaddle = new enemy; playerPaddle = new player; gameClock = Clock(); gameSpeed = (1000/60.0); windowEvent = Event(); } engine::~engine(){ delete enemyPaddle; delete playerPaddle; delete gameBall; } void engine::handleWindow(){ if ( refWindow.pollEvent( windowEvent ) ) { if ( windowEvent.type == Event::Closed ) refWindow.close(); } } bool engine::start() { while( refWindow.isOpen() ) { while( gameClock.getElapsedTime().asMilliseconds() > gameSpeed ) { eventUpdate(); eventDraw(); // Restart Clock gameClock.restart(); } handleWindow(); } return true; } void engine::eventUpdate(){ gameBall->update(); } void engine::eventDraw(){ refWindow.clear( Color::Black ); gameBall->draw(); refWindow.display(); } Vector2f engine::getWindowSize(){ Vector2f tempVec; tempVec.x = refWindow.getSize().x; tempVec.y = refWindow.getSize().y; return tempVec; } void engine::drawPart(Drawable &art){ refWindow.draw( art ); }
Master engine class for a Pong game
c++;object oriented;game;sfml
A master class is a very close relative to a singleton or a global. It can easily be a design which violates the Dependency Injection principle, and leaves you with non-modular code. In this case your engine is also violating the Single Responsibility principle, as it's doing a lot of unrelated tasks: it's handling windows, providing the game's main driver, moving the ball, drawing the screen, and hosting all kinds of different data.Try this task: write a unit test that exercises just the engine::handleWindow() routine without needing to create a real ball, enemy, or player. It's hard, because your constructor builds all of those objects.You've already got a start. For example, you can easily write a unit test that tests engine::eventDraw without creating a real RenderWindow, because you can pass a mock RenderWindow on the engine constructor. You're using dependency injection.As you're going to have a singleton in main (and every program does at some level), I recommend you try to keep that singleton as thin as possible.It's not that your existing code isn't going to work, but it's going to be a problem to maintain, especially as you extend it to add functionality. Where does scorekeeping come in? Player preferences? High score table? Head-to-head play with two people? The more you want to add to this, the more you're going to need to change engine, and the less confident you're going to be that you aren't breaking something else.
_unix.145099
The situationI would like to use Wireshark to analyze traffic on one of our servers, but I don't want to install Wireshark on the server itself. I understand that I can pipe tcpdump traffic via SSH to my local machine (Ubuntu) which has Wireshark installed. The problemI cannot login to the server with a root account because that is disabled. I have sudo rights, but when logged in to the server the command sudo tcpdump does not work. The command below (with or without sudo) won't work:$ ssh [email protected] sudo tcpdump -s 0 -U -n -w - -i eth0 not port 22 > /tmp/remoteThe questionIs there a way to get this working? If so - how?
Piping tcpdump traffic via SSH - but no root ssh access
ssh;centos;sudo;tcpdump
You can run this command via sudo on the server to capture the data first, and then send the resulting file back to your workstation to review the data sudo tcpdump -i eth0 -s 65535 -w /tmp/wireshark
_unix.4718
I need to manage a growing set of similar-but-different ASCII files. ( It so happens that they're Apache VirtualHosts, but that's not particularly relevant. ) For each production website, the developers might want as many as four variant configs for a variety of reasons.Would you please recommend your favorite templating system? I know of a few, M4 and Template::Toolkit come to mind. My most important feature isn't power, it's intuitive operation and elegant simplicity.
Simple Templating for Config Files
administration
I'm a big fan of using make and m4. I set up Nagios configuration files with extensive use of make and m4; Nagios is full of repetitive blocks that can be simplified through the use of m4.The nice thing about make and m4 is that they are usually part of the base install or at least the base package repository on Linux and UNIX systems; with something like Template::Toolkit you'd have to install it. Perl is also heavier than m4 and make.You can also, if you like, set up a semi-automated m4 run by putting this at the top of your m4 file (assuming the file is file.m4 for instance):#!/usr/bin/m4 > file.confIf you don't want to rewrite file.conf, then remove the redirection from the command:#!/usr/bin/m4You'd have to make the file.m4 file executable then as well:chmod +x file.m4
_unix.257907
I unpacked the .tar.gz file. I installed the gcc compiler. I ran the ./configure command with various flags and options. I ran make check and found an error. The exit status is 2. Only 0 is without errors. In the output I see this:/bin/ld: cannot find -lcap collect2: error: ld returned 1 exit status make[6]: *** [test-crypto] Error 1The ld utility is installed. I don't know what -lcap is. I found one website that seemed to have lcap packages. But the links were broken for Centos version 7. If you post a place where I can download lcap (which is not installed on my CentOS 7 server), please confirm the link isn't broken.How do I fix this error so I can use the make install command to get NTP installed?
How do I install NTP from source on CentOS v7? (/bin/ld: cannot find -lcap)
centos;compiling;make;configure;ntp
I don't know what -lcap isThe -l flag to the GCC C compiler tells it to link in a library, in this case called cap, which is an abbreviated version of the library name.The full name is libcap.so.2.22 on CentOS 7, with the alias libcap.so.2. Chasing such details down is not your problem; leave it to the linker. What does matter here is that you're missing the development package, which installs libcap.so, without the version number, which is what GCC's linker is looking for. It also installs a bunch more files which may also be necessary. So:$ sudo yum install libcap-develThat is a common pattern: to build programs using libfoo, you typically need to install libfoo-devel first.
_webmaster.53708
I have a website which is accessible via several hostnames.I would like to put something in an .htaccess file that would simply block any request requesting a particular hostname.For example, say example1.com and hello.somehost.com both point to the same website. I would like to put something in the .htaccess file that will allow users to view the website if they visit example1.com, but will not allow users to view it if they visit hello.somehost.com.You'd think this would be easy to Google but if there are any results out there, they're drowned out by people who want to block access if the user is coming from a particular hostname...
prevent access via .htaccess *TO* a given hostname
htaccess
null
_unix.333307
I recently got a Lenovo Yoga 2 13 inch. It came with windows 8.1 which works great. I decided to install Linux(Fedora 25) and so far(with the exception of wi-fi) works great. However, when trying to use the tablet mode, which disables the keyboard, I can't get the onscreen keyboard to show up in Chrome(running newest chrome 55). Does anyone know any way to force the keyboard to show in chrome? The problem happens in both Wayland and Xorg sessions.
Onscreen keyboard in chrome on a touchscreen laptop running with Gnome?
gnome;touch screen
After a bit of experimenting I found out that there is already a gesture in GNOME(or maybe in a more recent version) that lets me start the onscreen keyboard. I simply had to swipe with one finger bottom-up from the bottom edge of the screen. This works for all apps, not just chrome.
_unix.111564
I'd like to setup machine for test some computation in my old laptop, before replicate the tests on the server. The computation will be image-processing and machine learning, run some program, load images and videos and run a svm training for object detection. the trainig could be 1 week of computations, maybe more.The server will be CentOS, so I'm thinking about a Fedora machine. I'd like to make a setup bash script where I install all the needed (vpn, zsh, cmake, python, numpy, ffmpeg, libsvm, opencv, qt) and send me a report via mail when finished.I'd like to automate everything with a script and make the image of the filesystem because the main idea is to have some data, analyse them in the next days, then reset the system, use new parameters for the learning algorithm, and run again the training program. repeat it.The machine will have to run and I will wait it to finish so that I'm thinking about some watchdog with cronjob that tell me how is working, send me report in the end, send me a mail if something goes wrong, etcI'm not a Linux guru so.. any kind of advice are welcome!
setting up script in a linux machine for scientific computation
command line;scripting;system installation
null
_unix.68889
Is there a way to cancel duplicity (running over rsync and symmetric gpg encryption) without messing up the running backup and resume it later (for example after rebooting the laptop) without problems?Suppose for example that after starting a duplicity backup on my laptop I notice that it will take too long time and that I have to shutdown the laptop in a few minutes.
Cancel and resume a duplicity backup
backup;rsync;duplicity
According to duplicity and rsync man, you should try this if you stop during the upload (don't know whether it's safe during encryption):duplicity --rsync-options=-P other_args
_codereview.55567
I've refactored my code such that every function has only one responsibility. Now I'd like like to work on making it DRY.I'm noticing a lot of duplication in the DocumentAnalyzer class. In nearly every function, I make a reference to @document.Should my one-statement functions be collapsed into one line?require 'set'class Document attr_reader :words def initialize(words) @words = words endendclass DocumentAnalyzer def initialize(document) @document = document end def unique_words @document.words.to_set end def unique_words_count unique_words.count end def word_count @document.words.size end def total_characters total = 0.0 @document.words.each { |word| total += word.size } total end def average_word_length total_characters / word_count endendd = Document.new %w(here are some words)da = DocumentAnalyzer.new(d)
Less-repetitive code for document-analyzer
object oriented;ruby
To my eyes, there should really only be one class: Document.As you noticed, the methods in DocumentAnalyzer all use @document. The analyzer class is so tied up in Document (and its methods are so simple) that it probably shouldn't be a wholly separate class.But if there's a reason for it to be separate class (I can't think of any), then there's nothing inherently wrong in referencing the same variable in several places.DRY does not mean Don't ever repeat anything, ever!. It means Don't duplicate logic. Accessing a variable isn't in itself logic; logic is what you do with it.So if you want to always upcase all the words (or something), you should make a method to do that for you, instead of repeating that bit of logic everywhere you need it. But even so, you'd still have to call your upcased_words method in all those places, so it's not like you can avoid any and all repetition.And no, don't collapse your methods. A single line is still a method body. Collapsing code is practically only used when you make a completely empty method or class on purpose, and want to really highlight that it's intended to be empty. E.g. def no_op; end.You'll also see it in code that defines custom exception classes. The classes just inherit from an existing exception class, but they neither add or override anything; the point is just to define them as distinct classes. Hence, they're usually defined with class CustomError < ExistingError; endOther things I noticed:Fix your indentation. Sometimes it's 2 spaces, sometimes it's 4. Stick to 2.Your Document class could - in its current form - be replaced by a plain array, really. It doesn't really do anything as it is right now. I'd expect a class named Document to (for instance) have methods to load/read a file or something. Instead, you give it an array, and it stores that array. But if you already have that array, why bother?You don't need Set. You can just do words.uniqYour total_characters method is odd. Why does total start out as a float? It'll always be an integer (unless you've discovered fractional characters)Speaking of, the summing up can be done with inject (aka reduce)def total_characters @document.words.inject(0) { |sum, word| sum += word.length }endAlso, the method should probably be called character_count to stick to the convention established by word_count and unique_word_count. Neither of those is called total_...You should probably memoize your methods. That is, store the return value after calculating it the first time, so it doesn't have to be calculated again later:def total_characters @total_characters ||= @document.words.inject(0) { |sum, word| sum += word.length }endThis code will return the instance variable immediately unless it's nil or false. Otherwise, it'll actually evaluate the right-hand expression (i.e. sum up the character count), assign the result to the instance variable, and then return the value.If you want to memoize return values, you should also freeze the words array. Otherwise you can do something like some_document.words.fill(foobar) after which your previously computed values stop making sense.I might just skip the *_count methods, since they're not even shortcuts. Anyone can call some_document.words.count or some_document.unique_words.count. Heck, you could even skip unique_words since it's the same as words.uniq (which is even shorter!).Basically, if the class itself doesn't rely on a method, and the logic is trivial, there's no reason to add that method (i.e. unique_words isn't used by the class, and is very trivial).Edit As jwg points out in the comments, memoization might be a good reason to add a method ahead of time. Still, if the class itself doesn't have an obvious use for the method, think twice before adding it.Here's what I might writeclass Document attr_reader :words def initialize(words) @words = words.dup.freeze end def characters @characters ||= words.flat_map { |word| word.chars.to_a }.freeze end def average_word_length return 0 if words.empty? # avoid division by zero characters.count / words.count.to_f endendAgain, I don't think the *_count methods add anything, since you can just write .count anyway:doc = Document.new(%w(here are some words))doc.words # => [here, are, some, words]doc.characters # => [h, e, r, e, a, r, e, s, o, m, e, w, o, r, d, s]doc.average_word_length # => 4.0doc.words.count # => 4doc.characters.count # => 16doc.words.uniq # => [here, are, some, words]doc.words.uniq.count # => 4As you can see, I've also left out the unique_words method, because it's so simple. However, if the words array is very long, it might be more efficient to provide a memoized method for people to use. I.e.def unique_words @unique_words ||= words.uniqend
_unix.37392
EnvironmentMy LAN setup is quite basic:A router connected to the ISP's modem and the internetMy development pc directly connected to the routerThe router provides DHCP but does not run its own DNS server. In fact, there is no DNS server hosted anywhere on my LAN (typical home network setup). The router is configured to send the ISP's DNS servers as part of the DHCP lease information.I set up a VirtualBox machine on my development PC and installed Debian Squeeze (6.0.4) on it. The VirtualBox network mode is Bridged Adapter to simulate a standalone server on my LAN. Being a VirtualBox server instead of a physical server is not really important, but I mention it for completeness.The ProblemEvery time a network operation executes a DNS reverse lookup of a LAN ip prior to executing, the server has long delays. Some examples of slow network operations:SSH connection to the server from my dev PCConnection to admin port of Glassfish servernetstat -l (netstat -nl is very fast)Starting MTA: exim4 on boot takes a long time to completeSome of these have workarounds like adding my dev pc's Ip to /etc/hosts or adding a command-specific option to avoid doing DNS reverse lookups. Obviously, using /etc/hosts only goes so far because it is at odds with DHCP.However, I can't help but think that I'm missing something. Do I really need to setup a DNS server somewhere on my LAN? That seems like a huge and useless effort for my needs and I can't believe there isn't another option in a DHCP environment like mine.I searched the net a lot for this and maybe I don't have the right search terms, but I can't find the solution...update 1 following BillThor's answerUsing host (dig gives the same results):# ip of stackoverflow.com$ time host -v 64.34.119.12Trying 12.119.34.64.in-addr.arpa;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 15537;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0;; QUESTION SECTION:;12.119.34.64.in-addr.arpa. IN PTR;; ANSWER SECTION:12.119.34.64.in-addr.arpa. 143 IN PTR stackoverflow.com.Received 74 bytes from 192.168.1.1#53 in 15 msreal 0m0.020suser 0m0.008ssys 0m0.000s# ip of dev pc$ time host -v 192.168.1.50Trying 50.1.168.192.in-addr.arpa;; connection timed out; no servers could be reachedreal 0m10.004suser 0m0.004ssys 0m0.000sMy /etc/resolv.conf (was automatically created during installation)nameserver 192.168.1.1Both host and dig return very fast for a public ip but take 10s to timeout for a LAN ip. I guess 10s is my current timeout value.update 2With dev-pc in /etc/hosts file:$ time getent hosts 192.168.1.50192.168.1.50 dev-pcreal 0m0.001suser 0m0.000ssys 0m0.000sWithout dev-pc in /etc/hosts file:$ time getent hosts 192.168.1.50real 0m10.012suser 0m0.004ssys 0m0.000sIt looks more and more like I'll have to find piecewise program options or parameters for each one trying to do reverse DNS lookups! None of the machines (virtual or not) can act as a DNS server on my LAN since they are not always up. Unfortunately, the router's firmware doesn't include a DNS server.
Reverse DNS lookups slowing down network operations on LAN
linux;debian;networking;dns
Is 192.168.1.1 your router's IP address?nameserver 192.168.1.1 suggests your router is advertising itself as a DNS server, rather than sending the ISP's DNS servers.What brand and model of router do you have? Does the web interface show log messages?I'm wondering if your router is forwarding the request to your ISP's nameservers, but your ISP's nameservers are dropping the request, because they don't want you to know what their machine with IP 192.168.1.50 is called.Suggestions:Double check your router's settings. It should answer requests for your own private network. Maybe you can add a static host entry in your router's web interface?Try installing Avahi on all the systems on your network.Tell your router to use Google Public DNS (8.8.8.8 and 8.8.4.4) or OpenDNS
_unix.335435
How can I remove dummy information from a file named results.txt with lines like this?Lines inside file are like this:_my0001_split00000000.txt:Total Dynamic Power = 0.0000 mW _my0001_split00000050.txt:Total Dynamic Power = 117.5261 uW (100%)And they should change to tab seperated format like this:0001 00000000 0.0000 mW 0001 00000050 117.5261 uW
Split lines inside files with fixed width columns
text processing;columns;text formatting
How about a using sed instead of awk?sed -r 's/^_my([0-9]+)_split([0-9]+)\.txt:[^=]*=\s*([0-9.]+) *(\S+).*/\1\t\2\t\3 \4/' /path/to/file