id
stringlengths
5
27
question
stringlengths
19
69.9k
title
stringlengths
1
150
tags
stringlengths
1
118
accepted_answer
stringlengths
4
29.9k
_webmaster.84850
I have an existing canonical URL in the form http://example.com/page1 for a page called http://example.com/page1.html and use .htaccess to rewrite the URL of anything without an extension so it ends in .htmlHowever, I want to create a new page which can be accessed as either http://example.com/page1 or http://example.com/page1-alternative-name (or the .html versions of either). Can I add a canonical URL for this alternative name, but have google & other search engines index it under both names, but recognize both as the same page with the same rank/SEO result, and combined webmaster stats? If a canonical URL should not be used will the .htaccess access rewrite rule alone by enough to allow search engines to recognize non-duplicate content with alternative names? Is there something I can do to flag this alternative name like link=alternate? Page names and given SEO weight and certain terms/phrases have multiple preferred terms (this is not some kind of keyword stuffing).So far from reading many answers here I can see multiple canonicals are allowed, but cannot find anything similar to this situation.
Multiple canonical URLs for same page
seo;google search console;canonical url;search results;rel alternate
null
_unix.304574
I feel that with all the additional apps pre-installed, and relying heavily on deriving elements from Ubuntu and Gnome, elementary must be heavy.So I would like to know an as-quantitative-as-possible analysis of how heavy the OS is on RAM (and may be the system in overall) compared to Classic-Ubuntu/Gnome-Ubuntu. This is a problem that every user who is stunned by the awesomeness of Pantheon would like to get an answer to, before switching their OS/Desktop, so that they don't feel the hesitation that it would slow down their PC.PS: Please feel free to add external links that may be helpful, but as of now I haven't been able to find a proper place that provides some sane discussion of this technical overhead comparison.
How heavy is elementaryOS over classic Ubuntu?
ubuntu;gnome;memory;elementary os;ram
What applications are preinstalled is completely irrelevant. An application that is installed but not running costs nothing but disk space.I don't know why you feel that elementary must be heavier than Gnome. Gnome itself is pretty heavy.There was an article comparing Linux desktop environments in the Layer 3 Networking Blog in April 2013. Elementary didn't exist yet but the author tested a lot of environments. While figures can vary quite a bit depending on what applets, widgets and so on are loaded, the order of magnitude is telling: ~200MB for KDE, slightly less for Unity and Gnome3, ~50MB for lightweight desktop environments, a few MB for heavyweight window managers, <1MB for lightweight window managers. (Those figures are for the WM/DE only, not the base system.)Hectic Geek compared elementary Luna with Gnome in August 2013. They found that there was no significant difference in memory usage and boot times.Brendan Ingram compared the RAM usage of several configurations in July 2016. He found that Gnome on Ubuntu 16.04 took 700MB (that's total RAM, not just the desktop environment) while Pantheon on the elementary OS version based on 14.04 took 600MB, i.e. Pantheon used slightly less memory but that was an older version.The upshot is that Pantheon as configured by elementary and Gnome or Unity as configured by Gnome use similar amounts of memory. Elementary's default setup requires roughly the same amount of resources than Ubuntu's.
_unix.193095
I have picked up -- probably on Usenet in the mid-1990s (!) -- that the constructexport var=valueis a Bashism, and that the portable expression isvar=valueexport varI have been advocating this for years, but recently, somebody challenged me about it, and I really cannot find any documentation to back up what used to be a solid belief of mine.Googling for export: command not found does not seem to bring up any cases where somebody actually had this problem, so even if it's genuine, I guess it's not very common.(The hits I get seem to be newbies who copy/pasted punctuation, and ended up with 'export: command not found or some such, or trying to use export with sudo; and newbie csh users trying to use Bourne shell syntax.)I can certainly tell that it works on OS X, and on various Linux distros, including the ones where sh is dash.sh$ export var=valuesh$ echo $varvaluesh$ sh -c 'echo $var' # see that it really is exportedvalueIn today's world, is it safe to say that export var=value is safe to use?I'd like to understand what the consequences are. If it's not portable to v7 Bourne classic, that's hardly more than trivia. If there are production systems where the shell really cannot cope with this syntax, that would be useful to know.
Where is export var=value not available?
shell;history;compatibility
export foo=baris not supported by the Bourne shell. That was introduced by ksh.In the Bourne shell, you'd do:foo=bar export fooor:foo=bar; export fooor with set -k:export foo foo=barNow, the behaviour of:export foo=barvaries from shell to shell.The problem is that assignments and simple command arguments are parsed and interpreted differently.The foo=bar above is interpreted by some shells as a command argument and by others as an assignment (sometimes).For instance,a='b c'export d=$ais interpreted as:'export' 'd=b' 'c'with some shells (ash, zsh (in sh emulation), yash) and:'export' 'd=b c'in the others (bash, ksh).Whileexport \d=$aorvar=dexport $var=$awould be interpreted the same in all shells (as 'export' 'd=b' 'c') because that backslash or dollar sign stops those shells that support it to consider those arguments as assignments.If export itself is quoted or the result of some expansion (even in part), depending on the shell, it would also stop receiving the special treatment.The Bourne syntax though:d=$a export dis interpreted the same by all shells without ambiguity.It can get a lot worse than that. See for instance that recent discussion about bash when arrays are involved.(IMO, it was a mistake to introduce that feature).
_codereview.123822
I'm trying to figure out if there's a better way to run the code below.Basically Course is an association of Student and courses_needed is an array of Course where I have many Students have and need many Courses and I'm trying to figure out the demand.I've came up with the following code and it runs, which is fine, but when I want to display it on a statistics page with 36 Courses, the same code needs to be run once for each Course. I've solved it now by having it run once a day, instead of real-time. def self.calculate_needed Course.all.each do |course| neededArray = Array.new needed = 0 Student.all.each do |s| unless s.courses_needed.nil? s.courses_needed.each do |c| if c == course needed += 1 end end end end course.needed = needed course.save end end
Count associations in a Ruby model
ruby;ruby on rails;active record
This should be interesting. The fastest way I can think of is to pluck all the courses_needed arrays out of Student, group them together, and count them:course_hash = Student.where.not(courses_needed: nil).pluck(:courses_needed). flatten.group_by { |c| c }.map { |k, v| [k, v.size] }.to_hEssentially, I grab all students that actually have courses_needed, I then grab just all the courses needed from students. Flatten the course arrays so that all courses are within the same array, then I group them by course. After that I map again to replace the values (just the list of all same courses) with the number of times each course is listed. Then I do to_h to turn each [course, number] into a course => number hash that you can access easier.So pluck returns:[[course, course2, course3], [course, course2]]Flatten makes this:[course, course2, course3, course, course2]Group_by turns it into:{course => [course, course], course2 => [course2, course2], course3 => [course3]}Map does:[[course, 2], [course2, 2] , [course3, 1]]Then to_h:{course => 2, course2 => 2, course3 => 1}At that point you can access the course hash and get the number.course_hash[course]# 2Now that we have the hash we can update the needed column in Course:Course.find_each do |course| course.update_attributes(needed: course_hash[course].to_i)endThe to_i is used so that if course_hash does not contain the course it returns nil, then to_i will turn nil into 0.
_unix.184179
A couple of months ago, I re-installed Cygwin on my Win7 machine. Since then, when clicking the XWin Server entry in the Start Menu, it not only starts the (familiar) X tray icon along with a xterm window (this is running in rootless mode), but also a frame-less, grey window with the same (slightly larger) X icon. It is placed in the screen's top-left corner and on being clicked, it offers a small menu of applications to execute and to Exit Cygwin/X. Its taskbar entry shows panel as its window title.Since this panel window's functionality is duplicated in the tray icon's right-click menu (which has more options anyway), I am wondering how to suppress the start of this window.I had a look at the man pages for Xwin and XWinrc as well as the files under /etc/X11/xinit/, but since I am new to X11 I might have missed something. The Manpage of XWin and the Configuring Cygwin/X pages weren't helpful either.
Cygwin XWin server: How to disable the creation of the panel window?
cygwin
I launch my X Server with this: XWin.exe -multiwindow
_webapps.33778
I would like to email everyone in my Trello organization to clarify changes I make (like permissions, new boards, etc.) on a periodic basis. Is this possible to do easily?
Is it possible to send an email to everyone in my Trello Organization?
trello;trello organization
null
_cogsci.15932
Neuronal networks can make loops because a neuron has a direction (from dendrite to axon).What's the smallest area in the cortex where we can find a loop and what are these loops?I understand there are loops between different cortical areas through the white matter.Experiments, like this one, show there are interactions between cortical layers. But it doesn't necessary mean there are loops.Other experiments, like this one, looking at signals propagation in pieces of cortex with a cut showed the propagation could somehow circumvent the cut and keep propagating. Again it shows the existence of some local circuits but not necessarily loops.Do we have a proof of local loops in the cortex? How large a piece of cortex has to be to contain a loop? What are these loops?
Are there neural loops within a column or an area of the cortex?
neurobiology;theoretical neuroscience;neural network
null
_softwareengineering.339884
When creating time estimates for tickets should the time taken for testers (QAs) be included in a tickets estimate? We have previously always estimated without the testers time but we are talking about always including it. It makes sense for our current sprint, the last before a release, as we need to know the total time tickets will take with one week to go. I always understood estimation was just for developer time as that tends to be the limiting resource in teams. A colleague is saying that wherever they have worked before tester time has also been included. To be clear, this is for a process where developers are writing unit, integration and UI tests with good coverage.
Should tester's time be included when estimating tickets?
agile;scrum;estimation;qa
My recommendation: You either include testing time in the ticket, or add a ticket to represent the testing task itself. Any other approach causes you to underestimate the real work needed.While developer time is often a bottleneck, in my experience, there are many teams constrained on test. Assuming the limiting resource is one or the other without evidence, can bite you.As your colleague, I haven't seen a successful organization that doesn't take testing time into account.Addendum per your clarification: Even if devs write automated tests, particularly unit tests (integration tests do better), they are insufficient to properly test.If there is QA people involved, their time need to be estimated, one way or another. Only if you are deciding to remove QA people from payroll, then their work time has effectively vanished and you can remove it from the estimation. But this would have side-effects that are easy to ignore. And you may still be missing performance, stress, security and acceptance testing.
_unix.14205
I had ldc2 and gdc compiled from source and working up until a month ago. Nothing has changed, except I can't remember the variable(s) I would set in the terminal to get ldc2 and gdc to work.I get the following errors when trying to compile D source code; with gdc ($ /home/Code/D/gdc/Bin/usr/local/bin/gdc -o t4 t4.d):/home/Code/D/gdc/Bin/usr/local/bin/../libexec/gcc/x86_64-unknown-linux-gnu/4.4.5/cc1d: error while loading shared libraries: libmpfr.so.1: cannot open shared object file: No such file or directoryWith ldc2 (/home/Code/D/ldc2/bin/ldc2 -o t4 t4.d):/home/Code/D/ldc2/bin/ldc2: error while loading shared libraries: libconfig++.so.8: cannot open shared object file: No such file or directoryI can't remember if it was just an addition to PATH or something to DFLAGS. Any ideas?
Cannot open shared object file when using D compiler
executable;dynamic linking
Here you can't even run the compiler executable, because it can't find the libraries it needs. gdc is looking for libmpfr.so.1 and ldc2 is looking for libconfig++.so.8.If these libraries are still present on your system, perhaps in /home/Code/D/gdc/Bin/usr/local/lib, you can add that directory to the LD_LIBRARY_PATH environment variable (on most unices; on MacOSX, the variable is called DYLD_LIBRARY_PATH).LD_LIBRARY_PATH=/home/Code/D/gdc/Bin/usr/local/lib gdc You may want to write wrapper scripts to run gdc and ldc2, or put this in your ~/.profile:export LD_LIBRARY_PATH=/home/Code/D/gdc/Bin/usr/local/libIf these libraries were in /usr/lib and disappeared in a system upgrade, you'll have to either restore the required versions, or recompile the D tools for the new versions of the libraries.
_webmaster.101090
The <title> tag is displayed to the user of the search engine. Given that it is also what the search engine uses for ranking, why would one need to include a <meta name=title content=> tag?
Is redundant?
seo;meta tags;title
Yes, <meta name=title ../> is superfluous.It is clear, after reading the HTML specification of the meta tag:The meta element represents various kinds of metadata that cannot be expressed using the title, base, link, style, and script elements.So the meta title doesn't provide any additional information to the title tag, and it is not even one of the meta properties recognized by Google.
_softwareengineering.263514
I am exploring how a Minimax algorithm can be used in a connect four game. I was looking through a program and found this evaluation function.private static int[][] evaluationTable = {{3, 4, 5, 7, 5, 4, 3}, {4, 6, 8, 10, 8, 6, 4}, {5, 8, 11, 13, 11, 8, 5}, {5, 8, 11, 13, 11, 8, 5}, {4, 6, 8, 10, 8, 6, 4}, {3, 4, 5, 7, 5, 4, 3}};//here is where the evaluation table is calledpublic int evaluateContent() { int utility = 128; int sum = 0; for (int i = 0; i < rows; i++) for (int j = 0; j <columns; j++) if (board[i][j] == 'O') sum += evaluationTable[i][j]; else if (board[i][j] == 'X') sum -= evaluationTable[i][j]; return utility + sum; }And then a MiniMax algo is used to evaluate the possible solutions.I am not sure how/why this works. Would anyone be able to explain?
Why does this evaluation function work in a connect four game in java
java;algorithms;machine learning
The numbers in the table indicate the number of four connected positions which include that space for example:the 3 in the upper left corner is for one each of horizontal, vertical, and diagonal lines of four which can be made with it.the 4 beside it is for two horizontal (one including starting in the corner, one starting on it, one vertical, and one diagonal)This gives a measurement of how useful each square is for winning the game, so it helps decide the strategy.I believe that the evaluateBoard function returns a number <0 ifint utility = 128is a typo - it should be initialized to 138 (since the sum of all the values in the table is 276 = 2 x 138). This would make the evaluateBoard function return:< 0 if the player whose marker is 'X' is likely to win (has the most strategic places based on the utility function)= 0 if the players are equally likely to win> 0 if the player whose marker is 'O' is likely to win.
_webmaster.78239
We all are quite aware that hyphen is the title word separator as described in this video by Matt Cutts. But I was shocked to find that Google was listing the matching page titled SomePrefix City-Enrollment Centers in the bottom in SERP (of 100 results) when I entered this query:SomePrefix City Enrollment CentersHowever when I keyed in this query, it showed the page in top in SERP:SomePrefix City-Enrollment CentersI'm wondering whether I should have given space around the hyphen in the page title otherwise it seems that Google is considering City-Enrollment as single word.In short how to prevent such situation in which Google may consider those as single words or phrases?Notes:I'm not including quotes around my search phrase.Right now I've removed hyphen altogether to make it simple.
Is hypen a word separator in the title?
seo;google search;title
null
_unix.94247
I'm having issues while connecting to my Local Centos 6.3 VM with 500 MB ram.Below is the output of ssh -vvv localhost connection:OpenSSH_6.3, OpenSSL 1.0.1e 11 Feb 2013debug1: Reading configuration data /usr/local/etc/ssh_configdebug2: ssh_connect: needpriv 0debug1: Connecting to localhost [127.0.0.1] port 22.^^^^^^^^^^ Loading this statement takes more than a minutedebug1: Connection established....debug1: Next authentication method: password root@localhost's password:^^^^^^^^^^ This step takes a minute toodebug3: packet_send2: adding 64 (len 50 padlen 14 extra_pad 64)debug2: we sent a password packet, wait for replydebug1: Authentication succeeded (password).Authenticated to localhost ([127.0.0.1]:22).debug1: channel 0: new [client-session]debug3: ssh_session2_open: channel_new: 0debug2: channel 0: send opendebug1: Requesting [email protected]: Entering interactive session.debug2: callback startdebug2: fd 3 setting TCP_NODELAYdebug3: packet_set_tos: set IP_TOS 0x10debug2: client_session2_setup: id 0debug2: channel 0: request pty-req confirm 1debug2: channel 0: request shell confirm 1debug2: callback donedebug2: channel 0: open confirm rwindow 0 rmax 32768debug2: channel_input_status_confirm: type 99 id 0debug2: PTY allocation request accepted on channel 0debug2: channel 0: rcvd adjust 2097152debug2: channel_input_status_confirm: type 99 id 0debug2: shell request accepted on channel 0Last login: Wed Oct 9 13:27:02 2013 from 10.0.0.2Please suggest on how do I get rid of this delay.
SSH connection establishment too slow
networking;ssh;centos
null
_softwareengineering.66408
I am wondering what is the default graphics engine used in Photoshop?It's great tool. And I don't know how they make it?I mean, if I want to create a simple tool like it, I will use MFC/GDI+.So, what is core to make Photoshop being great tools?
What graphics engine is used in Photoshop
graphics
null
_webapps.105643
Is there a way to set up the form where a customer is required to put their card info but we charge it a later time? If anyone has used jotform they allow a person to put down their card info then it sends a token to stripe letting it know that the card info has been submitted which can be charged at a later time.
Able to charge customer at a later time?
cognito forms
null
_unix.80420
Please advise what's wrong in my ksh code. I want to remove the IP's as defined in bb array from aa array so the IP's 255.0.0.0 and 255.255.255.0 will be removed from the list in aa array.When I run my ksh code and later print the array aa, I see that the IP - 255.255.255.0 was not deleted?Please advise what's wrong in my syntax? echo ${aa[*]} 45.32.3.5 255.0.0.0 255.255.255.0 19.23.2.12 echo ${bb[*]} 255.0.0.0 255.255.255.0ksh program: for run in ${bb[*]} do for ((i=0; i<${#aa[@]}; i++)); do [[ ${aa[i]} == $run ]] && unset aa[i] done donetest: echo ${aa[*]} 45.32.3.5 255.255.255.0 19.23.2.12 NOTE: 255.255.255.0 should be deleted from the above list.
How to filter an array of strings in ksh
linux;shell;perl;ksh
I don't know why your code does not work for the presented inputs. It does on my system under ksh.But your original code has a problem: the conditional part i<${#aa[@]} is fragile - since ${#aa[@]}, i.e. the array size is decremented after each unset - but the following array elements are not automatically shifted to the left. For your example45.32.3.5 255.0.0.0 255.255.255.0 19.23.2.12this does not make a difference - but it would make a difference for - say:45.32.3.5 255.0.0.0 19.23.2.12 255.255.255.0I improved the code with respect to that issue (note the assignment before loop entry). I also eliminated an inner loop (using an associative array) which improves the runtime from quadratic to linear:$ cat x.shoutputs it:aa=(45.32.3.5 255.0.0.0 255.255.255.0 19.23.2.12)bb=([255.0.0.0]=1 [255.255.255.0]=1)print Size of input ${#aa[*]}print Size of exclude list ${#bb[*]}n=${#aa[*]}for ((i=0; i<$n; ++i))do if [[ ${bb[${aa[i]}]} ]] then print Removing element with index $i: ${aa[i]} unset aa[i]; fi print New size of input ${#aa[*]}doneprint Resulting size of input ${#aa[*]}print Resulting elements ${aa[*]}for ((i=0; i<$n; ++i))do print Index $i, Value 'a['$i']'=${aa[$i]}doneIt produces following output on Fedora 17:$ ksh x.shSize of input 4Size of exclude list 2New size of input 4Removing element with index 1: 255.0.0.0New size of input 3Removing element with index 2: 255.255.255.0New size of input 2New size of input 2Resulting size of input 2Resulting elements 45.32.3.5 19.23.2.12Index 0, Value a[0]=45.32.3.5Index 1, Value a[1]=Index 2, Value a[2]=Index 3, Value a[3]=19.23.2.12
_unix.371737
I'm trying to run a test under GCC 7. According to How to install gcc-7 or clang 4.0? on Ubuntu.SE, we can perform the following to install GCC 7 on Ubuntu:add-apt-repository ppa:ubuntu-toolchain-r/test && apt-get update && apt-get install -y gcc-7The command fails at the install:# apt-get install -y gcc-7...E: Unable to locate package gcc-7And trying 7.1:# apt-get install -y gcc-7.1...E: Unable to locate package gcc-7.1E: Couldn't find any package by glob 'gcc-7.1'E: Couldn't find any package by regex 'gcc-7.1'According to List all packages from a repository in ubuntu / debian on Server Fault, we can search a particular repo for a package with:# grep ^Package: /var/lib/apt/lists/ppa.launchpad.net_*_Packages | grep gcc-7#But I am not sure if the command above is searching ppa:ubuntu-toolchain-r.I kind of pieced things together, but they are not working as expected. Either the Ubuntu.SE answer is wrong, the Server Fault search is failing, or I am doing something wrong.(I don't have a Debain 8 machine available for gcc-7 package, and Fedora 25 appears to lack GCC 7. So I am pretty much stuck with Ubuntu).What am I doing wrong? Or, how can I install GCC 7?# lsb_release -aNo LSB modules are available.Distributor ID: UbuntuDescription: Ubuntu 16.10Release: 16.10Codename: yakkety
Install GCC 7 on Ubuntu?
ubuntu;apt;gcc;ppa
null
_cogsci.17696
Specifically, I am trying to quantify trends in learning for certain mediums of audio-visual communication, and what I've gathered so far suggests that there are 4 distinguishable types, being linear, logarithmic (or possibly asymptotic), exponential and ogive. How can I go from peoples qualitative observations to an actual mathematical function to show these patterns for a specific medium? Would one measure...success rate over time and that's it? Or what?
What variables allow one to empirically and scientifically quantify trends for learning curves?
experimental psychology;statistics;experiment design
Short answerIn psychophysical tests, often %correct rates are determined. Hence, training effects are often measured by determining correct rates. The ultimate outcome measures can be wildly variable, as they are dependent on the physical characteristics of the stimulus (visual, auditory, tactile, gustatory etc).BackgroundLearning curves can be measured by measuring the performance on a certain task.From what I understand of your question you are:...trying to quantify trends in learning for certain mediums of audio-visual communication... and you are looking forWhat one measure...success rate over time and that's it? Or what?Taking a personal vantage point here, I have measured learning effects using various auditory, tactile and visual psychophysical tests (though not a combination of them like an audio-visual test as you are planning). I will provide a few tests I have done so far to look at training effects and I will provide some basic background information on psychophysics. Please following the links if you wish to learn more on specific subjects. I have measured the following, among others:Speech understanding by measuring the speech-recognition threshold (SRT) in noise using the Dutch Matrix test (Houben & Dreschler, 2015). The SRT basically shows you the signal-to-noise ratio where speech understanding is 50% correct. In other words, it shows how much noise a listener can handle to still understand 50% of the words in the sentences heard. I've performed this test for 12 times over four several sessions and within as well as between-session learning effects were observed, and also within-run training effects (unpublished observations); Vibro-tactile detection threshold. Basically we asked the subject to answer in a yes/no task if they felt a stimulus and the outcome measure was that stimulus level where the correct rate was 50%. There was no learning effect observed within and between sessions. A within-run training effect was observed, which may have been due to procedural training effects (unpublished observations);Tactile spatial acuity using (2-point discrimination); here a person was asked to answer whether one or two stimuli were felt and then, again, a percent-correct rate (here: 62.5%) score was determined ultimately expressed as that distance where correct rate was 62.5%. No training effects other than procedural learning were observed (Stronks et al, 2017);A vibrotactile intensity-difference (JND) task, where the subject was asked to indicate whether they could feel the difference in intensity of two stimuli. Again the correct rates were measured and expressed as that intensity where the %correct scores equaled a certain threshold (Stronks et al, 2017).Visual acuity was measured with a grating task - again percent correct is measured, but there the outcome is visual acuity, namely an angle of resolution where the %correct rate exceeds a certain threshold. There was procedural learning observed (unpublished observations). Note that most of the above tasks were alternative forced choice (AFC) tasks, where the threshold (%correct) is dependent on the number of choices.References- Houben & Dreschler, Trends Hear (2015); 11(19): 1-10- Stronks et al, Artif Organs (2017); in press
_webmaster.32910
I've got a client who is looking to have a fundraising site built in a matter of days so there's very little time for custom building something.I'm wondering if anyone knows of any software or online service that might be customised.The fundraising site would operate in the following way (for example):Users registerRegistered users select a challenge to complete, ie. 5km run every day for 4 weeksFriends/family of the registered user sponsor the user $5 for every day they run $5kmFriends/family of the registered user can also make a donation (ie. not requiring sponsorship)Donations & sponsorships would be made direct to the fundraising site (ie. not via registered user)Registered users can link their challenge progress to their facebook pageIf anyone has some ideas, I'd really appreciate. Just to be clear, I'm looking for an online service or software that can be customised.
Online service or software for fundraising site?
web services;software
While I've decided to decline the job described above, I did find Convio's Common Ground Fundraising which may be of assistance to others in future. The downside is their pricing.See Convio's API & Webservices for further information.
_softwareengineering.334500
Let's say I have a method called setDate. I also have another method called isValidDate to see if a string is a valid date string.For convenience, setDate uses isValidDate internally as a mean of validation, so the developer doesn't have to do the validation manually. But isValidDate is used in other methods as well. It will also throw an exception when the passed string is not a valid date string.I have unit tests for isValidDate to make sure the logic works fine. I also have some unit tests for setDate but none of them is overlapped with isValidDate tests.That means if someone accidentally removes the call to isValidDate from setDate method, all of its tests would pass, as well as all the tests for isValidDate method, but in fact setDate now can set invalid dates.Do I have a design flaw in structuring my code, or should I just write duplicated tests for both methods if I want that extra bit of reliability?
Should I write duplicated tests for 'setDate' and 'isValidDate' methods?
unit testing
I'll assume setDate() looks something like this:public void setDate(Date d) { if (!isValidDate(d)) throw SomeException(...); this.date = d;}public Date getDate() { return this.date; }I'm including a getDate() as well since tests for setting and getting can't be separated.There are two approaches to handle the test duplication.Only test what the method does directly.There are two schools of though regarding unit tests:The test should describe the full behaviour of the unit under test.The test should only cover the value added by the unit under test, and ignore work done by external parts.Using the latter approach, what does setDate() do? For invalid dates (determined with an external methods that's not going to be tested here), it throws an exception. Otherwise, we can get the same date back with getDate().This gives us exactly two test cases. In a sketch:void test_setDate__throwsOnInvalidDates() { MyObject obj = new MyObject(); Date invalidDate = ...; try { obj.setDate(invalidDate); assert(false, setDate() did not reject the invalid date); } catch (SomeException e) { assert(true); }}void test_getDate__canRetrieveValuesFromSetDate() { MyObject obj = new MyObject(); Date d = new Date(...); obj.setDate(d); assertEquals(obj.getDate(), d);}Generate test data once, use for both tests.By storing a list of valid and invalid dates, we can test both isValidDate() and setDate() without notable repetition. How you can parametrize your tests to use a list of cases depends on your framework, here I'll put the loop inside a test:Date[] validDates = { ... };Date[] invalidDates = { ... };void test_isValidDate__acceptsValidDates() { for (Date d : validDates) assertTrue(isValidDate(d), d.toString());}void test_isValidDate__rejectsInvalidDates() { for (Date d : invalidDates) assertTrue(!sValidDate(d), d.toString());}...void test_getDate__canRetrieveValuesFromSetDate() { for (Date d : validDates) { MyObject obj = new MyObject(); obj.setDate(d); assertEquals(obj.getDate(), d); }}void test_setDate__throwsOnInvalidDates() { for (Date d : invalidDates) { MyObject obj = ...; try { obj.setDate(d); assertTrue(false, ...); } catch (SomeException e) { assertTrue(true); } }}In practice, these should be separate test cases instead of loops within a single test case, so that a failing test does not prevent the other dates from being tested more data on which dates fail or succeed can make debugging much easier.While this approach is immune to refactoring, it does cause tests to run longer (an issue for very large test suites), and creates the problem of generating the necessary data.I personally prefer the first approach only testing the function added immediately by some method. This helps to keep test suites small and meaningful. But if you feel that is not sufficient, or if you expect that a programmer would carelessly remove a validation check, then generating a reusable list of test data is probably better. I have used both approaches, and both work well.
_softwareengineering.314200
Suppose I work at Microsoft. I would probably write the bulk of my code using Visual Studio, which is one of Microsoft's most popular projects. Therefore, dogfooding.Now suppose I work at Netflix, which provides a video streaming service for entertainment value. I'm not going to watch House of Cards on the job (wink). I might when I get home, though. Can an employee's use of a company's product off the clock (e.g. entertainment software, tools for personal projects, etc.) be considered dogfooding?
Is an employee's use of his/her company's product outside of work considered dogfooding?
terminology;dogfooding
No.The term dogfooding is specifically reserved for a company using its own products, for testing and promotional (we use our own stuff) purposes, not for casual use of those same products outside of work, even by employees. The only scenario of that kind that I would consider dogfooding would be Netflix giving their employees free subscriptions in return for bug reports and telemetry. The company has to have some skin in the game, in other words.In a testing scenario, you would want to be exercising the UI more than would happen when you're just passively watching House of Cards. Unless, of course, all you're testing is the stability of the video player.
_codereview.79905
Below is the code I have written to capitalize all the words of a sentence except ifThe words belong to the littleWords list.The word would be capitalized if it's the first word of the sentence even if it is in the littleWords list. def titleize(sentence) littleWords = [end, over, and, the] words = sentence.split(/^(\w+)\b/) sentence = if words[2] words[2].split( ).map do |word| littleWords.include?(word) ? ( + word) : ( + word.titleize) end end words[1].titleize + (sentence||[]).join()endSPEC describe titleize doit capitalizes a word do titleize(jaws).should == Jawsendit capitalizes every word (aka title case) do titleize(david copperfield).should == David Copperfieldendit doesn't capitalize 'little words' in a title do titleize(war and peace).should == War and Peaceendit does capitalize 'little words' at the start of a title do titleize(the bridge over the river kwai).should == The Bridge over the River KwaiendendI am new to ruby/script and am coming from Java. The code above doesnt looks as nice and clean as I think could be done with ruby.
Titleize words in a sentence but with some conditions
beginner;strings;ruby;unit testing
null
_unix.285624
Suppose I run sudo mount -a after setting /etc/fstab to: /dev/usbhd1 /path/to/mount/point ntfs rw,auto,nofail 0 1 Yesterday, upon asking what steps our architect and I should do next after a SanDisk USB disconnect on an Ubuntu Linux 16.04 operating system installed from a Live CD on a Lenovo Thinkstation quad-core desktop, I was instructed by Serge, meuh and Julie Pelletier to implement the following steps: If you are going to connect and disconnect your HD regularly,then set up udev rule to mount it upon insertion at expected location. you could omit fstab entry in this caseHow do I set up a udev rule to automatically mount and unmount the SanDisk Cruzer USB upon insertion and removal of the same USB in order to eliminate an fstab entry? I would like this udev rule to apply to reboots also.How do I make udev and fstab rules to differentiate between 2 identical SanDisk Cruzer 8 Gigabyte USB drives I purchased from BestBuy?Any help is greatly appreciated.
How do I set up a udev rule to mount the SanDisk Cruzer USB upon insertion in order to eliminate an fstab entry?
ubuntu;mount;udev;fstab;unmounting
null
_codereview.134028
Part 2 here.I wrote this class for packing data.Would it benefit from being named BitPacker rather than BitStream (and change write/read to pack/unpack), or it works as is?How can I improve it? Any way to make it more efficient? How can I reduce the amount of code? I have a lot of copy/pasted code with minor things changed that I'm not sure how (if?) I can condense.And, of course, any other comments.using System;using System.Collections;using System.Collections.Generic;/// <summary>/// Used to store data as bits. Acts as a queue - first data added is the first data removed./// Data should be read in the same order it is written. If read in a different order, it gives undefined results./// Reading from an empty BitStream returns 0./// </summary>public class BitStream{ ulong scratch_write; int scratch_write_bits; ulong scratch_read; int scratch_read_bits; Queue<ulong> buffer; /// <summary> /// How many bits are currently in the BitStream /// </summary> public long StoredBits { get; private set; } #region Constructors /// <summary> /// Make a new BitStream /// </summary> public BitStream() { scratch_write = 0; scratch_write_bits = 0; scratch_read = 0; scratch_read_bits = 0; buffer = new Queue<ulong>(); } /// <summary> /// Make a new BitStream /// </summary> /// <param name=bitCount>How many bits you expect this stream will hold. A closer value nets increased performance.</param> public BitStream( long bitCount ) { scratch_write = 0; scratch_write_bits = 0; scratch_read = 0; scratch_read_bits = 0; buffer = new Queue<ulong>( (int) IntDivideRoundUp( bitCount, 64 ) ); } /// <summary> /// Make a new BitStream containing bits from the byte array /// NOTE: StoredBits may return a higher count than there are actual bits to read if the byte array came from another BitStream. /// </summary> /// <param name=bits>contains bits to be stored in the bitstream</param> public BitStream( byte[] bits ) { scratch_write = 0; scratch_write_bits = 0; scratch_read = 0; scratch_read_bits = 0; buffer = new Queue<ulong>(); foreach ( var bite in bits ) { Write( bite, byte.MinValue, byte.MaxValue ); } } #endregion /// <summary> /// Get the bits stored in a ulong array (left-endian) /// </summary> /// <returns>ulong array of bits</returns> public ulong[] GetUlongArray() { ResetBuffer(); if ( scratch_write_bits > 0 ) { ulong[] result = new ulong[ buffer.Count + 1 ]; Array.Copy( buffer.ToArray(), result, buffer.Count ); result[ buffer.Count ] = scratch_write; return result; } return buffer.ToArray(); } /// <summary> /// Get the bits stored in a byte array (left-endian) /// </summary> /// <returns>byte array of bits</returns> public byte[] GetByteArray() { ResetBuffer(); int extraBytes = (int) IntDivideRoundUp( scratch_write_bits, 8 ); byte[] result = new byte[ buffer.Count * 8 + extraBytes ]; Buffer.BlockCopy( buffer.ToArray(), 0, result, 0, result.Length - extraBytes ); int index = buffer.Count * 8; int bits = scratch_write_bits; ulong scratch = scratch_write; while ( bits > 0 ) { int bitsToStore = bits >= 8 ? 8 : bits; result[ index ] = (byte) ( scratch >> ( 64 - bitsToStore ) ); scratch <<= bitsToStore; bits -= bitsToStore; index++; } return result; } /// <summary> /// Get the bits stored in a BitArray /// </summary> /// <returns>all bits in the stream in a BitArray</returns> public BitArray GetBitArray() { ResetBuffer(); BitArray ba = new BitArray( buffer.Count * 64 + scratch_write_bits ); var tempBuf = buffer.ToArray(); int counter = 0; for ( int i = 0; i < ba.Count; i++ ) { for ( int j = 0; j < 64; j++ ) { ba[ counter ] = ( tempBuf[ i ] & ( (ulong) 1 << ( 63 - j ) ) ) > 0; counter++; } } for ( int i = 0; i < scratch_write_bits; i++ ) { ba[ counter ] = ( scratch_write & ( (ulong) 1 << ( 63 - i ) ) ) > 0; counter++; } return ba; } #region Write /// <summary> /// Write bits to the stream /// </summary> /// <param name=data>bits to be written</param> /// <param name=bits>how many bits</param> protected void Write( ulong data, int bits ) { if ( bits == 0 ) return; scratch_write |= ( ( data << ( 64 - bits ) ) >> scratch_write_bits ); scratch_write_bits += bits; if ( scratch_write_bits >= 64 ) { buffer.Enqueue( scratch_write ); scratch_write = 0; scratch_write_bits -= 64; if ( scratch_write_bits > 0 ) scratch_write |= ( data << ( 64 - scratch_write_bits ) ); } StoredBits += bits; } /// <summary> /// Write 1 bit to the stream /// </summary> /// <param name=data>bit to be written</param> public void Write( bool data ) { Write( BitConverter.GetBytes( data )[ 0 ], 1 ); } /// <summary> /// Write bits to the stream /// </summary> /// <param name=data>bits to be written</param> /// <param name=min>the minimum number that can be written</param> /// <param name=max>the maximum number that can be written</param> public void Write( byte data, byte min, byte max ) { if ( min > max ) swap( min, max ); if ( data < min || data > max ) throw new ArgumentOutOfRangeException( data, data, must be between min and max ); Write( data, BitsRequired( max ) ); } /// <summary> /// Write bits to the stream /// </summary> /// <param name=data>bits to be written</param> /// <param name=min>the minimum number that can be written</param> /// <param name=max>the maximum number that can be written</param> public void Write( sbyte data, sbyte min, sbyte max ) { if ( min > max ) swap( min, max ); if ( data < min || data > max ) throw new ArgumentOutOfRangeException( data, data, must be between min and max ); if ( data == sbyte.MinValue ) { Write( (ulong) data, 64 ); return; } long data2 = data; int bits = BitsRequired( min, max ); if ( data2 < 0 ) { data2 = ~data2 | ( 1L << ( bits - 1 ) ); } Write( (ulong) data2, bits ); } /// <summary> /// Write bits to the stream /// </summary> /// <param name=data>bits to be written</param> /// <param name=min>the minimum number that can be written</param> /// <param name=max>the maximum number that can be written</param> public void Write( char data, char min, char max ) { if ( min > max ) swap( min, max ); if ( data < min || data > max ) throw new ArgumentOutOfRangeException( data, data, must be between min and max ); int bits = BitsRequired( min, max ); Write( (ulong) data, bits ); } /// <summary> /// Write bits to the stream /// </summary> /// <param name=data>bits to be written</param> /// <param name=min>the minimum number that can be written</param> /// <param name=max>the maximum number that can be written</param> public void Write( short data, short min, short max ) { if ( min > max ) swap( min, max ); if ( data < min || data > max ) throw new ArgumentOutOfRangeException( data, data, must be between min and max ); if ( data == short.MinValue ) { Write( (ulong) data, 64 ); return; } long data2 = data; int bits = BitsRequired( min, max ); if ( data2 < 0 ) { data2 = ~data2 | ( 1L << ( bits - 1 ) ); } Write( (ulong) data2, bits ); } /// <summary> /// Write bits to the stream /// </summary> /// <param name=data>bits to be written</param> /// <param name=min>the minimum number that can be written</param> /// <param name=max>the maximum number that can be written</param> public void Write( ushort data, ushort min, ushort max ) { if ( min > max ) swap( min, max ); if ( data < min || data > max ) throw new ArgumentOutOfRangeException( data, data, must be between min and max ); Write( data, BitsRequired( max ) ); } /// <summary> /// Write bits to the stream /// </summary> /// <param name=data>bits to be written</param> /// <param name=min>the minimum number that can be written</param> /// <param name=max>the maximum number that can be written</param> public void Write( int data, int min, int max ) { if ( min > max ) swap( min, max ); if ( data < min || data > max ) throw new ArgumentOutOfRangeException( data, data, must be between min and max ); if ( data == int.MinValue ) { Write( (ulong) data, 64 ); return; } long data2 = data; int bits = BitsRequired( min, max ); if ( data2 < 0 ) { data2 = ~data2 | ( 1L << ( bits - 1 ) ); } Write( (ulong) data2, bits ); } /// <summary> /// Write bits to the stream /// </summary> /// <param name=data>bits to be written</param> /// <param name=min>the minimum number that can be written</param> /// <param name=max>the maximum number that can be written</param> public void Write( uint data, uint min, uint max ) { if ( min > max ) swap( min, max ); if ( data < min || data > max ) throw new ArgumentOutOfRangeException( data, data, must be between min and max ); Write( data, BitsRequired( max ) ); } /// <summary> /// Write bits to the stream /// </summary> /// <param name=data>bits to be written</param> /// <param name=min>the minimum number that can be written</param> /// <param name=max>the maximum number that can be written</param> public void Write( long data, long min, long max ) { if ( min > max ) swap( min, max ); if ( data < min || data > max ) throw new ArgumentOutOfRangeException( data, data, must be between min and max ); if ( data == long.MinValue ) { Write( (ulong) data, 64 ); return; } int bits = BitsRequired( min, max ); if ( data < 0 ) { data = ~data | ( 1L << ( bits - 1 ) ); } Write( (ulong) data, bits ); } /// <summary> /// Write bits to the stream /// </summary> /// <param name=data>bits to be written</param> /// <param name=min>the minimum number that can be written</param> /// <param name=max>the maximum number that can be written</param> public void Write( ulong data, ulong min, ulong max ) { if ( min > max ) swap( min, max ); if ( data < min || data > max ) throw new ArgumentOutOfRangeException( data, data, must be between min and max ); Write( data, BitsRequired( max ) ); } /// <summary> /// Write bits to the stream /// </summary> /// <param name=data>bits to be written</param> /// <param name=min>the minimum number that can be written</param> /// <param name=max>the maximum number that can be written</param> /// <param name=precision>how many digits after the decimal</param> public void Write( float data, float min, float max, byte precision ) { if ( min > max ) swap( min, max ); if ( data < min || data > max ) throw new ArgumentOutOfRangeException( data, data, must be between min and max ); int mult = IntPow( 10, precision ); double infoMax = Math.Round( max * mult, MidpointRounding.AwayFromZero ); double infoMin = Math.Round( min * mult, MidpointRounding.AwayFromZero ); if ( infoMax > uint.MaxValue || -infoMax > uint.MaxValue || infoMin > uint.MaxValue || -infoMin > uint.MaxValue ) { Write( (ulong) BitConverter.DoubleToInt64Bits( data ), 32 ); return; } int info = (int) Math.Round( data * mult, MidpointRounding.AwayFromZero ); Write( info, (int) infoMin, (int) infoMax ); } /// <summary> /// Write bits to the stream /// </summary> /// <param name=data>bits to be written</param> /// <param name=min>the minimum number that can be written</param> /// <param name=max>the maximum number that can be written</param> /// <param name=precision>how many digits after the decimal</param> public void Write( double data, double min, double max, byte precision ) { if ( min > max ) swap( min, max ); if ( data < min || data > max ) throw new ArgumentOutOfRangeException( data, data, must be between min and max ); int mult = IntPow( 10, precision ); double infoMax = Math.Round( max * mult, MidpointRounding.AwayFromZero ); double infoMin = Math.Round( min * mult, MidpointRounding.AwayFromZero ); if ( infoMax > ulong.MaxValue || -infoMax > ulong.MaxValue || infoMin > ulong.MaxValue || -infoMin > ulong.MaxValue ) { Write( (ulong) BitConverter.DoubleToInt64Bits( data ), 64 ); return; } long info = (long) Math.Round( data * mult, MidpointRounding.AwayFromZero ); Write( info, (long) infoMin, (long) infoMax ); } #endregion #region Read /// <summary> /// Read bits from the stream /// </summary> /// <param name=bits>How many bits to read</param> /// <returns>bits read in ulong form</returns> protected ulong Read( int bits ) { StoredBits -= bits; if ( buffer.Count == 0 ) { scratch_read = scratch_write; scratch_read_bits = scratch_write_bits; } if ( bits == 0 || ( buffer.Count == 0 && scratch_write_bits == 0 ) ) return 0; ulong data = scratch_read >> ( 64 - bits ); if ( scratch_read_bits < bits ) { bits -= scratch_read_bits; if ( buffer.Count == 0 ) { scratch_read = scratch_write; scratch_read_bits = scratch_write_bits; data |= ( scratch_read >> ( 64 - bits ) ); scratch_read <<= bits; scratch_read_bits -= bits; scratch_write = scratch_read; scratch_write_bits = scratch_read_bits; } else { scratch_read = buffer.Dequeue(); scratch_read_bits = 64; data |= ( scratch_read >> ( 64 - bits ) ); scratch_read <<= bits; scratch_read_bits -= bits; } } else { scratch_read <<= bits; scratch_read_bits -= bits; if ( buffer.Count == 0 ) { scratch_write = scratch_read; scratch_write_bits = scratch_read_bits; } } if ( StoredBits <= 0 ) // handle the case of asking for more bits than exist in the stream { StoredBits = 0; scratch_write = 0; scratch_write_bits = 0; scratch_read = 0; scratch_read_bits = 0; } return data; } /// <summary> /// Read a bit from the stream and write it to data /// </summary> /// <param name=data>the variable to be written to</param> public void Read( out bool data ) { data = Read( 1 ) > 0; } /// <summary> /// Read bits from the stream and write that information to data. /// WARNING: If you read data in a different order than written, there is a possibility that the actual number written to data is outside of the given range. In such a case, you may want to check the bounds yourself. /// </summary> /// <param name=data>the variable to be written to</param> /// <param name=min>the smallest possible number that could have been written</param> /// <param name=max>the largest possible number that could have been written</param> public void Read( out ulong data, ulong min, ulong max ) { if ( min > max ) swap( min, max ); int bits = BitsRequired( max ); data = Read( bits ); } /// <summary> /// Read bits from the stream and write that information to data. /// WARNING: If you read data in a different order than written, there is a possibility that the actual number written to data is outside of the given range. In such a case, you may want to check the bounds yourself. /// </summary> /// <param name=data>the variable to be written to</param> /// <param name=min>the smallest possible number that could have been written</param> /// <param name=max>the largest possible number that could have been written</param> public void Read( out uint data, uint min, uint max ) { if ( min > max ) swap( min, max ); int bits = BitsRequired( max ); data = (uint) Read( bits ); } /// <summary> /// Read bits from the stream and write that information to data. /// WARNING: If you read data in a different order than written, there is a possibility that the actual number written to data is outside of the given range. In such a case, you may want to check the bounds yourself. /// </summary> /// <param name=data>the variable to be written to</param> /// <param name=min>the smallest possible number that could have been written</param> /// <param name=max>the largest possible number that could have been written</param> public void Read( out ushort data, ushort min, ushort max ) { if ( min > max ) swap( min, max ); int bits = BitsRequired( max ); data = (ushort) Read( bits ); } /// <summary> /// Read bits from the stream and write that information to data. /// WARNING: If you read data in a different order than written, there is a possibility that the actual number written to data is outside of the given range. In such a case, you may want to check the bounds yourself. /// </summary> /// <param name=data>the variable to be written to</param> /// <param name=min>the smallest possible number that could have been written</param> /// <param name=max>the largest possible number that could have been written</param> public void Read( out byte data, byte min, byte max ) { if ( min > max ) swap( min, max ); int bits = BitsRequired( max ); data = (byte) Read( bits ); } /// <summary> /// Read bits from the stream and write that information to data. /// WARNING: If you read data in a different order than written, there is a possibility that the actual number written to data is outside of the given range. In such a case, you may want to check the bounds yourself. /// </summary> /// <param name=data>the variable to be written to</param> /// <param name=min>the smallest possible number that could have been written</param> /// <param name=max>the largest possible number that could have been written</param> public void Read( out char data, char min, char max ) { if ( min > max ) swap( min, max ); int bits = BitsRequired( max ); data = (char) Read( bits ); } /// <summary> /// Read bits from the stream and write that information to data. /// WARNING: If you read data in a different order than written, there is a possibility that the actual number written to data is outside of the given range. In such a case, you may want to check the bounds yourself. /// </summary> /// <param name=data>the variable to be written to</param> /// <param name=min>the smallest possible number that could have been written</param> /// <param name=max>the largest possible number that could have been written</param> public void Read( out long data, long min, long max ) { if ( min > max ) swap( min, max ); int bits = BitsRequired( min, max ); ulong readBits = Read( bits ); if ( (long) readBits == long.MinValue ) { data = (long) readBits; return; } if ( min < 0 || max < 0 ) { ulong negative = readBits >> ( bits - 1 ); if ( negative > 0 ) { readBits ^= ( negative << ( bits - 1 ) ); readBits = ~readBits; readBits |= ( negative << 63 ); } } data = (long) readBits; } /// <summary> /// Read bits from the stream and write that information to data. /// WARNING: If you read data in a different order than written, there is a possibility that the actual number written to data is outside of the given range. In such a case, you may want to check the bounds yourself. /// </summary> /// <param name=data>the variable to be written to</param> /// <param name=min>the smallest possible number that could have been written</param> /// <param name=max>the largest possible number that could have been written</param> public void Read( out int data, int min, int max ) { if ( min > max ) swap( min, max ); int bits = BitsRequired( min, max ); uint readBits = (uint) Read( bits ); if ( (int) readBits == int.MinValue ) { data = (int) readBits; return; } if ( min < 0 || max < 0 ) { uint negative = readBits >> ( bits - 1 ); if ( negative > 0 ) { readBits ^= ( negative << ( bits - 1 ) ); readBits = ~readBits; readBits |= ( negative << 31 ); } } data = (int) readBits; } /// <summary> /// Read bits from the stream and write that information to data. /// WARNING: If you read data in a different order than written, there is a possibility that the actual number written to data is outside of the given range. In such a case, you may want to check the bounds yourself. /// </summary> /// <param name=data>the variable to be written to</param> /// <param name=min>the smallest possible number that could have been written</param> /// <param name=max>the largest possible number that could have been written</param> public void Read( out short data, short min, short max ) { if ( min > max ) swap( min, max ); int bits = BitsRequired( min, max ); ushort readBits = (ushort) Read( bits ); if ( (short) readBits == short.MinValue ) { data = (short) readBits; return; } if ( min < 0 || max < 0 ) { uint negative = (uint) readBits >> ( bits - 1 ); if ( negative > 0 ) { readBits ^= (ushort) ( negative << ( bits - 1 ) ); readBits = (ushort) ~readBits; readBits |= (ushort) ( negative << 63 ); } } data = (short) readBits; } /// <summary> /// Read bits from the stream and write that information to data. /// WARNING: If you read data in a different order than written, there is a possibility that the actual number written to data is outside of the given range. In such a case, you may want to check the bounds yourself. /// </summary> /// <param name=data>the variable to be written to</param> /// <param name=min>the smallest possible number that could have been written</param> /// <param name=max>the largest possible number that could have been written</param> public void Read( out sbyte data, sbyte min, sbyte max ) { if ( min > max ) swap( min, max ); int bits = BitsRequired( min, max ); byte readBits = (byte) Read( bits ); if ( (sbyte) readBits == sbyte.MinValue ) { data = (sbyte) readBits; return; } if ( min < 0 || max < 0 ) { uint negative = (uint) readBits >> ( bits - 1 ); if ( negative > 0 ) { readBits ^= (byte) ( negative << ( bits - 1 ) ); readBits = (byte) ~readBits; readBits |= (byte) ( negative << 63 ); } } data = (sbyte) readBits; } /// <summary> /// Read bits from the stream and write that information to data. /// WARNING: If you read data in a different order than written, there is a possibility that the actual number written to data is outside of the given range. In such a case, you may want to check the bounds yourself. /// </summary> /// <param name=data>the variable to be written to</param> /// <param name=min>the smallest possible number that could have been written</param> /// <param name=max>the largest possible number that could have been written</param> /// <param name=precision>how many digits after the decimal</param> public void Read( out double data, double min, double max, byte precision ) { if ( min > max ) swap( min, max ); int mult = IntPow( 10, precision ); double infoMax = Math.Round( max * mult, MidpointRounding.AwayFromZero ); double infoMin = Math.Round( min * mult, MidpointRounding.AwayFromZero ); if ( infoMax > ulong.MaxValue || -infoMax > ulong.MaxValue || infoMin > ulong.MaxValue || -infoMin > ulong.MaxValue ) { data = BitConverter.Int64BitsToDouble( (long) Read( 64 ) ); return; } long readBits; Read( out readBits, (long) infoMax, (long) infoMin ); data = readBits / (double) mult; } /// <summary> /// Read bits from the stream and write that information to data. /// WARNING: If you read data in a different order than written, there is a possibility that the actual number written to data is outside of the given range. In such a case, you may want to check the bounds yourself. /// </summary> /// <param name=data>the variable to be written to</param> /// <param name=min>the smallest possible number that could have been written</param> /// <param name=max>the largest possible number that could have been written</param> /// <param name=precision>how many digits after the decimal</param> public void Read( out float data, float min, float max, byte precision ) { if ( min > max ) swap( min, max ); int mult = IntPow( 10, precision ); float infoMax = (float) Math.Round( max * mult, MidpointRounding.AwayFromZero ); float infoMin = (float) Math.Round( min * mult, MidpointRounding.AwayFromZero ); if ( infoMax > uint.MaxValue || -infoMax > uint.MaxValue || infoMin > uint.MaxValue || -infoMin > uint.MaxValue ) { data = (float) BitConverter.Int64BitsToDouble( (int) Read( 32 ) ); return; } int readBits; Read( out readBits, (int) infoMax, (int) infoMin ); data = readBits / (float) mult; } #endregion #region Helpers /// <summary> /// /// </summary> /// <param name=max>the maximum number that will be written</param> /// <returns>how many bits are needed</returns> protected int BitsRequired( ulong max ) { if ( max == 0 ) return 1; for ( int i = 1; i < 64; i++ ) { if ( max < ( (ulong) 1 << i ) ) return i; } return 64; } /// <summary> /// /// </summary> /// <param name=min>the minimum number that will be written</param> /// <param name=max>the maximum number that will be written</param> /// <returns>how many bits are needed</returns> protected int BitsRequired( sbyte min, sbyte max ) { if ( min > max ) swap( min, max ); if ( min == sbyte.MinValue ) return 8; int signBit = 0; if ( min < 0 ) { min = (sbyte) ~min; signBit = 1; } if ( max < 0 ) { max = (sbyte) ~max; signBit = 1; } return BitsRequired( ( max > min ) ? (ulong) max : (ulong) min ) + signBit; } /// <summary> /// /// </summary> /// <param name=min>the minimum number that will be written</param> /// <param name=max>the maximum number that will be written</param> /// <returns>how many bits are needed</returns> protected int BitsRequired( short min, short max ) { if ( min > max ) swap( min, max ); if ( min == short.MinValue ) return 16; int signBit = 0; if ( min < 0 ) { min = (short) ~min; signBit = 1; } if ( max < 0 ) { max = (short) ~max; signBit = 1; } return BitsRequired( ( max > min ) ? (ulong) max : (ulong) min ) + signBit; } /// <summary> /// /// </summary> /// <param name=min>the minimum number that will be written</param> /// <param name=max>the maximum number that will be written</param> /// <returns>how many bits are needed</returns> protected int BitsRequired( int min, int max ) { if ( min > max ) swap( min, max ); if ( min == int.MinValue ) return 32; int signBit = 0; if ( min < 0 ) { min = ~min; signBit = 1; } if ( max < 0 ) { max = ~max; signBit = 1; } return BitsRequired( ( max > min ) ? (ulong) max : (ulong) min ) + signBit; } /// <summary> /// /// </summary> /// <param name=min>the minimum number that will be written</param> /// <param name=max>the maximum number that will be written</param> /// <returns>how many bits are needed</returns> protected int BitsRequired( long min, long max ) { if ( min > max ) swap( min, max ); if ( min == long.MinValue ) return 64; int signBit = 0; if ( min < 0 ) { min = ~min; signBit = 1; } if ( max < 0 ) { max = ~max; signBit = 1; } return BitsRequired( ( max > min ) ? (ulong) max : (ulong) min ) + signBit; } /// <summary> /// If scratch_read contains any bits, moves them to the head of the buffer. /// NOTE: Not a short operation, use only when necessary! /// </summary> protected void ResetBuffer() { if ( scratch_read_bits > 0 && scratch_read != scratch_write ) { if ( scratch_write_bits > 0 ) buffer.Enqueue( scratch_write ); var oldBuf = buffer.ToArray(); buffer.Clear(); int tempBits = scratch_write_bits; scratch_write = 0; scratch_write_bits = 0; Write( scratch_read, scratch_read_bits ); scratch_read = 0; scratch_read_bits = 0; for ( int i = 0; i < oldBuf.Length - 1; i++ ) Write( oldBuf[ i ], 64 ); Write( oldBuf[ oldBuf.Length - 1 ], tempBits ); } } void swap<T>( T obj1, T obj2 ) { T temp = obj1; obj1 = obj2; obj2 = temp; } long IntDivideRoundUp( long upper, long lower ) { return ( upper + lower - 1 ) / lower; } int IntPow( int x, uint pow ) { int ret = 1; while ( pow != 0 ) { if ( ( pow & 1 ) == 1 ) ret *= x; x *= x; pow >>= 1; } return ret; } #endregion}It works by determining how many bits are actually required to store a number based on the min and max (e.g. 63 needs 6 bits, 64 needs 7 bits).Example use (as requested):BitStream bs = new BitStream();int min1 = -1000, max1 = 1000, num1 = 287;float min2 = 0f, max2 = 50f, num2 = 16.78634f;double min3 = double.MinValue, max3 = double.MaxValue, num3 = 9845216.1916526;byte fltPrec = 2;byte dblPrec = 0;bs.Write( num1, min1, max1 ); // 12 bits (11 bits for 1000 plus 1 bit for negative sign)bs.Write( num2, min2, max2, fltPrec ); // converts to 1679 int, 14 bits (maximum converted to int is 5000)bs.Write( num3, min3, max3, dblPrec ); // precision is ignored here as min/max are too high to try to convert to an integer, so the value is stored using all 64 bits of the doublebs.Write( true ); // 1 bitint num4;float num5;double num6;bool checker;bs.Read( out num4, min1, max1 ); // num4 = 287bs.Read( out num5, min2, max2, fltPrec ); // num5 = 16.79, there is some loss of precision herebs.Read( out num6, min3, max3, dblPrec ); // num6 = 9845216.1916526, no loss of precisionbs.Read( out checker ); // checker = trueint newNum;bs.Read( out newNum, -100, 100 ); // newNum = 0 as there are no bits left in the BitStream
Packing and unpacking bits
c#;bitwise;serialization;stream
BugThe swap<T>() method isn't doing what you think it does, because the passed in T obj1, T obj2 aren't passed with the ref keyword the values ar only changed in that method not targeting the variable values of the calling method. So thisint min = 10;int max = 5;swap(min, max);Console.WriteLine(String.Format({0} : {1}, min, max);will output 10 : 5 But using the ref keyword wouldn't be that good either. using regions is considered to be a antipattern, not only because of the reasons statet in the answer of the link, but also because having 4 regions indicates that your class is doing too much. based on the .NET naming guidelines variables should be named using camelCase instead of snake_case casing. you should always use braces {} although they might be optional. Using them will make your code less error prone. The least you should do is that you stick to a choosen style. Right now you are mixing the styles, sometimes using braces and sometimes you don't , e.g if ( data2 < 0 ){ data2 = ~data2 | ( 1L << ( bits - 1 ) );}by using constructor chaining, you can remove some of the duplicated code like so public BitStream(){ scratch_write = 0; scratch_write_bits = 0; scratch_read = 0; scratch_read_bits = 0; buffer = new Queue<ulong>();}public BitStream(long bitCount) : this(){ buffer = new Queue<ulong>((int)IntDivideRoundUp(bitCount, 64));}public BitStream(byte[] bits) : this(){ foreach (var bite in bits) { Write(bite, byte.MinValue, byte.MaxValue); }} or you can just initialize some of the values like so ulong scratch_write = 0;int scratch_write_bits = 0;ulong scratch_read = 0;int scratch_read_bits = 0;Queue<ulong> buffer = new Queue<ulong>();public BitStream(){ }public BitStream(long bitCount){ buffer = new Queue<ulong>((int)IntDivideRoundUp(bitCount, 64));}public BitStream(byte[] bits){ foreach (var bite in bits) { Write(bite, byte.MinValue, byte.MaxValue); }}the spaces after opening ( and before the closing ) are looking strange in my eyes. A C# developer wouldn't expect them. protected int BitsRequired( long min, long max )
_unix.174181
I recently got a Samsung SSD. I have debian wheezy installed on it. I carry it around in a USB enclosure and boot both my work and home computers from it. How can I ensure that the system properly powers down the drive during shutdown? The following SMART metrics seem to indicate that it doesn't:ID# ATTRIBUTE_NAME FLAG VALUE WORST THRESH TYPE UPDATED WHEN_FAILED RAW_VALUE 12 Power_Cycle_Count 0x0032 099 099 000 Old_age Always - 24235 Unknown_Attribute 0x0012 099 099 000 Old_age Always - 23I believe the numbers indicate the drive has been powered up 24 times and has lost power unexpectedly 23 times, i.e. every power down. The metrics are described on Samsung's website as follows:ID # 12 Power-On CountThe raw value of this attribute reports the cumulative number of power on/off cycles. This includes both sudden power off and normal power off cases.ID # 235 Power Recovery CountA count of the number of sudden power off cases. If there is a sudden power off, the firmware must recover all of the mapping and user data during the next power on. This is a count of the number of times this has happened.I read that unexpected power loss is bad for an SSD.Edit: Now I'm not sure this is a real question. I tried attaching the drive to a different system, putting it to sleep with hdparm -Y /dev/sdX, and then disconnecting the USB cable. It still increments the power recovery count. I tried this with three different enclosures. I think I'll take this issue to Samsung.
Properly power down SSD during shutdown
debian;usb;shutdown;smart
null
_cstheory.27417
In 1982, Barahona proved that finding the ground state of an Ising model is NP-hard. Later, in 2000, Istrail proved that it is NP-complete. When I look up the citations of these two papers using Google scholar, it appears that the previous and weaker result has 647 citations while on the other hand the more recent and stronger result has 109 citations.Shouldn't it be the other way round? Isn't a stronger result more useful?
Which complexity information of Ising model is more important?
np hardness;np complete;combinatorics;statistical physics;citations
null
_webmaster.108302
I have a single-page application, and I am tracking events on the page, in Google Analytics, passing our internal user ID and timestamp as attributes on the event. I would like to know the best way to find the top bounce (UPDATE: exit is a better term for this) events - i.e. events that are more than averagely likely to be the last event that a user fires. I think I can do this by extracting the raw event data from the GA API, and simply running my own analyses on it, using the timestamps. Is this correct? (UPDATE: It seems not, because GA doesn't allow the export of raw event data.) Is there any way to do this within the GA interface? I think I'm right in saying that the Event Flow won't show me the overall exit rates for a particular event. I'm looking to create information like this:create new document: last event 10% of the time it was firededit document: last event 5% of the time it was firedturn on track changes: last event 80% of the time it was firedSo that I can spot which events look problematic, like the last one in this example.
Google Analytics - find exit rate for events, rather than pages?
google analytics
null
_unix.152953
On Linux within bash the Pseudo Terminal window (terminator) as well as the Terminal itself freezes when trying to use autocomplete (TAB) as well as after getting an error message using gzip and tar.So far this only happens with gzip and tar…after getting an error message (own fault, typos, etc.)using autocompleteCTRL+C somehow solves the problem in so far as I can work on and have (up to now) no problems with other commands EXCEPT tar. Thus, the problem is repeatable. I would very much appreciate help from here on.I can isolate the problem further, as it had a comback: As hinted in a comment, un commenting the following section in ~/home/USER/.bashrc # if ! shopt -oq posix; then# if [ -f /usr/share/bash-completion/bash_completion ]; then# . /usr/share/bash-completion/bash_completion# elif [ -f /etc/bash_completion ]; then# . /etc/bash_completion# fi# fihelped in so far as trying to use autocompletestill sends the Terminal Emulation (pts) into deep freeze when using TAB after the first occurrence of -- until CTRL+C ends itthe real terminal (tty) seems to ignore TAB completely with gzip and tar. I could live that and a long face, but then … really?Config FilesThe other config file (I know) for completion would be /etc/bash.bashrc which would turn completion off completely I guess. Not good. The config files for the terminal emulator doesn't have any settings for autocomplete or suchI can type some characters and then the Terminal freezes – takes no more keystrokes. This happens both in an emulated terminal window (pts) in the GUI and also real promt (tty).I work from a keyboard connected via USB, and not on a laptop or the like.What would be a proper way to kill a terminal session like: »kill tty1 from tty2« because this is exactly what I'm stuck here!
Terminal freezes after using tar or gz
bash;terminal;tar;gzip
null
_unix.43695
For some reason, my laptop (HP ProBook 5320m) refuses to boot when I install the ISO images for openSUSE 12.1 on an USB stick (the stick starts to blink and then the internal fan goes into overdrive and I have to switch off the laptop).I also tried the NET version, different USB sticks, no game. Currently, openSUSE 11.4 is installed on the laptop, is it's not impossible to install. My guess is that something was changed in the 12.1 release which the BIOS of the laptop doesn't like.So my last hope is to create a bootable external hard disk but when I look into the folder /boot of the ISO image, I can't find GRUB or anything that I recognize.Questions:Is there a way to replace the ISO boot loader with GRUB?Is there some other way to install 12.1 on openSUSE 11.4? Ubuntu can do a dist upgrade in the running system, for example. Is something like that possible with openSUSE, too?Could I boot with the installer for 11.4 and somehow make it use the installation files for 12.1?PS: Dear HP engineers. Your BIOS looks great but I'd prefer one that works. Just saying :-(
How do I install openSUSE 12.1 from an external hard disk?
opensuse;system installation;usb drive;bios
Probably not. GRUB is a general purpose bootloader. The SYSLINUX bootloaders are different, there is one for each medium.How to upgrade OpenSuSE 11.4 to 12.1
_webmaster.38099
I'm getting a warning when submitting my sitemap to webmaster tools it saying that my pages are blocked by robots.txt when they are not. Has any one come across this or a way to resolve this before ?Here is the error message:Here is my robots.txt file:User-agent: *Disallow:Sitemap: http://mydomain.co.uk/sitemap.xml
Google Webmaster Tools is showing incorrect warnings - blocked by robots.txt
google search console;robots.txt
Some times that warning means there is a meta noindex tag on your site not just robots.txt blocking the robots. Go to your website and view the source code in a private browser session. Are you using any CMS such as WordPress or another?Also if you've made changes to allow robots it can take hours or up to 48 hours for Google to recognize the changes and successfully crawl and access your sitemap. You can go to Health on the sidebar in Google webmaster tools and fetch as Googlebot it'll probably give you the same error no matter what page you try and access.
_softwareengineering.263644
(I am currently using groovy but it should apply to most OO languages so I also put the langauge-agnostic tag)I try to program in a function style which also includes method chaining and avoiding variables. Therefore I often find myself writing code with the with method in groovy that every object has. It works likes this:someobject.doSomething().doEvenMore() //this results in an object that I need check for some condition, e.g. a String.with { String result -> if (result != I AM A CORRECT RESULT) throw new Exception(assertion failed) else return result //need to do this because else the closure will return null}.doAnotherThingOnTheResult()//and so on(See also https://codereview.stackexchange.com/questions/57676/better-way-to-assert-correct-return-values-in-groovy for a real life example I asked some time ago)This is rather unconcise so I was searching for a better way to check for conditions without using to have with. I came up with an idea I would like to hear your opinions to.That is, an method that all objects have and that can be used like this:someobject.doSomething().doEvenMore() //this results in an object that I need check for some condition, e.g. a String.assertTrue (new Exception(custom exception)) { it == I AM A CORRECT RESULT }.doAnotherThingOnTheResult()//and so onor for default behaviour with a default exception typesomeobject.doSomething().doEvenMore() //this results in an object that I need check for some condition, e.g. a String.assertTrue { it == I AM A CORRECT RESULT } //results in AssertionException or sth similiar.doAnotherThingOnTheResult()//and so onIn groovy I can make it that every (new) created object is decorated with such a method. What do you guys think about it? Are there better ways or should I stay with the with method?
Method for all objects for checking conditions which also includes method chaining and avoiding variables
language agnostic;clean code;groovy;meta programming;method chaining
First, I think it is a good idea to refactor the with part into its own function. It makes IMHO the code easier to read, and it corresponds to the Single Level of Abstraction principle, which is one characteristic of clean code. Second, if it is a good idea to decorate every class of your program with this additional method, depends. I would do this only if you need this function all over your whole program, in many classes. Otherwise, I would restrict it to the classes which really use the method. This helps to avoid unintentional naming collisions.
_codereview.101234
I made a commandline tool for renaming files, similar to the rename command in Ubuntu. Here is the code:import scala.collection.mutable.Mapobject Main extends App { val usage = |A commandline tool for renaming files (written in Scala) | |Usage: | | screname [-a] [-t] -s search_pattern -r replace_pattern filenames | |Type screname and return to print this message. .stripMargin // Print usage and exit def printHelpExit() = { println(usage) System.exit(0) } if (args.length == 0) { printHelpExit() } val arglist = args.toList type OptionMap = Map[Symbol, Any] // Is the arg a switch? def isSwitch(s: String) = (s(0) == '-') // Function for parse args def nextOption(map: OptionMap, list: List[String]): OptionMap = { list match { // List is exhausted case Nil => map case -a :: tail => { nextOption(map ++ Map('replaceAll -> true), tail) } case -t :: tail => { nextOption(map ++ Map('testRun -> true), tail) } case -s :: searchPattern :: tail => { if (map.contains('searchPattern)) throw new IllegalArgumentException(Only one search pattern allowed.) nextOption(map ++ Map('searchPattern -> searchPattern), tail) } case -r :: replacePattern :: tail => { if (map.contains('replacePattern)) throw new IllegalArgumentException(Only one replace pattern allowed) nextOption(map ++ Map('replacePattern -> replacePattern), tail) } case filename :: tail => { map.update('files, filename :: (map.getOrElse('files, List())).asInstanceOf[List[String]]) nextOption(map, tail) } } } val options = nextOption(Map(), arglist) // Validate options if (!options.contains('searchPattern)) throw new IllegalArgumentException(No search pattern provided) if (!options.contains('replacePattern)) throw new IllegalArgumentException(No replace pattern provided) if (options.getOrElse('files, List()).asInstanceOf[List[String]].size == 0) throw new IllegalArgumentException(No filenames provided) // Rename val fileRenamer = new FileRenameByPattern(options.getOrElse('files, List()).asInstanceOf[List[String]], options.getOrElse('searchPattern, ).asInstanceOf[String], options.getOrElse('replacePattern, ).asInstanceOf[String], options.getOrElse('replaceAll, false).asInstanceOf[Boolean]) if (options.getOrElse('testRun, false).asInstanceOf[Boolean]) { fileRenamer.printFileNamePairs() } else { fileRenamer.rename(); }}import java.io.File/** * Created by IDEA on 17/08/15. */class FileRenameByPattern(val oldFileNames: List[String], val searchPattern: String, val replacePattern: String, val replaceAll: Boolean) { val newFileNames = getNewFileNames() def getNewFileNames(): List[String] = { oldFileNames map { (x: String) => if (replaceAll) x.replaceAll(searchPattern, replacePattern) else x.replaceFirst(searchPattern, replacePattern) } } def getFileNamePairs() = { oldFileNames zip newFileNames } def rename(): List[Boolean] = { rename(getFileNamePairs()) } def rename(pairs: List[(String, String)]): List[Boolean] = { pairs map { case (o, n) => new File(o) renameTo new File(n) } } def printFileNamePairs() = { val w1 = oldFileNames.map(_.length).max val w2 = newFileNames.map(_.length).max getFileNamePairs() map { case (s1, s2) => println(%%%ds %%%ds.format(w1, w2).format(s1, s2)) } }}The -t option is for a dry run. I am thinking how to make it more extendable, like adding a sequence of numbers at the beginning, appending a date at the end, etc, but any suggestions on improvement are welcome.
A rename utility in Scala
strings;scala;file system
null
_webmaster.47098
I have been hosting my site in a shared environment at http://www.example.com/MYSITE/ for a while and I've built up a following there, I have decent ranking in Google and Bing, as well as I've been using the Facebook comment plug-in to allow users to comment on specific pages like http://www.example.com/MYSITE/Items/Details/52434.I am moving to a dedicated server and the new version of the URLS listed above are http://www.example.com/ and http://www.example.com/Items/Details/52434 The site is an ASP.NET MVC site, I'd love to slam everything over, but I want anyone who goes to the old URLS to get sent to the right place. Is this something I can do with a web.config modification? I'd like to avoid a coding change if at all possible.
I am moving my site from a virtual directory to a dedicated server, can I save me SEO urls via a web.config change?
seo;redirects;url;301 redirect;asp.net mvc
Ended up doing a url rewrite. Added this to my web.config file:<system.webServer> <rewrite> <rules> <rule name=Rewrite to article.aspx> <match url=^MYSITE/(.*)/(.*) /> <action type=Redirect url=/{R:1}/{R:2}/ /> </rule> </rules> </rewrite></system.webServer>So my uris are now correctly redirected.
_webapps.21784
I really like this theme, and I'd like to use the Blogger platform rather than Tumblr.While Tumblr's theme are relatively easy to understand, trying to make sense of all the stuff that's going on in Blogger has proved difficult.Is there a step-by-step guide somewhere on how to convert an existing Tumblr theme to be used at Blogger?
Converting a Tumblr theme to a Blogger template
tumblr;blogger;tumblr themes;blogger themes
null
_unix.48724
I'm trying to install SLIME on Fedora 17 so that I can do some lisp.Here is what I downloaded:http://www.common-lisp.net/project/slime/#downloadingThe CVS Snapshot link.I have a .emacs file:(add-to-list 'load-path ~/programming/slime/slime-2012-09-18)(setq inferior-lisp-program /usr/local/sbcl)(require 'slime)(slime-setup)When I start emacs --debug-init, I get the following message:Debugger entered--Lisp error: (file-error Cannot open load file slime) require(slime) eval-buffer(# nil /home/sam/.emacs.el nil t) ; Reading at buffer position 159 load-with-code-conversion(/home/sam/.emacs.el /home/sam/.emacs.el t t) load(~/.emacs t t) #[0 \205\262What am I doing wrong ?
Installing slime and emacs
fedora;emacs;debugging
null
_softwareengineering.332903
With hierarchical state machines, and their UML state chart counterparts, all the references I've found so far suggest that an active state must be a leaf state.I've looked at Samek, and papers that implement HFSMs in C++. Most suggest any transition to a composite (read parent) state must be followed by successive initial transitions to a leaf state.Firstly, is this in the definition? Given that these 'program by difference', surely a composite state could have all we need for an actual state!?
Must a hierarchical finite state machine only 'exist' in a leaf state?
design patterns;c++;uml
null
_unix.306409
Kickstart gives two options to install the GRUB bootloader either on MBR or first sector of /boot partition.If we choose to install it on /boot partition then what would 512 bytes of MBR contain?
Difference between installing GRUB on MBR sector or first sector on boot partition?
linux;debian;ubuntu;ext3
null
_unix.162663
I typed firefox -v in my console. The output wasfirefox -v(process:5516): GLib-CRITICAL **: g_slice_set_config: assertion 'sys_page_size == 0' failedMozilla Firefox 33.0What is that failed assertion? Something serious?
What is the GLib-CRITICAL in Firefox?
firefox
null
_softwareengineering.267333
I'm trying to make a service that's polymorphic based upon what mode is specified in the URL. If the char param in the route is set to 'p', I want to use a PresentMode service. If the char param is set to 'n', I want to use a NoteMode service. Each of these present the same interface, but I want to choose one at a time.So far the best solution I've come up with is something like this:var mod = angular.module('modeModule', []);mod.service('modeService', function($routeParams, presentMode, noteMode) { if ($routeParams.char === 'p') { this.mode = presentMode; } else if ($routeParams.char === 'n') { this.mode = noteMode; }}mod.service('presentMode', function() {});mod.service('noteMode', function() {});This works, but it requires that I append .mode to the end of every access (eg modeService.mode.blah(). Is there a better way to do this?
How do I create a modal service with AngularJS?
javascript;angularjs;service
null
_cstheory.32530
In theoretical physics, there is a branch of quantum field theory dealing with chiral gauge theories. It has been conjectured by Feynman [1] and others that all quantum field theories can be simulated in a limit computable manner efficiently on a quantum computer. However, there is the challenge of finding an efficient limit computable simulation of chiral gauge theories on a quantum computer. Does this problem lie within $\mathsf{BQP}$? [1] Richard P. Feynman. Simulating Physics with Computers. International Journal of Theoretical Physics, Vol. 21, Nos. 6/7, 1982
Does simulating chiral gauge theories lie within BQP?
cc.complexity theory;complexity classes;quantum computing;quantum information;physics
null
_codereview.141464
A Z^m number system includes integers in the interval [0, m) when m > 0 or (m, 0] when m < 0. The code defines a trait Mod to represent numbers in this system and the +, -, and * operator for it. use std::ops::Add;use std::ops::Mul;use std::ops::Sub;use std::ops::Rem;struct Mod<T> where T: Modulo<T> + Mul<Output=T> + Sub<Output=T> + Add<Output=T> + Rem<Output=T> + Copy + Clone{ modulo: T, i: T,}trait Modulo<T> where T: Add<Output=T> + Rem<Output=T> + Copy + Clone{ fn modulo(self, n: T) -> T;}impl<T> Modulo<T> for T where T: Add<Output=T> + Rem<Output=T> + Copy + Clone{ fn modulo(self, n: T) -> T { ((self % n) + n) % n }}impl<T> Mod<T> where T: Modulo<T> + Mul<Output=T> + Sub<Output=T> + Add<Output=T> + Rem<Output=T> + Copy + Clone{ fn new(modulo: T, i: T) -> Mod<T> { let n = i.modulo(modulo); Mod { modulo: modulo, i: n, } }}impl<T> Add for Mod<T> where T: Modulo<T> + Mul<Output=T> + Sub<Output=T> + Add<Output=T> + Rem<Output=T> + Copy + Clone{ type Output = Mod<T>; fn add(self, other: Mod<T>) -> Mod<T> { Mod::new(self.modulo, self.i + other.i) }}impl<T> Sub for Mod<T> where T: Modulo<T> + Mul<Output=T> + Sub<Output=T> + Add<Output=T> + Rem<Output=T> + Copy + Clone{ type Output = Mod<T>; fn sub(self, other: Mod<T>) -> Mod<T> { Mod::new(self.modulo, self.i - other.i) }}impl<T> Mul for Mod<T> where T: Modulo<T> + Mul<Output=T> + Sub<Output=T> + Add<Output=T> + Rem<Output=T> + Copy + Clone{ type Output = Mod<T>; fn mul(self, other: Mod<T>) -> Mod<T> { Mod::new(self.modulo, self.i * other.i) }}fn main() { let x = Mod::new(-5i8, 3i8); let y = Mod::new(-5i8, 8i8); println!({}, (x + y).i); let x = Mod::new(-5i8, 3i8); let y = Mod::new(-5i8, 8i8); println!({}, (x - y).i); let x = Mod::new(-5i8, 3i8); let y = Mod::new(-5i8, 8i8); println!({}, (x * y).i); let x = Mod::new(-5i16, 3i16); let y = Mod::new(-5i16, 8i16); println!({}, (x + y).i); let x = Mod::new(-5i16, 3i16); let y = Mod::new(-5i16, 8i16); println!({}, (x - y).i); let x = Mod::new(-5i16, 3i16); let y = Mod::new(-5i16, 8i16); println!({}, (x * y).i); let x = Mod::new(-5, 3); let y = Mod::new(-5, 8); println!({}, (x + y).i); let x = Mod::new(-5, 3); let y = Mod::new(-5, 8); println!({}, (x - y).i); let x = Mod::new(-5, 3); let y = Mod::new(-5, 8); println!({}, (x * y).i); let x = Mod::new(5u8, 3u8); let y = Mod::new(5u8, 8u8); println!({}, (x + y).i); let x = Mod::new(5u8, 3u8); let y = Mod::new(5u8, 8u8); println!({}, (x - y).i); let x = Mod::new(5u8, 3u8); let y = Mod::new(5u8, 8u8); println!({}, (x * y).i);}I tried to achieve the goals laid out in the previous version:Changed the modulo method for better performance. Generalized over a bunch of types other than i32.All suggestions are still welcome. In particular, requiring T to implement Copy and Clone might be a bit too restrictive, I would like to relax that.
Z^m number system in Rust version 2
rust
Place multiple imports from the same module on one line.I would heartily recommend against interleaving a trait definition (Modulo) and a struct definition (Mod).I prefer to not put trait bounds on the trait definition. Those usually want to be a supertrait or just on a trait implementation.Similarly, I prefer not put trait bounds on a struct definition; just on on implementation.There's no need for the Clone bound it's never used.I'd make your new operator trait match others: Parameterize the right-hand side (Rhs) and the Output as an associated type.Then you can DRY up your duplicated trait bounds by creating a new trait that has all the other traits as a supertrait.While you are at it, remove the type parameter T because you always use it in the same fashion; it might as well be hardcoded.Place a space around = when restricting associated types in traits.There's no need for the temp var in the Mod constructor.Tests. TESTS. TESTS You are so close to already having tests! Your main function can be basically transformed into a sequence of tests. Then the computer can verify them, instead of having to read the output each time. Please give them useful names that describe what each tests, not my stupid sequential names.use std::ops::{Add, Mul, Sub, Rem};trait Modulo<Rhs = Self> { type Output; fn modulo(self, n: Rhs) -> Self::Output;}impl<T> Modulo<T> for T where T: Add<Output = T> + Rem<Output = T> + Copy{ type Output = T; fn modulo(self, n: T) -> T { ((self % n) + n) % n }}trait ZMod: Modulo<Output = Self> + Mul<Output = Self> + Sub<Output = Self> + Add<Output = Self> + Rem<Output = Self> + Copy {}impl<T> ZMod for T where T: Modulo<Output = T> + Mul<Output = T> + Sub<Output = T> + Add<Output = T> + Rem<Output = T> + Copy{}struct Mod<T> { modulo: T, i: T,}impl<T> Mod<T> where T: ZMod{ fn new(modulo: T, i: T) -> Mod<T> { Mod { modulo: modulo, i: i.modulo(modulo), } }}impl<T> Add for Mod<T> where T: ZMod{ type Output = Mod<T>; fn add(self, other: Mod<T>) -> Mod<T> { Mod::new(self.modulo, self.i + other.i) }}impl<T> Sub for Mod<T> where T: ZMod{ type Output = Mod<T>; fn sub(self, other: Mod<T>) -> Mod<T> { Mod::new(self.modulo, self.i - other.i) }}impl<T> Mul for Mod<T> where T: ZMod{ type Output = Mod<T>; fn mul(self, other: Mod<T>) -> Mod<T> { Mod::new(self.modulo, self.i * other.i) }}#[test]fn t0() { let x = Mod::new(-5i8, 3i8); let y = Mod::new(-5i8, 8i8); assert_eq!(-4, (x + y).i);}#[test]fn t1() { let x = Mod::new(-5i8, 3i8); let y = Mod::new(-5i8, 8i8); assert_eq!(-4, (x + y).i);}#[test]fn t2() { let x = Mod::new(-5i8, 3i8); let y = Mod::new(-5i8, 8i8); assert_eq!(0, (x - y).i);}#[test]fn t3() { let x = Mod::new(-5i8, 3i8); let y = Mod::new(-5i8, 8i8); assert_eq!(-1, (x * y).i);}#[test]fn t4() { let x = Mod::new(-5i16, 3i16); let y = Mod::new(-5i16, 8i16); assert_eq!(-4, (x + y).i);}#[test]fn t5() { let x = Mod::new(-5i16, 3i16); let y = Mod::new(-5i16, 8i16); assert_eq!(0, (x - y).i);}#[test]fn t6() { let x = Mod::new(-5i16, 3i16); let y = Mod::new(-5i16, 8i16); assert_eq!(-1, (x * y).i);}#[test]fn t7() { let x = Mod::new(-5, 3); let y = Mod::new(-5, 8); assert_eq!(-4, (x + y).i);}#[test]fn t8() { let x = Mod::new(-5, 3); let y = Mod::new(-5, 8); assert_eq!(0, (x - y).i);}#[test]fn t9() { let x = Mod::new(-5, 3); let y = Mod::new(-5, 8); assert_eq!(-1, (x * y).i);}#[test]fn t10() { let x = Mod::new(5u8, 3u8); let y = Mod::new(5u8, 8u8); assert_eq!(1, (x + y).i);}#[test]fn t11() { let x = Mod::new(5u8, 3u8); let y = Mod::new(5u8, 8u8); assert_eq!(0, (x - y).i);}#[test]fn t12() { let x = Mod::new(5u8, 3u8); let y = Mod::new(5u8, 8u8); assert_eq!(4, (x * y).i);}
_webmaster.57953
I want to use CSS display table in place of JS for vertical-alignment and equal heights of HTML elements, however I'm not sure if there are any SEO implications of this, will crawlers try and interpret the contents of elements displayed in this way as tabular data or will they ignore it and interpret it as normal content?
CSS Display Table, any SEO implications?
seo;css;table
null
_unix.282400
I'm in the middle of writing a script to automate configuring MySQL replication between two servers (Master/Master replication), and was looking for some advice on a few things related to MySQL. The goal is to basically allow the same script to be executed on both servers (probably just prompting for the IP of the other master server), and have it completely configure MySQL. Most of it is pretty easy, but a few of the configuration values are unique to the server. The servers are pretty much identical (including MySQL credentials)The /etc/my.cnf file has two settings that are unique to the server, there's a server-id and an auto-increment-offset. Does the server-id need to start at any order or be consecutive? Because if not, then I was just going to grab the numeric value from the servers hostname (it's something like appdb-stg-m01, so I could grab the 01, or whatever number, since that will be unique), or even the last octet in the servers IP address... Would that suffice?Then for the auto-increment-offset, can this not be set the same on both servers? I have it set at 1 on the first master, then 2 on the other. I got those values from some online tutorials, but they didn't explain why they were different.Then for the values used in the CHANGE MASTER TO command... It needs the MASTER_LOG_FILE and the MASTER_LOG_POS...We can assume that these servers are relatively new, with no existing databases on them. So I was thinking that just resetting the MASTER_LOG_FILE to mysql-bin.000001 would suffice, but then id need to delete the other mysql-bin.? from /var/lib/mysql, as well as from /var/lib/mysql/mysql-bin.index. Would that suffice?The only other setting that I'm somewhat hung up on would be the MASTER_LOG_POS... Is there a way to set that myself? I'm trying to make this as least complicated as possible, so connecting to the other mysql server and looking at the output of SHOW MASTER STATUS is something id like to stay away from. Is there a way instead to reset it to 313?Thanks!
Automating Master/Master replication setup and configuration on two servers
centos;mysql;mariadb;replication
null
_unix.339890
I have CentOS 7 on an OpenVZ VPS running OpenVPN, Privoxy, and CSF.When redirecting OpenVPN's web traffic to Privoxy, with my current configuration, I can't reach the internet. From my csfpre.sh:iptables -A FORWARD -s 172.27.1.0/24 -j ACCEPTiptables -A FORWARD -i as0t0 -o venet0:0 -m state --state RELATED,ESTABLISHED -j ACCEPTiptables -A FORWARD -i venet0:0 -o as0t0 -m state --state RELATED,ESTABLISHED -j ACCEPTiptables -t nat -A PREROUTING -i as0t0 -p tcp -m multiport --dports 80,443 -j REDIRECT --to-ports 8118iptables -t nat -A POSTROUTING -s 172.27.1.0/24 -o venet0:0 -j MASQUERADEiptables -A OUTPUT -o as0t0 -j ACCEPTWhen I comment out the REDIRECT line, I can reach the internet while connected via OpenVPN.I would like to redirect OpenVPN's web traffic to Privoxy and still be able to reach the internet.Update: I removed the 443 port redirection so the REDIRECT line is now:iptables -t nat -A PREROUTING -i as0t0 -p tcp --dport 80 -j REDIRECT --to-port 8118This FIXED the issue!
When connected via OpenVPN to my VPS, how can I redirect web traffic to Privoxy
openvpn;privoxy
To my recollection, Privoxy does not support https protocol in intercepting mode. You can definitely intercept the unencrypted traffic. Probably you would have checked out following things. Can yo confirm the same?Ensure Privoxy is working. You can comment out the REDIRECT in iptables and configure your browser to use the proxy manually. If you can browse, your Privoxy installation is working correctly.Make sure you have the following entry in Privoxy configuration file.accept-intercepted-requests 1
_unix.239493
Debian has a cronjob /etc/cron.d/mdadm that starts a raid check (& resync?). It costs a lot of IO and can take up to 96 hours on 3TB disks. At this time the performance of the service will go really down.My question is: As far as I know, Linux will immediately restore the failed RAID. Is it really necessary to run this check? If so, why?
Soft raid1 schedule resync
debian;cron;raid;software raid
No, it's not really necessary. I used to disable it on most systems.It can, however, be useful. Linux mdadm RAID will only detect errors that occur while the RAID filesystem is being read or written to. This mdadm raid check cron job, just causes the entire raid array to be read so that read errors can be detected.In a similar fashion, both btrfs and zfs have a scrub command to cause all of the data on them to be read....and reading data on those filesystems causes checksums to be verified, thus detecting any errors even on files that don't get accessed very often. zfs scrub or btrfs scrub are usually run weekly or monthly from cron.
_datascience.2494
I have 1-4 gram text data from wikipedia for 14 categories, which I am using for NE classification.I feed named entity from sentence to lucene indexer which searches named entity from these 14 categories. Issue I am facing is, for single entity I get multiple classes as a result with same score.like while search titanic, indexer gives this resultScore - 11.23Title - titanicCategory - BookScore - 11.23Title - titanicCategory - MovieScore - 11.23Title - titanicCategory - Productnow problem is which class to be considered?I already tried with classifiers (NB,ME in nltk,scikit learn), but as it consider each entity from dataset as feature, it works as indexer only.Why lucene?
What is the best practice to classify category of named entity in sentence
machine learning;data mining;classification;nlp
null
_unix.118254
I would like to understand if my below scenarios are possible in Heartbeat in Linux. Setup: Two Database Servers running Mysql in Active/Passive mode in replication mode having Heartbeat setup for HA or failover mechanism. Application connects to DB using VIP that is started at the time of Heartbeat.Failover VIP to passive site if primary Mysql intance is shut down.Bring down the heartbeat in primary if the role has been given to passive/secondary site inorder to avoid split brain.
Linux Heartbeat options possibilities
linux;mysql
null
_softwareengineering.112383
In the book Hard Code by Eric Brechner, he states, Lying is one of a handful of valuable process canaries that can warn you of trouble.I've heard a dev or two toss around the old canary. What is it? [Google didn't answer it for me. Perhaps my keywords were a poor choice.]
What is a Process Canary
terminology
Canaries were once used in coal mines to find out if any poisonous gasses were around (the canary would die - the miners would get out). It was much safer than an open flame.One assumes in this context that if there is much lying, the process is poisonous.
_unix.342655
I am currently working with HASYv2 dataset which contains the hasy-data directory with 168.233 images of size 32px x 32px. I just wanted to copy that directory with Caja, but I skipped this after about 5 minutes (and Ubuntu told me it would take another 10 minutes).Copying the files with cp -a source_dir target_dir took less than 9 seconds.However, creating a tar.bz2 archive, copying the archive, extracting the files was done within about 15 seconds (everything combined).Why is that the case?(Side questions: When I press Ctrl+C, Ctrl+V to copy files within Caja the copying process is started by Caja, right? Does it make sense to internally use a similar procedure if many files are about to be copied?)
Why is copying many files with Caja much slower than compressing+copying+uncompressing?
filesystems;file copy;compression;caja
null
_cs.64791
The diameter-constrained Minimum Spanning Tree (MST) problem is as follows: you have a undirected weighted graph $G = (V,E)$ of different weights where $V$ is the set of vertices and $E$ is the set of edges between vertices, and a constant $d$. The goal is to find an MST such that the diameter (i.e., the maximum distance of the shortest paths between vertices) of the MST is at most $d$. My question is that I am debating whether the following is true or not: Once you have an MST of a graph $G$, if the diameter of the MST is $>d$, then is it true to say that there exist no feasible solution. Also, once you have a MST of $G$, then is the diameter of that MST the maximum diameter of $G$? or minimum? or what could be said about the diameter of a MST?
Diameter-constrained Minimum Spanning Tree Problem
graphs;graph theory;weighted graphs;spanning trees;minimum spanning tree
There is no direct relationship between the diameter of a (minimum) spanning tree and the total cost of the tree1. Consider the following example:The spanning tree on the left (whose edges are highlighted in red) is minimum. Its total cost is 7 and the diameter is equal to 5. In contrast, the spanning tree on the right is not minimum (since its total cost is 12), but it has a smaller diameter: 4.The same situation may occur when two spanning trees are minimum, as suggested by Yuval. Consider the following example (for the complete graph $K_4$):In this case, the total cost of the two Minimum Spanning Trees (MST) is 3; however, the MST on the left has a diameter that is equal to 3, while the MST on the right has a smaller diameter: 2.This counter-example disproves your assumption:It is, indeed, possible to find two different MSTs $T$ and $T'$ whose diameters are $\gt d$ and $\leq d$, respectively, within the same weighted undirected graph $G$.1. Note that Minimum-Diameter Spanning Trees (MDST) can be found in polynomial time, but the problem becomes NP-Hard when we also want the MDST to be minimum (i.e., when we want the total cost of the tree to be minimized).
_unix.299030
I have a human written text file that contains time stamps in form of dd-mm-yyyy,HH:MM or HH:MM:SS. I have managed to extract time stamps from text file using regex but I would like to also get a line of corresponding time stamp. It would be nice to have time stamps in one file and corresponding lines in the other. There could be multiple time stamps per line so same line should occur multiple times.If this can be done, what if I want only few words or few lines around a time stamp. Idea is just to get time stamps and their context extracted.For now I have been using matlab for this, but any *nix tool will do.Edit: seems to be that not all tools will do. I'm using mac and sometimes portable git bash for windows. At least mac's grep doesn't support anymore -P options for perl regex which is apparently needed for look around (?<![0-9])Here is example of original file and desired outputs:original:L&L logfile14-5-1216-05-2012Experiment 1Device 77212-123-123123Instrument 2, 34g, 66hzNotes:Something weird happened 12:34Everything is fine 13:07Log8:00 routine 18:20 routine 28:40 routine 3, 8:45 something went south8:50 routine 4, 8:50:12 weird peak at dataoutput1:14-5-1216-05-201212:3413:078:008:208:408:458:508:50:12output2:14-5-1216-05-2012Something weird happened 12:34Everything is fine 13:078:00 routine 18:20 routine 28:40 routine 3, 8:45 something went south8:40 routine 3, 8:45 something went south8:50 routine 4, 8:50:12 weird peak at data8:50 routine 4, 8:50:12 weird peak at data
Regex for time stamps and corresponding lines
text processing;regular expression
null
_unix.237036
I did a clean Ubuntu install on a Lenovo Ideapad P500. The backlight started okay, but after pressing the keyboard light function once, it got reset to a very dark state. The brightness setting wasn't adjustable then, even after restarting the system. I found a partial fix that involved changing a setting in /etc/default/grub; specifically, I added acpi_osi=Linux acpi_backlight=vendor in the variable GRUB_CMDLINE_LINUX_DEFAULT. But this is only a partial fix because it selects a zero-brightness level at startup, and it also turns the brightness off when selecting the max level. This is an annoyance. I discovered that this behavior is independent of Ubuntu, since something similar happened when I installed OpenSUSE in dual boot; and I also found similar posts that were related to different Lenovo laptops. My question is if this has to do with the Linux kernel, and/or if I have to update the drivers? If so, how can I fix this?Let me know if I can provide more details to fix this. Thanks for helping out.
Backlight control configuration misbehaves on an Ideapad.
linux kernel;grub;backlight
null
_unix.332448
I recently started using Awesome WM (on Debian), so I apologize if this is a newbie question. I'm using the default awesome theme. One thing I really like is how notifications are handled for pidgin - when a new message comes in the tag label (in the upper left of the screen, on the top bar) turns red.Is there a way I could make Icedove have the same kind of notifications? I would especially like the tag label to turn red when a new unread message arrives in the inbox. Right now I set my Icedove preferences to show an alert, but this only generates a notification box in the lower right of the screen. Update: Installing the New Mail Attention add-on for Thunderbird adds the red color notifications!
Awesome WM: Change Tag Label Color for Notifications?
awesome
null
_webmaster.30114
I have a WP 3.3.2 site and i use the google analytics code.Though everything seems ok with the results i get there is an error.All visitors drop off after homepage.You can check the image here.! http://imgur.com/shyNXI change position of the GA code and from just before < / body> i moved it to just before < / head> and now i use a wordpress plugin for this work.Still nothing changes.
100% visitors drop off after home
google analytics;analytics
null
_cs.9221
Just a basic question to askDoes the write through cache copies the whole block or just the byte which is updated?I went through the following questionArray A contains 256 elements of 4 bytes each. Its first element is stored at physical address 4096.Array B contains 512 elements of 4 bytes each. Its first element is stored at physical address 8192. Assume that only arrays A and B can be cached in an initially empty, physically addressed, physically tagged, direct mapped, 2K-byte cache with an 8 byte block size. The following loop is the executedfor(i=0; i<256; i++)A[i] = A[i] + B[2*i];How many bytes will be written to memory if the cache has a write-through policy?I calculated it as follows:The cache can store the whole array with 2 elements per block (block size = 8bytes, element size = 4bytes). For every write, the whole block will be copied. For $0^{th}$ element, the block containing $0^{th}$ and $1^{st}$ element would be written. The same would be done for $1^{st}$ element as well.So, for every iteration the 2 elements would be written. This makes the number of bytes as $256*2* (4bytes / element) = 2048bytes$.But in the solution, they have just calculated the number of loop iterations ($256$) multiplied by the element size ($4byte$) which makes the answer $1024bytes$.If this is true, then the cache would update only the updated byte (not the whole block). Which is correct?
Does the write through cache copies the whole block or just the byte which is updated?
computer architecture;cpu cache
The caching strategies could be very domain specific like efficient data caching for numerical data structure, graph data structures and algorithms, bio-informatics data structure, etc.. This is a nice Ph.D thesis about it: Cache-efficient Algorithms and Data Structures: Theory and Experimental EvaluationFor your specific program I think it will cache whole block of memory not only the specific data in array. It uses a general cache strategy. See Cache algorithms on Wikipedia.
_scicomp.27567
I've a read a paper about investing where they used a dynamic programming approach to solve a finite horizon problem, i.e. $$\max_{x_t} E[u(W_T)] $$where $u$ is a utility function and $W_T$ denotes the terminal wealth. The Bellman equation can then be written as $$ V_t(W_t) = \max_{x_t}E[V_{t+1}(W_{t+1})|W_t]$$with $V_T=u$. I have a continuous and concave utilitiy function which penalizes not hitting a certain target amount$$ u(w) = \begin{cases} K_1 & \text{if } w \geq K_1 \\ w - c\max{(0,(K_2-w))}^2 & \text{if } w < K_1 \end{cases}$$where $K_1>K_2$ are constant and $c>0$ a scaling factor. Above $K_1$, $u$ is constant, below $K_2$ you add a penalty. $c$ is a control parameter how much we should penalize $u$. For $K_1 = 12$, $K_2=10$ and $c= 100$ we get the following picture.and to see the linearity of $u$ between $K_2$ and $K_1$ another picture:Since I'm using a backward induction algorithm and discretize the space I've naively tried a uniform space grid $\{x_i\}$ in a fairly large interval $[w_1,w_2]$. Afterwards, I've solved for all the grid points $\{x_i\}$ the problem leading to solutions $y_i$. The pair $(x_i, y_i)$ was then used to approximate $V_t$. For this I've used a shape preserving method. What I've seen from experimenting with the problem that the approximation is very good far out on the left and right side, away from high curvature region. Moreover, the solution becomes quite stationary in these wing regions, too. What I then thought is to generate a non uniform grid which is denser where curvature is high. The problem is I don't know a priori the shape of $V_t$ (expect for $t=T$) so that it's hard to come up with a rule. Is there a generic way how to construct such non uniform grids? If someone has a concrete example or could point me into the right direction to do my own research, that would be really appreciated. I will potentially add another dimension to the state space so that the same question would arise in a higher dimension. That's why I put the mesh-generation tag as well
adaptive / smart grid choice for dynamic programming
mesh generation;grid;dynamic programming
null
_softwareengineering.165469
My company is building an iOS version of an Android app that our client is developing (but has not yet released). We have access to the latest builds and source, however since the software is frequently re-structured and refactored, we're doing a lot of unnecessary re-work. In addition, the due date on the contract will likely be passed before the client's application is even ready for release. In other words, we're supposed to build the iOS version before the original Android version is even complete. Luckily the client tossed out the original deadline, but now we may have to renegotiate pricing... never a fun situation.Are we handling this incorrectly? How are ports (especially between mobile platforms) normally done? Is there a correct way to pipeline development for multiple platforms without so much re-work?Thanks in advance! :)
How to handle porting software that's still in development
project management;mobile;contract;porting
If your only source of information for the application is it's unfinished android source, there is no way to escape this mess other than waiting for it's finish.A good way is this case is having a requirements file etc. that describes the work. For contract work, if what needs to be done is unclear, you WILL encounter lots of problems regarding the delivery date and pricing.Talk with the client, and formalize what needs to be done before you do more work. Use acceptance tests/use cases/requirements file/user stories/whatever to document what needs to be delivered and work on that. This way, you will know what you are responsible for(instead of an ever changing requirements when the android version changes) and you can talk in even terms with the client.
_reverseengineering.10937
During runtime. With minimal performance impact on the target.Platform is Windows 7.Objective is to gather a lot of data for clustering and ML. To ultimately assist with protocol reversing. All input will also be logged including packets (decrypted).
How to log every memory read/write action and the registers of the action?
tools
null
_unix.330874
I am configuring our new RHEL 7 server and I am have a real pickle in trying to get it to accept my private/public keypair.Everything seems similar enough compared to the sshd config from the older server.Current sshd_config:Port 22Protocol 2HostKey /etc/ssh/ssh_host_rsa_keyHostKey /etc/ssh/ssh_host_ecdsa_keyHostKey /etc/ssh/ssh_host_ed25519_keyKeyRegenerationInterval 3600ServerKeyBits 1024SyslogFacility AUTHPRIVRSAAuthentication yesPubkeyAuthentication yesAuthorizedKeysFile .ssh/authorized_keysPasswordAuthentication yesChallengeResponseAuthentication noGSSAPIAuthentication yesGSSAPICleanupCredentials yesUsePAM yesX11Forwarding yesUsePrivilegeSeparation sandboxAcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGESAcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENTAcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGEAcceptEnv XMODIFIERSSubsystem sftp /usr/libexec/openssh/sftp-serverLogging in using PuTTY I receive:Using username jweinraub.Server refused our keyMy permissions aredrwx------. jweinraub jweinraub unconfined_u:object_r:ssh_home_t:s0 .ssh/-rw-------. jweinraub jweinraub unconfined_u:object_r:ssh_home_t:s0 authorized_keysAnd with debug 3debug1: trying public key file /home/jweinraub/.ssh/authorized_keysdebug1: fd 4 clearing O_NONBLOCKdebug2: key not founddebug1: restore_uid: 0/0debug3: mm_answer_keyallowed: key 0x7ff339f8afa0 is not allowedFailed publickey for jweinraub from 10.18.66.11 port 55147 ssh2: RSA 1c:9d:1c:c7:cf:14:48:56:4f:23:5d:cb:16:a6:1d:18debug3: mm_request_send entering: type 23debug2: userauth_pubkey: authenticated 0 pkalg ssh-rsa [preauth]debug3: userauth_finish: failure partial=0 next methods=publickey,password [preauth]
Server refusing public key with PuTTY
ssh;putty;key authentication
null
_unix.385635
man umount2 says: MNT_EXPIRE (since Linux 2.6.8) Mark the mount point as expired. If a mount point is not currently in use, then an initial call to umount2() with this flag fails with the error EAGAIN, but marks the mount point as expired. The mount point remains expired as long as it isn't accessed by any process. A second umount2() call specifying MNT_EXPIRE unmounts an expired mount point. This flag cannot be specified with either MNT_FORCE or MNT_DETACH.umount doesn't seem to support it.Are there any utilities which allow one use this flag?
Are there any utilities which support umount2(2)'s MNT_EXPIRE?
unmounting
You can easily access C functions from Python.#!/usr/bin/env pythonimport os, sysfrom ctypes import *libc = CDLL('libc.so.6', use_errno=True)MNT_EXPIRE = 4libc.umount2(c_char_p(sys.argv[1]), c_int(MNT_EXPIRE))if get_errno() != 0: print os.strerror(get_errno()) exit(1)
_softwareengineering.148405
I recently started learning Android development and I decided to follow the following development processes:Preinstall Scala in emulatorEdit source files in IntelliJ IDEA 11Compile the project with sbt in command lineDex generated classes without Scala librariesBuild APK and test in emulatorIn the above steps, except step 3, I think other steps can be easily handled by command line/makefile. So here I am, I want a sample build.sbt to allow me easily specify the following information:Source directoriesReference librariesOutput directoryI am aware of sbt android plugin and sbt idea plugin but I want to avoid them for the following reason: projects generated by android plugin dex Scala libraries for each build but I want to have control on that part: I want to skip Scala libraries for development but include them for release build, which seams requires a lot of digging if I do it with the plugin but can be easily handled if it is done from command line/makefile.If overall what I plan to do makes sense, could someone familiar with sbt provide such a sample build.sbt? I have already spent hours following sbt tutorials but felt its so hard to make each seemed simple change to the default behavior of sbt.A side question, it seems that source directories added by unmanagedSourceDirectories get compiled every time regardless of the time stamp. If thats the case, whats the point of using sbt? I can just feed all sources files into scalac.UPDATEThis is the build.sbt based on Daniel C. Sobral's answer. When I type in sbt compile, it only prints some info like Set current project to HelloAndroid.... No compilation happens.name := HelloAndroidscalaVersion := 2.8.2unmanagedSourceDirectories := List( file(src), file(gen))libraryDependencies := List() // remove Scala's library from dependenciesunmanagedJars := List(Attributed.blank(file(C:/bin/android/platforms/android-10/android.jar)))target := file(target)I didn't expect it compiles because I still need to work out the jar files but at least I should get some compiler error. Any hint?UPDATE: the sbt compile outputs the following:[info] Set current project to HelloAndroid (in build file:/C:/Users...[success] Total time: 0 s, completed May 14, 2012 10:36:23 AMI have two source files in src directory:src/com/example/[HelloScala.scala MyActivity.java]No class file is found under target folder.
A sample build.sbt to allow me easily specify source dirs and libraries?
android;scala
I'd like to understand better what trouble you are having, because there really isn't much to it. This is all pretty simple:// build.sbtunmanagedSourceDirectories in Compile := List(file(\path\to\my\source))libraryDependencies := List() // remove Scala's library from dependenciesunmanagedJars in Compile := List(Attributed.blank(file(\path\to\my\library.jar)))target in Compile := file(\path\to\my\target\directory)Note that the above completely raw: it doesn't let SBT manage libraries through ivy, it doesn't let SBT find the jar files inside the directories for the unmanaged libraries and it uses absolute paths for everything.EDITAs I said, the above use absolute paths, and it seems you want relative paths for your source. Use this:unmanagedSourceDirectories <<= baseDirectory( base => List(src, gen) map (base / _ ))Also, you are using the default target, so you don't need it. However, SBT will create the files inside a subdirectory of that target, which is probably not what you want. You can change that this way:target in Compile <<= baseDirectory(_ / sbt-stuff) // move everything else to sbt-stuffclassDirectory in Compile <<= baseDirectory(_ / target) // generate the class files on targetAs for the error message you did not understand, it would have been easier to ask what it meant than to ask for the whole configuration.
_unix.236518
I use vpnc in terminal to setup a vpn connection, is there a way that i can make a script so when i execute the script it just starts. Instead of putting again al the gateway info etc.
Vpnc script bash
bash;shell script;vpn
null
_unix.133989
Any ideas how to back up a directory structure for which there are some files and/or directories for which you do not have permission to read? I'd like to just ignore those, without backup (tar? jar?) crashing.
How to backup dir structure ignoring files & dirs without read permission
permissions;files;backup;tar
null
_codereview.88907
The following code is from a utility I've written for myself.It takes a file in this format: [SOME_CODE] Some following text [SOME_OTHER_CODE] Some following multi-line textAnd then outputs a C header file containing some #defines with the strings encoded.The bottom function, convert, is the one I'm scratching my head about. It works just fine, but I'm sure there's a better way of organising the loop. Performance isn't a great issue here, just maintainability. It doesn't have to be super-resilient to unexpected input either. It uses JUCE - hence the non-std string class and file operations.bool isShortCode(const String & stringToCheck){ return (stringToCheck.length() > 1) && (stringToCheck[0] == '[');}String getEncodedDefineAndComment(const String & shortCode, const String & originalText){ String t; t += \n; t += // + originalText.replace(\n, \\n) + \n; t += #define JCF_ENCODED_ + shortCode + + getDefineForString(originalText) + \n; return t;}void convert(File inFile, File outFile){ auto inString = inFile.loadFileAsString(); if (inString.isEmpty()) { cout << error reading input << endl; return; } auto inLines = StringArray::fromLines(inString); String shortCode; String text; String outputText; auto p = inLines.begin(); while (p != inLines.end()) { String s = *p; if (isShortCode(s)) { shortCode = s.removeCharacters([] ); text = String::empty; p++; } else { if (shortCode.isEmpty()) { cout << error: input must start with a shortcode << endl; return; } bool firstTime = true; while ((p != inLines.end()) && (! isShortCode(*p))) { // I only want a new line where there are multiple lines. I don't want one for the last line. if (! firstTime) { text += \n; firstTime = false; } text += *p; p++; } outputText += getEncodedDefineAndComment(shortCode, text); } } // Happy to assume no errors here. outFile.replaceWithText(outputText);}
Organising loops for parsing a text file
c++;parsing;file
null
_webapps.21031
I set up a filter on my personal gmail that forwards all mail from a certain domain to my work email. When I saved the filter, the following notification popped up at the top of my window:(Your filters are forwarding some of your email to [email protected]. This notice will end in 7 days.)Can I dismiss this message? Or must I look at it for 7 days? I clicked both Review Settings and Learn more, and it's still there. There is no X or Dismiss button all the way on the right. Am I stuck with it for a week?
Can I dismiss Gmail's warning about my filter forwarding my mail?
gmail;gmail filters
It's going to be there for a week, but will only appear at login for a minute or two so you don't get banner blindness. It's a security feature that should help remind you to double-check for any dubious forwarding filters during that time.How long will I see this notice?For about a week, this notice will appear for a few minutes each time you sign in to your account. Displaying the notification in this way helps ensure that you have a chance to see the notice, rather than someone who might try to gain unauthorized access to your account and use this setting improperly. The notice will disappear immediately if you choose to disable the forwarding filter setting, but that decision is up to you.
_ai.2594
I am currently trying to understand and implement a conversational agent, seeing in the network there are many apis to do something similar, but what they generate are intelligent bots, not intelligent conversational agents (wit.ai, recast.ai, Api.ai, etc.), however I have seen Watson virtual agent which paints very well and seems to cover my needs.However I am a developer and I would like to ask those with more experience, which would be the way to go to implement my objective, an agent similar to what the video of watson virtual agent, with thematic ones that I can train in the agent, and That he can learn from it.Take a language course, but focused on the generation of programming languages, lexical analysis, syntactic, semantic, etc., however I know that the natural language can not be compared to the language of the machines, reading some thesis vi to make a Conversational agent could do a great grammar (I can not imagine its syntactic tree), using probabilities with ngrams, or using neural networks or expert systems.As for the expert systems I understand that for these learn needs their knowledge base be modified, and as for the neural networks these fit, learn, so I think that it is best to use neural networks.Summarizing which way should I go? , I'm currently taking stanford's natural language processing course, and a deep learning course from google, I thought I'd use ntlk for that important or natural part.Any suggestion, criticism, contribution, thank you in advance.machine-learning nlp artificial-intelligence agent
Conversational agent,query
neural networks;machine learning;deep learning;natural language;language processing
null
_softwareengineering.334079
So for my newest hobby project, I want to create a simple chat application where users can just log in with a nickname (no passwords) and talk to anybody on the network. Off the top of my head, I'm thinking about this design where a frontend Client acquires a User object by registering with a nickname.A Message object can behave like packets in the network, with a Postman delivering a given Message object to the intended recipient.When a user sends a message, they call: postman.addMessage(message);and the Postman then delivers this to the inTray located in Server.The receiver's Postman eventually finds a Message object intended for them in the outTray and fetches it for its Client.Any thoughts on the design? For all I know, it probably sucks but some constructive criticism is always welcome.
Design verification - chat application architecture
java;architecture;messaging
According to your explanations, the user interacts with a postman to send and receive messages, which are stored on a server. That's a good start. But I'm not sure that the class diagram fully reflects your explanations; It also raises some questions: the user would be composed of several clients ?? I thought that the user user would register to a client. Or eventually that a client would own several users. is the client supposed to represent the user interface ? the postman would be composed of several users ?? Do you mean that a postman serves several users. And what is the relationship between a postman a client and a server ? are the intray/outray on the sever organized by postman ? by user ? or is it global for the all the users/postman ? are messages stored twice on the server: in outray (send by user) and in the intray (adressed to user) ? when the message is sent to the server, is a copy kept in the postman ? when a message is retrieved from the server, is it removed there ? the notion of user session is not represented here. What if a user logs off, and logs in later ? What will happens to the messages that he has received in the meantime ? will the same postman always serve the same user ? As you can see above, you are very much at the beginning of your design. Without addressing all these points, I'd already propose you a reviewed diagram: Some key aspects: There is no permanent relation between postman and server: a posman is not structurally related to a server. There is only a dependency, because when a postman is told to connect with a server, he has to know the interface of the server (yet to be defined)The messages are either stored in a postman, or on a server (see the black diamonds). there is a link to be clarified between a user and a postman (e.g. the user has a link to the postman, or the postman has a list of users). there is a link to be clarified beteween a user and a ClientUI. As the user seems to be created when connecting to UI, we could imagine that the User is created by the UI.it has to be clarified how the servers are managed: does every client manage a server ? Is teh server given when login ? Are server operated independently ? are server searched via a network protocol by the postman when he needs it ? You need to clarify this.
_unix.61749
So I have been using linux mint for a while now. A few months ago my Gnome shell crashed and I was unable to use the full 3d features and loaded into fallback mode only. From that day (around 2 months ago) I still have only fallback mode (both Gnome and cinnamon). I installed Linux mint maya, and Ubuntu 12.04 both as windows file and complete installation in an external hard drive. and for many times I sitll cannot fix this problem. ps I made sure to download all the drivers for my graphics card. what could the problem be?
Gnome and Cinnamon loads in fallback (classic) mode only
linux;ubuntu;gnome;linux mint;cinnamon
null
_webmaster.44188
A question asked on my website here http://www.wrangle.in/topic/av5b5ymlhoyc/what-is-the-difference-between-www-or-ww I want to give them answer but I didn't find anywhere on google. So I thought better asking it here.
Why is ww35 used in some URLs?
url;url rewriting;no www;web hosting
null
_scicomp.10687
Within Fenics what ordering is used for storing vectors as upper triangular matrices? Th:e question really is I define a green Lagrange strain tensor in the following way:V = VectorFunctionSpace(mesh, Lagrange, 1)u = Function(V)I = Identity(V.cell().d) # Identity tensorF = I + grad(u) # Deformation gradientC = F.T*F # Right Cauchy-Green tensorE = (C-I)/2 #green strain tensorBut when I accesses the elements later,psi = stress1*E[0,0]+stress2*E[1,1]+stress3*(E[2,2])+stress4*E[1,2]+stress5*E[0,2]+stress6*E[0,1]I assumed Voigt notation but it occurs to me that this may not be the case. Using this method to initialize the strain tensor is this the notation I should be using or is there a different type or initialization that would be more appropriate?Thanks for any help.
Tensor notation in fenics
fenics
null
_unix.303742
I am about to start working on an embedded system which runs kernel v2.6.x.It is configured to use its serial line as a TTY (accessible via e.g. minicom, stty), but I want to run IP over the serial line so that I can run multiple multiplexed sessions over the link (e.g. via UDP/TCP or SSH).I don't have much more information about the boards yet (will post more when the documentation arrives), but assuming that the kernel provides reasonable abstraction over the hardware - what would be the process to configure it to run PPP or (C)SLIP over the serial link in place of TTY?
How to configure embedded kernel to use serial line for PPP instead of TTY
linux kernel;configuration;serial console;ppp;uart
You would first disable getty running on your serial port device /dev/ttyS0 (or whatever it is named for your hardware) to free it (for example, by editing /etc/inittab and running telinit q - if you managed to steer away from systemd) and then you would run pppd(8) on it (either manually with appropriate parameters or via additional tools like wvdial)
_codereview.20167
I have many thousands of image files spread around various places and would like to copy them into one directory. However, may of the files are duplicates with the same names (often thumbnails or reduced resolution etc). I want to delete all files that have the same name except for the largest. The following code reads a list of these file paths (fullpath/name). It splits the filename from the path, determines the size of the file and adds each filename and its size to a list (map). Where a name is found that is already in the list, the larger of the two is kept in the list and the smaller is 'deleted' (by which I mean emitting the command rm path/to/file).I know this is naive C++, because I am a novice (though not at C). Any help making it less naive would (or just better) is appreciated. #include <iostream>#include <string>#include <sys/stat.h>#include <map>using std::map;using std::string;class filedata { std::string path; size_t size;public: filedata (void) : path(), size(0) { } filedata (const string& p, size_t s) : path(p), size(s){ } filedata (const filedata& f) : path(f.path), size(f.size) { } size_t filesize(void) { return size; } string& filepath(void) { return path; } std::ostream& print(std::ostream& os) const { os << size << << path << \n; return os; }};std::ostream& operator<<(std::ostream& os, const filedata& f){ return f.print(os);}static size_t file_size(const string& s){ struct stat st; if (stat(s.c_str(), &st) == 0) { return st.st_size; } return 0;}static void delete_file(const string& s){ std::cerr << rm \ << s << \\n;}static bool file_name(const string& path, string& name){ size_t pos = path.rfind('/'); if (pos == string::npos) { return false; } name = path.substr(pos+1); return true;}int main(int argc, char **argv){ (void) argc; (void) argv; string s; map<string, filedata> files; while (getline(std::cin, s)) { string name; if (file_name(s, name) == false) { break; } size_t size = file_size(s); if (size == 0) { delete_file(s); } else if (files.count(name) > 0) { filedata f(files[name]); if (f.filesize() <= size) { delete_file(f.filepath()); files[name] = filedata(s, size); } } else { files[name]= filedata(s, size); } } for (auto i = files.begin(); i != files.end(); ++i) { std::cout << i->first << << i->second; } return 0;}
Reading a list of file paths and adding them to a map
c++;beginner;file
Looks good overall (though I'm by no means a C++ expert).In coming brain-dump though:void argument lists are rare in C++. Yes, in C, int c() and int c(void) are different, but in C++, that's not the case. In C++, int c() is implicitly the same declaration as int c(void).The no-op statements on argv and argc jump out as odd. If you did that so a warning of an unused variable won't be issued, you could always use one of the alternate main declarations (i.e. int main().Opinion again, but I'm not a fan of comparison to booleans: if (file_name(s, name) == false). It reads more easily as if (!file_name(s, name))This might be on purpose, but the path property of filedata can be mutated from outside:filedata f(name, 10);f.filepath() = new;I would probably make these objects immutable since they seem to be value objects (I think you probably intended to do this, just non-intuitive references got you).You should return either by value or by const reference from filepath. Even though it will create a usually unnecessary copy, I highly suggest the value route. If you return a const reference, you run the risk of a dangling pointer. Consider this (bad) example:filepath* f = new filepath(blah, 10);const std::string& s = f->filepath();delete f;// Any use of s past here is undefined behaviors is essentially a const pointer to f->path. This means that when f is released, s becomes invalid. Note that if you immediately create a copy of a string based on the constant reference [i.e. if you had std::string s = ...] this does not apply. That still creates a copy though, so you might as well return a value.(Also, obligatory note: raw pointers have very few legitimate uses in C++. Avoid pointers if at all possible, and use a smart pointer when not. The only (possible) exception is low level container implementations.)I'm not a fan of print style member functions. In this application this aversion doesn't make sense, but imagine if some third party library you used provided print methods for some of it's classes. Do you think it would print out in exactly the format you want? I prefer to use helper-type functions for printing rather than putting it as a member of the class. (Though once again, on this application since it's so small, it matters nothing at all.)(Oh, and this once again is opinion.)filedata (void) : path(), size(0) { }filedata (const string& p, size_t s) : path(p), size(s){ }filedata (const filedata& f) : path(f.path), size(f.size) { }There's a bit of redundancy here. Technically you could write this just as:filedata (const string& p = , size_t s = 0) : path(p), size(s){ }Or if you wanted:filedata (const string& p = string(), size_t s = size_t()) : path(p), size(s){ }Though I'd probably go with the first.The copy constructor doesn't need to be defined since it's the same as the implicit one. When using the same functionality as the implicit one, do not define one. The implicit one isn't prone to typos or a future failure to update the copier to reflect new properties.I would give more descriptive names to p and s:filedata (const string& path, size_t size) : path(path), size(size) { }I'd probably go with something like uint64_t instead of size_t since size_t will probably be 32 bits on a 32 bit system. If you'd like to abstract away exactly what the type is, you could have a typedef ... size_type member of your class. Not only does that offer a more semantic meaning, it allows for easier future change (assuming consumers actually proper use the typedef...).I tend to declare define the end of an iterator up front:for (auto i = files.begin(), end = files.end(); i != end; ++i) {Not only does it potentially offer a tiny performance advantage (though not really on any modern compiler), it has clearer meaning. With this version, there much more suggestion that end is not mutated inside of the loop (though it's still not guaranteed since end isn't const).std::begin and std::end should be preferred in C++11. They have all the capabilities of the member-function versions plus a bit more.stat failing probably shouldn't just return a size of 0. You might end up accidentally deleting a file if something weird happens. (Then again, most of the reasons stat would fail would also cause an attempt to delete a file to fail.)If you had the input include the file sizes, you could reduce your program to pure text processing. I'm also not sure if your program should be emitting rm commands. Seems like a coupling of sorts. Then again, the output would just be transformed into rm commands anyway, so might as well do it directly I guess :).The data put out on stdout seems to be debugging-esque information whereas the stderr data seems to be what you're actually after. Seems like these streams should be swapped.I'd be tempted to use a reference instead of copying the item in the map:filedata f(files[name]);Could be:filedata& f = files[name];The performance difference is going to be non-existent; mostly just a (opinion-y) style thing. It would also allow you to simplify the reassignment from files[name] = ... to just f = ....The filesize member of filedata can't permute size, so you might as well have the method be const. Same for filepath() if it wasn't meant to allow the perumtation of path (as mentioned earlier).Another personal-style thing: I don't like implicit visibility scoping:class filedata { std::string path; size_t size;os << size << << path << \n;return os;Can be simplified to:return os << size << << path << \n;
_webmaster.51356
Which is the best place to post a URL to get a backlink?SignatureForum profileAnswering a question and giving a related post URL as the answerDo Google's algorithms consider all of these to be spam/blackhat?
Is it best to put a link in signature, forum profile, or in a post to get backlinks?
backlinks;forum
null
_unix.355266
How can I sort numbers such as these using a sort command. 10111211314151617181920212223456789XY
How can I sort numbers in a unix shell?
sort
null
_webapps.37315
I want to setup Bing search for my own website with the help of Bing API. Is it possible to get some sort of statistics that tells me what kind of searches users made on my website or where they are coming from, etc? Is there any feature available in Bing that give me these kind or any other kind of statistics?
Can we get statistics from Bing search?
bing
null
_unix.173943
The problemI've got two graphics cards in my computer:Nvidia GTX 580Intel Graphics (onboard) The Nvidia part is working fine: plugged in a DVI cable to my monitor and everything works perfectly. The Intel part is totally ignored. xrandr says it is disconnected, and even tty is not visible at the Intel/HDMI display. When having xf86-video-intel installed, my monitor says no signal, if it is uninstalled, it says 1024-768 connected with a black screen. (completely black, no tty)InformationI am using Arch Linux. After installing xf86-video-intel I also added to /etc/mkinitcpio.conf the i915 tag in the MODULES line:MODULES=i915Calling uname -r gives me:3.14.25-1-ltsCalling lscpi -v gives me (among other things):00:02.0 Display controller: Intel Corporation 2nd Generation Core Processor Family Integrated Graphics Controller (rev 09)Subsystem: ASRock Incorporation Device 0122Flags: bus master, fast devsel, latency 0, IRQ 45Memory at f7400000 (64-bit, non-prefetchable) [size=4M]Memory at d0000000 (64-bit, prefetchable) [size=256M]I/O ports at f000 [size=64]Capabilities: [90] MSI: Enable+ Count=1/1 Maskable- 64bit-Capabilities: [d0] Power Management version 2Capabilities: [a4] PCI Advanced FeaturesKernel driver in use: i915Kernel modules: i915Calling xrandr gives me:Screen 0: minimum 320 x 200, current 1920 x 1200, maximum 8192 x 8192DVI-I-1 connected 1920x1200+0+0 (normal left inverted right x axis y axis) 518mm x 324mm 1920x1200 59.95*+ 1600x1200 60.00 1280x1024 75.02 60.02 1280x960 60.00 1152x864 75.00 1024x768 75.08 70.07 60.00 832x624 74.55 800x600 72.19 75.00 60.32 56.25 640x480 75.00 72.81 66.67 60.00 720x400 70.08DVI-I-2 disconnected (normal left inverted right x axis y axis)HDMI-4 disconnected (normal left inverted right x axis y axis)Possible causes which are not the causeThe cable is not the problem. It runs perfectly fine booting on Windows.
Intel HDMI monitor not recognized
arch linux;xrandr;dual monitor;intel;hdmi
null
_webapps.80728
Facebook has recently started allowing sign ups for Messenger with only a phone number instead of a full Facebook account.So:If I sign up to Messenger with only a phone numberAnd I have previously used that number as an account recovery mechanism for a full Facebook accountAnd that account has since been deactivated (but not deleted)Will Facebook join the dots and attempt to reactivate my dormant full Facebook account when I try to sign up on Messenger?
Sign up to Messenger with just a phone number already used on a deactivated Facebook account - will the account be reactivated?
facebook;facebook chat
Facebook will recognise the number and tell you to either:Log in with Facebook (thus connecting your full account)or Continue signing up (which will keep your new Messenger identity separate, and you will go on to enter a first name, last name, and optionally a photo).If you do this separate phone number sign up, and you search for your own name in the contact search screen, you may be able to find what looks like a full Facebook profile of yourself. Nope, they did not reactivate your full account. They actually seem to create a new Facebook account with your name, phone number, and profile photo all publicly visible - this is presumably their chosen way make you discoverable to people with full Facebook accounts.Source: Messenger for iOS (UK)
_codereview.163781
I've written this very simple quiz program, I'm trying to get to grips with OOP (Object Orientated Programming), so I've started simple with very basic Classes. The nature of the code would have suited using functions but I wanted to practice with Python Classes.Any comments or suggestions about my code would be most welcome, my ultimate goal is to be as pythonic as possible in future projects.I've tried to follow Python PEP8 guidelines. from colorama import *import randomimport osinit()class StartQuiz(): def __init__(self, capital_dict: str = {}, randomize_keys: str = []): self.capital_dict = capital_dict self.randomize_keys = randomize_keys def set_up(self): with open('capitals.txt') as file: for data in file: [country, capital] = data.split(',') self.capital_dict[country] = capital.strip() self.randomize_keys = list(self.capital_dict) random.shuffle(self.randomize_keys) return [self.capital_dict, self.randomize_keys]class DisplayAnswer(StartQuiz): def __init__(self, capital_dict, randomize_keys): super().__init__(capital_dict, randomize_keys) def show_answer(self): for city in self.randomize_keys: print(Fore.BLUE + f'{self.capital_dict[city]}', end=' ') print('\n')class DisplayQuestion(StartQuiz): score: int = 0 def __init__(self, capital_dict, randomize_keys): super().__init__(capital_dict, randomize_keys) def ask_question(self): for country in self.randomize_keys: print(Fore.YELLOW + f'Capital of {country} is ? ', end='') answer = input(Fore.WHITE) if answer.lower() == self.capital_dict[country].lower(): print(Fore.BLUE + 'Correct!') self.score += 1 else: print(Fore.RED + 'Incorrect!') return [self.score, len(self.capital_dict)]def main(): startQuiz = StartQuiz() while True: os.system('CLS') print(Fore.WHITE + '*** Capital City Quiz ***\n') print('Choose the correct city from the list below:\n') DisplayAnswer(startQuiz.set_up()[0], startQuiz.set_up()[1]).show_answer() total_score = DisplayQuestion(startQuiz.set_up()[0], startQuiz.set_up()[1]).ask_question() print(Fore.WHITE + f'\nYou scored: {total_score[0]} out of {total_score[1]}') input('\nPress <Enter> to play again')if __name__ == __main__: main()
Simple Capital City Quiz in Python3
python;object oriented;python 3.x;console;quiz
null
_webapps.324
I'm looking to start a web-based business, and I'd like to better understand how Google AdWorks works, and if it's worth the money for me to purchase keywords?Is there a way to limit how much it will cost me to use adwords? Is there a way to track the effectiveness of certain search keywords?
How does Google's AdWords model work?
google adwords
You asked a lot of questions, I will do my best to answer each one:Adwords is worth the money if you can quantify your entire costs (including obviously the campaign) and the value of the new customer. This may seem easy at first, but there are likely to be several factors in determining these values. (sorry there is no easy answer here)There is a way to limit your campaigns - both by individual bid amount (per click) and you will be notified when you balance is low so you can make sure your credit card is not charged.Yes: the analytics provided are robust, all keywords are tracked. You can also filter, sort and analyze a few hours away if you have enough keywords :)Overall, I would suggest finding a free Adwords code. Try searching on twitter. You can generally get about $100 to try it out -- by then you should be pretty comfortable with the system and how to bid effectively (i.e. do not pay suggested price!)Good Luck
_unix.309322
I have an ASUS ME176CX tablet, which only has 64-bit EFI booting support. No legacy option. But there are device drivers for 32-bit only Linux. How do I boot a 32-bit Linux OS through 64-bit Grub in EFI mode?
How to boot 32-bit Linux kernel with 64-bit EFI Grub?
grub2;grub;bios;uefi
null
_softwareengineering.352491
I'm planning on making a web app that'll use MySQL as the database, Java/Grails as the backend and JavaScript/VueJS as the frontend and then they'll communicate using only RESTful JSON APIs (that way I can have frontend apps running on any platform, all with the same backend). What I'm thinking is that every action (that requires db access) will have to be authenticated so I'm thinking that when a user logs in (successfully) I'll create an auth token on the backend, encrypt it and send it to the front end where it gets stored in browser storage so from that point on every time a user does something that token gets used for authentication. But what I'm not sure about how to implement is authentication for user registration (and any other action that doesn't require the user to be logged in, e.g. sending a Contact Us query). For example I could have a REST_PASSWORD variable in the front-end JavaScript that gets used for these unlogged-in actions but that's essentially useless because anyone can access the JavaScript code and grab the password.So my question is what is the best way to implement user registration through a JSON REST API so that my application doesn't get taken advantage of by bots/malicious users? It's been suggested that I implement CAPTCHA on the frontend and while I'm definitely gonna give that a look, I'm wondering if that'll be enough security and/or if I need more that?
User registration web service
rest;security;authentication
null
_softwareengineering.225049
I am a experimental physicist. In our research, we have our experimental data in a 400*400*400 matrix(x, y, z axis of a 3d space), each entry is associated with a value(brightness). We expect the brightest entries will form a closed path in the 3d space. But some portion of the path is always too dark to identify, also there are some noise in the space(random bright lines).Our current algorithm generates random seed points into the space, they are attracted by the brightness of the data. After certain amount of time, they will be trapped in the path. If we record the seed points position we can get the path. Our current algorithm does a fairly good job while I still need to manually add those relatively dark points to the path.I am not familiar with machine learning, but I am wondering if it can be used on this case? For example, is it possible that I tell the program which data points are on the path, the program will know how to choose the data points for the path in the future. Or if there is some other method we can use? Thanks!
Can I use machine learning for screening experimental data?
machine learning;image processing;noise
null
_unix.305145
I'm trying to get ibus's popup selection to work. I followed the instructions in the Arch wiki, by installing the ibus and ibus-libpinyin packages. ibus appears to partially work. ibus-setup works fine, and I can select inputs. In my text editor, I can then switch between English and (say) Arabic. Input changes as expected. However, after switching to Chinese Pinyin, text just appears as normal, with no pop-up appearing.All packages are up-to-date.KDE Plasma 5.7.3-1ibus 1.5.14-1ibus-qt 1.3.3-6ibus-libpinyin 1.7.92-1libpinyin 1.5.92-1(Previously posted on the Arch forum with no reply.)EDITI recently upgraded some of these packages, but I still am having this problem.KDE Plasma 5.7.4-2libpinyin 1.6.0-1
How can I enable ibus's input popup?
special characters;input method;ibus
Inspired by the Arch wiki, I added export QT_IM_MODULE=ibus to ~/.xprofile, which fixed it. I was initially thrown, because normal ibus input worked without this fix. In any case, I've edited the wiki to be a little clearer.
_unix.59180
In XFCE 4.10, you can enable an option that allows windows to tile automatically when dragged to the edges. The default is to tile to half the screen (half-top, half-bottom, half-left, or half-right). I want to change this so that dragging to the top edge maximizes a window, but I don't see any options in the settings anywhere to change this. Can this be done or am I out of luck here?
How do I change XFCE tiling to maximize on top edge?
xfce
I'm afraid you're out of luck, unless you want to patch the sources (and possibly also offer the patch upstream). However there are two alternative approaches: assign maximizing the window to double clicking on the window headeruse keyboard short-cut (it used do be Alt+F5, but I'm not sure what the default is today).
_cstheory.29210
The standard Assignment Problem asks for an optimal one-to-one assignment between agents and tasks.Now consider the following generalization: Instead of specifying a cost of a single agent-task pair, assume that you can specify a cost of an arbitrary set of agent-task pairs. The problem is then defined by a set of constraints, where each constraint is a cost c and a set S of task-agent pairs. Meaning of a such constraint is that a cost c occurs when all pairs in S are satisfied, and the overall cost is the sum of costs of all satisfied constraints.Note that this problem can be encoded as Weighted Partial MAX-SAT, where hard clauses encode one-to-one assignment between agents and tasks, and each constraint is a (weighted) soft clause.However, I am interested if this can be reduced to something simpler or if this is a known problem, but so far wasn't able to find an answer.Thanks for your help.
Is there a name for this Assignment definition
ds.algorithms;optimization;sat
null
_unix.341633
using Linux has been an interesting quest for the best system to fulfill my needs and wishes. 5 months ago I arrived to a good comfort-zone.Now I want to change my harddrive. In order to make my initial customization more efficiently, I thought of looking up all the commands I've typed in the bash since my last installation. The history command and my .bash_history file under ~$ and ~# only show the command of my last days..How do I do this? and/or How to best keep track of all (successfull) command I type?
How to see all commands since last system install(5 months)?
bash;command history;bashrc;bash expansion
null
_codereview.171101
Context:This code compute the data from table ItemReturn into StatReturn.It take about 1 700 000 ItemReturn on the first run. For 2minute, computation and database insert.ItemReturn: (int)Itm_Id, (int)Itm_Item_Serial, (datetime)Itm_CDate, [...]StatReturn : (int)Stat_id, Itm_Id, NbReturn, NbReturn_at30d, NbReturn_at60d, [...]For every return, we need to know: How many time this item was return in different timeframe (30,60,90.. days).An item is unique based on his Serial (Itm_Item_Serial).Function:This function take in input a list of a ItemReturn give as result the `StatReturn.private List<StatReturn> ComputeReturnStat(IEnumerable<ItemReturn> todoReturn){ var ttMSE = todoReturn .GroupBy(x => x.Itm_Item_Serial) .Select(grp => new InfoReturn(grp.Key , grp.Select(x => new MseDate((DateTime)x.Itm_CDate, x.Itm_Id)) .OrderBy(x => x.InterD) .ToArray() , grp.Count() ) ); var result = new List<StatReturn>(); foreach (var mse in ttMSE) { var statReturn = new StatReturn(); statReturn.SR_Compteur = 0; statReturn.SR_NbRetour = (byte)mse.NbRetour; statReturn.SR_NbRetour30J = 0; statReturn.SR_NbRetour60J = 0; statReturn.SR_NbRetour90J = 0; statReturn.SR_NbRetour120J = 0; statReturn.SR_NbRetour180J = 0; statReturn.SR_NbRetour365J = 0; if (mse.NbRetour == 1) { statReturn.SR_Compteur = mse.Items.First().MSE_key; result.Add(statReturn); } else { for (int i = 0; i < mse.NbRetour; i++) { statReturn = new StatReturn(); statReturn.SR_NbRetour = (byte)mse.NbRetour; statReturn.SR_NbRetour30J = 0; statReturn.SR_NbRetour60J = 0; statReturn.SR_NbRetour90J = 0; statReturn.SR_NbRetour120J = 0; statReturn.SR_NbRetour180J = 0; statReturn.SR_NbRetour365J = 0; statReturn.SR_Compteur = mse.Items[i].MSE_key; for (int j = i - 1; j >= 0; j--) { var delay = (mse.Items[i].InterD - mse.Items[j].InterD).Days; if (delay <= 30) { statReturn.SR_NbRetour++; statReturn.SR_NbRetour30J++; } else if (delay > 30 & delay <= 60) { statReturn.SR_NbRetour++; statReturn.SR_NbRetour60J++; } else if (delay > 60 & delay <= 90) { statReturn.SR_NbRetour++; statReturn.SR_NbRetour90J++; } else if (delay > 90 & delay <= 120) { statReturn.SR_NbRetour++; statReturn.SR_NbRetour120J++; } else if (delay > 120 & delay <= 180) { statReturn.SR_NbRetour++; statReturn.SR_NbRetour180J++; } else if (delay > 180 & delay <= 365) { statReturn.SR_NbRetour++; statReturn.SR_NbRetour365J++; } } result.Add(statReturn); } } }; return result;}Additional information:InfoReturn, is a custom class. int nser; // Itm_Item_SerialMseDate[] items; // list of Return id (Itm_Id) and Dateint nbRetour; // Total of returnThere is a byte cast in code because database is in small in so Linq-to-SQL type is byte.All comment have been delete, and all variable have been translated for the post. A lot of column in database are nullable, so we set them to 0 by default.
Counting the number of returning item for a TimeFrame
c#
first var var statReturn is only used in if (mse.NbRetour == 1)delay > 30 and other > are redundant change statReturn to default those values to 0 I think you could do this sorted output and not need the GroupBy if you are having performance issues. Or do it in TSQL.
_unix.232216
I have website which is password protected where runs a php app on it. Now I have to unprotect a sub-url of that website but without disablng the protection of the main site which is configured through plesk. This sub-url is given by the php app and is not a physical folder. Any hints how I can achieve that?OS Ubuntu 14.04.3 LTSWebserver Apache2 Plesk Version 12.0.18How do I find where plesk is storing/managing the RequireUser directives for my website? I assuming it is writing in somewhere into a vhost.conf? Or does plesk uses a different approach to manage password protected directories?
Ubuntu & Plesk - How to exclude a sub-url from password protection?
ubuntu;password;plesk;apache virtualhost
null
_codereview.110256
The task was to build a knight_moves method which when called would display the simplest path from one given square to the other given square.My Solution:class Square attr_accessor :x, :y, :children, :parent def initialize(x,y, parent=nil) @x = x @y = y @children = [] @parent = parent endenddef create_children(board) potentials = [] potentials.push( [board.x + 2, board.y + 1], [board.x + 2, board.y - 1], [board.x + 1, board.y + 2], [board.x + 1, board.y - 2], [board.x - 2, board.y + 1], [board.x - 2, board.y - 1], [board.x - 1, board.y + 2], [board.x - 1, board.y - 2] ) valid_children = potentials.select do |space| space[0].between?(0,8) && space[1].between?(0,8) end valid_children = valid_children.map do |space| Square.new(space[0], space[1], board) end @children = valid_childrenenddef knight_moves(first_square,final_square) first_children = Square.new(first_square[0],first_square[1]) create_children(first_children) bfs(final_square, @children)enddef bfs(search_value,children) queue = children loop do current = queue.shift if [current.x,current.y] == search_value display_path(current) break else create_children(current).each {|child| queue << child} end endenddef display_path(current) parent = current.parent array = [] while !parent.nil? array << [parent.x,parent.y] parent = parent.parent end array.reverse! array << [current.x,current.y] puts Your path is: array.each {|i| p i}endMethod Callknight_moves([2,5],[4,7])
Knight's Travails in ruby
algorithm;ruby;chess
BugThis:knight_moves([2,5],[2,5])prints:Your path is:[2, 5][4, 6][2, 5]Not the shortest path. In knight_moves, simply call bfs with [first_child] as the children argument. There's no need to call create_children in knight_moves; bfs can compute the first level of the search tree the same way it computes all other levels.Global variableIn create_children, you're setting @children which acts like a global variable as this method isn't inside a class. Simply return valid_children without setting any variables.(You're not setting Square#children because the method isn't inside Square. You actually never use Square#children. Remove this field from Square).NamingRename:Square -> Node (The class represents a node in the search tree. A true Square class would only have x and y fields).create_children -> child_nodesfirst_children -> rootboard argument -> node (or parent)display_path -> print_pathMissing Square classThe code sometimes uses an [x, y] array for squares, and sometimes the x and y fields of Node. This makes the code full of wrapping of unwrapping:# lines that unwrap an [x, y] array:Node.new(space[0], space[1], board)first_child = Node.new(first_square[0],first_square[1])# lines that create an [x, y] array:if [current.x,current.y] == search_value array << [current.x,current.y]You can eliminate this by creating a Square class and use it for representing squares everywhere in the code (including in Node):class Square attr_reader :x, :y def initialize(x, y) @x = x @y = y end def ==(other) [self.x, self. y] == [other.x, other.y] end def to_s [self.x, self.y].to_s endendI already implemented equality (for the comparison in bfs) and to_s (for printing in print_path). Then change Node to use a Square: (also, use attr_reader)class Node attr_reader :square, :parent def initialize(square, parent=nil) @square = square @parent = parent endendNow replace any [x, y] array in the code with a Square:# in child_nodes:square = node.square...Square.new(square.x + 2, square.y + 1),...space.x.between(0, 8) &&...Node.new(space, node)# in knight_moves:Node.new(first_square)# in bfs:if current.square == search_value# in print_path:array << parent.squarearray << current.squareputs i # instead of p i, so to_s is used# calling knight_moves:knight_moves(Square.new(2, 5), Square.new(4, 7))Missing Square methodsMost of child_nodes deals with squares, so most of its functionality should be inside Square methods. The only thing it does that doesn't involve only squares is creating nodes, so it should do just that:def child_nodes(node) node.square.knight_moves.map do |square| Node.new(square, node) endendSquare#knight_moves is a new method that returns an array of the squares that can be reached from the current one. It should look something like this:def knight_moves [ Square.new(self.x + 2, self.y + 1), ... ].select { |square| square.valid? }endThis requires adding a Square#valid? to check if a square's coordinates are legal.Revisiting knight_movesknights_moves does too little now, it only creates a root node and put it in a one-element array. I would remove it and move its functionality to bfs (Make bfs accept first_square and final_square as arguments, and call it directly).Seperating logic and printingDon't print the path in bfs, just return it (the array of squares) and let the main code print it. You can simplify the code for getting the path:def path_from_root(current) array = [] loop do array << current.square current = current.parent break if current.nil? end array.reverseend
_cs.40699
I am working on the following problemFind the linear least squares unit weights for the `OR' problem, ie.$v_1^T = (0,0), v_2^T = (1,0), v_3^T = (0,1), v_4^T = (1,1)$ and $u_1 = 0, u_2 = u_3 = u_4 = 1$.Here $v$ represent inputs and $u$ outputs. For problems like this I usually find a matrix $W$ (the weights) such that $$u_i=Wv_i \quad i=1,2,3,4$$ but I think it is obvious a matrix doesn't exist. my reasoning being that the problem is equivalent to finding the matrix $W = \begin{pmatrix} x_1 & x_2 \end{pmatrix} $ such that $$\begin{pmatrix} 0 & 1 & 1 & 1 \end{pmatrix} = \begin{pmatrix} x_1 & x_2 \end{pmatrix} \begin{pmatrix} 0 & 0 & 1 & 1 \\ 0 & 1 & 0 & 1 \end{pmatrix}$$ And looking at the two middle columns of the left vector and right matrix we must have $x_1=x_2 =1$ but then we get $1 + 1 = 1$, a contradiction. In a unit perceptron a function may be applied to the output, and a step function $$f(x) \begin{cases}0 & x \leq 0 \\1 & x > 0\end{cases}$$ would work here.My question here is, is this correct? I wasn't quite sure if I am answering the right question. I am pretty sure $u_i = f(Wv_i)$ but I am not too familiar with what is meant by linear least squares unit weights in this context?
Creating a single layer perceptron for the OR problem
neural networks;linear algebra;boolean algebra
The fact that you mention linear least squares error seems to hint that they want you to use a completely linear model $u_i=Wv_i$ for your perceptron. In this case you won't get exact answers like $0$ and $1$; you will only get approximations with some amount of error.That said, I don't think a linear model makes sense for this problem, since it is a classification problem with two classes. Using a non-linear step-like function $f$ before the final output of a perceptron classifier is a pretty standard thing to do, so I see no problem with using $u_i=f(Wv_i)$. Assuming you can use $f$, using the weights $x_1 = x_2 = 1$ as you mentioned solve this problem exactly with zero error.
_webmaster.101608
I have a Google site in which I have a gadget which sends data to Google Analytics using its send method which is written in the javascript of my Google gadget.I am able to see the data in my User Explorer of Google Analytics. I get a Review permission button on my Google sites page which I find very annoying. It adds the gadget to the list of user's authorized apps which the user can easily delete and hence the user wont be tracked. I need some custom parameters to be extracted from Google sites while the user is browsing my website.A better option was to provide an add-on. However, due to Google's restriction on Javascript that was not possible.Is there any better way to do get user analytics. If so, please suggest.
How to implement Google Analytics explicity in Google sites?
google analytics;google sites
null
_unix.185252
sudo service squid3 status works, implying squid is in upstart.However a listing of services usingsudo service --status-all does not show squid. Neither does sudo update-rc.d squid3 defaultswork (gives an error saying update-rc.d: /etc/init.d/squid3: file does not exist).On doing some research I found that:squid3.conf is in /etc/initBut not in /etc/init.dNot listed in any runlevels /etc/rc?.dMy objective is to not have squid start at runtime. I was hoping to do this using upstart. Without this my only option is to comment out the run level line: start [2345l]. Correct?Also why this weirdness? Any thoughts, explanations?I am on Ubuntu 14.04.
update-rc.d squid3 init.d init weirdness
ubuntu;upstart;squid
null
_softwareengineering.276778
After having written some python scripts with comments for documentation inside, is it a good idea and possible to aggregate the documentation comments from multiple scripts into some standalone documentation file such as README?Furthermore, is it possible to aggregate them in some markup format such as Markdown?Thanks.
Aggregate documentation comments from multiple scripts into README?
python;documentation generation
null
_scicomp.25294
I want some scalar spline function defined on regular 2D grid $F(x,y)$ with continuous first derivative which is easy to intersect with arbitrary ray/line ${\vec l}(t) = (c_x t,c_y t,c_z t)$. Finding the intersection means finding roots of equation $f_{c_x,c_y}(t)-c_zt=0$ where $f_{c_x,c_y}(t)=F(c_x t, c_y t )$ are values of the spline along the line ${\vec l}(t)$.Since it is easy to find roots of quadratic polynominal I want $f_{c_x,c_y}(t)$ to be piecewise quadratic polynominal for any ${c_x,c_y}$.What is the problem / what is not a solution:consider bi-quadratic B-spline on rectangular grid created by tensor-product of 1D quadratic B-splines. The result is bi-quadratic which means it is $f_{c_x,c_y}(t)$ is 4-th order polynominal.function composed of Quadratic Bezier-triangles. While it is certainly just quadratic function along any direction, it is hard ensure continuous derivatives at the boundary between triangles.
C1 continuous spline on regular 2D-grid with quadratic 1D cuts
interpolation;b spline;grid
null
_unix.329564
I love tmux, but whenever I need to create a split with a new pane or a new window it has to run my zsh init scrips and .profile, etc. And they take about a few seconds to run. Initializing stuff like fasd etc.Is it possible to make it faster to start?
Faster startup of zsh
zsh;performance;profiling
null
_unix.26189
The execstack program can be used to mark ELF-binaries as needing an executable stack. Is there a similar way to mark the heap as executable? Preferably for a single binary but if that's not possible, a system-wide solution would be useful too.
Set executable heap
linux;executable
null
_scicomp.1988
It appears that matlab's eigs is giving me bad approximations of the smallest eigenvectors of a matrix. I assume I can use some slower methods which would also be more accurate...I am looking to find the 2nd smallest eigenvector of a lapalcian matrix (known as the fiedler vector). I know of course that the smallest eigenvector of a laplacian matrix is the constant vector.Any suggestions for a more accurate method?P.SIn all the above, when I say smallest eigenvector I mean the eigenvector associated with the eigenvalue of smallest magnitude.
Compute smallest eigenvectors of a matrix
eigensystem;matlab
There is a straightforward way to exploit your a priori knowledge of the smallest eigenpair: you could simply project out the component of the current eigenvector estimate in the direction of the constant vector in each iteration of, say, inverse iteration. You should then expect the iterate to converge to the eigenvector corresponding to the second smallest eigenvalue, your desired Fiedler vector.Depending on the connectivity of your graph, you may or may not want to run a sparse-direct factorization before inverse iteration in order to accelerate the applications of $A^{-1}$. Once the inverse iteration approach is working, you could also consider replacing it with a Krylov algorithm, which takes a little more work to code but should converge faster.
_unix.38167
Some days ago I bought headet (Jabra BT2045) and I want to use it in Skype voicechat and for example to forward to it another sound streams from my KDE.I've successfully paired and setup as headset Jabra with Blueman or BlueDevil. After that Jabra interface appeared in Phonon list and I moved it to the top of list to transfer music to Jabra, not to my main output. But! There is no sound even if I change output manually with kmix for the streams, or when I've already setup Jabra as default output interface, microphone even don't work! Skype don't see that Jabra interface at settings and sound will appear if I reset all to my standard output (loudspeakers).What am I doing wrong? My dist is Linux Mint and pulseaudio/kde/blueman/bluedevil are up to date from mint repos.
Pulseaudio, Phonon, KDE and forwarding sound to headset
kde;audio;pulseaudio
null
_softwareengineering.101434
I've wanted to learn C++ for awhile and took AP Computer Programming in High School (back when it was C++ and not Java). I enjoy C and just haven't found the time to learn C++ or I'll just fall back on C# where I'm much more productive. My question is this: given that C++ '11 has been approved (although I know not fully implemented) does this change the way I should approach learning C++? I own C++: The Complete Reference By Herb Schildt which is from 1998. Does the newly approved standard make learning from such books less important than some of the newer tutorials/books that include things from the standard? Is there any benefit from learning from the older books?
Given C++ '11 Was Approved, Does This Change How A C++ Beginner Learns The Language?
learning;c++
Absolutely. These days three things that are usually in lesson 2 should move much, much later:strings as arrays of char*, the strlen, strxxx methods, and so on arrays in general and pointer arithmeticdelete what you new, delete[] what you new[], and even destructorsThese things that are usually in lesson 99 should move much, much earliertemplates as things to use (write, not so much)std::stringstd::shared_ptr<>std::vector<>, iterators, other collectionsEvey raw pointer should immediately be given to a smart pointer wrapper (I would start with shared, and consider unique later since it requires explaining std::move and rvalue references). Doing this will make learning C++ feel a lot like learning Java or C#, where you learn the library at the same time as the language. It will take away a lot of the memory work, too, and leave people less worried about gotchas.I would also work lambdas into the picture the first time we wanted to iterate through a collection and do something to each element.Disclaimer: I am writing a C++ course for Pluralsight right now and using this approach. The last module is understanding other people's code and that is where I will put the confusing stuff like char* strings, manual memory management, pointer arithmetic, and so on.Update: a few people have asked why the existence of C++0x inspires teaching things that could have been taught with C++03. I think it's a number of things:truly smart pointers, that are collection friendly, take away the need for things like an array of Employee pointers that were causing us to always fall back on new/delete, pointer arithmetic etcauto takes away the pain of iterator declarations lambdas make foreaching something an ordinary person would doeven something as trivial as parsing >> correctly eliminates the gotcha that would be there when declaring some templates of templatesand so onThe way I see it, there are things we could have changed about the way we were teaching C++ some time ago, but some of us held back because we still needed the old-school way for a fallback or because teaching it just involved a lot of arcane knowledge.
_unix.210346
My Fedora 22 (workstation-gnome) home pc has two accounts: steve, which has no password, and root which does have a password. On this website, the fedora 22 - change from gnome to kde4topic may have reached an impasse. It seems that the Gnome to KDE desktop is user specific; its manipulation apparently requires that the user ID have a password, at least temporarily.I believe that I can resolve this by:logging in as rootsetting a password for the steve accountlogging in as steve, with the password, simultaenously changing the steve account to kdelogging back in as root and eliminating the password from the steve account.How do I do #'s 2 and 4 above? After #4, I will want the steve account to have no password.
Manipulating a (non-root) password in Fedora 22
password
null