id
stringlengths
5
27
question
stringlengths
19
69.9k
title
stringlengths
1
150
tags
stringlengths
1
118
accepted_answer
stringlengths
4
29.9k
_unix.253267
I'm using iTerm 2 nightly and I have the following tmux config setting for the left status bar:set -g status-left #[fg=green]#h @ #[fg=cyan]#(extip | awk '{print \ip \ $1}') #[fg=yellow]#(ifconfig en0 | grep 'inet ' | awk '{print \en0 \ $2}') #[fg=red]#(ifconfig tun0 | grep 'inet ' | awk '{print \vpn \ $2}'Which is supposed to print my external IP, en0 and, if connected, my vpn connection. extip is my own tool that I wrote myself, but haven't touched in quite some time, and it works great from the command line (and I can see that it gets invoked and returns correctly when attaching a debugger to it). It all worked great until a couple of weeks ago, and since then it just displays <'extip | awk '{print ip $1}'' not ready> instead of my external IP address. The rest is still working perfectly without any issues. At first I thought it was just iTerm nightly being unstable, but a couple of updates have passed and it still doesn't work, so I'm feeling that maybe it wasn't supposed at all ever and just did by some kind of fluke? Can anyone give me some pointers with regards to why it may have stopped working and how I can get it to work again?
Tmux displays in the status bar
shell script;tmux;iterm
null
_webapps.25964
I posted something the other day and wish I could find the video again. Is there a way I can see all of my comments?
Is there a way I can see a list of all my YouTube comments over time?
youtube
null
_opensource.1273
This question is partially inspired by How is selling FLOSS packages for monetary compensation a viable strategy?After reading that question and some of its answers, I was left wondering if there are licenses which allow modification and redistribution of the project on the condition that one does not charge less money for the distribution than you paid yourself. This would circumvent the problems addressed in the above question.Are there any licenses that allow this and if so for what reasons would these licenses (not) be considered Open Source/Free?I strongly suspect that these licenses would not be considered Free or Open, but one never knows.
Can I forbid distributing my open source project for less money than I do?
licensing;distribution;commercial
Anybody can make pretty much any license they want so yes you could ask a lawyer to write a license like you're describing.But this would not fit the definition of an open source license. The whole point of open source is to let other people take your work and build on it, and that includes having a different pricing structure to your own.Sometimes they might take your entire project and take it in a totally different direction, other times they might just fix a couple bugs that you haven't fixed and make it available on GitHub, other times they might include your project as a child work in a larger project, or perhaps they might just grab 5 lines of code you wrote and include it in their own completely unrelated project.Any restrictions on pricing makes all of those situations nearly impossible. The only viable option under your license would be to take your project and sell it under a different name, but that's extremely rare. Why would anybody do that when it's so much easier to just contribute to the project you're running instead?
_scicomp.3131
I've been reading about implementing dense matrix multiplication when the matrix doesn't fit in cache. One of the graphs I've seen (slide 9 from these slides) shows sudden drops in performance using the naive algorithm. This drops are to around 50% of the speed, occur while the matrix still fits in cache, and only occur for one or two sizes. I'm not planning on using the naive algorithm, but I would like to know where the sudden drops in performance come from. (The drops also occur with blocked algorithms, but are much smaller.)
Sudden drops in matrix multiplication performance
linear algebra;matrices;blas
That is a classic example of cache associativity. The stride associated with that problem size is filling up certain sets causing cache eviction despite there being lots of space in other sets.Figure from Gustavo Duarte's excellent blog post on the topicSee also Drepper's What every programmer should know about memory.
_softwareengineering.216717
So I am trying to understand this TLB (Translation Lookaside Buffer). But I am having a hard time grasping it. in context of having two streams of addresses, tlb and pagetable.I don't understand the association of the TLB to the streamed addresses/tags and page tables. a. 4669, 2227, 13916, 34587, 48870, 12608, 49225b. 12948, 49419, 46814, 13975, 40004, 12707TLBValid Tag Physical Page Number1 11 121 7 41 3 60 4 9Page TableValid Physical Page or in Disk1 50 Disk0 Disk1 61 91 110 Disk1 40 Disk0 Disk1 31 12How does the TLB work with the pagetable and addresses? The homework question given is: Given the address stream in the table, and the initial TLB and page table states shown above, show the final state of the system also list for each reference if it is a hit in the TLB, a hit in the page table or a page fault. But I think first i just need to know how does the TLB work with these other elements and how to determine things. How do I even start to answer this question?
Understand how the TLB (Translation Lookaside buffer) works and interacts with pagetable and addresses
caching
null
_scicomp.26450
I have to solve a system $Ax^{(n)} = b^{(n)}$ many times, $A$ being a sparse (pentadiagonal in most part of its structure), unsymmetric, constant matrix.Currently, I am performing the LU factorization with rows and columns permutations, i.e., $PAQ = LU$, and then I am using this factorization to compute $x^{(k)}$ in the following way:$x^{(n)} = Q*(U \backslash L \backslash (P*b^{(n)}))$I have read recently about iterative methods for sparse systems, but I am not very familiar with them. Could you please tell if there is any iterative method that could perform faster and if it is already implemented in Matlab?Thanks, Manu
Fastest way to solve a sparse unsymmetric system many times
sparse;iterative method;linear system;matrix factorization
Generally speaking, for many right-hand side (RHS) problems, a direct solver is a more feasible solution for several reasons:Major computations are performed during the factorization step (which is done only once for all RHS), and the solution find (for each RHS) is much cheaper.Direct solvers do not suffer from poor conditioning of the matrix or, in other words, you don't have to look for a nice preconditioner (required for iterative solvers) ensuring $\mathcal O(1)$ iterations for every RHS (relatively easy) and every matrix (much harder) resulting from a numerical simulation.NB. Sure, if the matrix is extremely ill-conditioned, the direct solver would also suffer, however, direct solvers extend the dynamic range of problems that can be solved without re-formulating a problem.There are a couple of things that I should mention:Usually, it is ill-advised to use an inverse based on LU-decomposition to find a solution. You might want to use a back-substitution LU subroutine that would be more efficient. From your formula, it is unclear if you are doing it in the right way.Since your matrix is sparse and has a stable structure, I would look into sparse direct solvers as opposed to full direct solver. It should speed up the computations significantly.In your case, I would consider doing partial pivoting ($PA=LU$) only, as opposed to full-pivoting ($PAQ=LU$). That might speed up the computations.Connecting a high-performance LAPACK library to MATLAB is also an option.Regarding sparse iterative solvers:You can try different iterative solvers, including GMRES, BiCGStab, TFQMR, etc. Your task would be to provide a fast sparse matrix-vector product to them. Most of them are already included in MATLAB. And if you are using sparse matrix storage there, using them should not be too hard.Repeating an item from above about advantages of a direct solver: you would have to implement a decent preconditioner for all those methods that would reduce the number of iterations they require to converge. One choice would be using incomplete LU (iLU) as a preconditioner. There are more sophisticated and easier options available.Using iterative solvers is a bit tricky. You have to figure out how well is you system conditioned, what is a reasonable choice for a preconditioner, what is a good tolerance to use with an iterative solver (accuracy of the obtained solution), have a feel what kind of problems (in the subset of problems you are solving using numerical simulations) cause non- or slow-convergence of your iterative algorithm.
_softwareengineering.181442
BackgroundI have a business question regarding web-based software licensing. A number of web sites offer software as a service for various APIs. A good example is Google's Custom Search API. The process to use web services typically resembles:Account. User creates an account.Server. User defines the IP address(es) of the server(s) that will make API requests.Key. User receives a public API key for the desired API(s).Guide. User is given documentation that shows how to use the API key to make a request.Test. User can make test requests to verify integration functionality.Billing. User pays to activate the account.Production. User integrates the web service into their applications.Deactivation. System deactivates accounts when expired, exceeds request limit, etc.These requirements are in addition to integration with the service being licensed.ProblemThat is a lot of work for a small business.QuestionsWhat off-the-shelf, open source projects address this problem?If there are no such projects, what would you do to architect a viable, low-cost solution (ideally, a percentage of each license)? That is, what software or existing commercial services would you use for a small business (having little to no income) that seeks to license web-based services?Thank you!Related LinksLicense key solution in web application, what is the best approach?API Management System
Generate commercial license key for web service
licensing;api;http;software as a service
This problem is called API Management and there are a number of solutions.Integrated Billing - FOSSSolutions that offer integrated billing that are Open Source, free, or charge a percentage (based on subscriptions, so no up-front fees):WSO2 API Manager3ScaleApigee and Apigee To-GoIntegrated Billing - CommercialSolutions that offer integrated billing, but charge for services:Agilis SoftwareMashery (Partner, API) - Was $499/month; prices are now unlistedWebServiusmashape - 20% of earnings; custom prices may be possibleapiary.io - in betaSOA Software OpenCloud Security Platform Vordel API ServerSDK BridgeComponentsVarious sites and software that offer partial solutions from which a complete solution can be created.API ManagementAPI AxleVarnish API KeyapiGroveAccountsDailyCred - for accountsDocumentationSaaS Pose - for API documentationBillingStripeFastSpring
_cogsci.13885
Let's think about it, we have all adopted to learn the meaning of words through experiences or emotions. We didn't learn each and every word from a dictionary. What if I understand a word slightly differently in my complex mind? Could it result in some sort of pessimistic or optimistic or abstract outcome? And how often is this case true in our society?
What if people understand or interpret words differently in their mind?
developmental psychology;language
null
_softwareengineering.117839
The guy who is in charge of our html emails is leaving and I have been asked to take over. We are an online retailer and send out an email once a week. An email will consist of a main image, a bit of an opening paragraph and then rows of product offers.As everyone knows html emails are painful to work with due to the archaic html and css you need to deal with. When something needs changing last minute it's a real pain to wade through the spaghetti of td's to get to the link that needs it's url and tracking code changing and the opportunities to make a mistake are plentiful.So I've decided to create an xml file consisting of all the data that needs to go in the email. For example, the products would be recorded like this:<products> <product id=1> <title>My Product</title> <image width=160px height=160px> <alt>My Product</alt> <url>http://somedomain.com/emails/image1.jpg</url> </image> <link> <term>my_term_for_google_analytics</term> <url>http://somedomain.com/products/1</url> </link> </product> <product id=2> <title>My Second Product</title> ... etc ... </product></products>I could then use an xslt template to create the email. The advantage of this is that when a product goes out of stock the morning the email is due to go out I can just change a bit of text in the xml file, generate the html and we're good to go again. I can also use the same xml to create a microsite for the email. The trouble is I've had a good ol' Google about this and I can't find anyone else who has really tried this. So I'm either a visionary genius or an idiot. It usually turns out I'm an idiot so has anyone else had any experience of creating html emails from xml using xslt or can anyone see any major pitfalls with this approach. Is it a good idea?Disclaimer - I don't really think I'm a potential visionary genius.
Is using xml + xsl to create a weekly html email a good or bad idea?
html;xml;email;xslt
We use XSLT templates to transform XML into HTML for reports all the time. It works well, but like anything else you can take it too far. Keep it simple or you end up with some pretty out of hand XSLT that nobody can understand.
_codereview.129856
I have an userform that has check boxes where user can decide which worksheets to print.Code in userform:Sub PrintOK_Click()PrintSelection = Summary.value + _CCSummary.value + _DivSalaries.value + _CCSalaries.value + _PrintAll.value _' Displays warning box if no report is selectedIf PrintSelection = 0 Then MsgBox No Report(s) selected. Please select Report(s) to print., 0 + vbExclamation, Incomplete RequestEnd If' Check to see which worksheets have been selected and' Run print modules for selected worksheets If Summary.value = -1 Then Call setup(Summary) End If If CCSummary.value = -1 Then Call setup(Monthly CC Sum) End If If DivSalaries.value = -1 Then Call setup(Div Sal Sum) End If If CCSalaries.value = -1 Then Call setup(CC Sal Sum) End If If PrintAll.value = -1 Then Call setup(PrintAll) End If' Close Form boxEndEnd SubUserform selection is passed into the following. Takes the worksheet(s) selected and stores into array.Sub setup(Optional tabs As String)'store sheets into arrayDim arr() As Variant'called from printer icon on activesheetIf tabs = Then arr = Array(ActiveSheet.Name)'called via checkbox from print menuElseIf tabs = PrintAll Then arr = Array(Summary, Monthly CC Sum, Div Sal Sum, CC Sal Sum)Else arr = Array(tabs)End IfCall goPrint(arr)End SubWhich then passes the array to another sub to do the printingSub goPrint(tabArr As Variant)Dim ws As WorksheetDim area As StringDim title As String'loop through array to print each sheetFor i = 0 To UBound(tabArr) Set ws = Worksheets(tabArr(i)) With ws If .Name = Summary Then area = PRNSUMMARY title = $1:$9 ElseIf .Name = Monthly CC Sum Then area = PRNMONTHLYCCSUM title = $2:$16 ElseIf .Name = Div Sal Sum Then area = PRNDIVSALSUM title = ElseIf .Name = CC Sal Sum Then area = PRNCCSALSUM title = $2:$16 End If With .PageSetup .PrintArea = area .PrintTitleRows = title .PrintTitleColumns = .LeftHeader = .CenterHeader = .RightHeader = .LeftFooter = Year(Now()) & Budget: &F .CenterFooter = Page &P of &N .RightFooter = &D: &T .LeftMargin = Application.InchesToPoints(0.25) .RightMargin = Application.InchesToPoints(0.25) .TopMargin = Application.InchesToPoints(0.5) .BottomMargin = Application.InchesToPoints(0.5) .HeaderMargin = Application.InchesToPoints(0) .FooterMargin = Application.InchesToPoints(0.25) .PrintHeadings = False .PrintGridlines = False .PrintComments = xlPrintNoComments '.PrintQuality = 600 .CenterHorizontally = False .CenterVertically = False .Orientation = xlLandscape .Draft = False .PaperSize = xlPaperLetter .FirstPageNumber = xlAutomatic .Order = xlDownThenOver .BlackAndWhite = False .Zoom = False .FitToPagesWide = 1 .FitToPagesTall = False End With 'Debug.Print tabArr(i) 'Debug.Print area .PrintOut Copies:=1, Collate:=True End WithNextEnd SubThere's a delay of maybe two seconds after pressing OK before the printer starts to print. The previous (much longer) code had no discernible delay. How to improve speed?(Previous code had a different sub for each worksheet thus repeating the pagesetup code block multiple times.)
Print worksheets depending on checkbox. Slower than before
vba;excel
(Previous code had a different sub for each worksheet thus repeating the pagesetup code block multiple times.)Was the previous code also working directly with Worksheet objects by any chance?You're working with an array of strings / sheet names...'called from printer icon on activesheetIf tabs = Then arr = Array(ActiveSheet.Name)'called via checkbox from print menuElseIf tabs = PrintAll Then arr = Array(Summary, Monthly CC Sum, Div Sal Sum, CC Sal Sum)Else arr = Array(tabs)End If...and then creating worksheet objects as you iterate the array:'loop through array to print each sheetFor i = 0 To UBound(tabArr) Set ws = Worksheets(tabArr(i))Why not work with an array of Worksheet objects instead, and simply iterate that array?If tabs = vbNullString then arr = Array(ActiveSheet)ElseIf tabs = PrintAll then arr = Array(SummarySheet, MonthlySummary, DivSalSumSheet, CCSalSumSheet)Else sheetNames = Split(tabs, ,) arrLength = UBound(sheetNames) ReDim arr(0 To arrLength) For i = 0 To arrLength arr(i) = ThisWorkbook.Worksheets(sheetNames(i)) NextEnd IfThat's still brittle though - ideally you'd have the worksheet references themselves handy, ready to be passed to that goPrint method.The goPrint method could then simply iterate the object array with a simple For Each:For Each ws In tabArrThis code isn't ideal either; your previous code was also a little faster because it didn't need to check this condition: If .Name = Summary Then area = PRNSUMMARY title = $1:$9 ElseIf .Name = Monthly CC Sum Then area = PRNMONTHLYCCSUM title = $2:$16 ElseIf .Name = Div Sal Sum Then area = PRNDIVSALSUM title = ElseIf .Name = CC Sal Sum Then area = PRNCCSALSUM title = $2:$16 End IfIf the sheet name is CC Sal Sum then you accessed and compared the worksheet's name 4 times already. And if it's something else, ...you get whatever you get.This would be a nice case for a Select Case statement:Select Case .Name Case Summary '... Case Monthly CC Sum '... Case Div Sal Sum '... Case CC Sal Sum '... Case Else 'handle unexpected input? End SelectAt runtime, a Select Case block pretty much amounts to a conditional GoTo jump, which means no matter how many cases you have, you'll only ever evaluate the condition once.A note about this:' Close Form boxEndThat's the big red NUKE 'EM ALL button. Sure, End will close the form box. But it will also end the macro. It's very very very rare that you actually need to do this.Compare to:'Close form boxMe.HideIs that comment even needed then?Structurally, the main issue I'm seeing is that the code is relying on side-effects: the form calls setup, and then closes. What's setup doing then? Shouldn't it set things up for printing?Oh, it does... but it's also calling goPrint - which is a side-effect that makes it much harder to write a test for the method and see if it works as intended. Everything is coupled, and the UI is running the show.What if you flipped things around instead, and controlled things from the outside?Sub PromptAndPrint() Dim model As New SelectionModel model.Selection = PrintAll Dim view As New SelectionForm Set view.ViewModel = model view.Show vbModal If view.IsCancelled Then Exit Sub ConfigurePageSetup model.SelectedWorksheets PrintSheets model.SelectedWorksheetsEnd SubThat's right: the UI becomes nothing more than a presentation tool; the execution flow is controlled by the macro, not by the UI, and then you have some SelectionModel class responsible for encapsulating the data you want to pass around, and abstract away the sheet names -> worksheet objects transformation; you can test ConfigurePageSetup without wasting a sheet of paper, and you can test the whole SelectionModel functionality without even showing the UI, without configuring page setup and without wasting a sheet of paper: VBA is much more object-oriented than people generally want to admit.Nitpicks:Indentation isn't always consistent. Consider using VBE add-ins like the latest MZ-Tools or Rubberduck, which offer automatic indentation (disclaimer: I'm heavily involved in Rubberduck).Member names don't follow common naming conventions. Use PascalCase, not camelCase, for public members; that's consistent with every single type library and object model available to VBA.Also:Consider using explicit access modifiers. Procedures are implicitly Public by default.Consider using explicit parameter modifiers. Parameters are passed ByRef unless specified otherwise.Consider extracting the margins to a user-defined type, or at least a few constants.Consider removing the Call keyword, which is obsolete/useless (and then, remove the parentheses).Consider using the zero-footprint vbNullString built-in constant, instead of an empty string literal that eats up a whole 2 bytes for no reason.
_unix.159684
The following script fails to resize an already maximized window:wmctrl -i -r :ACTIVE: -b remove,maximized_vert,maximized_horzxdotool windowunmap --syncxdotool windowmap --syncwmctrl -r :ACTIVE: -e 0,300,168,740,470I am pretty sure the culprit is in the middle two lines, which I am meaning to apply to the currently active window.
Resizing a maximized window from the command line
window management;wmctrl;xdotool
Looks like the -i option in the first wmctrl cmd is causing trouble.Try this:wmctrl -r :ACTIVE: -b remove,maximized_vert,maximized_horzwmctrl -r :ACTIVE: -e 0,300,168,740,470
_webmaster.11322
Anyone know where I can find info about which Microsoft fonts I can use with Cufon for my websites? (for free, of course).Ideally, I would like to use one of the following:CalibriCorbelSegoi UITahomaVerdana
Cufon for Microsoft's fonts
fonts
It's a complex matter. If you were just using css to specify the font to render in the users machine, it'd make the browser render a font already present in the user machine, so, no issues. But Cufon seems to be actually converting the design to a vectorial shape, and making it available to every browser through a conversion to javascript. This would be actually using the design physically,(even if not using the ttf file) which might have been registered as a design. There's controversy though, in the case of fonts.These fonts seem not to be totally free for every use, also. They've made them available for certain free uses for Powerpoint viewers, Office applications, etc. But I'd check on each font's license to know what is allowed.The other way is simply use in css alternative ok looking fonts, and set these as optional, in the order you prefer. This, instead of embedding.
_webmaster.86797
Search engines recorded referrals from links like this: http://subdomain1.example.com, http://subdomain2.example.com. Subdomain pages display the contents of main domain pages but subdomains do not exist. CMS writes canonical link with subdomain address for subdomain page and with domain address for main domain page.Is the correct solution for SEO to set 301 redirect from non-existent subdomains on main domain or can I just rewrite href attribute in canonical link before output for subdomain pages?
Redirect from non-existent subdomains is correct?
seo;subdomain;canonical url
Setting the correct canonical URL in the link element should be sufficient (although you might need to verify these non-existent subdomains in Google Search Console?), however, it would be preferable to set a 301 redirect which will catch users as well and prevent them linking to the wrong domain, etc.This sort of redirect can be (should be) included as part of your canonical (www / non-www) redirect.For example, to redirect all requests that are not for your canonical domain (eg. example.com) to your canonical domain then you can do something like the following in your server config, or .htaccess:RewriteEngine OnRewriteCond %{HTTP_HOST} !=example.comRewriteRule .* http://example.com/$0 [R=301,L]
_softwareengineering.269744
At many places, I read that we can use HashMap here for O(1) search. Actually, I want to ask how I can implement easy hashmaps which can satisfy this property. Can anyone tell few hashmaps including collision thing into consideration. I don't want complete codes. I want just pseudo code or algorithm for this. I am curious to know thing thing because I read this hashmaps use a lot and at many places. Thanks a lot in advance.
What are some hashmaps we can easily implement?
c++;data structures;search;hashing
null
_unix.350773
I'm trying to figure out what commands I can use to help me map IPv6 to IPv4 addresses on a local network.I would like to be able to do the operation both ways (IPv4 -> IPv6 and IPv6 -> IPv4) where possible.I'm hoping there's a better solution than what I'm currently doing:Get MAC address from IPv4 address:arping 192.168.1.1Get MAC address from IPv6 address:ndisc6 fe80::a00:27ff:feec:bb4c wlan0See if they match
Mapping IPv6 to IPv4 addresses
ipv6;ipv4
null
_unix.297095
I have input text file e.g myfile.txt which is contains data like WO_ID ------------------------------------------------------------------------moveover_virus_8493020020_virus.final moveover_virus_7483920322_virus.csvwork etc. only phone number is changing I have some 13 work orders like this I need to take only number as a input from this for that I need a script in perl. please help me to create that script I am trying grep but I am unable get only numbers.
read phone numbers from file and store them in other file uniquely
shell script
Looking at your input file you can do something like this, using awk:awk -F_ '{print $3}' inputfile | uniq > outputfileor using grep,grep -o -E '[0-9]+' inputfile | uniq > outputfileusing sed,sed 's/[^0-9]*//g;/^\s*$/d' inputfile | uniq
_unix.277816
As pointed in the title I'm in a situation where a VirtualBox guest (Windows 7) resets host (Slackware 13.1).This happens when the guest (Windows) in booting up. The same happens with two virtual machines.How little Windows can put big Linux down this way?
VirtualBox guest (Windows 7) resets host (Slackware 13.1)
linux;virtualbox;virtual machine;slackware
null
_codereview.83531
The goal here is to only save (to file) the most recent Objects created if Object::maxMemoryOfObjects is exceeded. #include <iostream>#include <list>#include <algorithm>#include <fstream>#include <map>struct Object { const int ID; Object() : ID(++lastObjectID) {} static const int maxMemoryOfObjects = 200; static int totalMemoryOfObjects, lastObjectID;};int Object::totalMemoryOfObjects = 0, Object::lastObjectID = 0;struct Location { std::list<Object*> objectsLyingAround; Location() { for (int i = 0; i < 12; i++) { Object* object = new Object; objectsLyingAround.push_back(object); Object::totalMemoryOfObjects += sizeof(*object); } }};struct Person { void visitLocation (const Location*) {}};std::list<Location*> itinerary;void saveObjects() { std::ofstream outfile (Objects.txt); std::map<int, Object*/*, std::greater<int>*/> objectMap; for (Location* x : itinerary) for (Object* o : x->objectsLyingAround) objectMap.emplace (o->ID, o); std::cout << Objects being saved (from oldest to newest) IDEALLY are:\n; for (const auto& x : objectMap) std::cout << x.first << ' '; if (Object::totalMemoryOfObjects > Object::maxMemoryOfObjects) { std::cout << \nAlert! totalMemoryOfObjects > maxMemoryOfObjects! Will save only the newest objects.\n; auto it = objectMap.begin(); while (Object::totalMemoryOfObjects > Object::maxMemoryOfObjects) { Object::totalMemoryOfObjects -= sizeof(*it->second); std::cout << totalMemoryOfObjects reduced to << Object::totalMemoryOfObjects << std::endl; it = objectMap.erase(it); } std::cout << Objects being saved (from oldest to newest) NOW are:\n; for (const auto& x : objectMap) std::cout << x.first << ' '; }outfile << objectMap.size() << std::endl;for (const auto& x : objectMap) outfile << x.first << ' ';}void loadObjects() { int numObjects; std::ifstream infile (Objects.txt); infile >> numObjects; // etc...}int main() { Person sam; for (int i = 0; i < 5; i++) { Location* nextLocation = new Location; itinerary.push_back (nextLocation); sam.visitLocation (nextLocation); } saveObjects(); loadObjects();}Output:Objects being saved (from oldest to newest) IDEALLY are:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60Alert! totalMemoryOfObjects > maxMemoryOfObjects! Will save only the newest objects.totalMemoryOfObjects reduced to 236totalMemoryOfObjects reduced to 232totalMemoryOfObjects reduced to 228totalMemoryOfObjects reduced to 224totalMemoryOfObjects reduced to 220totalMemoryOfObjects reduced to 216totalMemoryOfObjects reduced to 212totalMemoryOfObjects reduced to 208totalMemoryOfObjects reduced to 204totalMemoryOfObjects reduced to 200Objects being saved (from oldest to newest) NOW are:11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60But the way I'm doing it ironically adds more memory to the Object class (its ID data member). Is there a better way to do this? We assume here that the Objects are being saved and loaded many times until megabytes or even gigabytes of data are being stored in memory, at which a max should be enforced. Really old items that are lying around in Locations but never picked up will assume to be discarded first since they are probably forgotten anyway.
Limiting the save content of file to certain size
c++;file
First: Crappy indentation makes it hard to read.Your algorithm seems unnecessarily complicated. Why not work out how many items you want to serialize and just serialize those items. // Work out how many items we will need to drop. std::size_t countOfItems = objectMap.size(); std::size_t maxNumberOfItems = Object::maxMemoryOfObjects/sizeof(Object); std::size_t advance = (countOfItems > maxNumberOfItems) ? (countOfItems - maxNumberOfItems) : 0; // Get an iterator to the first item // Then advance it forward the number of items we want t drop // These are the older items (as map is a sorted container). auto printer = objectMap.begin(); std::advance(printer, advance); // Print all the items using std::copy and a stream iterator // May not work out the box for you but you should learn how to do this. std::copy(printer, objectMap.end(), std::ostream_iterator<Object>(outfile));Memory OwnershipYour code is littered with pointers.This is not a good idea in general (but hard to tell without more context in this case). RAW Pointers are very rare in C++ as they do not convey object ownership. Usually pointers are managed by some owning object that manages their lifespan (as a result you never interact with them directly but via their owning object).You should be using containers of object (not pointers) or if you have object hierarchies then use pointer containers that understand their content is a pointer and can act accordingly. If you don't have pointer containers available (they are in boost) then you should at least be using smart pointers to maintain the concept of ownership.Looks like an error:for (const auto& x : objectMap) outfile << x.first << ' ';}You are not serializing the object but only the ID. I think you meant:for (const auto& x : objectMap) outfile << x.second << ' ';}But now you also need to define:std::ostream operator<<(std::ostream& str, Object const& data){ returns str << /* Serialize object */}std::istream operator>>(std::istream& str, Object& data){ returns str >> /* De-Serialize object */}Looks like it might be an issue.Object::totalMemoryOfObjects += sizeof(*object);The size of an object in memory is always fixed. So you may as well count the number of objects. Note: sizeof() is computed at compile time not runtime. If you want to add up the number of bytes in things like strings you need to write your own method to do it.But when you use operator<< the object is generally serialized and the number of bytes can vary (unless you write your object in binary fixed size format to the stream (but then you need to worry about machine peculiarities like endianness (so unless there is an extreme need for speed it is usually best to use a non binary format)).Declare variables JUST before you use themstd::ofstream outfile (Objects.txt);// 500 lines of code not using outfileoutfile << objectMap.size() << std::endl;for (const auto& x : objectMap) outfile << x.first << ' ';}Move the declaration of outfile to the point just before you tart using it. In C++ because of constructors/destructors the side affects may allocate resources. If you don't need them don't use them so wait until you need them.It also has the benefit of making the declaration near the code that uses it so it makes it real easy to see the type of the object you are using (as it is just there with the code).Encapsulationstruct Person {You seem to be making all your objects publicly accessible. This does not help encapsulation. You should make all your data members private by default. Then provide methods (which are verbs) that act on the object.class Object{ static int const maxMemoryOfObjects = 200; static int totalMemoryOfObjects = 0; static int lastObjectID = 0; static int allocateNextAvailableID() { return ++lastObjectID; } const int ID; public: Object() : ID(allocateNextAvailableID()) {} // define an ordering on your objects. friend bool operator<(Object const& lhs, Object const& rhs) { // With an ordering you can use Object as the key. // in a sorted container. return lhs.ID < rhs.ID; }};int main(){ std::set<Object> objectSet; // No need to allow access to the ID // to external entities that do not need to know. // provide the appropriate access method (in this // case `operator<()` that defines the ordering.}
_unix.340051
I am currently working in a shell script to automate some things (copying files and preserving their change date). I tested all commands on my shell, but when I run them on a script, they don't behave correctly.If I run this o my shell, I get the appropriate result:$> filename=/home/root/data/ABCD1234/20170123-231000.wav$> echo $filename/home/root/data/ABCD1234/20170123-231000.wav$> cdate=$(date +%Y%m%d%H%M.%S -r $filename)$> echo $cdate201701232310.00$> cp $filename $filename.bck touch -t $cdate $filename.bckBut when I run the following script:#!/bin/bash# list desired filesfiles=$(find /home/root/data/ABCD1234/*)# iterate over every file foundfor filename in $filesdo echo $filename cdate=$(date +%Y%m%d%H%M.%S -r $filename) echo $cdate cp $filename $filename.bck touch -t $cdate $filename.bckdoneexit 0I get the following output (assuming there are 2 files in this folder)/home/root/data/ABCD1234/20170123-231000.wav': No such file or directory/data/ABCD1234/20170123-231000.wav/home/root/data/ABCD1234/20170123-231500.wav': No such file or directory/data/ABCD1234/20170123-231500.wavPS: I am using an ARAGO distro and most shell commands are a redirect to BusyBox.PS: In my original script I am not actually copying files, so keeping timestamp on the cp command won't solve my problem.
File not found while running a sh script
linux;bash;shell script
null
_unix.89992
I'm trying to install the various i386 libraries required for skype on linux (debian 7.0 wheezy 64-bit), but I've run into a problem where apparently the two versions of libsqlite-3-0 are each blocking the other. Here's the output from aptitude:libsqlite3-0 : Breaks: libsqlite3-0:i386 (!= 3.7.16.2-1~bpo60+1) but 3.7.13-1+deb7u1 is to be installed.libsqlite3-0:i386 : Breaks: libsqlite3-0 (!= 3.7.13-1+deb7u1) but 3.7.16.2-1~bpo60+1 is installed.I've done a bit of tracking, and here is what I know about those packages:libsqlite3-0:i86 is not yet installed.libsqlite3-0:amd64 (the normal one) is installed, but instead of the wheezy default of 3.7.13-1, I have a different version from squeeze-backports (from before I upgraded to wheezy): 3.7.16.2-1.A google search for libsqlite3-0 3.7.16.2-1 finds several pages about iceweasel. I've tried removing iceweasel, but that's not an option; gnome-core depends on it apparently.Any ideas for how to resolve this, or investigate further?FYI: derobert's advice got this sorted. The command I needed was this one, to downgrade the libsqlite3-0 (amd64) package:aptitude installpackage=versione.g. in this case aptitude installlibsqlite3-0=3.7.13-1+deb7u1in full:root@hephaestus:/etc/apt# aptitude install libsqlite3-0=3.7.13-1+deb7u1The following packages will be DOWNGRADED: libsqlite3-0 0 packages upgraded, 0 newly installed, 1 downgraded, 0 to remove and 0 not upgraded.Need to get 455 kB of archives. After unpacking 48.1 kB will be freed.Get: 1 http://ftp.uk.debian.org/debian/ wheezy/main libsqlite3-0 amd64 3.7.13-1+deb7u1 [455 kB]Fetched 455 kB in 1s (452 kB/s) dpkg: warning: downgrading libsqlite3-0:amd64 from 3.7.16.2-1~bpo60+1 to 3.7.13-1+deb7u1(Reading database ... 179321 files and directories currently installed.)Preparing to replace libsqlite3-0:amd64 3.7.16.2-1~bpo60+1 (using .../libsqlite3-0_3.7.13-1+deb7u1_amd64.deb) ...Unpacking replacement libsqlite3-0:amd64 ...Setting up libsqlite3-0:amd64 (3.7.13-1+deb7u1) ...
Incompatible versions of libsqlite3-0 (i386 and amd64) block each other
debian;package management
The ~bpo in the version number means it comes from Debian backports. If you check packages.debian.org, you'll see that the version you have installed is from squeeze-backports.Also, the :i386 means that it's a 32-bit version. So it looks like you had Squeeze installed before and also Squeeze backports. And also 32-bit squeeze backports. Or at least, you had that backport installed.The fix is to upgrade your squeeze backports to Wheezy versions. I suspect that didn't happen automatically because you don't have multi-arch enabled. See https://wiki.debian.org/Multiarch/HOWTO and https://wiki.debian.org/Multiarch
_codereview.70706
I have ChannelWrapper and Channel Value Object. I want to convert each and every field of ChannelWrapper to Channel Value Object.public class ChannelWrapper extends BaseWrapper implements APIWrapper<Channel>, APIUnwrapper<Channel> { @XmlElement private Long id; @XmlElement private User user; @XmlElement private Tenant tenant;// Getter Setters @Override public Channel unwrap(HttpServletRequest arg0, ApplicationContext arg1) { // TODO Auto-generated method stub return null; } @Override public void wrapDetails(Channel model, HttpServletRequest request) { this.id = model.getId(); this.user = model.getUser(); this.tenant = model.getTenant(); } @Override public void wrapSummary(Channel model, HttpServletRequest request) { wrapDetails(model, request);}Channel Value Object:public class Channel { private Long id; private User user; private Tenant tenant; //getter setters }Converter:Channel channel = new Channel();channel.setId(channelWrapper.getId());channel.setUser(channelWrapper.getUser());channel.setTenant(tenant);Is this the best way to create a converter?Any other general comments are appreciated.
Converting a wrapper object to a value object
java;converting;spring;rest
null
_cstheory.16904
In many papers involving context-free grammars (CFGs), the examples of such grammars presented there often admit easy characterizations of the language they generate. For example:$S \to a a S b$ $S \to $generates $\{ a^{2i} b^i | i \geq 0\}$,$S \to a S b$ $S \to a a S b$ $S \to $generates $\{ a^i b^j \mid i \geq j \geq 0 \}$, and$S \to a S a$ $S \to b S b$ $S \to $generates $\{ w w^R \mid w \in (a|b)^* \}$, or equivalently $\{ ((a|b)^*)_1 ((a|b)^*)_2 \mid p_1 = p_2^R \}$ (where $p_1$ refers to the part captured by $(...)_1$).The above examples can all be generated by adding indices ($a^i$), simple constraints on these indices ($i > j$) and pattern matching to regular expressions. This makes me wonder whether all context-free languages can be generated by some extension of the regular expressions.Is there an extension of regular expressions that can generate all of or some significant subset of the context free languages?
Does there exist an extension of regular expressions that captures the context free languages?
fl.formal languages;context free;context free languages
Yes, there is. Define a context-free expression to be a term generatedby the following grammar:$$\begin{array}{lcll}g & ::= & \epsilon & \mbox{Empty string}\\ & | & c & \mbox{Character $c$ in alphabet $\Sigma$} \\ & | & g \cdot g & \mbox{Concatenation} \\ & | & \bot & \mbox{Failing pattern} \\ & | & g \vee g & \mbox{Disjunction}\\ & | & \mu \alpha.\; g & \mbox{Recursive grammar expression} \\ & | & \alpha & \mbox{Variable expression}\end{array}$$This is all of the constructors for regular languages except Kleenestar, which is replaced by a general fixed-point operator $\mu\alpha.\;g$, and a variable reference mechanism. (The Kleene star isnot needed, since it can be defined as $g\ast \triangleq \mu\alpha.\;\epsilon \vee g\cdot\alpha$.)The interpretation of a context-free expression requires accountingfor the interpretation of free variables. So define an environment$\rho$ to be a map from variables to languages (i.e., subsets of$\Sigma^*$), and let $[\rho|\alpha:L]$ be the function that behaveslike $\rho$ on all inputs except $\alpha$, and which returns thelanguage $L$ for $\alpha$.Now, define the interpretation of a context-free expression as follows:$$\newcommand{\interp}[2]{[\![{#1}]\!]\;{#2}}\newcommand{\setof}[1]{\left\{#1\right\}}\newcommand{\comprehend}[2]{\setof{{#1}\;\mid|\;{#2}}}\begin{array}{lcl}\interp{\epsilon}{\rho} & = & \setof{\epsilon} \\ \interp{c}{\rho} & = & \setof{c} \\ \interp{g_1\cdot g_2}{\rho} & = & \comprehend{w_1 \cdot w_2}{w_1 \in \interp{g_1}{\rho} \land w_2 \in \interp{g_2}{\rho}} \\ \interp{\bot}{\rho} & = & \emptyset \\ \interp{g_1 \vee g_2}{\rho} & = & \interp{g_1}{\rho} \cup \interp{g_2}{\rho} \\ \interp{\alpha}{\rho} & = & \rho(\alpha) \\ \interp{\mu \alpha.\; g}{\rho} & = & \bigcup_{n \in \mathbb{N}} L_n \\ \mbox{where} & & \\ L_0 & = & \emptyset \\ L_{n+1} & = & L_n \cup \interp{g}{[\rho|\alpha:L_n]}\end{array}$$Using the Knaster-Tarski theorem, it's easy to see that theinterpretation of $\mu \alpha.g$ is the least fixed of the expression.It's straightforward (albeit not entirely trivial) to show that youcan give a context-free expression deriving the same language as anycontext-free grammar, and vice-versa. The non-triviality arises fromthe fact that context-free expressions have nested fixed points, andcontext-free grammars give you a single fixed point over a tuple. This requires the use of Bekic's lemma, which says precisely that a nested fixed points can be converted to a single fixed point over a product (andvice-versa). But that's the only subtlety. EDIT: No, I don't know a standard reference for this: I worked it outfor my own interest. However, it's an obvious enough construction thatI'm confident it's been invented before. Some casual Googling revealsJoost Winter, Marcello Bonsangue and Jan Rutten's recent paperContext-Free Languages, Coalgebraically, where they give a variantof this definition (requiring all fixed points to be guarded) whichthey also call context-free expressions.
_cstheory.16550
This question is related to (but not the same as):How to define a function inductively on two arguments in Coq?In particular, I used those techniques (defining a second fixed point function) and Coq still complains.Consider the following formalization of regular expressions.Inductive symbol : Set := Zero | One.Definition string := list symbol.Fixpoint symbol_eq (a:symbol) (b:symbol) : bool := match a with Zero => match b with Zero => true | One => false end | One => match b with Zero => false | One => true end end.Inductive regexp : Set := Symbol (s:symbol) | Concat (r1:regexp) (r2:regexp) | Union (u1:regexp) (u2:regexp) | Star (u1:regexp) .Fixpoint rgm (r:regexp) (s:string) := match r with Symbol ss => match s with nil => false | a::nil => (symbol_eq ss a) | a::b::tl => false end | Union r1 r2 => (orb (rgm r1 s) (rgm r2 s)) | Concat r1 r2 => let fix f s1 s2 := match s2 with nil => (andb (rgm r1 (rev s1)) (rgm r2 s2)) | a::tl => (orb (andb (rgm r1 (rev s1)) (rgm r2 s2)) (f (a::s1) tl)) end in (f nil s) | Star r1 => match s with nil => true | a::tl => let fix f s1 s2 := match s2 with nil => (rgm r1 (rev s1)) | a::tl => (orb (andb (rgm r1 (rev s1)) (rgm r s2)) (f (a::s1) tl)) end in (f (a::nil) tl) end end.Coq refuses to compile it for the following reason:Error: Cannot guess decreasing argument of fix.Question: how can we fix this?
Defining Mutually Recursive functions in Coq
pl.programming languages;coq
null
_webmaster.85593
I using DFP.I have one banner that impression set as 500,000 impressions, however the banner will sometimes show Google Adsense ads while the impression count is not reached yet.How do I set the banner keep displaying the banner that I uploaded until the impression is finished running?Update Question:My Deliver Impressions was set as As Fast as possible but sometimes it still showing other google ads.
In DFP, how do I set a banner keep displaying until the impression is finished running?
advertising;google dfp;impressions;ad server
null
_codereview.17622
I am trying to write a merge sort algorithm. I can't tell if this is actually a canonical merge sort. If I knew how to calculate the runtime I would give that a go. Does anyone have any pointers?public static void main(String[] argsv) { int[] A = {2, 4, 5, 7, 1, 2, 3, 6}; int[] L, R; L = new int[A.length/2]; R = new int[A.length/2]; int i = 0, j = 0, k; PrintArray(A); // Make left and right arrays for (k = 0; k < A.length; k++) { if (k < A.length/2) { L[i] = A[k]; i++; } else { R[j] = A[k]; j++; } } PrintArray(L); PrintArray(R); i = 0; j = 0; // Merge the left and right arrays for (k = 0; k < A.length; k++) { System.out.println(i + + j + + k); if (i < L.length && j < R.length) { if (L[i] < R[j]) { PrintArray(A); A[k] = L[i]; i++; } else { PrintArray(A); A[k] = R[j]; j++; } } } PrintArray(L); PrintArray(R); PrintArray(A);}public static void PrintArray(int[] arrayToPrint) { for (int i = 0; i < arrayToPrint.length; i++) { System.out.print(arrayToPrint[i] + ); } System.out.print(\n);}
Is this attempt at a merge sort correct?
java;algorithm;sorting;mergesort
When a prospective employer asks you a question like this one, they most likely want to see something original. They want you to show them that you can create code and not just copy and paste bits and pieces of code.If what you wrote works and runs correctly, then you have accomplished the answer.Sometimes employers are trying to find out if you know the theory behind a merge sort. It looks to me like you have done that as well.The only thing that I can think of that you could do to make your code better is to improve the naming of your variables.int[] A = {2, 4, 5, 7, 1, 2, 3, 6};int[] L, R;L = new int[A.length/2];R = new int[A.length/2];Change them to int[] array = {2, 4, 5, 7, 1, 2, 3, 6};int[] leftSide;int[] rightSide;leftSide = new int[array.length/2];rightSide = new int[array.length/2];This would make it much easier to read.
_webmaster.59093
I have disabled IIS7 in my machine. installed WAMP server. Stopped skype, antivirus which used port 80. When i ran Wamp server, phpmyadmin is working great and when i click on localhost it is showing Default IIS7 page. Can anyone please help me out , how can i avoid this and get wamp localhost.
Wamp local host defaults to IIS 7
wampserver
null
_webapps.53112
I have several dates in let's say:A1:A with this syntax: dd/mm/yyyy and I would like to COUNTIF the cells that are years. I started with this formula, but that didn't work:=COUNTA(UNIQUE(YEAR(A1:A)))
How to COUNTIF cells are years in Google Spreadsheet?
google spreadsheets
Use this formula:Formula=COUNTUNIQUE(ARRAYFORMULA(IFERROR(YEAR(A1:A15))))ExplainedThe ARRAYFORMULA around the YEAR formula makes it possible to accept a range. The COUNTUNIQUE counts the unique entries. It's simply a combination of COUNT and UNIQUE.ExampleI've created an example file for you: COUNT UNIQUE YEARS
_unix.237758
Is there a way I can make vlc play all videos at 50% volume by default? I looked at the online documentation but it didn't say if there is a configuration file I could tweak. Is there any way, by editing a configuration file or any other method, to set vlc's default volume to 50%?
How can I make vlc play all videos at 50% volume?
vlc
First, let's be lazy: this can be done using the GUI. Which GUI to use however depends on the audio output system you're using. Open VLC, and go to Tools > Preferences > Audio. The Output module setting will tell you what you're using.If you're using Pulse, then your default volume level is handled by Pulse itself. The easiest way to configure that is to use pavucontrol. Install it using your package manager, start VLC (with audio), and open pavucontrol. Get to the Playback tab, and set VLC's new value (in your case, 50%).If you're using ALSA, you can set your value in VLC directly. Just above the Output module option, check the Always reset audio start level to box, and select 50% in the slider next to it.If you want to configure the volume level without using VLC/pavucontrol, then again, the method depends on your audio output. Let's have a look at VLC's code:static int getDefaultAudioVolume(vlc_object_t *obj, const char *aout){ if (!strcmp(aout, pulse)) return -1; else if (!strcmp(aout, alsa) && module_exists(alsa)) return cbrtf(config_GetFloat(obj, alsa-gain)) * 100.f + .5f; else if (!strcmp(aout, sndio)) return -1; return -1;}I've simplified it a bit, but basically:If you're using Pulse, VLC's configuration has no impact. You'll need to configure Pulse itself. Have a look at pactl (or maybe pacmd for an interactive interface). Here's a little one-liner to set VLC's default level:$ pactl set-sink-input-volume $(pactl list short sink-inputs | grep $(pactl list short clients | grep vlc | cut -f1) | cut -f1) 50%And yes, that's ugly. Basically, I'm getting VLC's index (as a client), and finding the associated sink input's index. Then I inject that index into set-sink-input-volume, and set the value to 50%. Have a look at pactl(1) for more information about these pactl commands. Remember that you can also use pavucontrol to configure Pulse in a GUI :)If you're using ALSA, your default volume level is determined using the alsa-gain setting in ~/.config/vlc/vlcrc. For a default volume of x, you should set this value to ((x - 0.5) / 100) ^ 3, since cbrtf is a cube root. In your case, that means alsa-gain = (49.5 / 100) ^ 3 = 0.121287375. You'll also need to set the volume-save setting to 0 (false) in order to apply your new default value every time, regardless of the volume level you were at the last time you closed VLC.
_webapps.5032
I noticed that recently Facebook recently changed the friends who liked this feature on the News Feed. Before, it would show all your friend's names such as Friend A, Friend B, and Friend C like this. Now, it just shows 3 people like this and when you click on it the list is fetched via AJAX. Before, this only happens when a lot of people like something, but now it happens when at least 2 friends like something.Out of curiosity, did Facebook do this to make the user experience more uniform or is it for scalability reasons?
Did Facebook x people like this for scalability reasons?
facebook
null
_vi.10566
I have a file formatted like this+---------------------------------+| Text text text || Text text text || Text text text |+---------------------------------+Within the ASCII box I would like to remap the standard VIM keys, like $, _, ... to ignore the ASCII box during editing.For example, $ should place the cursor on the last letter of the text and not on the '|'. I can make it with the simplennoremap <buffer> $ f\|geThis works great, but when I try to combine the new $ with other VIM commands, this doesn't work any more. For example, d$ deletes the entire like including the last '|' char.In my understanding, I have to use onoremap somehow to support motions, and then vnoremap to support visual mode.My question is:How should I remap $ so that it nicely integrates with all VIM-aspects? (visual mode, motions, objects, ...)
Remap standard motions
cursor motions;object motions;key bindings
null
_unix.176372
When does swap start to be used? Is it when the memory is fullyused? Or when the memory hasn't been fully used?When does a process get an Out of memory error and be killed bythe kernel? is it when both RAM and swap are fully used? or justwhen RAM is?
When does swap start to be used? When does a process get an out of memory error and be killed?
swap;virtual memory
null
_unix.340308
We have a RaspberryPi device that we are trying to deploy an audio player in a museum setting. We would like to program the Pi device to play an auto file between the hours of X and Y on repeat. This part is simple we can just set a cron job to launch the following command:mpg123 --loop 2 test.mp3But this won't work well if we lose power or the device isn't turned on by the time the job needs to kick-off.Does anyone have suggestions on how to potentially check and see if the audio is playing and if not kick-off the task again? Ideally with minimal delay between looping audio.
Playing an audio file on repeat between x hour and y hour?
audio
null
_vi.5727
Sometimes (I can't reproduce it reliably), after opening a tab, the height of my command line becomes excessively big.When it begins, the buffer displayed in the first newly created tab has only 10 lines. The buffers displayed in the subsequently created tabs have only 3 lines. All the rest is taken by the command line.I've found 4 ways to make the command line take only one line again.Switching to another tab and coming back (gt, gT) Creating a split and closing it (:sp, :q) Maximizing the window (<C-w> + _)Dragging the status line to the bottom of the screen with the mouseAfter that, cycling between the tabs doesn't change the command line height.However, as soon as I close one, the command line of the tab which gains the focus becomes high again. I usually hit <C-w> + _, which fixes the height until I open or close a tab.It only concerns a new tab, or the first tab which gains the focus after closing another one.The value of my 'cmdheight' option is 1, 'cmdwinheight' is 7 and 'winheight' is 999.If I can't find the cause, maybe I will add an autocmd (something like au TabEnter * wincmd _), but before doing that, is there a way to find what is causing the command line height to be changed when I sometimes open or close a tab ?
How to find what is causing the command line height to be changed after opening / closing a tab?
command line;vim windows
To find where an option was last set, use :verbose set <option>?. In this case,:verbose set cmdheight?See:help :verbose-cmd
_cstheory.17888
This is a problem I have found very difficult to solve, given how the two different uses of reversal confuses search engines.Reversal-bounded multicounter machines are described at length in his paper Reversal Bounded Multicounter Machines and their Decision Problems. Essentially, the bound on reversals refers to the number of times any of the counter are allowed to switch from incrementing to decrementing.Let $DCM$ be the family of languages accepted by deterministic reversal-bounded multicounter machines, and $NCM$ the nondeterministic class.Let $L^R = \{w^R | w \in L \}$ where $w^R$ is $w$ reversed.I'm wondering, for $L \in DCM$, is $L^R \in DCM$? Are there subclasses of $DCM$ which have this property? Formal Modelling of Viral Gene Compression by Daley and McQuillan tells that $NCM$ is closed under reversal, but I have found no such reference for the deterministic case.
Are Reversal-bounded Multicounter Machines closed under reversal?
reference request;fl.formal languages;automata theory;counter automata
DCM is not closed under reversal. I don't know of a reference, but it is easy to show it using the expressveness lemmata of Chiniforooshan, E., Daley, M., Ibarra, O.H., Kari, L., Seki, S.: One-reversal counter machines and multihead automata: revisited.In particular, they state that for any DCM language $L$, there is a word $w$ such that $L \cap w\Sigma^*$ is a nontrivial regular language. Now let $D$ be the following hinted version of the complement of the prefixes of the Dyck language:$$D = \{a^nw_1w_2\cdots w_k \mid w_i \in \{[, ]\} \land |w_1w_2\cdots w_n|_] > |w_1w_2\cdots w_n|_[\}.$$In other words, $D$ is the complement of the Dyck where the number of $a$'s in the prefix gives a position witnessing the unbalancing of the parentheses. Also, $(\{a\}^*)^{-1}D$ is the complement of the prefixes of the Dyck. Note that $D$ is in DCM. Now consider $D^R$ and a word $w \in \Sigma^* = \{a, [,]\}^*$. Then either $D^R \cap w\Sigma^*$ is finite, or it is nonregular, hence $D^R \notin$ DCM.I don't know of any interesting subclass of DCM closed under reversal. (Ad placement!) However, we studied a model called Unambiguous constrained automata which is close but not comparable to DCM, and which enjoys closure under reversal --- constrained automata, or Parikh automata, themselves are equivalent to NCM in the nondeterministic case, and a strict subset of DCM in the deterministic case.
_softwareengineering.326516
Lets say I have multiple websocket servers that maintain many connections to clients to send updates. These websocket servers will be pulling said updates from a rabbitmq broker, and broadcasting them to all relevant clients who happen to be on a page that needs an update.My question is how can all clients who are on page[x] get an update for it if they are split up across multiple websocket servers? WS-server-A will recieve an update and forward it out to all its clients on page[x], but whate about the clients connected to WS-server-b who has clients on the same page?(edited below to add more details)The way I'm imagining this scenario is like so:For an imaginary forum, we have a multi-threaded web server that does page rendering and responds to api calls. When someone saves a post on a topic, the web server saves the post to the db, then passes the post off to rabbitmq.Rabbitmq forwards this post to the relevant exchange (say, 'new-posts'. There are also other exchanges: 'new-topics', 'alerts', etc), where the websocket server picks it up, examines the header and forwards the post to all users who are on the relevant page.
How can an update message from a rabbitmq broker reach all relevant clients via multiple websocket servers?
web services;message queue;websockets;messaging;message passing
What probably happens right now is that some messages are processed by server A, and never delivered to B, and some are processed by B, but A never receives them. This is because you haven't specified the exchange: the default one is the direct exchange, meaning that messages are sent to one of the queues at a time, using round robin.In order for multiple servers to receive the message, you may use the fanout exchange routing. With this type of routing, the same message will be routed to every queue.The exchange routing type is specified when you create the exchange.You can find additional information about different types of exchanges on the official RabbitMQ website.
_hardwarecs.6185
Acer Aspire ATC-220-EB52 Desktop (Refurbished)- AMD A10-7800 3.5GHz- 8GB DDR3- 1TB HDD- AMD Radeon R7 Graphic- Windows 10 Home 64-bit- CAD$ 409 + 13% taxI am considering this for a general purpose desktop + Adobe Lightroom use. Will add an SSD to speed up. Thoughts?My current Adobe Lightroom computer is a Mid 2013 MacBook Air and it works reasonable well. The CPU & Graphics in the AMD A10 is better so the overall performance should be better (assuming Windows & Mac versions are similar).Is this line of thinking accurate? Happy for alternatives or even a build recommendation within the same budget. Thank you.
Refurbished Acer AMD A10-7800 Desktop
desktop
As for another option, here's a build using an Intel CPU. Personally, I'm not a big fan of AMD CPUs, I haven't had a good experience with them. Here's the link to the PC part picker list. Again, everthing's off Amazon. I'd personally go with this Intel build over the AMD build I mentioned. The i3 6100 has a benchmark that is slightly above/better than the AMD A10 7800. Regardless, both these builds should do what you need.CPU: Intel Core i3-6100 3.7GHz Dual-Core Processor ($126.28 @ Amazon) Motherboard: MSI B150M Pro-VD Micro ATX LGA1151 Motherboard ($60.54 @ Amazon) Memory: Crucial 8GB (1 x 8GB) DDR4-2133 Memory ($41.99 @ Amazon) Storage: Seagate Barracuda 1TB 3.5 7200RPM Internal Hard Drive ($47.99 @ Amazon) Case: Rosewill Galaxy-03 ATX Mid Tower Case ($29.99 @ Amazon) Power Supply: CoolMax 400W ATX Power Supply ($23.22 @ Amazon) Other: Windows 10 Home 64 Bit OEM DVD ENGLISH ($75.99 @ Amazon) Total: $406.00Prices include shipping, taxes, and discounts when available
_unix.50541
I am tasked to explain the variation of gpg errors that happened in one of my batch script. Currently when I perform gpg decrypt for a specified file it returns 2. The problem with this is when I search the form, it shows that the file has been decrypted properly but the error code is causing the script to stop because it only assumed that 0 is the only success value.gpg -o XXX --decrypt XXX.gpgRETVAL=$?if [ RETVAL -ne 0 ]; then exit 1fiI searched the net and found the header list for gpg. It defines error 2 as Unknown Packet.http://www.gnu-darwin.org/www001/src/ports/security/libgpg-error/work/libgpg-error-1.5/src/err-codes.h.inThe normal error text being displayed is [gpg: [don't know]: invalid packet (ctb=14)].What exactly does the unknown packet mean? I am trying to search any documents on understanding the error codes. After showing all the verbose information using the [-vv] option. I compared the resulting gpg file decryption with a file that returns 0 code.The only thing I noticed is the byte of the key is different.The decryption of the gpg that is error free have the following log::pubkey enc packet: version 3, algo 16, keyid <16-hexdigit> data 1023 bits data 1024 bitsThe decryption of the gpg causing error have the following log::pubkey enc packet: version 3, algo 16, keyid <16-hexdigit> data 1022 bits data 1022 bitsWhat does this mean? why can it still be decrypted properly even if the key bit is not the same? Note that the key-id and passphrase used to decrypt the two file are the same. Also, does anyone know any detailed resource on explaining the error of gpg.
What does gpg error code 2(GPG_ERR_UNKNOWN_PACKET) mean?
gpg;return status
null
_unix.144090
When I do the following:tar czvf ../myarchive.tar.gz ./I get a single (annoying) root folder in my tar archive:How do I remove this awful period when creating the archive?
Create a tar archive of the current directory without preceding period
tar
You don't.name=${PWD##*/}cd ..tar czf $name.tar.gz $name(Note: this doesn't work if your shell has current directory symbolic link tracking turned on and the current directory is accessed via a symbolic link.)Yes, this isn't what you asked, but this is what you should do. Archives that expand a lot of files in the current directory are annoying: it puts the burden of creating a target directory for the file on each person who unpacks the archive, andif they accidentally unpack them in a non-empty directory, it's hard to clean up. Most of the time, an archive should create a single toplevel directory whose name is the base name of the archive.
_softwareengineering.354852
I am considering how to write a repository for a new project.I like the idea of a generic repository like this for the basic CRUD operations:public class Repository<TEntity> : IRepository<TEntity> where TEntity : class, IEntityHowever, I also read that this is against the spirit of DDD. Therefore as a compromise I was thinking about creating a generic repository and then a few repositories that inherit from it e.g. CustomerRepository: Repository etc. However, I cannot find any documentation to support this idea. Q1) Is it a reasonable idea to create a base repository?Also, I am trying to create one repository per aggregate root rather than one repository per entity. Say I have two classess i.e. Order and OrderItem (Order is the aggresgate root), then:Q2) Is it reasonable for all the data access for the OrderItem to go in the Order repository (the aggregate root)? i.e. SELECT * FROM OrderItem WHERE OrderID=@OrderID (translates to LINQ).
Options for designing a Repository
c#;domain driven design
null
_codereview.140332
Purpose: The intention behind this code is to have multiple applications that each implement an Actor. Each application should be responsible for defining which actions the given Actor should implement and how they should be implemented. The main() is an example of how an application might define Actor behavior.I am looking for overall feedback regarding this pattern. Does it have a specific name? It seems to resemble the delegate/callback/handler model I remember using back in C#.Otherwise, I am looking for specific feedback regarding my use of std::function, is that the right use for it? How about std::map to deduce the specialized handler? In this example there are only 3 action types but I plan on having about 15.Finally, are there any changes you would make to optimize the code? Such as applying some sort of tempalting in order to reduce code bloat? Perhaps switching to a generic callback so that my Actor class doesn't end up having 15 different callbacks that need connecting?#include <functional>#include <iostream>#include <map>#include Action.h#include Distance.h#include DriveParameters.h#include Speed.h#include Style.h#include SwimParameters.h#include Vehicle.h#include WalkParameters.hclass Actor {private: std::function<bool(const Vehicle&, const Speed&, const Distance&)> driveCallback; std::function<bool(const Style&, const Distance&)> swimCallback; std::function<bool(const Speed&, const Distance&)> walkCallback; bool driveHandler(const Action&); bool swimHandler(const Action&); bool undefinedHandler(const Action&); bool walkHandler(const Action&); std::map<Action::Type, bool(Actor::*)(const Action&)> ActionToHandler = { { Action::Type::UNDEFINED, &Actor::undefinedHandler }, { Action::Type::DRIVE, &Actor::driveHandler }, { Action::Type::SWIM, &Actor::swimHandler }, { Action::Type::WALK, &Actor::walkHandler }, }; bool driveHandler(const Action& action) { if (!driveCallback) { return false; } DriveParameters parameters = std::static_cast<DriveParameters>(action.getParameters()); if (!parameters) { return false; } return driveCallback(parameters.getVehicle(), parameters.getSpeed(), parameters.getDistance()); } bool swimHandler(const Action& action) { if (!swimCallback) { return false; } SwimParameters parameters = std::static_cast<SwimParameters>(action.getParameters()); if (!parameters) { return false; } return swimCallback(parameters.getStyle(), parameters.getDistance()); } bool undefinedHandler(const Action& action) { return false; } bool walkHandler(const Action& action) { if (!walkCallback) { return false; } WalkParameters parameters = std::static_cast<WalkParameters>(action.getParameters()); if (!parameters) { return false; } return walkCallback(parameters.getSpeed(), parameters.getDistance()); }public: void connectDriveCallback(std::function<bool(const Vehicle&, const Speed&, const Distance&)> callback) { driveCallback = callback; } void connectSwimCallback(std::function<bool(const Style&, const Distance&)> callback) { swimCallback = callback; } void connectWalkCallback(std::function<bool(const Speed&, const Distance&)> callback) { walkCallback = callback; } bool performAction(const Action& action) { (this->*(ActionToHandler[action.getType()]))(action); }};bool driveCallback(const Vehicle& vehicle, const Speed& speed, const Distance& distance) { std::cout << Vehicle = << vehicle << , Speed = << speed << , Distance = << distance << std::endl;}bool swimCallback(const Style&, const Distance&) { std::cout << Style = << style << , Distance = << distance << std::endl;}bool walkCallback(const Speed&, const Distance&) { std::cout << Speed = << speed << , Distance = << distance << std::endl;}int main() { Actor actor; actor.connectDriveCallback([&](const Vehicle& vehicle, const Speed& speed, const Distance& distance) { return driveCallback(vehicle, speed, distance); }); actor.connectSwimCallback([&](const Style& style, const Distance& distance) { return swimCallback(style, distance); }); actor.connectWalkCallback([&](const Speed& speed, const Distance& distance) { return walkCallback(speed, distance); }); WalkParameters parameters; parameters.setDistance(Distance::METERS, 100); parameters.setSpeed(Speed::KPH, 5); Action action; action.setType(Action::Type::WALK); action.setParameters(parameters); actor.performAction(action);}
Call Specialized Callback from Generic Object
c++;c++11;callback
null
_webapps.87046
I want to extract friend's caller Id picture which I had on my Android phone, and synced with my Gmail account. However I lost my phone. Now the Gmail contact is showing the caller Id picture, but when tried to save image as... is can save only low resolution thumbnail. Need to know procedure to download or open the actual image with full resolution as was there in phone caller Id.
How to extract caller Id picture from Gmail contacts?
gmail;google contacts
null
_unix.350301
I've a very specific question about fork system call. I've this piece of code:int main (void) { for (int i = 0; i < 10; i++) { pid_t pid = fork (); if ( !pid ) { printf(CHILD | PID: %d, PPID: %d\n, getpid(), getppid()); _exit(i + 1); } } for (int i = 0; i < 10; i++) { int status; waitpid(-1, &status, 0); if (WIFEXITED(status)) { printf(IM %d AND CHILD WITH EXIT CODE %d TERMINATED\n, getpid(), WEXITSTATUS(status)); } else { printf(ERROR: CHILD NOT EXITED\n); } } return 0;}which produces this output:CHILD | PID: 3565, PPID: 3564CHILD | PID: 3566, PPID: 3564IM 3564 AND CHILD WITH EXIT CODE 1 TERMINATEDIM 3564 AND CHILD WITH EXIT CODE 2 TERMINATEDCHILD | PID: 3573, PPID: 3564CHILD | PID: 3567, PPID: 3564IM 3564 AND CHILD WITH EXIT CODE 9 TERMINATEDIM 3564 AND CHILD WITH EXIT CODE 3 TERMINATEDCHILD | PID: 3568, PPID: 3564IM 3564 AND CHILD WITH EXIT CODE 4 TERMINATEDCHILD | PID: 3569, PPID: 3564IM 3564 AND CHILD WITH EXIT CODE 5 TERMINATEDCHILD | PID: 3570, PPID: 3564IM 3564 AND CHILD WITH EXIT CODE 6 TERMINATEDCHILD | PID: 3571, PPID: 3564IM 3564 AND CHILD WITH EXIT CODE 7 TERMINATEDCHILD | PID: 3572, PPID: 3564IM 3564 AND CHILD WITH EXIT CODE 8 TERMINATEDCHILD | PID: 3574, PPID: 3564IM 3564 AND CHILD WITH EXIT CODE 10 TERMINATEDwhich makes me wonder how fork really works and what code new processes really execute. Looking at the above output results, I can not understand:How does second for cycle prints before first for finish all iterations? I've also noticed this second for is always executed by parent process, which makes me wonder if while on first for cycle, if pid != 0 (which means parent process calling) second for cycle is executed (?)Why does CHILD processes are not sorted printed by PID?So, bottom line, how does fork really works and who executes what?
How does fork system call really works
c;system calls;fork
When you fork, the kernel creates a new process which is a copy of the forking process, and both processes continue executing after the fork (with the return code showing whether an error occurred, and whether the running code is the parent or the child). This continue executing part doesnt necessarily happen straight away: the kernel just adds the new process to the run queue, and it will eventually be scheduled and run, but not necessarily immediately.This explains both behaviours youre asking about:since new processes arent necessarily scheduled immediately, the parent might continue running before any child gets a chance to run;creation order doesnt have much (if any) impact in the run queue, so theres no guarantee the child processes will run in the order theyre created.
_codereview.153235
I am building a web-application in NodeJS (using TypeScript) and MongoDB (using Mongoose).In my application I have 6 types of permissions. For the simplicity, let's use P1, P2, ..., P6 to represent my permissions. In addition, the application has several organizations.Each user in the application belongs to one organization and can have several permissions (P1-P6) for each organization (not necessarily the one he belongs to).For example: - User U1 belongs to O1 organization, has permissions P1, P3 in organization O1 and permissions P2, P6 in organization O2.- User U2 belongs to O2 organization, has permission P1 in organization O2.- User U3 belongs to O1 organization, has no permissions.I am trying to implement this structure in the user schema (using Mongoose schema) and need some opinions about my implementations.This is my user schema:var userSchema: mongoose.Schema = new mongoose.Schema({ _id: { type: String }, firstName: { type: String, required: true }, lastName: { type: String, required: true }, mail: { type: String, required: true, unique: true }, organization: { // User's organization type: mongoose.Schema.Types.ObjectId, ref: 'Organization' }, permissions: [{ organization: { type: mongoose.Schema.Types.ObjectId, ref: 'Organization' }, permissions: [{ type: String, enum: [ Permission.P1, Permission.P2, Permission.P3, Permission.P4, Permission.P5, Permission.P6, ] }] }]});For the permissions enum I use:export enum Permission { P1 = <any>'P1', P2 = <any>'P2', P3 = <any>'P3', P4 = <any>'P4', P5 = <any>'P5', P6 = <any>'P6',}I use this enum as string values because I think it's better to have the string value of the permission and not just the enum number values (1-6). Of course, the permission names (P1-P6) are replaced with the real permission name - for example, P1 is Administrator.I am not sure about my current implementation and would like to get some opinions whether I am doing good or should I change something.
Implementation of user permissions
javascript;node.js;mongodb;mongoose
null
_softwareengineering.186154
Background / The ProblemI need to make a (large) application with a certain set of core functionality, and certain functionality for multiple clients within it. Each client has different requirements and while they may share some functionality, I need to separate the code for each client, so a change to one won't affect others. Each client section of the application should also inherit some features from the core application. Ideally I would like to separate the databases for each client too. In terms of a user system, core users should be able to have access to each client's functionality, but client users should only be able to interact with their specific client section of the site.Current SolutionEach client has its own subdomain and the MVC can override the core's MVC files IF they exist. In a nutshell, my custom MVC's autoloader checks the client directory for the matching M,V, or C file when a subdomain is present in the URL and loads that particular client's file INSTEAD OF the core file. It's an override ability in a sense.QuestionsAm I solving this problem in a way that would be considered good practice in terms of software design?If I were to use an existing PHP Framework (I would like to), how might I go about setting it up to solve this problem? Specifically I have been looking at Yii and CodeIgniter.Thanks in advance!Update:I have discovered a design pattern called HMVC (Hierarchical MVC) and it seems to be essentially what I have described. I see that Kohana 3 is built using it and that Codeigniter has an extension that allows it.
Possible with PHP MVC Framework? A better solution to client 'override' of core functionality?
php;web applications;frameworks;object oriented design
null
_webapps.24679
Please - what steps should I take to trouble shoot this?I use Pinterest on Google Chrome, on Snow Leopard.It works fine when I access from an Internet cafe.But when I try to connect using my mobile broadband dongle (Huawei e173 on T Mobile in the UK) it doesn't fully load. Everything else (all other websites I try) appears to work fine.See these screenshots - you can see that the pinterest website partially loads, and Chrome thinks it's finished, but there's no content in the main screen. Clearing cache and force reload makes no difference.You can see here that I've selected the architecture category. Normally I'd get lots of pins to look at, but not when I connect via broadband dongle.Please - what steps should I take to trouble shoot this?(There doesn't seem to be anything on the Pinterest support site about this yet.)
Pinterest doesn't load properly when I use a mobile broadband dongle
pinterest
Use HTTPS instead of HTTP to load Pinterest. The certificate will throw warnings but that is because they aren't securing their images.
_codereview.41587
I have a Factory class for a queuing system I'm playing around with.Consuming classes only care that they get a particular interface (Job) as a result of calling the factory's load method. Some Jobs may require a database connection, so I want to inject a PDO instance. Others may require something else, and I don't want to give all Jobs a PDO instance regardless of whether they need it.This is what I've ended up with:IoC class:use Queue\Job\MeterData;use PDO;class IoC{ const DATABASE = 'db'; const METER_DATA_JOB = 'job_meterData'; public function get($item) { switch ($item) { case self::DATABASE: return new PDO(''); case self::METER_DATA_JOB: return new MeterData($this->get(self::DATABASE)); } }}Resulting Queue Factory class:namespace Queue\Job;use IoC;class Factory{ const METER_DATA = 'meter-data'; private $ioc; public function __construct(IoC $ioc) { $this->ioc = $ioc; } public function load($job) { switch ($job) { case self::METER_DATA: return $this->ioc->get(IoC::METER_DATA_JOB); default: throw new \Exception('No job class found for ' . $job); } }}In my mind having the Factory isn't strictly necessary but is advantageous, as I can doc-comment the load method and it will ensure that consuming code knows what type of object it is dealing with. It'll also keep all queue jobs together neatly, rather than having the consuming code access the IoC container directly instead of the more specific Queue Factory.The problem is, if we assume that IoC container is going to be one class for a full application, isn't it going to get very messy very quickly, with a ton of import statements and such?Is that really such an issue, because at least it will be limited to just the IoC container and it will keep the rest of the application clear?
Is this a sensible way of using an IoC container?
php;design patterns;dependency injection
No. What you are doing is called The Service Locator Antipattern. And it's a bad thing.The basic rule of thumb: Don't inject the container!.The IoC container is supposed to be some sort of overseer, wiring your objects together at the bootstrap and configuration level. It isn't an object that's supposed to be injected into other objects, to create objects there.
_unix.105200
it is there any way to run a domain on my router instead of running dyndns or other alternatives (Dynamic DNS) etc. on tomato or dd-wrt firmware ?
Run domain on tomato/dd-wrt
dns
DNSMasq & /etc/hostsTake a look at these instructions from the dd-wrt website. The article is titled: DNSMasq Local Network. This method makes use of the routers /etc/hosts file to act as the master list of name/IP mappings. Depending on your needs this might be a good fit.DHCPThere is also this method discussed in this howtogeek.com article titled: How To Access Your Machines Using DNS Names with DD-WRT. With this method you're using the dd-wrt router's DHCP service to do 2 things for you. One, it will force all the systems that lease IP's from it, to get your LAN's domain name. Second, you can use the router's DHCP server to act as your DNS server as well by adding all the hosts in your LAN to the DHCP table. You're using DHCP, but you're using it to statically assign IP's to the same hosts whenever they join the domain.Which method?Either method will do what you want.If I were you and you have a small domain, I'd go with the DHCP route first.
_webapps.63235
When a Google spreadsheet is displayed in a Google site window, the complete table being displayed moves when the displayed window is scrolled. The top row containing headers moves out of view. This makes it very difficult to understand which column contains what information. How do I freeze the first row of a Google spreadsheet when displayed in a Google site?
Freeze first row of Google spreadsheet when displayed in Google site
google spreadsheets;google sites
null
_unix.174635
I have an rpm that builds two packages. I tried to add separate Prefix tags in the preamble each of the packages. However, as there is one prep section, I am not able to address the prefix each of the packages individually. (%prefix indicates only the Prefix of the subpackage)Is there a way to specify package-specific prefix?
Multiple prefix tags in rpm spec file
rpm;rpmbuild
null
_cs.74165
I understand that many algorithms have space/time tradeoffs-that is, to run faster, you can do things like caching data, which reduces time taken in exchange for space consumed.Given conservation of energy and spacetime equivalence, is there any relationship between the time saved by using extra space and vice versa? After all, extra running time consumes more energy-is this energy equivalent to the energy taken to store the extra data in any way, or the other way around?
Spacetime Tradeoff
time complexity;space complexity
null
_webmaster.85274
In words: I developed a website with MediaWiki 1.22.5 (PHP 5.3.3 (apache2handler), SQLite 3.6.20 with full-text search support) and now it's public through, say, www.example1.com/~myname/mediawiki/index.php/website_name. The website has both a public and a private area (accessible with login).Now, I register the website but under another domain, say, www.example2.com, by making a cross-reference associated with the new domain. The problem is that, if I go on www.example2.com I can surf on the public pages, but not all of them: for instance, when I click on the login button, as well as on the private pages, nothing happens, I just remain on the same page.Any suggestion please?P.S.: Sorry, if I do not provide other info, I'm not an expert in web development, but if you ask to provide more specific info I'll be glad to do it.
Cross-reference to a MediaWiki website's URL partially not working
web development;mediawiki
Since this is a webmastering site (and not really a site for web development), I'm gonna make a few suggestions that may help from a website troubleshooter perspective:Check the cookies. If on the original site, cookies are attached to the domain and you move the site from domain to domain, then no login information will be saved. Here's an example of a cookie header outputted from a site:Set-Cookie: A=1;path=/;domain=www.example1.com;expires=Thu, 22 Oct 2015 21:30:27 GMTIt sets a cookie with a name A equal to 1 on www.example1.com anywhere on the site starting at the root folder and the cookie expires on October 22nd.If this was outputted when a page is requested from www.example2.com then the cookie wouldn't apply because the domains do not match.See https://www.ietf.org/rfc/rfc2109.txt for more info on how cookies should be setup for proper operation.The next thing you need to do is check all hyper links in your HTML that you output. All absolute URLs must be updated. For example, if your HTML initially contained this:<a href=http://www.example1.com/something>Do something</a>Then you'll need to change it to:<a href=http://www.example2.com/something>Do something</a>
_webmaster.95539
I have a small site representing a software hosted on github.io domain. I use Google Analytics. For the last week or so, I get this statistics at the user acquisition tab: VisitsDirect 96Social 10Organic Search 4 Referral 4 But I'm quite sure I'm getting most traffic from other sites, mostly the project repository on github.com. I think I am doing something wrong when working with the data. How do I see where the people came from and how many?
According to Google Analytics 80% of my visitors are direct, but I suspect that isn't true, what can I do?
google analytics;traffic;referrer
I guess your website is not https and since most traffic comes from github.com, which has https, the referrer will not be set.You can read it on the RFC pageA user agent MUST NOT send a Referer header field in an unsecured HTTP request if the referring page was received with a secure protocol.
_webapps.43423
Okay, so our school gave everybody a Gmail account, and everybody chatted on it when we were supposed to be working. One day we went on gmail and everybody's chat is gone completely. We all think its the School that went into our accounts and turned it off. So my question is, How do you turn it back on?!
Gmail Chat How to turn it on
gmail;chat
null
_codereview.111957
It is common to shorten city names when writing, or at least in Sweden.Gteborg (Gothenburg) is often referred to as GbgUddevalla is commonly written as UaTrollhttan is often written as Thn...and a whole lot of other city names are often shortenedUddevalla could also be shortened as Uva, Uvalla, or even Udl (although I've never seen anyone actually type that, according to my rules here it would be allowed). vd however would not be allowed as the letters must appear in order, dv would be allowed as an abbreviation for Uddevalla as v comes after d.Given a list of cities (or more generally: Strings) and a search string, print the city names that can be constructed by using these abbreviation rules.Example cities (my townnames.txt file):StrmstadSkeeverbyTanumRabbalshedeHllevadsholmDingleMunkedalUddevallaLjungskileSvenshgenStenungsundStora HgaKodeYtterbyGteborgTrollhttanVnersborgVarbergStockholmSimrishamnThese are cities in Sweden, mostly in around my area. With the above list and the search string Sm the following cities are printed:[Strmstad, Stockholm, Simrishamn]Instead given the string Vbg the results are:[Vnersborg, Varberg]After looking at the review I got from my previous Haskell question I wrote the following code to accomplish this:module Main wherenameMatch :: [Char] -> [Char] -> BoolnameMatch [] [] = TruenameMatch s [] = FalsenameMatch [] s = TruenameMatch search@(s:restSearch) (c:city) | c == s = nameMatch restSearch city | otherwise = nameMatch search citymain = do putStrLn Loading list of towns... text <- readFile townnames.txt putStrLn Enter search phrase: search <- getLine let cities = lines text putStrLn $ show $ filter (nameMatch search) citiesAny possible improvements or suggestions welcome.
Vc as in Vancouver, or Valencia?
beginner;strings;haskell;search
null
_unix.303279
lshw and df -h see a different partition size (5.5 TB vs. 200 MiB) for one of the partitions of my computer (Ubuntu 14.04.4 LTS x64). I'm pretty sure df -h is right, as when I created the partition with parted, I configured the partition to be of size 5.5 TB. (here are the instructions I used to create the partition if it matters). Also, I tried to place more than 200 MiB of files in that partition and it worked fine.How comes lshw doesn't seem the same size as df -h?Below is the output of the two commands (the partition in question is /dev/sdb1, mounted to /crimea)username@server:/crimea$ df -hFilesystem Size Used Avail Use% Mounted onudev 63G 12K 63G 1% /devtmpfs 13G 1.7M 13G 1% /run/dev/dm-2 923G 54G 823G 7% /none 4.0K 0 4.0K 0% /sys/fs/cgroupnone 5.0M 0 5.0M 0% /run/locknone 63G 0 63G 0% /run/shmnone 100M 0 100M 0% /run/user/dev/mapper/vg_system-openafs 2.9G 49M 2.7G 2% /var/cache/openafsAFS 2.0T 0 2.0T 0% /afs/dev/sdb1 5.5T 58M 5.2T 1% /crimeausername@server:/crimea$ sudo lshw -C volume *-volume:0 description: LVM Physical Volume vendor: Linux physical id: 1 bus info: scsi@0:0.0.0,1 logical name: /dev/sda1 serial: S3pp6Q-ZaaU-1Y3I-DE05-0cdd-xYZZ-4WvaKP size: 953GiB capabilities: multi lvm2 configuration: name=primary *-volume:1 description: BIOS Boot partition vendor: EFI physical id: 2 bus info: scsi@0:0.0.0,2 logical name: /dev/sda2 serial: ce1dec5b-2888-49fd-a770-1f159765f7c5 capacity: 1023KiB capabilities: nofs configuration: name=primary *-volume description: EXT4 volume vendor: Linux physical id: 1 bus info: scsi@1:0.0.0,1 logical name: /dev/sdb1 logical name: /crimea version: 1.0 serial: c3552308-705b-99db-9855-8e456c96a1ce size: 200MiB capacity: 5589GiB capabilities: journaled extended_attributes huge_files dir_nlink extents ext4 ext2 initialized configuration: created=2016-06-24 14:56:55 filesystem=ext4 lastmountpoint=/boot modified=2016-07-01 17:15:55 mount.fstype=ext4 mount.options=rw,relatime,data=ordered mounted=2016-07-01 17:07:19 name=primary state=mounted
lshw and df see a different partition size (5.5 TB vs. 200 MiB). Why?
partition;disk usage
null
_ai.2482
I remember reading or hearing a claim that at any point in time since the publication of the MNIST dataset, it has never happened that a method not based on neural networks was the best given the state of science of that point in time.Is this claim true?
Neural Networks unmatched on MNIST?
neural networks;history
null
_unix.172514
I want to mount a NFS file system with user/group ownership of <admin> . How it can be done ? mkdir /certchown admin.admin /certmount -t nfs 192.168.2.149:/portalweb /cert/
Mounting a NFS file system by changing default owner
linux;permissions;mount;nfs
Create user and group admin with non-interactive shell on NFS server, assuming that admin user and group exists in nfs client. The non-interactive shell option will prevent admin at NFS client from gaining access to NFS server. It works, because nfs maps uid and gid of server with its clients, so any file permissions assigned to the exported directories will remain intact as long the uid and gid matches between the server and client for admin user and group. ACL is an nfsv3 specific option.Note down the admin uid and gid (primary) in client machine and use it to create an account in NFS server. For example uid|gid of admin in client machine = 502NFS Server:As root user:useradd -u 502 -s /sbin/nologin adminmkdir /portalwebchmod 770 /portalwebchown admin /portalwebchgrp admin /portalwebls -ld /portalwebgetfacl /portalwebYou can allow collaboration among admin group members through setgid bit placed on /portalweb directory.vim /etc/exports /portalweb 192.168.2.149(ro,sync,root_squash):wqexportfs -rvNFS Client:As root user:mkdir /certvim /etc/fstab192.168.2.149:/portalweb /cert nfs ro,nfsvers=4 0 0:wqmount -adf -h -F nfsmount | grep nfs 192.168.1.71:/exports on /cert type nfs (r0,nfsvers=4,addr=192.168.2.49,clientaddr=192.168.2.50)Root user cannot access the files in /cert, because root has been squashed to user and group: nobody (see /etc/exports on NFS server). But root has the privilege to mount the NFS exports on the client machine, by default. If you prefer to use autofs service, normal users like admin do not have privilege to set automounting NFS directories using autofs service, unless they have been given special administrator privileges as like sudo users.ls -ld /cert drwxrwx---. 12 admin admin 4096 Dec 10 /certls /cert ls: cannot open directory /cert: Permission deniedsu - adminAs admin user (only admin user (or admin group if properly configured with uids matching between client and server) can access the /cert contents):ls /certAs any other user:ls /cert ls: cannot open directory /cert: Permission denied
_reverseengineering.4513
I'm analyzing an rather ancient 3D mesh format (from 1995 or 1996). Inside the files, there are blocks of what I think are vertices.For example, the following is a direct hex dump from such a part:7855DAFF5BE60E00353D0200C82D0B005BE60E00353D0200C82D0B005BE60E00B61AEDFF7855DAFF5BE60E00B61AEDFF7855DAFF59D2FDFF363D0200C82D0B0059D2FDFF363D0200C82D0B0059D2FDFFB61AEDFF7855DAFF59D2FDFFB61AEDFFThese blocks are introduced by a little header, which has a value that could be the number of vertices that are present in the corresponding data block. For this excerpt, there is a 0x08. Since we have 24 values of 32bit, I think it is safe to assume that these blocks are actual vertices (0x08 * 3 = 24, with xyz). Other headers also have this value and their data blocks also have the exact number of dwords ([value in header] * 3 => number of dwords).But, now I'm struggling at deciphering the number format that was used. It isn't IEEE754; a friend of mine also pointed out that the hardware that was used these days didn't perform well with floating-point numbers and therefore often fixed-point numbers where used.So, any idea what kind of format this could be ?
Ancient number formats (probably fixed-point)
binary analysis;file format
if you reverse the byte order, and assume signed numbers you get these triplets:-2468488 976475 146741 732616 976475 146741 732616 976475 -1238346-2468488 976475 -1238346-2468488 -142759 146742 732616 -142759 146742 732616 -142759 -1238346-2468488 -142759 -1238346these seem like the coordinates of the corners of a 3d cube x=(-2468488 .. 732616)y=( -142759 .. 976475)z=(-1238346 .. 146742)
_opensource.1134
While driving in the car recently I noticed a Google Streetview car go by outside. Once I got home I went onto Google Streetview and looked around for a bit. This is when I noticed the copyright notice:My question:How is Google able to take photos of already possibly copyrighted/licensed objects, and how is it that they are able to relicense it?
How is Google able to relicense their photos on Google Streetview, which may contain copyrighted content?
licensing;copyright
Photography is a lovely thing. I can take a picture of my school, from one angle, and it will be my own work. Also, someone else can take a picture of my school, from the same angle, and it will be their work. Really, it depends on who clicked the button. Take this for example: This is my shot, and I totally reserve all rights Darn user contributionsSourceI'll tell you right now, they are the same model (Airbus A330), same location (Amsterdam Schipol), same a lot of things. But the works are distinct, in that I took the shot on top, and someone else took a shot on the bottom.When people apply licenses to their photographic work, it is normally only to their work, not the object that they took a picture of. Hence, if you were to open source the road, and I take a picture of the road, then the picture will be my work, and under full copyright.Therefore, Google doesn't really need to do much. Many things that Google blurs out is for privacy reasons, if I walk beside a street view car, they'll have to blur out my face. So, if there is any issue, they simply blur it out.The pictures that Google takes is their own work. Therefore, they are able to license/place a full copyright... etc. And because the photos belong to Google, they are able to do whatever they want, regardless of whether a similar shot has been taken.Bottom Line:Google is able to relicense these works because the photos belong to them. Since it is their own work, they are able to do whatever they would like with it.
_codereview.111619
This is purely testing my skills; I am not actually coding for a bank. This is part of a bank account class.public void withDraw(double amount) { if(balance - amount >= odLimit) { balance -= amount; } else { Console.WriteLine(Error. Withdrawing will take you below overdraft limit. Enter a new amount: ); double amount2; while (!double.TryParse(Console.ReadLine(), out amount2) || (balance - amount2 < odLimit)) { Console.WriteLine(Enter a valid number: ); } balance -= amount2; } }odLimit is the overdraft limit. The code checks if the balance - amount is greater than or equal to the odLimit (say -900), and if so, it simply takes that money from the account. If that's not the case then it keeps asking the user to enter an amount they wish to withdraw, and when they enter a value that won't take the account below the overdraft limit and is a double.Just checking that this is the most efficient way to do this. I prefer minimum lines of code.Also in the main program class. Would you find it more efficient to create a menu function and call the withDraw function from the menu using a switch statement within the menu, or call a method in the program class from the switch statement that asks the user for their value, and then calls the withDraw function in the bank account class?
Checking if a user can withdraw money
c#;object oriented;validation
null
_webmaster.59504
Bought a Godaddy doman and redirected & masked it (301) to a temporal free hosting site(freehostingeu), the redirection and masking works perfectly but the URL of the various pages in my server's folder doesn't show in the nav bar when I click a link that sends me to that page.
Godaddy redirect doesn't show file names in URL
redirects;301 redirect;godaddy
null
_cs.10131
From my recitation class - Can you please explain why does operator $+$ signature is $ int \rightarrow (int \rightarrow int)$ ?How does this graph is build ?And what is mean $t=u \rightarrow s$ ?Thanks in advance .
ML - Type Interface
programming languages;functional programming;type inference;type checking
ML functions take a single argument. There are two common techniques to pass two arguments to a function.One is to create a pair (2-tuple) p = (x, y) and apply the function to the pair; the type of the function is then ('a * 'b) -> 'c.The other approach is to make a function that takes one argument and returns a function that receives the second argument and does the work. This approach is what is done for + here and is called currying. The function then has the type 'a -> ('b -> 'c). Since this is common, the -> operator on types is chosen to be right-associative, so 'a -> ('b -> 'c) can be written 'a -> 'b -> 'c.The graph, and the derivation on the left, present a simple approach to ML type inference by unification. The first steps are with the atomic subexpressions: 2 : int, + : int -> (int -> int), and so on. Next, building on, we have the subexpression plus 2, which is an application; the types of + and 2 must be unified with $p \to q$ and $p$ for some $(p,q)$, which leads to $p = \mathrm{int} \to \mathrm{int}$ and $q = \mathrm{int}$ and the type of (plus 2) is $\mathrm{int}$. The derivation on the left shows the type inference for $(\lambda x. ((+ \: 2) \: x))$ from the types of $(+ \: 2)$ and $x$.The graph represents the unification steps (with some trivial steps for atomic subexpressions omitted). Four variables $r$, $s$, $t$, $u$ are created to designate the type of each of the non-atomic subexpressions. The straight lines show the expression tree. The curvy line links the occurrence of the variable $x$ with its binding site.
_unix.226576
In order to install a service on Ubuntu 14.04 like openemm I have created a user name and group:sudo sudo useradd openemm -m -G openemm -d /home/openemmNow I want to login with that usernamesu openemmUnfortunatelly the system asks me for a password which I have never set:Password: su: Authentication failureIs there a default password? If not, how do I switch to that user in order to start the servicesu - openemmopenemm.sh startThank you for any help on this.
What is the default password on ubuntu for users created with useradd?
ubuntu;authorization
null
_unix.253163
Right now I can't access HTTPS site from PhantomJS headless WebKit browser because of TLSv1.2 In my CentOS 5.8 I have following OpenSSL 0.9.8e-fips-rhel5 01 Jul 2008 verison installed.I think I need to upgrade my OpenSSL lib in order to support TLSv1.2. Am I right ? If so, could you please show me an example how it can be achieved ?
TLSv1.2 support in CentOS 5.8
centos;openssl;ssl
You have to build OpenSSL manually - https://miteshshah.github.io/linux/centos/how-to-enable-openssl-1-0-2-a-tlsv1-1-and-tlsv1-2-on-centos-5-and-rhel5/
_webmaster.42622
I recently decided to leave GoDaddy in choice of NameCheap as my preferred hosting package for my mothers business, I also had to bring my domain name to the guys i register my local domain names.Once I had finally gotten control of my domain name I changed the DNS settings and set up the hosting package and waited for the domain name to resolve.. 24/48 Hrs (as I wasn't in a big rush) later I went back to check and found it had finally resolved.I then uploaded the old site that used to be hosted with godaddy via ftp to my nameCheap server... However once I had done this I decided to search for my mums business on Google and found it looked like thisSo I logged into ftp and found the cgi-bin and deleted it thinking that was the problem.. but still no luck. If you click the link it takes you to index.html perfectly... its just in the search result I have this weird erro, any idea how to fix would be greatly appreciated.
Google search showing Index of /. cgi-bin/
google;html;google search;namecheap
That means you didn't have a valid index file last time google crawled your site and /. cgi-bin/ was accessible without an index file itself. That should sort itself out with no problem as long as the public html folder has a valid index file.
_unix.339463
I have seen the following install command used in multiple yocto recipes install -d ${D}${libdir}I am aware of the install command and its purpose, however I am unable to understand the purpose of ${D} variable as it is often nowhere defined in the recipe. Can somebody explain the purpose of this shell variable?
${D} variable in install command
compiling;yocto
The ${D} variable allows the software being built to be installed in a directory other than its real target. For example, you might configure the software so that libdir is /usr/lib, but that's for the target device; when you run the installation on your build system, you don't want the newly-built files to actually be installed in /usr/lib, you want the placed somewhere isolated so that they can be readily identified and copied across to the target system. So you create a temporary directory and install there:mkdir /tmp/yocto-targetmake install D=/tmp/yocto-targetThat way the files end up in /tmp/yocto-target/usr/lib and so on. You can then archive all of /tmp/yocto-target using whatever tool you prefer, dropping the /tmp/yocto-target prefix, copy the archive to the target device and install its contents there.In other build systems, the DESTDIR variable is used for the same reason.
_unix.330302
I have a file that contains:1 1 1 1 text17 9 4 2 text22 2 0.5 0.7 text35 4 1 2 text4I want to sort it (output to the terminal) according to the maximum of the first two columns.expected output:1 1 1 1 text12 1 0.5 0.7 text35 4 1 2 text47 9 4 2 text2how can this be achieved? thanks!
sort by the maximum of the first two columns
scripting;terminal;sort
Your input file is:1 1 1 1 text17 9 4 2 text22 2 0.5 0.7 text35 4 1 2 text4With this input a simple sort will work:$ sort << EOF> 1 1 1 1 text1> 7 9 4 2 text2> 2 2 0.5 0.7 text3> 5 4 1 2 text4> EOF1 1 1 1 text12 2 0.5 0.7 text35 4 1 2 text47 9 4 2 text2If we amend the input to something like...$ cat test.txt1 3 1 1 text17 9 4 2 text22 1 0.5 0.7 text35 4 1 2 text4Then the input becomes challenging. A simple sort no longer works, and we can test other approaches:$ sort -k1,1n -k2,2n < test.txt1 3 1 1 text12 1 0.5 0.7 text35 4 1 2 text47 9 4 2 text2This isn't what we'd expect - The first two lines of output are reversed - the highest 1/2 column value in line 1 is 3, and the highest in line 2 is 2.The following appears to work, at least for the revised input file, but it's not pretty (my awk-fu is weak):$ awk '{ sorton=$1; if ($2>$1) { sorton=$2 }; print $1, $2, $3, $4, $5, sorton }' < test.txt | sort -k 6 | cut -d -f 1-52 1 0.5 0.7 text31 3 1 1 text15 4 1 2 text47 9 4 2 text2@Nominal-Animal and @JJoao suggested refinements, resulting in:$ awk '{ k= $1>$2 ? $1: $2 ; print k, $0 }' test.txt | sort -g | cut -d ' ' -f 2-2 1 0.5 0.7 text31 3 1 1 text15 4 1 2 text47 9 4 2 text2(Feel free to edit this post to refine an awk solution.)
_unix.168457
I want to clean cruft from my Oracle Linux server. For this, I need to know which application or directory isn't used or is hardly ever accessed. Is there any command or way to list directories or applications that meet those criteria.
How to list down all useless or less used files or application in my linux server?
command line;command history;oracle linux;disk cleanup
null
_unix.131904
I have a bash script, in which I call function in a background:process_manager $1 $2 $3 &The function runs / executes commands that are passed as an argument in the background.How can I get a list of child processes in the function process_manager ?I tried doing that:process_manager () { count=$1 interval=$2 cmd=$3 bash_pid=$$ last_pid=$! echo bash_pid: $bash_pid, ppid: $PPID, last_pid: $last_pid $cmd & $cmd & sleep 30 &}process_manager $1 $2 $3 &process_manager $1 $2 $3 &process_manager $1 $2 $3 &But here function process_manager won't display $! or $last_pid when its called for the first time.How should I get $last_pid in that situation and to be able to access children process list?
getting list of children processes by a background shell function
bash;shell script
$$ contains the pid of the shell that was executed to interpret the script. It's the same in every subshell of that shell.$! contains the pid of the last child command run in background (with & or coproc or process substitution)In the command run itself in background, $! it not set. $! is meant for the parent so it can wait or kill its child.bash has a $BASHPID variable that contains the pid of the current subshell.It's not always clear what process it is.In:echo $BASHPIDIt's the pid of the process that interpreted that echo command, but in/bin/echo $BASHPIDwhich does fork a process, $BASHPID does not report the pid of that forked process but the pid of the parent. While in:/bin/echo $BASHPID &(the only difference being that the parent doesn't wait for its child), $BASHPID reports the pid of the forked process:$ bash -c 'echo $$; echo $BASHPID; /bin/echo $BASHPID; /bin/echo $BASHPID &'3264326432643266In you case though, you can safely do:process_manager () { pid_of_last_command_run_in_background=$! mypid=$BASHPID cmd & cmd1pid=$! cmd & cmd2pid=$!}$pid_of_last_command_run_in_background will be the pid of the last command run in background (by the current subshell, or its parent or its grandparent). That's why you get something in $last_pid in the second run (the pid of the previous process_manager) and not in the first.
_scicomp.21488
I am in the process of implementing adaptive mesh refinement for a finite element code that solves the Poisson equation. I have had some trouble finding good references on deciding which elements to refine. I have come across the Kelly error estimator from the deal.ii library:\begin{equation} \eta^{2} = \Sigma_{F\epsilon{}\partial{K}}C_{F}\int_{\partial{K}_{F}}(\nabla{u_{h}}\dot{}n)^{2}do\end{equation} I have two questions about using this error estimator:1) My first question is about how to solve this integral. Let me run through what I am currently doing. Consider the triangular element: where $u_{1}$, $u_{2}$, and $u_{3}$ is the approximate solution at each node, i.e. $u_{h} = [u_{1},u_{2},u_{3}]$. Now to solve this integral over the first face $F_{1}$, i.e.:I calculate $(\nabla{u_{h}}\dot{}n)^{2}$ as:\begin{equation} (\nabla{u_{h}}\dot{}n)^{2} = [(u_{1}\frac{\partial{N_{1}}}{\partial{x}} + u_{2}\frac{\partial{N_{2}}}{\partial{x}} + u_{3}\frac{\partial{N_{3}}}{\partial{x}})n_{x} + (u_{1}\frac{\partial{N_{1}}}{\partial{y}} + u_{2}\frac{\partial{N_{2}}}{\partial{y}} + u_{3}\frac{\partial{N_{3}}}{\partial{y}})n_{y}]^{2}\end{equation}where for the linear triangle $\frac{\partial{N_{1}}}{\partial{x}}$, $\frac{\partial{N_{2}}}{\partial{x}}$, $\frac{\partial{N_{3}}}{\partial{x}}$, $\frac{\partial{N_{1}}}{\partial{y}}$... are all constant. Thus to calculate $\eta$ I first parameterize face 1 using:\begin{equation} x = x_{1}(1-s) + x_{2}s\\ y = y_{1}(1-s) + y_{2}s\end{equation}I can then calculate the line integral as (for face $F_{1}$):\begin{equation} \int_{0}^{1}(\nabla{u_{h}}\dot{}n)^{2}\sqrt{(dx/ds)^{2}+(dy/ds)^{2}}ds =(\nabla{u_{h}}\dot{}n)^{2}\sqrt{(x_{2}-x_{1})^{2}+(y_{2}-y_{1})^{2}}\end{equation}where again for linear triangles $(\nabla{u_{h}}\dot{}n)^{2}$ is constant. My first question is whether this how we correctly calculate this line integral on each face?2) Assuming that I am indeed calculating $\eta^{2}$ correctly, how do we use this to determine which elements should be refined? Do you find the maximum $\eta^{2}$ and then just refine only elements that are a certain percentage of the maximum?
Using finite element error estimators for adaptive mesh refinement
finite element;adaptive mesh refinement
As mentioned in a comment below the question, the formula you state is incorrect: it should read \begin{equation} \eta^{2} = \Sigma_{F\epsilon{}\partial{K}}C_{F}\int_{\partial{K}_{F}}([\nabla{u_{h}]}\dot{}n)^{2}do\end{equation} where $[\cdot]$ is the jump of the quantity across the face.Now for your question:Because for linear elements, the gradient is constant. Consequently, if you integrate over a single face $f \subset \partial K_F$, you have that\begin{equation} \int_{f}([\nabla{u_{h}]}\dot{}n)^{2}do= ([\nabla{u_{h}]}\dot{}n)^{2} \int_{f}do= ([\nabla{u_{h}]}\dot{}n)^{2} |f|.\end{equation} You use the error indicators computed for all cells to identify, for example, the 30% of cells with the largest indicators and then refine these. Alternatively, you can identify those cells with the largest indicators that together amount for 90% of the total error. Take a look, for example, at the documentation of the functions here: https://www.dealii.org/developer/doxygen/deal.II/namespaceGridRefinement.html#ad3b68e645838ebeb4f9c55352b56a0b3
_unix.308896
How do I (recursively) detect all symlinks in a directory that identify their target in an absolute as opposed to in a relative way?Since these links are very likely to break when an entire directory tree is moved I would like to have a way of identifying them.Even relative links may break if the directory tree is moved (if they happen to point outside the root of the directory tree), but I think this is addressed in this question.
Find all absolute links in a directory tree
symlink
To find absolute links, you can use find's -lname option if your find supports that (it's available at least in GNU find, on FreeBSD and macOS):find . -type l -lname '/*'This asks find to print the names of files which are symbolic links and whose content (target) matches /* using shell globbing.Strictly speaking, POSIX specifies that absolute pathnames start with one / or three or more /; to match that, you can usefind . -lname '/*' ! -lname '//*' -o -lname '///*'On what systems is //foo/bar different from /foo/bar? has more details on that.(Thanks to Sato Katsura for pointing out that -lname is GNU-specific, to fd0 for mentioning that it's actually also available on at least FreeBSD and macOS, and to Stphane Chazelas for bringing up the POSIX absolute pathname definition.)
_codereview.85471
I have created JavaScript code using REST API for getting the username of a SharePoint user from an active directory if you know the ID. Please suggest any improvements.// get user name from idfunction getUserFromId(userid) {// var userid = _spPageContextInfo.userId; var requestUri = _spPageContextInfo.webAbsoluteUrl + /_api/web/getuserbyid( + userid + ); var requestHeaders = { accept: application/json;odata=verbose }; $.ajax({ url: requestUri, async: false, contentType: application/json;odata=verbose, headers: requestHeaders, success: onSuccess, error: onError }); function onSuccess(data, request) { var Logg = data.d; userLoginName = Logg.Title; } function onError(error) { alert(error); } return userLoginName;}
Get username from active directory if you know active directory Id in SharePoint
javascript;rest;sharepoint
null
_softwareengineering.90803
Imagine a system which has a number of functions and a number of users. A user must have rights to a specific function. Users may belong to a group. A group may belong to a group.So as a simple illustration, user A has rights to function 1 and 2. User b has rights to function 2 and 3.User A is in group1 which has rights to function 3, but negative, i.e. explicit denied access to function 1.For extra complexity, perhaps the function has default rights. So you can say, but default everyone has access to function a, or no one has access to function a. I guess it's the same as having an Everybody group.So the question is how are you managing user rights? Do you make all rights additive? Do you allow the explicit denied I mention at the end? Do you have a system where the most access possible is granted or the least? Do you make user rights trump group rights, or vice versa?I've seen a number of variations for applying rights. I'm now defining my own and I'm really looking for any experience you have in that area where you wish you'd done something different, or were delighted you chose a particular way of doing things.Thanks
Coding user rights
access control
Do you make all rights additive? Do you allow the explicit denied I mention at the end? Do you make user rights trump group rights, or vice versa?These are really requirements questions. Talk it over with whoever owns the project and discuss the implications with them, then code what you and they decide is best for the project.Do you have a system where the most access possible is granted or the least?This is easier to give a solid answer to. The Principle of Least Privilege states that the system is most secure when no one has access to anything they don't actually need. This is a pretty well-understood principle that's been tested in real-world security for decades, and it makes a good guideline to go by.
_cs.11803
I am trying to understand an algorithm presented in Using Stable Communities for Maximizing Modularity by S. Srinivasan and S. Bhowmick, along with its complexity results. (The complete algorithm is presented on page 7, in pseudocode.)As I understand it, the idea of the algorithm is to identify densely connected communities (basically, subgraphs) in a graph, such that any subset of vertices in the community has more connections (that is, edges pointing to another vertex) inside the community than to any other community in the graph.Below I've cited the part of the algorithm I'm having trouble with:For all vertices v_i in network N that are not in any stable community Create a subset S of v_i and its neighbors For each neighbor n_j ... Identify y_j, the subset of external neighbors which are all within distance k of each otherI take external neighbors to mean the neighbours of $n_j$ that aren't in $S$, and where the distance between them is also never measured through $S$ (as otherwise, they would never be more than two hops apartthrough $n_j$).The authors state the following about the complexity of this part:...the average degree of a vertex is $d$......the complexity for computing $y_j$ for all possible values of $k$ is $O(d^3)$.On the next page, the authors make some more statements about the complexity of this part, including that the values of the shortest paths between external vertices can be reused for many neighbours and that setting $k$ to small values (24) is sufficient in most cases. I'm not sure if these considerations are already factored in, however I'm a bit stuck on all possible values of $k$ in the above quotation.My question is: what assumptions are necessary for the complexity result $O(d^3)$ to hold, with $d$ being the average degree of a vertex? How is the subset found in this case?
Complexity of finding a subset of vertices within distance k of each other, given a set of vertices
graph theory;time complexity
null
_vi.7922
I work a lot with visual block mode, which I find really useful for quick changes across a lot of lines.But something I'm struggling to do is inserting a newline like so:Selection is noted as []:Some [t]extSome [t]extSome [t]extSome [t]extSome [t]extI press I and I can add some text to be inserted before the t:Some other textSome [t]extSome [t]extSome [t]extSome [t]extWhen I press <Esc> I get the following:Some other textSome other textSome other textSome other textSome other textBut now if I press <CR> instead of the text I want to add, the newline is inserted as desired but not for the other lines. The result is the following:Some textSome textSome textSome textSome textDo you know why this isn't working?Note: since it works for c and r I'm not sure why is this not working...
Visual block insert new line
insert mode;visual block
Visual block I doesn't work like that. The best you can probably do is something like the following.Highlight a column in visual block mode (with [b] denoting a highlighted character as in your question):aaa[b]bbaaa[b]bbaaa[b]bbaaa[b]bbccccccPerform a substitution on the visual area with \%V::'<,'>s/\%V/\r/Vim will insert the '<,'> for you when you press :, so you don't need to type that bit.And the result:aaabbbaaabbbaaabbbaaabbbccccccIf you need to split lines at a visual block often, chances are it'll be readily available in your history, and you may not need to do any more than highlight, then :<up><return>.
_softwareengineering.271991
What is the best practice for that prevents the backlog from becoming a mess, but also maintaining developer productivityWho should we allow to add stories to the product backlog? And how do you make sure these stories meet certain requirements? For example I find a few small css bugs during the development of Feature X. Should I then as a developer be allowed to add a story describing the bugs to the bottom of the backlog? Or should I discuss it with the product owner?Having all ideas/bugs go through the product owner sounds like possible bottleneck.
Who should be allowed to add stories to the product backlog?
scrum;product owner;product backlog
The usual approach is that anyone can add stories to the backlog. The product owner prioritizes them and the team estimates them. Story quality issues generally get taken care of one way or another in planning meetings or retrospectives.That means the product owner isn't a bottleneck as long as you're satisfied with the priorities he's assigning. Otherwise, make your case.
_softwareengineering.345378
If the question title was a little too vague or confusing, I'm talking about something reminiscent of the Mindstorms NXT/EV3 IDEs. But the code editor, instead of having prefabbed generic blocks to work with, would use just boxes with code inside of them that links to other code.I'm interested how this implementation might be accomplished because I don't know many languages that can be used like this.
Would an IDE with a flowchart view be practical?
ide;flowchart
This can work and this could be a terrible idea and it really depends on what you're trying to achieve. Positive example: Arena is a simulation software that uses predefined blocks to create new simulations. This works great since the constructs are similar between any two simulations and working with a graphical tool is beneficial for that kind of work. Negative example: I have developed software using a proprietary software created in an organization I worked at. You could write your on code, define it as a block, and then wire blocks together through a GUI. Although this sounds good in principle there were a lot of issues, I'll write some of them here to let you get the feeling of how something like this could go horribly wrong:You had to derive from a base class of the framework so the framework would recognize your class as a block. This created a dependency and made it such that you couldn't derive from any other class To control the data flow, the data passed between blocks had to be a wrapper of the framework. Meaning that you couldn't pass the objects themselves but their wrapper (we also had type safely issues since these were not considered in the framework design) The framework created the blocks using reflection (so it could wire the data and pass it around) , this meant that the ctor had to be default and there was no good way of creating a class. Data sent from a block went to all those blocks connected to it. This created a problem where you would like to send some data to some blocks, but not others. Testability became an issue, both integration tests (since creating the system is something that the framework has done) and since that blocks were isolated (the framework was the one did the wiring) It was difficult to navigate the code (since block wiring was done in the framework configuration) This made IOC and dependency injection a nightmare since an application built with an IOC has one composition root, meaning one block. Changing the system so that it would work after the framework lost support was a nightmare (due to the above reasons).
_unix.61830
On my current Debian setup, I have a file /var/log/mail.log which Dovecot, Postfix, and Spamassassin's spamd all output messages to. I know that the logger command can output to syslog, but is there some command that easily lets me output to the mail log from a bash script, or do I have to manually open it and append to it?
How to log output to maillog?
bash;logs;email;logger
null
_codereview.125498
My team has developed an API and I've been tasked with creating an authentication layer that allows partners' applications to consume it. To that end, I've created a data store which houses an Application ID, Login and salted/hashed Password for that application to authenticate against. I want to hand back a Token for them to use (which is a key for session information that is kept on the server). The process to generate the Token is below. I have another process which reverses this to validate its authenticity. It seems to stand up to testing, but I'd like to know if there's anything else that should be done to make this properly secure.private const string Password = nottheactualpasswordthatisused..;private static readonly byte[] _Salt ={ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f};private static async Task<string> CreateSecureSessionTokenAsync(int applicationId, DateTime createDate){ using (var aes = Aes.Create()) { if (aes == null) { return null; } using (var deriveBytes = new Rfc2898DeriveBytes(Password, _Salt)) { aes.Key = deriveBytes.GetBytes(32); aes.IV = deriveBytes.GetBytes(16); } using (var encryptor = aes.CreateEncryptor()) using (var memoryStream = new MemoryStream()) { using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) using (var writer = new StreamWriter(cryptoStream)) { await writer.WriteLineAsync(Convert.ToString(applicationId)).ConfigureAwait(false); await writer.WriteLineAsync(Convert.ToString(createDate, CultureInfo.InvariantCulture)) .ConfigureAwait(false); } return Convert.ToBase64String(memoryStream.ToArray()); } }}
Secure Token for use in API calls
c#;security;api;authentication
null
_unix.385040
I want create a c++ application to send (ie. broadcast) data from one linux machine to multiple linux machines. Assume the linux machines are all under one switch and they are all under the same subnet.I'm seeing that this can be done using UDP multicast similar to Boost ASIO examples. In trying to maximize data throughtput, could I expect better performance using multiple UDP streams?
Better throughput - multicast or multiple UDP streams
linux;networking;c++
Yes, with multicast the data will be sent only once to the switch, which can pass it on to all receivers simultanously. With UDP, data needs to be sent to each receiver individually. So (in theory), max throughput with multicast as n times greater than with singlecast, where n is the number of receivers.Note that both with UDP singlecast and UDP multicast you'll have to deal with dropped packets and resending (unless the data is video/audio where the occasional dropped packet doesn't matter, but then you don't have to implement your own solution, just use a ready-made one), so use the appropriate protocol (PGM, ...).
_unix.53071
I thought I'd switch to zsh, so I did just that with chsh -s /usr/bin/zsh user, unfortunately, it broke my compose key (unresponsive both in the console and in an X terminal); also, when I read email in emacs rmail, Swedish characters are not displayed correctly (diamonds in the console, question marks in an X terminal) - but it is possible to display them, for example if I cat the mail files instead.To possibly reinitialize the compose key, I run setupcon again as superuser but it didn't help. In /etc/default/keyboard, this line is present XKBOPTIONS=compose:lwin,terminate:ctrl_alt_bksp.As for the compose key in X, and the character set in both the console and an X terminal, I'm clueless because I can't remember anytime setting up those things, they just worked.To double check, I switched back to bash with chsh -s /bin/bash user, and everything worked as before. I examined .profile and .bashrc to see if I possibly had done some keyboard/charmap initialization there, but I couldn't find anything to that extent.zsh --versionzsh 4.3.17 (i686-pc-linux-gnu)
zsh broke compose key and special chars
zsh;locale;keyboard layout
Since bash or zsh is in no way responsible for handling the Compose key, what must have broken is your session startup files. Check your ~/.profile or ~/.bash_profile, or /etc/profile, for commands that might have a bearing on the locale setting, such as values for the LANG or LC_CTYPE environment variables. It's likely that your keyboard configuration no longer matches your application's idea of the system character set.You can make zsh read your .profile by putting the following command in your ~/.zprofile:emulate -R sh -c '. ~/.profile'If that doesn't suffice (especially under X), tell us what distribution (e.g. Ubuntu, Fedora, ), what desktop environment (or window manager, e.g. KDE4, Gnome2, XFCE4, ) and what display manager (the GUI program where you enter your user name and password, e.g. GDM, KDM, Lightdm, ) you use.
_cs.75213
Here are the first few stages from the Earley parsing page on wikipedia.S(0): 2 + 3 * 4 (1) P S (0) # start rule (2) S S + M (0) # predict from (1) (3) S M (0) # predict from (1) (4) M M * T (0) # predict from (3) (5) M T (0) # predict from (3) (6) T number (0) # predict from (5)S(1): 2 + 3 * 4 (1) T number (0) # scan from S(0)(6) (2) M T (0) # complete from (1) and S(0)(5) (3) M M * T (0) # complete from (2) and S(0)(4) (4) S M (0) # complete from (2) and S(0)(3) (5) S S + M (0) # complete from (4) and S(0)(2) (6) P S (0) # complete from (4) and S(0)(1)S(2): 2 + 3 * 4 (1) S S + M (0) # scan from S(1)(5) (2) M M * T (2) # predict from (1) (3) M T (2) # predict from (1) (4) T number (2) # predict from (3)I've already got the algorithm written, and debugPrintState seems to be showing the correct Earley states.Here is the code, you can use it if you want:from cf_grammar import ruleSymbols, varNameclass SPPFNode: # Shared Packed Parse Forest stringSpaces = 5 def __init__(self, symbol, input_start, input_end, parent=None): self._parent = parent self._symbol = symbol self._start = input_start self._end = input_end self._children = [] @property def parent(self): return self._parent @property def children(self): return list(self._children) @property def symbol(self): return self._symbol @property def inputStart(self): return self._start @property def inputEnd(self): return self._end def addChild(self, node): if node is not None: self._children.append(node) def insertChild(self, index, node): if node is not None: self._children.insert(index, node) def toString(self, spaces=None): if spaces is None: spaces = 0 space_str = '' for k in range(0, spaces): space_str += ' ' string = '(' + ' + self._symbol + ' + ', ' + str(self.inputStart) + ', ' + str(self.inputEnd) + ')\n' for child in self._children: string += space_str + '|\n' string += space_str + '+--' string += child.toString(spaces=spaces + self.stringSpaces) return string def __str__(self): return self.toString()class EarleyParser: POS, RULE, ORIG, NODE = range(4) dummyStart = '0' def __init__(self, grammar): self._grammar = dict(grammar) self._grammar[self.dummyStart] = None self._state = None self._pos = None self._input = None def parse(self, string, start): assert (len(string) > 0) self._initState(start) self._input = string for k in range(0, len(string) + 1): while True: state_len = len(self._state[k]) for var, states in list(self._state[k].items()): for state in states: if not self._finished(state): if self._nextSymbolIsVar(state): var1 = self._varAtPos(state[self.POS], state[self.RULE]) self._predict(k, var1) elif k < len(self._input): self._scan(k, self._input[k], state[self.NODE]) else: self._complete(k, var, state[self.ORIG], state[self.NODE]) if len(self._state[k]) == state_len: break # If the states in the state set stabilize, then there's nothing more to do if len(self._state) == k: # If no new state set was added break return self._sppForest() def debugPrintState(self, where=None): if where is not None: print(where) for k in range(0, len(self._state)): print('\tS(' + str(k) + '):') for var, states in self._state[k].items(): print('\t\t' + var + ':') for state in states: print('\t\t\t' + str(state)) print('\n') def _sppForest(self): if len(self._state) != len(self._input) + 1: return [] forest = [] state_set = self._state[-1] for states in state_set.values(): for state in states: pos, rule, orig, node = state if pos == len(rule) and orig == 0: forest.append(node) return forest def _predict(self, k, var): rules = self._grammar[var] for rule in rules: symbols = ruleSymbols(rule) self._addState(k, var, (0, symbols, k, None)) def _scan(self, k, a, node): for var, states in self._state[k].items(): for i in range(0, len(states)): state = states[i] pos1, rule1, orig1, node1 = state if pos1 < len(rule1) and rule1[pos1] == a: if node1 is None: node1 = SPPFNode(symbol=a, input_start=k, input_end=k+1) states[i] = (state[self.POS], state[self.RULE], state[self.ORIG], node1) if node is None: node = SPPFNode(symbol=var, input_start=-1, input_end=-1) node.addChild(node1) print('scan: ') print(node) self._addState(k+1, var, (pos1+1, rule1, orig1, node)) def _complete(self, k, var, orig, node): for var1, states in self._state[orig].items(): for state in states: pos1, rule1, orig1, node1 = state var2 = self._varAtPos(pos1, rule1) if var2 == var: node2 = SPPFNode(symbol=var, input_start=-1, input_end=-1) node2.addChild(node) node2.addChild(node1) print('complete: ') print(node2) self._addState(k, var1, (pos1+1, rule1, orig1, node2)) def _finished(self, state): if state[self.POS] < len(state[self.RULE]): return False return True def _addState(self, k, var, state): if var != self.dummyStart: if k >= len(self._state): self._state.append({}) if var not in self._state[k]: self._state[k][var] = [state] else: for state1 in self._state[k][var]: if state1[self.POS] == state[self.POS] and \ state1[self.RULE] == state[self.RULE] and \ state1[self.ORIG] == state[self.ORIG]: return self._state[k][var].append(state) # Only add states not added, per wikipedia article def _nextSymbolIsVar(self, state): pos, rule, orig, node = state if pos < len(rule): var = varName(rule[pos]) if var: return True return False def _varAtPos(self, pos, rule): if pos < len(rule): var = varName(rule[pos]) if var: return var return None def _initState(self, start_rule): self._pos = 0 self._state = [] dummy_rule = ('{'+ start_rule + '}',) self._grammar[self.dummyStart] = dummy_rule state_set = {self.dummyStart: [(0, dummy_rule, 0, None)]} self._state.append(state_set) # The parser is seedd with S(0) consisting of only the top-level ruleif __name__ == '__main__': from led_ux_grammar import grammar, debugGrammar EarleyParser.dummyStart = 'P' parser = EarleyParser(debugGrammar) forest = parser.parse('2+3*4', start='S') for tree in forest: print(tree)However, it's hard for me to see how to construct the nodes as I build up the states using the algorithm.I don't need for you to read my code, just show me a 2 level tree given the first few stages above.If you want to run the code, here is the grammar in another file:debugGrammar = { 'S' : ['{S}+{M}', '{M}'], 'M' : ['{M}*{T}', '{T}'], 'T' : ['1', '2', '3', '4'],}And some utility functions for working with the grammar (cf_grammar.py):def charRange(begin, end): return [chr(x) for x in range(ord(begin), ord(end) + 1)]def ruleSymbols(rule): symbols = [] k = 0 while k < len(rule): c = rule[k] if c == '{': end = rule.find('}', k) + 1 sym = rule[k:end] symbols.append(sym) k = end else: symbols.append(c) k += 1 return tuple(symbols)def varName(symbol): if len(symbol) >= 3 and symbol[0] == '{' and symbol[-1] == '}': return symbol[1:-1] return Nonedef terminal(symbol): if len(symbol > 0): if symbol[0] != '{': return symbol elif varName(symbol): return None else: return None # Error in grammar spec return ''
What should the SPPF forest look like as this Earley parsing example progresses?
algorithms;trees;parsers
null
_softwareengineering.194513
I'm working on a realtime multiplayer game using Django and gevent-socketio, I'm facing some issues:I need to send an update of the game state to connected players every X seconds (~4 seconds), so basically I need to execute a function every x seconds which does some calculations and sends the connected players the new game state. What is the easiest way to achieve this? is using cron a good choice here or should I look for other tools like celery or ...? Also, the function needs to operate on some data. querying the database every time the function is executed does not seems to be a good idea, where can I store the game data (which is updated frequently during the game)?
Notify players every x seconds in a multiplayer game
python;database;game development;django
null
_webapps.58686
We use Google Groups Collaborative Inbox and would like it to email a member when they take a topic (when they assign it to themselves). At present it only emails when someone else assigns a topic to you (or when a new topic is raised which we have disabled for our purposes). Does anyone know how to achieve this?
Email when Taking a Topic using Google Groups Collaborative Inbox
email;google groups
null
_unix.10736
After having some problems with my NAS, I switched to Debian/Lenny. I've managed to install and configure most of the software I need, but I've hit a brick wall with Samba. I can access the shares and read all the files, but if I try and send anything across it tells me there's not enough space.I'm using Windows, so I opened a command prompt and ran > dir \\MyNAS.home\Public 1 File(s) 44,814,336 bytes 12 Dir(s) 507, 998, 060, 544 bytes freeThe free space reported is correct (~500GB), so what's the problem? The following is my smb.conf: [global] workgroup = MEDUS realm = WORKGROUP netbios name = MyNAS map to guest = bad user server string = My Book Network Storage load printers = no printing = bsd printcap name = /dev/null disable spoolss = yes log file = /var/log/samba/log.smbd max log size = 50 dead time = 15 security = share auth methods = guest, sam_ignoredomain, winbind:ntdomain encrypt passwords = yes passdb backend = smbpasswd:/opt/etc/samba/smbpasswd create mask = 0664 directory mask = 0775 local master = no domain master = no preferred master = no socket options = TCP_NODELAY SO_RCVBUF=65536 SO_SNDBUF=65536 min receivefile size = 128k use sendfile = yes dns proxy = no idmap uid = 10000-65000 idmap gid = 10000-65000 don't descend = /proc, /dev, /etc admin users = null passwords = yes guest account = nobody unix extensions = no [Public] path=/shares/internal/PUBLIC guest ok = yes read only = no dfree cache time = 10 dfree command = /opt/etc/samba/dfreeThe dfree command parameters I added myself, in an attempt to fix the problem (which didn't work). However, I suspect that the NAS is reporting the correct disk space anyway, as evident from the results of the command I used above.I've also tried playing around with the block size command, to no avail. I was able to create an empty text file on the share, and I repeatedly edited and saved the file -- it stopped at around 130 bytes.Does anyone have any idea what the problem might be?
Samba reporting not enough free space
networking;samba;disk usage
After going through my smb.conf file and commenting out almost everything, I found that the problem was caused by the configuration setting min receivefile size.This option changes the behavior of smbd(8) when processing SMBwriteX calls. Any incoming SMBwriteX call on a non-signed SMB/CIFS connection greater than this value will not be processed in the normal way but will be passed to any underlying kernel recvfile or splice system call (if there is no such call Samba will emulate in user space). This allows zero-copy writes directly from network socket buffers into the filesystem buffer cache, if available. It may improve performance but user testing is recommended. If set to zero Samba processes SMBwriteX calls in the normal way. To enable POSIX large write support (SMB/CIFS writes up to 16Mb) this option must be nonzero. The maximum value is 128k. Values greater than 128k will be silently set to 128k.Commenting out this line in the conf file fixed the issue, I guess this is what happens when you use someone else's recommended config settings. I'm not sure I fully understand what this setting does, anyway.
_softwareengineering.314421
Suppose I use a open source framework in my project and I would not contribute (submit changes) to that framework, and the current version is stable, should we keep the framework unchanged when possible?for example, if I found a function in a class of framework does not fulfill my requirements:public class Fruit{ public float calculatePrice(){ return weight*1.2; }}I would wrap it to add my requirements:public class MyFruit{ Fruit fruit; public float calculatePrice(){ return fruit.calculatePrice()*myConstant; }}instead of modify Fruit directly, and for another example, if I need to use a protected property in the class (e.g.:locale):public class Fruit{ protected String locale;}I would extend it to access the localepublic class MyFruit{ public void checkLocale(){ if(locale.equals(abc)){ } }}instead of changing locale into public.I think the motivations behind it are:The resources of the frameworks (e.g.:tutorials, behaviour ,bugs,issues) are based on the original version of the framework, when we change the framework directly, the resources may not be applicable to my modified framework anymore, or we may not be able to use the resource directly (e.g.:copy and paste online examples)It is easier to upgrade the framework when the framework keeps the original lookIf we modify codes in framework, it may introduce bugs in the framework, and debugging frameworks is more difficult than debugging my custom codes.Keeping the frameworks in original version allows us to add other extensions for the frameworks easily because most extensions are worked based on the original versionIt is more difficult to ask for help if we use a custom modified framework because you may need to post and explain the modified parts of the frameworkWhen problem occurs, if we just use the original version, it is faster and easier for volunteers to setup the environment, then reproduce and find out the problem, because they can just download the framework directly and then add my additional codes.is it true that we should not modify codes in frameworks directly when possible? And is this attitude correct?
If no contribute intention, should we never change codes in open source frameworks unless no alternatives available?
open source;maintainability
null
_cs.3526
I have a question and I haven't been able to figure out the answer yet. I need to do the on-line simulation of a two-head tape Turing machine using single-head tape(s). I've found some online articles for the fact that one single-head tape doesn't suffice for this problem and the simulation should be done using two single-head tapes, but I haven't been able to present an accurate simulation of two-head TM using these single-head tapes. Are there any thoughts on how to do so? Thanks,
On-line simulation of a two-head tape Turing machine using single-head tape(s)
computability;turing machines;machine models;simulation
null
_unix.171674
I am looking at how HTTP proxies and reverse proxies deal with slow client problems. The idea is that the upstream server only have a limited slots for clients and if the client is slow to receive data, it consumes a slot for a long time. A reverse proxy can be used to buffer the response, free the slot earlier on upstream and then forward slowly the response to the client.For instance, nginx suggests to enable upstream response buffering by allocating (by default) up to 8 buffers of 8k each. If those buffers are filled, it can start buffering on the disk (but I disabled this feature, my disks are busy enough).See: http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_bufferingHowever, I did multiple checks and it seems that the kernel allocates a quite large RCVBUF (receive buffer) of around 1-4MB. If upstream sends a response of 2MB while the end client don't read anything, the proxy buffers will be filled soon, and the kernel buffer will be used instead.Since the proxy will buffer less data than the kernel, I don't see how it helps to deal with slow clients. What can be the advantages of explicitly implementing/enabling a buffering feature in the proxy while the kernel does enough for us?Edit: after the first response, I would like to give some details about what I tested.a client program connects to the reverse proxy, waits during a few seconds and starts reading.the reverse proxy only buffers up to 8kB in user space memory, after a read(), it will log the size of the socket's receive buffer, .upstream serves a HTTP response of 2MB (plus headers), the log the time it took between accept() and close().When testing, I can see that the server will never wait on a write(), and even call close() before the slow client performed the first read(). Also, the size of the socket receive buffer will grow and exceed 2MB: the whole response from the server will be buffered.I ran the tests with the upstream server on the same host than the client and proxy, and with the upstream on a distant host, the observed behavior is the same.Also, I understand that the kernel may use smaller buffers under memory pressure, but this affects the reverse proxy too (which may thus be unable to buffer the response in user space).
Is it useful for a proxy to buffer less data than Linux RCVBUF can?
networking;performance;http proxy;buffer
null
_webapps.74117
I'm trying to create two cells that will update my query: A >= dateA1 and A <= date B1.My goal is to create a search page for the data, where the end user could insert a date or the =today() function and it would update the query. I am currently getting a formula parse error from:=QUERY(Data!6:1397,SELECT A,B,C,D,E,F,G,H,I,J,K,L WHERE A >= dateA1and A <= dateB1)
Dynamic date range query
google spreadsheets;google spreadsheets query
null
_unix.353204
I need to capture all incoming/outcoming http traffic of a unix machine, and then run a script on each http header/body.I have found that tcpdump captures all the requests, but big ones end up being split into multiple frames and is not easy to patch them together with a script that uses libpcap.tcpflow almost does what I need, but it puts the whole flow between the host/client in the same file, without a good token to separate them making it impossible to know when a request ended and other started automatically.Wireshark has the follow http option, but I couldn't find a way to use tshark to export one file for each flow.Any suggestions?
How to capture http requests headers and body
http;tcpdump;wireshark
null
_webmaster.65615
I've been told by an SEO specialist that, although every other page on a website has <h1> tags highlighting the correct headings for that page, that there needs to be one on the homepage, too.I'm dubious about this as the homepage should only rank for people searching for the company name directly -- which it already does perfectly (not least because the company name is their domain name). Obviously I don't see the harm in putting an exception in for that one page, but I also don't see the point, especially when I have lots of other more important things to be getting on with.Are there any SEO benefits to adding a <h1> element to the homepage, given that Google is already finding the company name perfectly well?
SEO benefit of H1 tags on the homepage
seo;google
null
_webmaster.69009
A lot of resources claim that websites with HTTPS + SSL will not be cached.Is this true?If so, why?If so, can this be prevented?I heard that this depends on the browser, but that the most browsers won't cache HTTPS.
Cache HTTPS + SSL
https;http
Yes, HTTPS content is cacheable. Historically, authenticated or content obtained via HTTPS may not have been cached by the browsers. This was never a technical requirement but thought as a good security practice. For example, Firefox used to cache HTTPS content only in memory. However, as the use of HTTPS increased, caching SSL enabled content to the disk became default. The important thing is to set Cache-control headers. Google has a good article on HTTP caching. I recommend you review it.You can use curl -I at the command line to check cache headers:curl -I www.google.comHTTP/1.1 200 OKDate: Thu, 11 Sep 2014 13:54:52 GMTExpires: -1Cache-Control: private, max-age=0Or there are online tools like http://redbot.orgI highly recommend setting Cache-Control headers are on all content. I also recommend setting explicit headers, such as max-age. With the increasing use of mobile, CDNs, content acceleration providers, users are often connecting via some sort of proxy. So you want to assure you have good cache policies so these proxies no how to handle your content.In the example above, you will see private. Historically, some user-agents would not cache data to disk when this directive is in place, but this practice is changing as well. For a detailed review of this, please see this 2013 report: Industry-Wide Misunderstandings of HTTPS
_unix.279769
A month ago I set cron to log to /var/log/cron.log by modifying /etc/rsyslog.d/50-default.conf. Logging worked great until I changed permissions on /var/log (by easing permission restrictions), and forced logrotate to rotate the logs by executing logrotate --force /etc/rsyslog.d/50-default.conf. Since then, cron seems to have stopped logging. There is no longer a /var/log/cron.log. I executed sudo touch /var/log/cron.log to create it, but it has remained 0 bytes since.More details on what I did with the permissions:I ran sudo chmod 775 /var/log, and subsequently changed permissions back with sudo chmod 755 /var/log. All other services appear to be logging correctly, and cron jobs are actually running (verified with ps aux | grep rsync, since I only run rsync via cron). I wasn't sure of the correct user and group access rights for cron.log so I tried changing it to syslog:adm like most of the other log files, but that didn't help, so I switched it back to root:root,Current permissions on cron.log: -rwxr-xr-x 1 root root 0 Apr 27 16:34 cron.logNot sure where to go from here. I know I can have cron log to any file I'd like (either by adding >> /path/to/logfile to end of cron job entries or by editing /etc/rsyslog.d/50-default.conf), but for consistency, I would prefer it continue logging to cron.log. I suppose I could add >> /var/log/cron.log to the end of each cron entry, but that seems a little hacky to me.EDIT: As per my comment below, I changed the log location to /tmp/cron.logand logging has resumed. At first, I had assumed this implied that either the folder or file permissions are wrong. However, I checked them against another machine running the same distro, and the folder permissions were correct. The file permissions were not restrictive enough, the correct permissions can be set with sudo chmod 640 cron.log.As a test, I deleted the empty cron.log, and it was never recreated. I modified the rsyslogd config to have it log to crond.log, but the file was never created.
Cron stopped logging to /var/log/cron.log
cron;logs;rsyslog
null
_unix.163517
I have a web application in that i want some of the files should always be cached like for atleast 24 hours in chrome browser. For that i have done some configuration in my apache webserver 2.4.9. But still my files are getting cached. It always gets downloaded from my web server. Any idea how to do setting in apache or chrome for enabling browser cache in chrome because it is working properly in Mozilla browser.Also I want to know I have already set my cache-control to 1 day but still in chrome it is showing no-cacheMy apache configuration settings.<ifModule mod_headers.c><filesMatch \.(html|htm|png|js|css)$> Header set Cache-Control max-age=86400, public, must-revalidate</filesMatch></ifModule>Ouput in browser netpanelRemote Address:xx.xx.xx.xx:80Request URL:http://test.com/test.js?buildInfo=1.1.2Request Method:GETStatus Code:200 OKRequest Headersview sourceAccept:*/*Accept-Encoding:gzip,deflate,sdchAccept-Language:en-US,en;q=0.8**Cache-Control:no-cache**Connection:keep-aliveCookie:JSESSIONID=169A6E41C963E44F2D9D2FA405E41A08Host:xx.xx.xxx.xxPragma:no-cacheReferer:http://test.com/User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36Query String Parametersview sourceview URL encodedbuildInfo:1.1.2Response Headersview sourceAccept-Ranges:bytesConnection:Keep-AliveContent-Encoding:gzipContent-Type:text/javascriptDate:Wed, 22 Oct 2014 05:02:31 GMTETag:W/7792381-1413890396000-gzipKeep-Alive:timeout=15, max=88Last-Modified:Tue, 21 Oct 2014 11:19:56 GMTServer:ApacheTransfer-Encoding:chunkedVary:Accept-Encoding
how to cache files in chrome
apache httpd;chrome;cache
null
_unix.200283
I want to copy a single file if (and only if) the destination does not exist. The source file changes rarely, maybe once a month. The destination almost never exists.Are there any differences between the -n and -u options? (Or both!)cp is being called directly from crond. No othercp options are used.The same cron job is called on several machines at the same time, reading from the same source and writing to the same destination (both on a shared GFS global file system). The destination file will be moved shortly thereafter by another process, so the only time it could exist is during the race when the cron job executes simultaneously on several nodes.Which would be more efficient? :cp -n source destcp -u source destcp -nu source destcp -pu source destI'm currently leaning towards the simple -n alternative.
cp options --no-clobber vs. --update
cp;gnu;coreutils
It's meaningless to combine -n and -u.Use -n if you never want to overwrite an existing file.Use -u if you don't want to overwrite newer files.The case where the two differ, then, is where you have a destination file that's older than the source file. Consider what you want to happen for this case, and write your command accordingly.I'd expect that -n is more efficient than -u - but the effect is unlikely to be at all measurable.(In the above, 'older', 'newer' etc. are all in terms of the mtime of the files.
_unix.235809
I have to install a program. When I run this command:sudo ./Vivado-Hardware-Server/xsetupI get the following error:./Xilinx_HW_Server_Lin_2015.2_0626_1/xsetup: line 67: /home/user/Xilinx_HW_Server_Lin_2015.2_0626_1/tps/lnx32/jre/bin/java: No such file or directory/home/user/Xilinx_HW_Server_Lin_2015.2_0626_1/tps/lnx32/jre/bin/java exists and its permissions are: -rwxr-xr-xThe OS is Ubuntu 64 bit and the Java version is:java version 1.7.0_79OpenJDK Runtime Environment (IcedTea 2.5.6) (7u79-2.5.6-0ubuntu1.15.04.1)OpenJDK 64-Bit Server VM (build 24.79-b02, mixed mode)This and this did not help me. Any suggestion?
No such file or directory java while executing script
linux;ubuntu
null
_unix.207658
How to make my bash script as service in CentOS 7? following is failing.$ cat /etc/systemd/system/mybash.service[Unit]Description=mybash ServiceAfter=network.target[Service]Type=simpleUser=rootExecStart=/root/runme.shRestart=on-abort[Install]WantedBy=multi-user.target$ systemctl start mybash$ systemctl status mybash -lmybash.service - mybash Service Loaded: loaded (/etc/systemd/system/mybash.service; disabled) Active: inactive (dead).....$ cat /root/runme.sh #!/bin/bashecho Start the node servera=$(pgrep -f a.js);kill $a;a=$(pgrep -f b.js);kill $a;node /home/www/html/a.js &node /home/www/html/b.js &
CentOS 7 - why the service file is not working to run my bash script?
bash;centos;node.js
Do it properly.Don't use forever under service managers. They already do this.Don't use pgrep and kill under service managers. They do this better.Don't use start-stop-daemon under service managers. They do this better.That entire mechanism with that shell script is wrongheaded to start with, and fixing its readiness protocol mismatch would be simply papering over some vast cracks. You don't need any of that entire cobbled-together-poor-imitation-of-daemon-management script at all. You have a service manager that can do that stuff directly and safely. Use it.# /etc/systemd/system/[email protected][Unit]Description=node service for %i.jsDocumentation=https://unix.stackexchange.com/questions/207658/After=network.target[Service]Type=simpleExecStart=/usr/local/bin/node /home/www/html/%i.jsRestart=on-abortSyslogIdentifier=node-%i[Install]WantedBy=multi-user.targetFix the path to /usr/local/bin/node as appropriate.The usual commands then apply:systemctl preset [email protected] [email protected] systemctl start [email protected] [email protected] systemctl status [email protected] [email protected] Further readingFlix Saparelli (2013-11-26). How To Deploy Node.js Applications Using Systemd and Nginx.Ruben Vermeersch (2013-01-16). Deploying Node.js with systemd.https://unix.stackexchange.com/a/200365/5132https://askubuntu.com/a/625378/43344
_unix.14655
I recently put Fedora Core 15 on my system, and I've had a behaviour change that I can't figure out. Using Tab-Complete in the BASH shell works fine except when I use the $HOME variable.If I type cd $HOME/dTAB, it will auto-complete to the proper directory (doc), but it also inserts a preceding \, so the result is cd \$HOME/doc. This then fails, as such a path does not exist.The error isbash: cd: $HOME/doc: No such file or directoryIf I don't use Tab-Complete it works, as $HOME still points to the proper directory. Where did this extra \ come from, and how do I make it go away?
Bash and Tab Auto-complete
bash;autocomplete
By issuing the command complete you'll get the list of all completion definitions. Then you can search the offending definition somewhere in /etc/bash_completion and /etc/bash_completion.d. There can be also some .bash_completion in your home directory. On my system the $HOME variable is completed properly, but then fails to complete anything.Did you try to use ~ instead of $HOME? It's easier to type and it works as expected...
_unix.31343
I just wrote a function in my ~/.bashrc that will let me create a folder for a new website with one command. The function looks like this:function newsite() { mkcd $* # mkdir and cd into it mkdir js mkdir imgs touch index.html touch main.css vim index.html}Woo hoo super complicated function... Okay in all seriousness I understand this is really basic, it's the first function I've made without copy and pasting from online though so bear with me.Now what I would like to do is, instead of just touching index.html and main.css I'd like to create basic template files for index.html and main.css problem is I have absolutely no idea how to do that. I don't know much about writing to files using bash commands. Typically I'd just open the files in vim and go to town but I'd like to have something already started when I get into vim...
Script to create files in a template
bash;vim;function
jw013's idea and HaiVu's answer are both correct. However for the sake of completeness for anyone who comes upon this question wanting the answer, here it is;function newsite() { mkcd $* # mkdir and cd into it mkdir js mkdir imgs cat > index.html <<'EOI'<html><head></head><body></body></html>EOI cat > main.css <<'EOI'body { font-family: Arial;}EOI vim index.html}The <<'EOI' thing is called a heredoc, most scripting languages have them.
_cstheory.30716
A distribution $D$ on $\{0,1\}^n$ is $k$-wise independent if any $k$ of the underlying $n$ random variables are independent and each is uniformly distributed.To me this looks similar in spirit to $D$ having $\textit{min-entropy}$ $k$.Is there any formal relation between $k$-wise independence of a distribution and its min-entropy?
k-wise Independence vs. Min-entropy
cc.complexity theory;pseudorandomness
null