id
stringlengths 5
27
| question
stringlengths 19
69.9k
| title
stringlengths 1
150
| tags
stringlengths 1
118
| accepted_answer
stringlengths 4
29.9k
⌀ |
---|---|---|---|---|
_softwareengineering.349237 | In the Java course I'm currently doing at university, a lot of emphasis is placed on using JML constructs like @require and @ensure clauses in Javadoc comments. I understand that this is implementing the design by contract paradigm and that certain tools exist that are capable of mathematical verification of software using JML (assuming these clauses are defined appropriately).I'm curious as to their prevalence in industry though. Are these clauses actually used? If so, how widely? It seems to me at least that enogh defensive programming can often make them redundant for trivial methods (even simple things like implementing null guards in the code). | Industry Prevalence of JML Specification | java;design patterns;javadocs;industry standard | null |
_unix.217345 | On my ubuntu 14.04 machine, rsyslog service is running healthily...service rsyslog status returns,rsyslog start/running, process 794cat /proc/794/cmdline shows,rsyslog #meaning rsyslog is running with default params.Now, i am trying to check if rsyslog is having a TCP/UDP listening connection on port 514 using,netstat -lnup | grep 514 #for udpnetstat -lntp | grep 514 #for tcpBoth of the netstat commands return empty.Still, how can it run a server without a listening port? | Figure out Rsyslog listening port number | rsyslog | rsyslog doesn't listen on INET sockets by default. Instead, it binds to /dev/log, which is a Unix domain socket.# ls -la /proc/$(pidof rsyslogd)/fdtotal 0dr-x------ 2 root root 0 Jul 20 11:28 .dr-xr-xr-x 7 root root 0 Jul 20 11:05 ..lrwx------ 1 root root 64 Jul 20 11:28 0 -> socket:[3559]l-wx------ 1 root root 64 Jul 20 11:28 1 -> /var/log/syslog...# netstat -x | grep 3559unix 19 [ ] DGRAM 3559 /dev/log |
_unix.128631 | I need to comment out an entry in rc.tcpip file inside /etc# Start up the snmpmibd daemon start /usr/sbin/snmpmibd $src_running# Start up the Simple Network Management Protocol (SNMP) daemon start /usr/sbin/snmpd $src_runningHow do I comment these lines using sed? | How can I comment out snmpmibd and snmpd in rc.tcpip in AIX using sed? | sed;scripting | To comment out lines that start with start /usr/sbin/snmpmibd, use the s command with a pattern using the ^ anchor and # in the replacement text, plus & which stands for the replaced text. You can either match the two lines separately, or notice that snmpd is snmpmibd with mib omitted (concision at the expense of clarity) and use snmp\(mib\)\{0,1\}d. Since the pattern contains a slash, use another character as the delimiter, such as !. Since sed is a filter, you'll need to write the output to a new file, then move the new file into place (redirecting the output of sed to the same file as the input wouldn't work: it would first erase the old file, then start reading from the now-empty file).sed -e 's!^start /usr/sbin/snmpmibd !#&!' -e 's!^start /usr/sbin/snmpmibd !#&!' </etc/rc.tcpip >/etc/rc.tcpip.newmv /etc/rc.tcpip.new /etc/rc.tcpipTo edit a file in place, you can use ed instead of sed.ed -s /etc/rc.tcpip <<'EOF'g!^start /usr/sbin/snmpd ! s/^/#/g!^start /usr/sbin/snmpmibd ! s/^/#/wqEOF AIX doesn't have \? or \| operators, only started BRE, so \(snmpmibd\|snmpd\) won't work. AIX sed doesn't have -i, that's a GNU extension. |
_webapps.6112 | I just tried to send an email in Gmail, and then it said that I needed to sign in. Since on the screen I was signed in, there is no sign-in link. How do I sign in without losing the email? [I've gone ahead and copied it for now, but I'd like to hope that there's a better solution.] | Sign in to Gmail after typing email | gmail;email;login | If you are using a browser that supports multiple tabs then you can open another tab and sign into Gmail in that tabbed window. Then youll be implicitly signed in on the tabbed window where you are composing the email, and youll be able to save or send it as required.You can also recreate the condition that you originally discovered by opening two tabbed windows, signed into Gmail. Then start composing an email in one window and sign out of Gmail in the other tabbed window. That will put your composing email tabbed window into the state that you originally discovered (and you can recover it using the above technique). |
_unix.53467 | I want to know if it is possible to make emacs, when running in a gnu screen or tmux session, use the same colors as when TERM=xterm. In a gnu screen or tmux session, TERM=screen and emacs uses a different set of colors as compared to when TERM=xterm.For example, when TERM=xterm-256color, the foreground color of font-lock-comment-face is 'Firebrick'. But when TERM=screen-256color, it is set to 'chocolate1'.For tmux to work properly, the TERM variable must be set to screen or some derivative, so resetting TERM is not an option for me. | emacs colors based on $TERM environment variable | terminal;emacs;gnu screen;colors;tmux | The definition of font-lock-comment-face includes many variants for cases of varying color support.The chocolate1 variant is used when there are at least 88 colors available and the background is dark.The Firebrick variant is used when there are at least 88 colors available and the background is light.The difference is caused by some code that gives special meaning to TERM values that start with xterm, rxvt, dtterm, and eterm: it considers them to have a light background.You should be able to customize frame-background-mode* to its light value to always use the light color variants.If your Emacs is not new enough to have its own term/screen.el, then you will also need to adapt one for yourself that makes the appropriate color-adjusting calls. You might use the one from Emacs trunk, or I have a Gist that includes a .emacs.d/lisp/term/screen.el (with some extra bits to recognize the modifier+arrows/Home/End sequences provided by tmuxs xterm-keys option), and the .emacs modification needed to let it automatically load.Of course, there could still be other bits of code that directly check the TERM value and do something different for screen- and xterm-like values* M-x customize-variable frame-background-mode |
_webmaster.31206 | I'm moving hosting and need to move the emails stored with the old domain and hosting. The hosting I want to transfer from uses Open-Xchange for its webmail and the hosting I want to move to uses Horde for their webmail.Is their an automated way from inside of the Open-Xchange webmail? Is there a way I can do it from inside of Outlook or Mac Mail? | Export emails from Open-Xchange webmail and import them to Horde webmail | email;webmail;openx | With Outlook or any other IMAP client you could simply connect to your mail server, Then pull the emails to a locally created profile (off the imap server). Then connect to your new email server and pull them again to its directly. Based on number of emails this process will TAKE A LONG TIME. |
_unix.138877 | I am just starting out using sed and I intend to use it to extract IP addresses from ping output. Here's what I am trying to achieve exactly:input text: ytmti (192.188.2.3) jjggydesired output: 192.188.2.3command I am trying: echo ytmti (192.188.2.3) jjggy | sed 's:\((\(192.188.2.3\))\):\2:' current output: ytmti 192.188.2.3 jjggyNote: ytmti and jjggy are really stand-ins for text like Pinging unix.stackexchange.com and with 32 bytes of data:.I think using awk might be a better solution for parsing ping output,but I would like to get accustomed to sed. | Extracting text using sed does not work as expected | sed;awk | The substitution command of sed replaces all characters matched in first section with all character of second section, so you will need .* or similar and group only the part to save, like:echo ytmti (192.188.2.3) jjggy | sed 's:^.*(\([^)]*\).*$:\1:'Note that I use [^)]* that avoids to hardcode the IP and generalize it for any of them. It yields:192.188.2.3 |
_cstheory.25254 | Can a infinite time Turing machine perform hyper-computation like checking the consistency of the set theory ZF without using infinite memory? | Does hyper-computational power of infinite time Turing machines also require infinite memory? | computability;turing machines;space complexity;hypercomputation | null |
_codereview.93649 | As you will soon see I'm not the best jQuery developer out there (I'm a designer). At best, I make a prototype barely work. That said, I envisioned this Persona-slider which is just like any other jQuery header sliders out there, but slightly different. See it in action here.Each persona has its own story consisting of:NameQuoteSome paragraphs2 videos: a walk-in & walk-out sequenceI tried to hack this together but it's very quirky as you can see (certainly without any preloaders).The switching of text is fairly simple, but I can't get the videos to work in a seamless fashion. When the user clicks a name, the persona is supposed to walk in, sit down in the chair and pause. It's not until the user clicks another persona, then the current persona walks out and the new walks in. Like if they're all sits down in to the same chair and tell their stories. To complicate things further, it should be on autoplay by default (around 5 sec for each slide/persona). Also, you shouldn't be able to click a persona while a current one is playing already.So obviously js/_personas.js needs a heavy clean-up and re-thinking to make it simpler, I use a lot of unnecessary variables etc, I believe.(function() {// Text for each Persona $('.personas--menu--item--01').click(function() { $('.selected').removeClass('selected'); replaceText('Benny', 'Hr hjlper dom mig ocks med att f ordning i min ekonomi.', 'Innan jag kom hit satt jag p ett rttpsykiatriskt sjukhus. Jag r fortfarande dmd men jag fick mjlighet att komma hit till Hillringsberg p ppenvrd. Det r bra fr hr r vi tillsammans och har mlet att jobba s att jag blir fri frn mina papper. Jag gr i terapi och gr mindfulness fr att jag ska funka bra rent mentalt, fr det kan bli kmpigt med drogsug och snt.', 'benny'); }); $('.personas--menu--item--02').click(function() { $('.selected').removeClass('selected'); replaceText('Gran', 'Hr har jag umgnge och jag r trygg.', 'Om jag inte vore hr skulle jag vara ett ensamt vrak med begrnsad ekonomi. Injektion o mediciner kostar. Frr var jag alkoholist, en sjlvmordsbengen sdan. En gng fann de mig halvdd, 31.5 grader hade jag i kroppstemperatur efter att ha tagit fr mnga Stilinoct.', 'goran'); }); $('.personas--menu--item--03').click(function() { $('.selected').removeClass('selected'); replaceText('Cecilia', 'Personalen anpassar sig vldigt mycket efter rdande omstndigeter.', 'Behandlingshemmet har en egen psykiatriker vilket har varit till stort std fr bgge mina brukare. Dessutom satsar de p att hjlpa och stdja brukarnas ekonomiska problematik vilket r superbra men nd ovanligt. Deras rehabilitering r ett individuellt anpassad och dom jobbar med bde KBT och Mindfulness.', 'cecilia'); }); $('.personas--menu--item--04').click(function() { $('.selected').removeClass('selected'); replaceText('Gustaf', 'Han var som ett vrak, en borttappad och lusfattig kriminell p permis.', 'Nr min bror kom till Hillringsberg efter att ha suttit mnga r p rttspsyk, hade vi ingen kontakt. Jag minns senaste gngen jag trffade honom nr han satt p rttspsyk. Han var som ett vrak, en borttappad och lusfattig kriminell p permiss. Han var tungt medicinerad och svr att f kontakt med.', 'gustaf'); }); PlayIn('benny'); function replaceText (name, h1, p, who) { event.preventDefault(); $('.personas--content--title').fadeOut('slow'); $('.personas--content--name').fadeOut('slow'); $('.personas--content--text').fadeOut('slow'); var current = $(#video1).attr(class); var mydiv = $(#player); var myvideo = $(<video id='video1' width='880' class='+ who +'><source src='http://688812344.r.cdn77.net/videos/+ current +_walkout.mp4' type='video/mp4'><source src='http://688812344.r.cdn77.net/videos/+ current +_walkout.ogg' type='video/ogg'>Your browser does not support HTML5 video.</video>); mydiv.html(myvideo); var myVideo = document.getElementById(video1); myVideo.load(); myVideo.play(); myVideo.onended = function(e) { PlayIn(who); $('.personas--content--name').fadeIn('slow').html(name); $('.personas--content--title').fadeIn('slow').html(h1); $('.personas--content--text').fadeIn('slow').html(p); $('.personas--main--content--btn--text').html(name +'s historia'); } } function PlayIn(newperson) { var mydiv = $(#player); var myvideo = $(<video id='video1' width='880' preload='auto' class='+ newperson +'><source src='http://688812344.r.cdn77.net/videos/+ newperson +_walkin.mp4' type='video/mp4'><source src='http://688812344.r.cdn77.net/videos/+ newperson +_walkin.ogg' type='video/ogg'>Your browser does not support HTML5 video.</video>); mydiv.html(myvideo); var myVideo = document.getElementById(video1); myVideo.load(); myVideo.play(); }})(); | jQuery Persona slider | javascript;jquery | I am not too clear on what you are asking for exactly, but here are some suggestions that I hope will help you out.I would suggest trying to make the code more generic. Instead of a function for each link, make one click event function apply to all links. You could then have the name or id as part of the link by either making it an attribute or a class. Then inside the click event handler, get that name/id and pass it to a new function. Pseudo code example:$('.any-link-with-class').click(function() { var id = $(this).attr('persona-id'); // custom attribute you make or something var previousId = getCurrentId(); // either store in a local var or get from a control updatePersona(id, previousId);});I would also suggest storing all the details in a file or other variable so you can load those dynamically and get the details to display by the name/id. You call the clear selected in each function, better to do this in one place, and update the text fields at same time. More pseudo code:function updatePersona(id, previousId) { playWalkOutVideo(previousId); // show video of them exiting updateSelected(id); // remove selected class and apply to new person updateText(id); playWalkInVideo(id); // pass in id to know which video to play}function updateText(id) { var persona = getPersonaDetails(id); // either load from file or array object you make $('.title').html(persona.Name); // etc.}If you don't want the text to appear until they finish walking in for the video, you can do a setTimeout call to delay the text appearing until the video finishes (5 seconds = 5000 milliseconds which the function call uses). You will probably at least want to add a setTimeout call before you play the next video.Edit based on comment:One way to implement the getCurrentId is to create a hidden input field like this on the page:<input type=text id=currentId style=display: none; />You can then set the value when you change the current person like this:$(#currentId).text(id); // if .text doesn't work, try .html(id)You can then get the id in a similar way:var id = $(#currentId).text();You can also use hidden input types and other means to hold values on a page, this is just one way to do it. People can view the source code, so it isn't secure, but it is fine for holding variables or data you want to use on the same page. |
_unix.242473 | After using my arch-linux system a decent time, it can happen, that the i3pystatus process is not freezable anymore. As a result I can't suspend my laptop anymore. Killing the process (killall -9 python) doesn't have any effect: The process resides as a zombie. Even shutdown doesn't work anymore. It stops and waits for that process forever. -- The system has now entered the suspend sleep state. Nov 10 16:26:22 mobook kernel: PM: Syncing filesystems ... done. Nov 10 16:26:22 mobook kernel: PM: Preparing system for sleep (mem) Nov 10 16:26:22 mobook kernel: Freezing user space processes ... Nov 10 16:26:22 mobook kernel: Freezing of tasks failed after 20.004 seconds (2 tasks refusing to freeze, wq_busy=0): Nov 10 16:26:22 mobook kernel: python D ffff88027f215200 0 737 706 0x00000004 Nov 10 16:26:22 mobook kernel: ffff880260a3b918 0000000000000086 ffffffff81812500 ffff880274480dc0 Nov 10 16:26:22 mobook kernel: ffff880260a3b918 ffff880260a3c000 00000001003a4842 ffff880260a3b968 Nov 10 16:26:22 mobook kernel: ffff88027f20e7c0 ffff88027528cb60 ffff880260a3b938 ffffffff8156dbfe Nov 10 16:26:22 mobook kernel: Call Trace: Nov 10 16:26:22 mobook kernel: [<ffffffff8156dbfe>] schedule+0x3e/0x90 Nov 10 16:26:22 mobook kernel: [<ffffffff81570533>] schedule_timeout+0x123/0x240 Nov 10 16:26:22 mobook kernel: [<ffffffff810dc4b0>] ? init_timer_key+0xb0/0xb0 Nov 10 16:26:22 mobook kernel: [<ffffffff8133cdc8>] ec_guard+0x159/0x1ab Nov 10 16:26:22 mobook kernel: [<ffffffff810b4c60>] ? wake_atomic_t_function+0x60/0x60 Nov 10 16:26:22 mobook kernel: [<ffffffff8133db27>] acpi_ec_transaction+0x17a/0x353 Nov 10 16:26:22 mobook kernel: [<ffffffff8133dd5a>] acpi_ec_read+0x5a/0x7a Nov 10 16:26:22 mobook kernel: [<ffffffff8133ddb9>] ec_read+0x3f/0x63 Nov 10 16:26:22 mobook kernel: [<ffffffffa01f950f>] acpi_smbus_transaction+0x1bc/0x2c1 [sbshc] Nov 10 16:26:22 mobook kernel: [<ffffffff810b4c60>] ? wake_atomic_t_function+0x60/0x60 Nov 10 16:26:22 mobook kernel: [<ffffffffa01f962f>] acpi_smbus_read+0x1b/0x1d [sbshc] Nov 10 16:26:22 mobook kernel: [<ffffffffa0210108>] acpi_battery_get_state+0x71/0x90 [sbs] Nov 10 16:26:22 mobook kernel: [<ffffffffa02106ba>] acpi_sbs_battery_get_property+0x3d/0x440 [sbs] Nov 10 16:26:22 mobook kernel: [<ffffffff8141ddf0>] power_supply_read_temp+0x40/0x80 Nov 10 16:26:22 mobook kernel: [<ffffffff814207b8>] thermal_zone_get_temp+0x58/0x70 Nov 10 16:26:22 mobook kernel: [<ffffffff81420a1d>] temp_show+0x2d/0x70 Nov 10 16:26:22 mobook kernel: [<ffffffff813cfb70>] dev_attr_show+0x20/0x50 Nov 10 16:26:22 mobook kernel: [<ffffffff812485d9>] sysfs_kf_seq_show+0xb9/0x130 Nov 10 16:26:22 mobook kernel: [<ffffffff81247060>] kernfs_seq_show+0x20/0x30 Nov 10 16:26:22 mobook kernel: [<ffffffff811f326c>] seq_read+0xec/0x390 Nov 10 16:26:22 mobook kernel: [<ffffffff81247ae7>] kernfs_fop_read+0x107/0x160 Nov 10 16:26:22 mobook kernel: [<ffffffff811d00f7>] __vfs_read+0x37/0x100 Nov 10 16:26:22 mobook kernel: [<ffffffff8126f8be>] ? security_file_permission+0xae/0xc0 Nov 10 16:26:22 mobook kernel: [<ffffffff811d09b7>] vfs_read+0x87/0x130 Nov 10 16:26:22 mobook kernel: [<ffffffff811d1755>] SyS_read+0x55/0xc0 Nov 10 16:26:22 mobook kernel: [<ffffffff8157162e>] entry_SYSCALL_64_fastpath+0x12/0x71 Nov 10 16:26:22 mobook kernel: python D ffff88027f2d5200 0 5294 706 0x00000004 Nov 10 16:26:22 mobook kernel: ffff8801adfb79c8 0000000000000086 ffff88027561b700 ffff8801e0a4ee00 Nov 10 16:26:22 mobook kernel: 0000000100000000 ffff8801adfb8000 ffff88007a76148c ffff8801e0a4ee00 Nov 10 16:26:22 mobook kernel: 00000000ffffffff ffff88007a761490 ffff8801adfb79e8 ffffffff8156dbfe Nov 10 16:26:22 mobook kernel: Call Trace: Nov 10 16:26:22 mobook kernel: [<ffffffff8156dbfe>] schedule+0x3e/0x90 Nov 10 16:26:22 mobook kernel: [<ffffffff8156dfe5>] schedule_preempt_disabled+0x15/0x20 Nov 10 16:26:22 mobook kernel: [<ffffffff8156f40a>] __mutex_lock_slowpath+0xca/0x140 Nov 10 16:26:22 mobook kernel: [<ffffffff8156f49b>] mutex_lock+0x1b/0x30 Nov 10 16:26:22 mobook kernel: [<ffffffffa01f93b9>] acpi_smbus_transaction+0x66/0x2c1 [sbshc] Nov 10 16:26:22 mobook kernel: [<ffffffff81160d9c>] ? __alloc_pages_nodemask+0x17c/0x960 Nov 10 16:26:22 mobook kernel: [<ffffffff812bf647>] ? vsnprintf+0x267/0x530 Nov 10 16:26:22 mobook kernel: [<ffffffff812bd9ef>] ? string.isra.2+0x3f/0xd0 Nov 10 16:26:22 mobook kernel: [<ffffffffa01f962f>] acpi_smbus_read+0x1b/0x1d [sbshc] Nov 10 16:26:22 mobook kernel: [<ffffffffa0210108>] acpi_battery_get_state+0x71/0x90 [sbs] Nov 10 16:26:22 mobook kernel: [<ffffffffa02106ba>] acpi_sbs_battery_get_property+0x3d/0x440 [sbs] Nov 10 16:26:22 mobook kernel: [<ffffffff8141d7e9>] power_supply_get_property+0x19/0x30 Nov 10 16:26:22 mobook kernel: [<ffffffff8141e684>] power_supply_show_property+0x54/0x250 Nov 10 16:26:22 mobook kernel: [<ffffffff8141e984>] power_supply_uevent+0xc4/0x270 Nov 10 16:26:22 mobook kernel: [<ffffffff813d1a1b>] dev_uevent+0xbb/0x2b0 Nov 10 16:26:22 mobook kernel: [<ffffffff811b3826>] ? kmem_cache_alloc_trace+0x1d6/0x200 Nov 10 16:26:22 mobook kernel: [<ffffffff813cf734>] uevent_show+0x94/0x100 Nov 10 16:26:22 mobook kernel: [<ffffffff813cfb70>] dev_attr_show+0x20/0x50 Nov 10 16:26:22 mobook kernel: [<ffffffff812485d9>] sysfs_kf_seq_show+0xb9/0x130 Nov 10 16:26:22 mobook kernel: [<ffffffff81247060>] kernfs_seq_show+0x20/0x30 Nov 10 16:26:22 mobook kernel: [<ffffffff811f326c>] seq_read+0xec/0x390 Nov 10 16:26:22 mobook kernel: [<ffffffff81247ae7>] kernfs_fop_read+0x107/0x160 Nov 10 16:26:22 mobook kernel: [<ffffffff811d00f7>] __vfs_read+0x37/0x100 Nov 10 16:26:22 mobook kernel: [<ffffffff8126f8be>] ? security_file_permission+0xae/0xc0 Nov 10 16:26:22 mobook kernel: [<ffffffff811d09b7>] vfs_read+0x87/0x130 Nov 10 16:26:22 mobook kernel: [<ffffffff811d1755>] SyS_read+0x55/0xc0 Nov 10 16:26:22 mobook kernel: [<ffffffff8157162e>] entry_SYSCALL_64_fastpath+0x12/0x71 Nov 10 16:26:22 mobook kernel: The same thing happened to me when I used i3status instead of py3status (I changed to py3status to overcome this issue). Any ideas what's the problem and how to track the bug?Best | i3pystatus-python process blocks suspend and shutdown | arch linux;process;i3 | null |
_unix.89284 | I've got a Tascam US-800 8-in/4-out audio interface that I use to record into Ardour. The setup is great, but I like to do my mastering and mixdowns elsewhere and I always have to drag around the audio interface because if it's not connected, Ardour won't open up. I'm wondering if there's some way to stub out the audio interface in jack so that I can trick ardour into thinking it's connected when it's really not. I looked into the connections, but I can't figure it out. When the interface is plugged in and ardour is running, this is what the connections pane looks like (I've collapsed ardour's connections because there are about 35 of them and the important part is the four system capture sources being used):jackd connection panel with US-800 connected http://www.bizlunch.net/craigslist/jackd_connections.pngI imagine that there's some way to fake system/capture_[1-8], right? Any tips? | How can I stub out an audio interface in jack? | audio;jack | null |
_codereview.27755 | I'm using a payment gateway and am trying to implement the post and response handling with CURL so that it all happens on one page.The following is tested and works but I want to double check it's secure. I'm not storing the card details but I'm essentially posting them to myself (via AJAX) and then curling that through to the gateway. I can't AJAX post it directly to the gateway because of cross domain restrictions.So, this all happens in https://mysite.com/payment.php:HTML<form method=post action=https://mysite.com/payment.php> <input type=hidden name=Amount value=1.00> <!-- fingerprint is a hash of my gateway passwords and fields on this form --> <input type=hidden name=Gateway_Fingerprint value=<?php echo $fingerprint ?>> <input type=hidden name=Gateway_ReturnURL value=https://mysite.com/payment.php> <input type=hidden name=Card_Number value=></form>PHP// when payment form is submittedif(isset($_POST['Card_Number'])){ // CURL the data to payment gateway foreach($data as $key => $value){ $fields .= $key . '=' . $value . '&'; } rtrim($fields, '&'); $post = curl_init(); curl_setopt($post, CURLOPT_VERBOSE, true); curl_setopt($post, CURLOPT_URL, 'https://gatewayurlhere'); curl_setopt($post, CURLOPT_POST, count($data)); curl_setopt($post, CURLOPT_POSTFIELDS, $fields); curl_setopt($post, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($post); // output result from gateway as JSON header('Content-Type: application/json'); echo $result; curl_close($post); exit();} // result returned from gateway, this will be the CURL result dataif(isset($_POST['restext'])){ echo json_encode($_POST); exit();} | Secure CURL to & handle response from Payment Gateway | php;security;curl;ssl | null |
_vi.7000 | I'm writing a vim function to set hard tabs and refactor indents in a whole file.This is the function:function RefInd() :set tabstop=4 softtabstop=0 noexpandtab shiftwidth=4 gg=GendfunctionAnd this is the error:Error executing the function RefInd:Line 2:E492: Not an editor command: ^Igg=GPress ENTER or type command to continueAny help? | Function to refactor indents and tabs | vimscript;indentation;functions | The problem is that gg, = and G are normal mode commands, as opposed to ex commands which are used within a script.Writing normal gg=G should solve your problem.As @Carpetsmoker has pointed out in his comment, using normal! instead of normal might be prudent to avoid running user-defined mappings by accident.See also :help :normal. |
_unix.111156 | want to execute a Bash command, followed by two actions if and only if the test returns an error. I would prefer to solve this task as a one-liner in Bash.Here are the two forms I have tried: ssh [email protected] ls /home/somefile || echo File does not exist && exit 1ssh [email protected] ls /home/somefile || echo File does not exist; exit 1The meaning is as follows: I want to test the existance of a file on a remote machine (or whatever, just an example), and in the case the first command returns an error, then - and only then- the two following commands (echo /exit) should be executed. The examples above execute the exit 1 statement independent of the return value of the ssh command. How to rewrite this line, so the echo and the exit commands are only executed if the first (ssh) command fails? | How to execute a Bash comand and execute two statements on failure? | bash;shell;control flow | ssh [email protected] ls /home/somefile || { echo File does not exist; exit 1; }This is called a compound command. From man bash: Compound Commands A compound command is one of the following: (list) list is executed in a subshell environment (see COMMAND EXECU TION ENVIRONMENT below). Variable assignments and builtin com mands that affect the shell's environment do not remain in effect after the command completes. The return status is the exit status of list. { list; } list is simply executed in the current shell environment. list must be terminated with a newline or semicolon. This is known as a group command. The return status is the exit status of list. Note that unlike the metacharacters ( and ), { and } are reserved words and must occur where a reserved word is permitted to be recognized. Since they do not cause a word break, they must be separated from list by whitespace or another shell metacharacter.The () syntax probably wouldn't work in your situation because the commands would be executed in a subshell, and then the exit would just close the subshell.EDIT: to explain the difference between the parentheses () and the curly braces {}:The parentheses cause the contained commands to be executed in a subshell. That means that another shell process is spawned which evaluates the commands, and the exit in OP's question would kill this subshell.The curly braces instead cause the commands to be evaluated in the current shell. Now the exit kills the current shell, which would be for example preferable if you use this line a shell script. |
_unix.12197 | I happen to know about rsyn, and I use rsync to sync between my mac and a linux server as follows.rsync -r -t -v MAC LINUXrsync -r -t -v LINUX MACI expected to run the first command to sync, but I needed the second command also when a change is made in LINUX.Am I missing something? Does rsync have an option to sync between two directories? | Syncing directories in both directions with rsync | rsync;synchronization | You want bi-directional sync. Take a look at unison, which does this: http://www.cis.upenn.edu/~bcpierce/unison/For example, on Debian/Ubuntu:$ sudo apt-get install unison$ unison MAC/ LINUX/If you have trouble with permissions (example ext4 -> FAT):$ unison -perms 0 vlc-2.2.0/ /media/sf_vlc/vlcContacting server...Looking for changesReconciling changesvlc-2.2.0 vlc new dir ----> / [f] Proceed with propagating updates? [] yPropagating updates |
_unix.191632 | I have a daily backups named like this:yyyymmddhhmm.zip // pattern201503200100.zip // backup from 20. 3. 2015 1:00I'm trying to create a script that deletes all backups older than 3 days. The script should be also able to delete all other files in the folder not matching the pattern (but there would be a switch for that in the script to disable this).To determine the file age I don't want to use backups timestamps as other programs also manipulate with the files and it can be tampered.With the help of: Remove files older than 5 days in UNIX (date in file name, not timestamp)I got:#!/bin/bashDELETE_OTHERS=yesBACKUPS_PATH=/mnt/\!ARCHIVE/\!backups/THRESHOLD=$(date -d 3 days ago +%Y%m%d%H%M)ls -1 ${BACKUPS_PATH}????????????.zip | while read A DATE B FILE do [[ $DATE -le $THRESHOLD ]] && rm -v $BACKUPS_PATH$FILE doneif [ $DELETE_OTHERS == yes ]; then rm ${BACKUPS_PATH}*.* // but I don't know how to not-delete the files matching patternfiBut it keeps saying: rm: missing operandWhere is the problem and how to complete the script? | How to delete old backups based on a date in file name? | bash;shell script;scripting;file management | The first problem in your code is that you are parsing ls. This means it will break very easily, if you have any spaces in your file or directory names for example. You should use shell globbing or find instead.A bigger problem is that you are not reading the data correctly. Your code:ls -1 | while read A DATE B FILEwill never populate $FILE. The output of ls -1 is just a list of filenames so, unless those file names contain whitespace, only the first of the 4 variables you give to read will be populated. Here's a working version of your script:#!/usr/bin/env bashDELETE_OTHERS=yesBACKUPS_PATH=/mnt/\!ARCHIVE/\!backupsTHRESHOLD=$(date -d 3 days ago +%Y%m%d%H%M)## Find all files in $BACKUPS_PATH. The -type f means only files## and the -maxdepth 1 ensures that any files in subdirectories are## not included. Combined with -print0 (separate file names with \0),## IFS= (don't break on whitespace), -d '' (records end on '\0') , it can## deal with all file names.find ${BACKUPS_PATH} -maxdepth 1 -type f -print0 | while IFS= read -d '' -r filedo ## Does this file name match the pattern (13 digits, then .zip)? if [[ $(basename $file) =~ ^[0-9]{12}.zip$ ]] then ## Delete the file if it's older than the $THR [ $(basename $file .zip) -le $THRESHOLD ] && rm -v -- $file else ## If the file does not match the pattern, delete if ## DELETE_OTHERS is set to yes [ $DELETE_OTHERS == yes ] && rm -v -- $file fidone |
_unix.165808 | New to bash scripting, and just need a little help.I've been testing this on a simple directory structure.I'm trying to change any directory and/or sub directory with the name Season to Sn.I got to a point where the script would change what I wanted...except for the top directory, as seen in the list below - Season 1 Season 2 Season 3.Directory structure:. AnotherShow Sn1 Sn2 Sn3 Sn4 Movie1 Sn1 Sn2 Movie2 Sn1 Sn2 Sn3 Sn4 Movie3 Sn1 Sn3 Movie4 Sn2 Sn3 Season 1 Season 2 Season 3 Show Sn1 Sn2 Sn3 Sn4 Sn5 TV Sn1 Sn2 Sn3 Sn4My script is:array=$(find . -maxdepth 2 -type d -iname 'Season*' -print); # A more refined way to search for Seasons in a directory.for dir in ${array[@]}; do # Put this list into an array. Surround the array with quotes to keep all space s (if any) together. new=$(echo $dir | sed -e 's/Season 0/Sn/' -e 's/Season /Sn/'); # Only change Season 0 to SN. Leave othe rs alone. sudo mv -v $dir $new && echo Changed $dir to $new; done | Renaming directory bash script - target ... No such file or directory | bash;scripting;file management | The issue is that you are not creating an array, you are creating a string. You can test this quite easily by attempting to print the first element of your array:$ array=$(find . -maxdepth 2 -type d -iname 'Season*' -print); $ echo $array./Season 3 ./Season 1 ./Season 2Looks good right? But if that were an array, you would be able to print each element separately. Unfortunately, the above is a simple string1 and not an array:$ echo ${array[0]}./Season 3 ./Season 1 ./Season 2$ echo ${array[1]}The array actually consists of a single string which is why the second element of the array (${array[1]}) is empty. In any case, you don't need an array for this, just read through the output of find (you also don't need the -print, that's what it does by default). A working version of your script could be:#!/usr/bin/env bashfind . -maxdepth 2 -type d -iname 'Season*' | sort -r |while IFS= read -r dirdo mv $dir ${dir/Season /Sn} && echo Changed $dir to $dir/Season /Sn}; doneThere are a couple of tricks used there. First, the while loop to go through the results of find. This is the same basic principle as the for loop that you used but combined with read can read from standard input. The IFS= is needed to avoid splitting on whitespace (without it, the directory Season 1 would be split into Season and 1). The -r of read tells it to not allow backslashes to escape characters (things like \t and \n are treated literally) which makes sure this can deal with even the strangest names. The sort -r is needed so that if you have a directory matching the pattern inside another matching directory, the child is listed before the parent. For example:./Season 12/Season 13./Season 12This ensures that you run mv Season 12 Sn12 after running mv Season 12/Season 13 Season 12/Sn13. If you don't do that, the second command will fail since Season 12 no longer exists. Finally, I removed the sudo. You should instead run the script as sudo script.sh. It is never a good idea to have random sudo calls in your scripts. 1I'm not sure about the details but apparently, bash treats string variables as arrays of one element. |
_codereview.43353 | I am a relative beginner to Python and as such I've been working on little things here and there in the office that strike me as something interesting that might be fun to try and code a solution.Recently, I was working with some cell phone data and decided to write a little script that would triangulate a cell phone location from ping strengths/XY locations from 3 different towers. As we only get one cell tower data returns in a exigence request anyway, this was pretty much a practice problem for me, which I would love to check the accuracy on anyway.As such, I was just looking for some critical feedback on any parts of this that could be written cleaner or functionally more efficient than what i have. It works fine if all the correct values are entered for all user inputs but I am not sure how to keep things moving along if an invalid value is entered. Right now, I just exit out of the script if a invalid number is entered and the user would have to start over. I would like to be able to loop(?) back through with the correct value after a prompt of some sort.Part 1User inputs (this was going to be a tool/script to be run from someones desktop in the shell)for tower signal strengths and then standardizing those inputs. I pulled all the math off another thread here.try: s1=float (raw_input (please enter signal strength number 1 + --> + )) s2=float (raw_input (please enter signal strength number 2 + --> + )) s3=float (raw_input ( please enter signal strength number 3 + --> + ))except (EOFError,ValueError,TypeError): oops2 = raw_input(An unusuable value was entered for the signal strength, Press ENTER and try again) print oops2 exit()if s1 < 0.31 or s1 > 99: badinput = raw_input(Signal strength #1 is invalid,\ please enter a value between 0.31 - 99. Press ENTER and try again) print badinput exit()if s2 < 0.31 or s2 > 99: badinput = raw_input(Signal strength #2 is invalid, please enter a value between 0.31 - 99. Press ENTER and try again) print badinput exit()if s3 < 0.31 or s3 > 99: badinput = raw_input(Signal strength #3 is invalid, please enter a value between 0.31 - 99. Press ENTER and try again) print badinput exit() print _______________ print else: def signal_strength(s1,s2,s3): w1=float(s1)/(s1+s2+s3) return w1 tower1_strength=signal_strength(s1,s2,s3) print (standardized signal strength for tower #1-->) + ( ) + str(tower1_strength) def signal_strength2(s1,s2,s3): w2=float(s2)/(s1+s2+s3) return w2 tower2_strength=signal_strength2(s1,s2,s3) print (standardized signal strength for tower #2-->) + ( ) + str(tower2_strength) def signal_strength3(s1,s2,s3): w3=float(s3)/(s1+s2+s3) return w3 tower3_strength=signal_strength3(s1,s2,s3) print (standardized signal strength for tower #3-->) + ( ) + str(tower3_strength) print _______________ print Part IIUser inputs to select which three towers to choose the XY data for, which is held in a dictionary. Right now I just have three sample values in the dictionary rather than all the cell tower xy's located in my AOI.# sample dictionary for cell carrier tower ID:X,Y Coordinates (Decimal Degrees), will use carrier ID's as keylongitude = {1:-89.928573,2:-89.813409,3:-89.825694}latitude = {1:43.899751,2:43.913357,3:43.82814}try: ID1 = int(raw_input (Carrier ID for tower #1 + --> + )) ID1x= longitude[ID1] ID1y = latitude[ID1] ID2 = int(raw_input (Carrier ID for tower #2 + --> + )) ID2x = longitude[ID2] ID2y = latitude[ID2] ID3 = int(raw_input (Carrier ID for tower #3 + --> + )) ID3x = longitude[ID3] ID3y = latitude[ID3]except Exception,e: oops = raw_input (An invalid Tower ID# was used,Please use the Carrier/Provider supplied identification number. Press ENTER and try again) print oops exit()#Need to figure out how to loop back through the Tower ID# (and signal strength for that matter) data entry chunk after exception, if possibleprint _______________print def user_x(tower1_strength,tower2_strength,tower3_strength,tx1,tx2,tx3): x_location=float(tower1_strength*tx1)+(tower2_strength*tx2)+(tower3_strength*tx3) return x_locationX_Coord=user_x(tower1_strength,tower2_strength,tower3_strength,ID1x,ID2x,ID3x)print (the X coordinate for the position is-->) + ( ) + str(X_Coord)def user_y(tower1_strength,tower2_strength,tower3_strength,ty1,ty2,ty3): y_location=float(tower1_strength*ty1)+(tower2_strength*ty2)+(tower3_strength*ty3) return y_locationY_Coord=user_y(tower1_strength,tower2_strength,tower3_strength,ID1y,ID2y,ID3y)print (the Y coordinate for the position is-->) + ( ) + str(Y_Coord)print _______________print ty = raw_input (thank you)print ty | Improving a triangulation test script | python;beginner;python 2.7;geospatial | Let's start with part I :Don't repeat yourselfYou can define small functions to avoid duplicating code for all signals.Also, you can use the relevant data structure to store information. For instance, the strength of the signal go by 3, let's put them in the same object (let's say a list to keep things simple).Finally, your attempt to write function for standardisation of signals was nice. However, you end up writing and computing the same things many times. You could compute the sum just once.Make things simple for the userInstead of asking for 3 inputs and then exit if something goes wrong, you can check each and every input as it is provided so that the user does not go through the hassle of providing many values only to get rejected because the first was invalid. Also, you do not need to exit if the input is not valid, you can just ask again.Taking the following comments into account, Part I becomes :def get_signal_strength_from_user(i): Prompt the user to get a signal strength. Loops til a valid value (float in the right range) is provided and return it. while True: try: s = float(raw_input(Please enter signal strength number + str(i) + --> )) except (EOFError,ValueError,TypeError): raw_input(An unusuable value was entered for the signal strength, Press ENTER and try again) continue if 0.31 <= s <= 99: return s # s has a valid value else: raw_input(Signal strength is invalid (value should be in [0.31 - 99]. Press ENTER and try again)# Using variables :s1,s2,s3 = (get_signal_strength_from_user(1), get_signal_strength_from_user(2), get_signal_strength_from_user(3))print(Signals strength is , s1, s2, s3)sum_signal = s1+s2+s3w1,w2,w3 = s1/sum_signal, s2/sum_signal, s3/sum_signalprint(Standardized signals strength is , w1, w2, w3)# Using lists :nb_src = 3signals = [get_signal_strength_from_user(i+1) for i in range(nb_src)]print(Signals strenght is , signals)sum_signal = sum(signals)standard_signals = [s/sum_signal for s in signals]print(Standardized signals strength is , standard_signals)I've done it using lists and different variables so that you can pick whatever is easier for you.Now for part II :I don't really understand why you need to user to pick 3 towers out of 3 towers.CorrectnessAlso, I'd like to point out that your algorithm will not work if the same tower (or if 2 towers at the same location - which is roughly the same) is used more than once. Indeed, localisation on a plan with relative strenght from 2 sources only gives you the direction as the mathematical property you are using is right for any point of a line.My feeling is that even more than that, the towers should not be aligned because this could lead to (at least) 2 distinct points in most cases.The fact that this does not seem obvious from the code lead me to think that maybe the maths behind are wrong too.Anyway, let's go back to the code.Don't repeat yourselfIt might not seem obvious because the names of the parameters are changed but you have defined the same function twice.def user_c(tower1_strength,tower2_strength,tower3_strength,c1,c2,c3): c = float(tower1_strength*c1) + (tower2_strength*c2) + (tower3_strength*c3) return c(c stands for coordinate here).Also, the conversion and the temporary variable are not useful here, the argument names do not need to be that long and the function could be renamed :def mean(s1,s2,s3,c1,c2,c3): return s1*c1 + s2*c2 + s3*c3 |
_codereview.124417 | I am trying to implement the MVC pattern in C++ & QT, similar to the question here:Other MVC QuestionsThe program has 2 line edits:mHexLineEditmDecLineEdit3 buttonsmConvertToHexButtonmConvertoDecButtonmClearButtonand just modifies strings.The difference with the other question is that I am trying to implement the Subject/Observer pattern to update the View once the Model is changed.Model.h#ifndef MODEL_H#define MODEL_H#include <QString>#include <Subject>class Model : virtual public Subject{public: Model(); ~Model(); void convertDecToHex(QString iDec); void convertHexToDec(QString iHex); void clear(); QString getDecValue() {return mDecValue;} QString getHexValue() {return mHexValue;}private: QString mDecValue; QString mHexValue;};#endif // MODEL_HModel.cpp#include Model.hModel::Model():mDecValue(),mHexValue(){}Model::~Model(){}void Model::convertDecToHex(QString iDec){ mHexValue = iDec + Hex; notify(HexValue);}void Model::convertHexToDec(QString iHex){ mDecValue = iHex + Dec; notify(DecValue);}void Model::clear(){ mHexValue = ; mDecValue = ; notify(AllValues);}View.h#ifndef VIEW_H#define VIEW_H#include <QtGui/QMainWindow>#include ui_View.h#include <Observer>class Controller;class Model;class View : public QMainWindow, public Observer{ Q_OBJECTpublic: View(QWidget *parent = 0, Qt::WFlags flags = 0); ~View(); void setController(VController* iController); void setModel(VModel* iModel); QString getDecValue(); QString getHexValue();public slots: void ConvertToDecButtonClicked(); void ConvertToHexButtonClicked(); void ClearButtonClicked();private: virtual void update(Subject* iChangedSubject, std::string iNotification); Ui::ViewClass ui; Controller* mController; Model* mModel;};#endif // VIEW_HView.cpp#include View.h#include Model.h#include Controller.h#include <QSignalMapper>VWorld::VWorld(QWidget *parent, Qt::WFlags flags): QMainWindow(parent, flags){ ui.setupUi(this); connect(ui.mConvertToHexButton,SIGNAL(clicked(bool)),this,SLOT(ConvertToHexButtonClicked())); connect(ui.mConvertToDecButton,SIGNAL(clicked(bool)),this,SLOT(ConvertToDecButtonClicked())); connect(ui.mClearButton,SIGNAL(clicked(bool)),this,SLOT(ClearButtonClicked()));}View::~View(){}void View::setController(Controller* iController){ mController = iController; //connect(ui.mConvertToHexButton,SIGNAL(clicked(bool)),this,SLOT(mController->OnConvertToHexButtonClicked(this))); //connect(ui.mConvertToDecButton,SIGNAL(clicked(bool)),this,SLOT(mController->OnConvertToDecButtonClicked(this))); //connect(ui.mClearButton,SIGNAL(clicked(bool)),this,SLOT(mController->OnClearButtonClicked(this)));}void View::setModel(Model* iModel){ mModel = iModel; mModel->attach(this);}QString View::getDecValue(){ return ui.mDecLineEdit->text();}QString View::getHexValue(){ return ui.mHexLineEdit->text();}void View::ConvertToHexButtonClicked(){ mController->OnConvertToHexButtonClicked(this);}void View::ConvertToDecButtonClicked(){ mController->OnConvertToDecButtonClicked(this);}void VWorld::ClearButtonClicked() { mController->OnClearButtonClicked(this);}void View::update(Subject* iChangedSubject, std::string iNotification){ if(iNotification.compare(DecValue) == 0) { ui.mDecLineEdit->setText(mModel->getDecValue()); } else if(iNotification.compare(HexValue) == 0) { ui.mHexLineEdit->setText(mModel->getHexValue()); } else if(iNotification.compare(AllValues) == 0) { ui.mDecLineEdit->setText(mModel->getDecValue()); ui.mHexLineEdit->setText(mModel->getHexValue()); } else { //Unknown notification; }}Controller.h#ifndef CONTROLLER_H#define CONTROLLER_H//Forward Declarationclass Model;class View;class Controller {public: Controller(Model* iModel); virtual ~Controller(); void OnConvertToDecButtonClicked(View* iView); void OnConvertToHexButtonClicked(View* iView); void OnClearButtonClicked(View* iView);private: Model* mModel;};#endif // CONTROLLER_HController.cpp#include Controller.h#include Model.h#include View.hController::Controller(Model* iModel):mModel(iModel){}Controller::~Controller(){}void Controller::OnConvertToDecButtonClicked(View* iView) { QString wHexValue = iView->getHexValue(); mModel->convertHexToDec(wHexValue);}void Controller::OnConvertToHexButtonClicked(View* iView) { QString wDecValue = iView->getDecValue(); mModel->convertDecToHex(wDecValue);}void Controller::OnClearButtonClicked(View* iView) { mModel->clear();}main.cpp#include View.h#include Model.h#include Controller.h#include <QtGui/QApplication>int main(int argc, char *argv[]){ QApplication a(argc, argv); Model wModel; View wView; Controller wCtrl(&wModel); wView.setController(&wCtrl); wView.setModel(&wModel); wView.show(); return a.exec();}I can post the Subject/Observer files later if they become relevant.Asides from general comments, can someone please answer these questions:1) Would it be better to connect the buttons signals to the Controller slots directly (like in the portion commented out in View::setController)? The Controller needs to know which View called so it can use the proper information from the View doesn't it? This would mean either:a) Reimplement a QSignalMapper or b) Upgrade to Qt5 and VS2012 in order to connect directly with lambdas (C++11);2) What is optimal way to know what has changed when update is called by the Model ? Is it a switch/looping through all possibilities, a predefined map... ?3) Also, should I pass the necessary info through the update function, or let View check the required values the of Model once it gets notified ?In the second case the View needs access the Model data...4) Should the View need to have a reference to the Model ? since it only acts with on controller? (View::setModel()) If not, how does it register itself as an observer to the Model ? | MVC and Subject-Observer pattern in C++ & QT | c++;mvc;qt | null |
_computergraphics.4664 | When converting from uniform hemisphere sampling to cosine weighted hemisphere sampling I am confused by a statement in an article.My current indirect contribution is calculated as:Vec3 RayDir = UniformGenerator.Next()Color3 indirectDiffuse = Normal.dot(RayDir) * castRay(Origin, RayDir)Where the dot product is cos()But in this article on better sampling (http://www.rorydriscoll.com/2009/01/07/better-sampling/) the author suggests the PDF is (cos() / pi), and there is no evidence of the N dot L calculation.My question is - does that mean that I no longer need to perform the normal dot rayDirection because it is included in the PDF, or is it in addition to the pdf? | Does cosine weighted hemisphere sampling still require NdotL when calculating contribution for indirect light? | raytracing;sampling;monte carlo;importance sampling | You always need to multiply by the cosine term indeed (that's part of the rendering equation). Though when you do indirect diffuse using ray-tracing and thus monte-carol integration (which is the most common technique in this case), you have to divide the contribution of each sample by your PDF. This is well exampled here.Note also that in the mentioned reference, if the PDF has terms that you also find in the rendering equations then you can optimise the code if you wish by cancelling out these terms.Don't forget that the BRDF of a diffuse surface is / where stands for the surface albedo. So we need to divide the result by . Though in the case of the indirect diffuse component, don't forget that we should have divided the result of castRay by the PDF of the random variable, which as we showed earlier in this chapter is 1/(2). Dividing indirectDiffuseby 1/(2) mis the same as multiplying this value by 2. And since the albedo is also divided by we can simplify the code...You have a similar situation. If you look at the PDF for the cosine sampling, then you will realise that terms can be cancelled out. Which doesn't mean they are 'not' strictly necessary. They are, they just cancel each other out which allows to optimize the code slightly (and avoid a few division, multiplication, etc.). You are more in the micro-optimisation here... which can be confusing if you try to learn the theory by just looking at optimised code (which is often not properly commented).$ \dfrac{(cos(\theta) ... )}{PDF} = \dfrac{(cos(\theta) ... )}{\dfrac{cos(\theta)}{\pi}} = ... $ |
_cs.9546 | Given this formula how do you calculate the following? I don't understand, can some one explain? 1MTTF(System) = ------------------------ [Summation] 1 ------------ MTTFi (was going to upload an image of the formula but they don't let me)A 10 TB disk drive has an MTTF of 6,000,000 hours. How much data can we store in a system comprised of these disks, if we want the system MTTF to be at least 1.2M hours?If we are allowed to make it redundant (i.e., two of them operating in a parallel mode), and if the MTTR is 120 hours, what is the system MTTF? | Mean time to failure calculation help | computer architecture | null |
_webmaster.7418 | I would like to do the following in confluence:Have one blog per individual (not associated with particular space). Have a set of blogs associated with a space such that anybody who had access to that space could post to them.Is this possible? How do I do this? | Blogs in Confluence | confluence | null |
_webapps.29156 | I want to know if I can have gmail auto create label based off the sender.For example if I receive an email from [email protected] I want gmail to to apply the filter sarah without me manually creating the label because I want every single email to be labeled in this nature. Is this possible? | Gmail auto generate label based for sender | gmail;gmail labels | null |
_unix.10976 | When I install php5-cli on Debian Wheezy (currently testing), the interactive prompt is very unusable due to missing readline support (bug 341868). What's the easiest way to install a version linked against libreadline (for usable line editing)? | How do I install a PHP CLI with a usable interactive prompt on Debian Wheezy? | command line;debian;php;readline | null |
_ai.2974 | I'm using a NN created with CNTK's SimpleNetworkBuilder to make choices (specifically in board games). I specified ReLU as the layer type, so outputs can be arbitrary numbers.When evaluating a custom set of features, getting the choice of the function/model is simple: Look for the output signal with the highest value. However, there are times when I wish to introduce some randomness and assign probabilities to each output signal, then select the choice based on each output's probability.Currently, what I'm doing is manually normalizing all the output using a sigmoid function specified here: https://en.wikipedia.org/wiki/Logistic_functionThen, I multiply them all by a scalar such that the sum total of all outputs is 1.At this point, I pick a random number 0..1, and see where along the map it falls; that is my selected choice.What I'd like to know is, is there a better way? | Assigning probability to output of a ReLU network | neural networks | null |
_unix.264129 | I have a long string of text saved in a file that I want to easily copy to clipboard using Os X 10.11 terminal | can i use .bash_profile to create an alias which copies text from a file? | terminal;osx | null |
_softwareengineering.139343 | I have read many websites talking about how to avoid and how to design etc. I completely understand those strategies.My question is based on the following preconditions:You have a company with 1000's of developers.There are different teams working on the same product but as modules.New developers writing new code not knowing the overall system, please consider an Enterprise application.High available software development where a downtime of 15 mins is considered as an SLA violation.I could write few more preconditions but I thought these could be strong enough to support my question about why I might need a recovering strategy for a Deadlock in a software.Please note that re-designing the modules whenever we find a deadlock is not realistic.Now this being said.Can someone take sometime to provide an input or brainstorm on an idea of how to resolve a deadlock if at all it happens, so that we can report it and move forward, instead of halting completely.Run a deadlock detector that runs periodically to look for deadlocks in the system.If a deadlock is detected, notify with an event to resolve the deadlock.The deadlock event listener will then kick in and act upon the deadlocked threads.For each thread identify the contention.Write an intelligent algorithm that could either release the locks and kill the thread or release the locks and re-evaluate the thread.In step 2 we handle the notification in multiple ways, out of which logging is one of the listener.I know how to go about steps 1,2,6. Will need help with 3,4 and 5.I know that Oracle RDBMS already has a deadlock detection and resolution strategy in place, I wonder if they would ever share their strategies in this thread :)Can't add my comment as an answer so adding it as a comment here.================================================================= I completely understand the risk of killing the threads. I was 100% certain that I would get answers like this but I was also hoping that someone would suggest something new. I'll keep the thread open as there is no answer in here that I already do not know, thank you very much for trying though. | How to avoid halting of the JVM due to a deadlock in java? | java;concurrency | null |
_codereview.56498 | I have been unable to find any other way to update a user config file than the following method. public class SettingServices : ISettingServices{ public UserSetting GetUserSetting() { XmlSerializer reader = new XmlSerializer(typeof(UserSetting)); StreamReader file = new StreamReader(UserConfig); UserSetting settings = new UserSetting(); settings = (UserSetting)reader.Deserialize(file); return settings; } public void CreateUserSetting(UserSetting userSetting) { XmlSerializer writer = new XmlSerializer(typeof(UserSetting)); StreamWriter file = new StreamWriter(UserConfig); writer.Serialize(file, userSetting); file.Close(); } public void UpdateUserSetting(UserSetting userSetting) { UserSetting currentSettings = GetUserSetting(); UserSetting newSetting = new UserSetting(); newSetting.Name = (userSetting.Name == null) ? currentSettings.Name : userSetting.Name; newSetting.ViewChangeLog = (userSetting.ViewChangeLog == null) ? currentSettings.ViewChangeLog : userSetting.ViewChangeLog; newSetting.PrimaryRowColor = (userSetting.PrimaryRowColor == null) ? currentSettings.PrimaryRowColor : userSetting.PrimaryRowColor; newSetting.SecondaryRowColor = (userSetting.SecondaryRowColor == null) ? currentSettings.SecondaryRowColor : userSetting.SecondaryRowColor; newSetting.Font = (userSetting.Font == null) ? currentSettings.Font : userSetting.Font; CreateUserSetting(newSetting); } private static string UserConfig { get { string configDirectory = new Uri(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + \\CVS\\ICMQuery).LocalPath; return new Uri(configDirectory + \\ + System.Environment.UserName + .config).LocalPath; } }}Can someone please show me the light. I would preferably like to be able to update singular elements within the UserSetting class without destroying and rewriting the file every time I have to update it. | Updating XML config files | c#;xml;winforms;serialization | Preferably I'd like to just be able to update that node in the XML file without having to rewrite the whole file every time a change is made.In general, that's simply not possible, because XML is a text-based format.Imagine you have the following file:<UserSettings> <Name>Aron</Name> <!-- other settings here --></UserSettings>Now you want to fix the name from Aron to Aaron:<UserSettings> <Name>Aaron</Name> <!-- other settings here --></UserSettings>But doing this means that everything that's after the Name line has to be moved by one byte in the file, so almost the whole file has to be rewritten.With config files, this usually doesn't matter, because they tend to be relatively small. If it does matter to you, you will have to use another way of saving the config; a good choice might be an embedded database, like SQL Server Compact or SQLite.Yet another option would be to use .settings files (built-in in VS). It doesn't save you from rewriting the file, but it saves you from having to write all that code. |
_unix.341076 | I am still very new to command line tools (using my Mac OSX terminal) and hope I haven't missed the answer somewhere else, but I have searched for hours.I have a text file (let's call it strings.txt) containing 200 combinations of 3 strings. [Edit 2017/01/30] The first five rows look like this:surveillance data surveillance technology cctv camerasocial media surveillance techniques enforcement agenciessocial control surveillance camera social securitysurveillance data security guards social networkingsurveillance mechanisms cctv surveillance contemporary surveillanceNote that I can change strings.txt to any other format, as long as the bigrams/ 2-word phrases like surveillance data in line 1 stay together. (That means I can delete the quotes if necessary, as for the answer by @MichaelVehrs below).Now I want to search a directory of more than 800 files for those files that contain at least one of the string combinations (anywhere in the file). My original idea was to use egrep with a pattern file like this:egrep -i -l -r -f strings.txt file_directoryHowever, I can only get this to work if there is one string per line. This is not desirable, because I need the identified files to contain all three strings of a given pattern. Is there a way to add some kind of AND operator to the grep pattern file? Or is there another way to achieve what I want using another function/tool? Many thanks!Edit 2017/01/30The answer by @MichaelVehrs below was very helpful; I edited it to the following:while read one two three four five sixdo grep -ilFr $one $two *files* | xargs grep -ilFr $three $four | xargs grep -ilFr $five $sixdone < *patternfile* | sort -uThis answer works when the pattern file contains the strings without quotes. Sadly, it only seems to match the pattern on the first line of the pattern file. Does anyone know why?Edit 2017/01/29A similar question about grepping multiple values has been asked before, but I need the AND logic in order to match one of the three-string-combinations from the pattern file strings.txt in the other files. I realise that the format of strings.txt might have to be changed for the matching to work and would appreciate suggestions. | How to find all files containing various strings from a long list of string combinations? | text processing;awk;grep;osx | Since agrep seems not to be present in your system, have a look in this alternative based on sed and awk to apply grep with and operation from patterns read by a local file. PS: Since you use osx i'm not sure if the awk version you have will support bellow usage.awk can simulate grep with AND operation of multiple patterns in this usage:awk '/pattern1/ && /pattern2/ && /pattern3/'So you could transform your pattern file from this:$ cat ./tmp/d1.txtsurveillance data surveillance technology cctv camerasocial media surveillance techniques enforcement agenciessocial control surveillance camera social securitysurveillance data security guards social networkingsurveillance mechanisms cctv surveillance contemporary surveillanceTo this:$ sed 's/ /\/ \&\& \//g; s/^/\//g; s/$/\//g' ./tmp/d1.txt/surveillance data/ && /surveillance technology/ && /cctv camera//social media/ && /surveillance techniques/ && /enforcement agencies//social control/ && /surveillance camera/ && /social security//surveillance data/ && /security guards/ && /social networking//surveillance mechanisms/ && /cctv surveillance/ && /contemporary surveillance/PS: You can redirect the output to another file by using >anotherfile in the end , or you can use the sed -i option to make in-place changes in the same search terms pattern file.Then you just need to feed awk with awk-formatted patterns from this pattern file :$ while IFS= read -r line;do awk $line *.txt;done<./tmp/d1.txt #d1.txt = my test pattern fileYou could also not transform patterns in your original pattern file by applying sed in each line of this original pattern file like this:while IFS= read -r line;do line=$(sed 's/ /\/ \&\& \//g; s/^/\//g; s/$/\//g' <<<$line) awk $line *.txtdone <./tmp/d1.txtOr as one-liner:$ while IFS= read -r line;do line=$(sed 's/ /\/ \&\& \//g; s/^/\//g; s/$/\//g' <<<$line); awk $line *.txt;done <./tmp/d1.txtAbove commands return the correct AND results in my test files that look like this:$ cat d2.txtThis guys over there have the required surveillance technology to do the job.The other guys not only have efficient surveillance technology, but they also gather surveillance data by one cctv camera.$ cat d3.txtAll surveillance data are locked.All surveillance data are locked and guarded by security guards.There are several surveillance mechanisms (i.e cctv surveillance, contemporary surveillance, etv)Results:$ while IFS= read -r line;do awk $line *.txt;done<./tmp/d1.txt#or while IFS= read -r line;do line=$(sed 's/ /\/ \&\& \//g; s/^/\//g; s/$/\//g' <<<$line); awk $line *.txt;done <./tmp/d1.txtThe other guys not only have efficient surveillance technology, but they also gather surveillance data by one cctv camera.There are several surveillance mechanisms (i.e cctv surveillance, contemporary surveillance, etv)Update:Above awk solution prints the contents of matching txt files.If you want to display the filenames instead of the contents, then use the following awk where necessary:awk $line{print FILENAME} *.txt |
_unix.14893 | I'm using a Red Hat 4 Enterprise Linux. But, when I upgrade the kernel, an error occurred. And after, when computer is booting with new kernel (red hat enterprse 2.6.9-100.el), I receive the following the error.mkrootdev: label /1 not foundmount: error 2 mountng ext 3mount: error 2 mountng noneswitchroot : mount failed :22umount /initrd/dev failed :2kernel panic -not syncing :Attemped to kill init!After, when I try to boot the system with old kernel (red hat enterprse 2.6.9-42.el), the system successfully booted.My question is; when I rebooted the system, it attempt to boot with new kernel every time and so I have got to choose the old kernel with hand all the time.How to get rid from this problem?How can I uninstall the new kernel without problem? or How can I use the new kernel without problem?something like this grub.conf;default=0timeout=5splashimage=(hd0,0)/boot/grub/splash.xpm.gzhiddenmenutitle Red Hat Enterprise Linux ES (2.6.9-100.ELsmp) root (hd0,0) kernel /boot/vmlinuz-2.6.9-100.ELsmp ro root=LABEL=/1 rhgb quiet initrd /boot/initrd-2.6.9-100.ELsmp.imgtitle Red Hat Enterprise Linux ES (2.6.9-100.EL) root (hd0,0) kernel /boot/vmlinuz-2.6.9-100.EL ro root=LABEL=/1 rhgb quiet initrd /boot/initrd-2.6.9-100.EL.imgtitle Red Hat Enterprise Linux ES (2.6.9-42.ELsmp) root (hd0,0) | Red Hat Kernel Upgrade problem | boot;rhel;grub;kernel panic | Get your machine running with the good kernel and then edit /etc/grub.conf so it defauts to your good kernel , check the line in grub which says default=0. Changing that will fix your manual intervention boot issue. In your case default would need to be default=3 to boot your old good smp kernelThen look at removing your problem kernel with rpm -e , may be do a test (rpm -e --dry-run |
_unix.335486 | I am trying to write a script to reformat a dashcam SD card, as is recommended by the manufacturer. I can do this on a windows system with a simple python script, a snippet here:...fm = windll.LoadLibrary('fmifs.dll')FMT_CB_FUNC = WINFUNCTYPE(c_int, c_int, c_int, c_void_p)FMIFS_UNKNOWN = 0clustersize = c_int(32768) # 32K cluster sizefm.FormatEx(c_wchar_p(Drive), FMIFS_UNKNOWN, c_wchar_p(Format), c_wchar_p(Title), True, clustersize, FMT_CB_FUNC(myFmtCallback))...So, this is using some windows DLL and formats, and it works. The full script can be found hereNow I want to basically do the same on a Ubuntu system. I am trying to use mkdosfs, and I use system calls, here the command line:mkdosfs -f 2 -F 32 -s 64 -S 512 /dev/sdb1This formats the SD card, but when unplugging the camera from my laptop and switching it on to start recording, it seems to crash, presumably because the expected file system on the SD card is not quite right.I should of course mention that in both cases of the MS windows and the ubuntu case, I do add a few directories that are expected (/DCIM/100MEDIA) and also add a file time.txt with a time stamp the camera reads on start-up to reset the internal clock that is added as a time-stamp to the video.The camera I use is a Roadhawk Bullet Ride, and the specs only say to use a FAT32 file system with 32k cluster size. I have compared the output I get from dosfdsk, both after formatting the card on windows and ubuntu, and I can't see what would be the significant difference, I get 512 byes per sector, 32768 bytes per cluster, 2 FATs, 32 bit entries, etc. I am not sure how important numbers, like 'reserved sectors' and all the other information dosfdsk delivers, are.Thanks for any help or tip you can provide. | mkdosfs to format dashcam SD card FAT32 with 32kb cluster size | ubuntu;filesystems;python | null |
_codereview.19994 | I have written some code which will fetch contents from a resource which is actually stored in a tree format. Since it is in a tree format, there will be a parent-child relation and hence recursion.I am facing lot of performance issue as tree is growing in size this particular piece of code takes up-to 25 sec which is very bad. This piece of code will basically read data stored in file system (just for example) each content has certain set of property which it has to read.import java.util.List;public class Links { private String nodeName; private List<Links> children; public List<Links> getChildren() { return children; } public void setChildren( List<Links> children ) { this.children = children; } public String getNodeName(){ return nodeName; } public void setNodeName( String nodeName ){ this.nodeName = nodeName; }}package menu;import java.util.ArrayList;import java.util.Iterator;import java.util.List;public class Utility { /* * IN this class NavModel,CModel,CNode are some dummy classes which help us read contents form some resources which * are stored in dummy format as Example of tree format stored data below is the example tree child1 child2 child3 * child3-1 child:q child:r child:a child3-2 child4 */ private static void populateLinks( NavModel navModel, ContentModel metaDataModel, Object objectNode, Links parent, boolean specialLinks ) throws IOException{ try{ List<Links> childLinks = new ArrayList<Links>(); // below code gets all the childrens of parent Iterator it = navModel.getChildren( objectNode ); while( it.hasNext() ){ NavNode node = (NavNode) it.next(); ContentNode contentNode = node.getContentNode(); Links links = new Links(); MetaData data = metaDataModel.getMetaData( contentNode ); Map<String, String> paramValues = new HashMap<String, String>(); // this particular piece of // code gets all the properties of content iterates and stores it in data structure Iterator metaDataIterator = data.getNames().iterator(); while( metaDataIterator.hasNext() ){ String pagePropertyKey = metaDataIterator.next().toString(); String pagePropertyValue = (String) data .getValue( pagePropertyKey ); if( pagePropertyKey.equalsIgnoreCase( LINK_TYPE ) ){ links.setLinkType( pagePropertyValue ); } else if( pagePropertyKey.equalsIgnoreCase( TCDID ) ){ links.setTcmIdMap( pagePropertyValue ); } else{ paramValues.put( pagePropertyKey, pagePropertyValue ); } } links.setParamValues( paramValues ); if( specialLinks ){ links.setNodeName( links.getParamValues().get( APPLICATIONNAME ) ); } else{ links.setNodeName( contentNode.getTitle( new Locale( en_US ) ) ); } links.setDisplayName( setAppDispName( links.getNodeName() ) ); childLinks.add( links ); if( navModel.hasChildren( node ) ){ // This is where recursion happens populateLinks( navModel, metaDataModel, node, links, specialLinks ); } } parent.setChildren( childLinks ); } catch( Exception e ){ } } // THis is the method which calls the recursion function public static Links setupLinks( String categoryLinkName, String name ){ Links categoryLinks = null; CModel contentModel = new CModel(); NavModel navModel = new NavModel(); categoryLinks = Utility.createCategoryLinks( categoryLinkName ); Object objectNode = contentModel.getLocator().findByUniqueName( name ); if( objectNode != null ){ if( navModel.hasChildren( objectNode ) ){ populateLinks( navModel, objectNode, categoryLinks ); } }} private static Object setAppDispName( String nodeName ){ // fetch value from db return null; } }I know code is not complete and may be in appropriate to review but I can't paste the whole of my code hence I hope you understand and review there is recursion and iteration any way I can better write this piece of code. | Recursion and iteration how can i optimize this code | java;optimization;recursion | null |
_cstheory.38887 | This is a follow-up question. In my previous question, I presented Welder proof assistant and I stated that I want to automate proofs about basic field theory. The only answer to this post states that a combinatorial search is sufficient since the goals are easy. I'm looking for a more general technique. I have read Equations and rewrite rules: a survey. In page 12, it reads:An abelian group theory unification algorithm is given by Lankford.The idea is as follows. Given some context equations $\Delta$ from where we can deduce some other equations $\Delta \vDash \{x_i = y_i\}$, the unification process will give the neccesary substitutions to proof all the equalities in the right part using the formulas in $\Delta$. Another interesting quote appears on page 28:This algorithm gave the first known solution to unification in group theory using for $\mathcal{B}$ the canonical set shown in the appendix.In the appendix on page 33, I find a very interesting practical session. I have some questions on the power of the methods used and the actual results that I can expect after well-understanding this 30 pages heavy mathematical paper. I hope someone can give some orientation:What is being simulated in the practical session? I describe what I think is happening. The canonical set $\mathcal{B}$ mentioned above corresponds to given axioms $R_1$, $R_2$ and $R_3$. Then some theorems about groups are deduced. I assume that this happens by application of the $\epsilon$-unification algorithm given at page 27 and the Knuth-Bendix completion. Am I right? Could you tell me what is exactly the role of each algorithm (page 27 and Knuth-Bendix) in the solution? If you think that I can use this scheme in my problem, what steps should I do, how should I integrate this algorithms? | Using -unification and Knuth-Bendix completion to automatically proof theorems about groups | lo.logic;proof assistants;term rewriting systems | null |
_softwareengineering.236560 | I'm working on an Open Source software project (LGPL) which uses another LGPL-licensed software. To make it easier for users and developers I'm delivering and linking against the compiled thirdparty.As far as I know I have to include the sources and license-statements of LGPL software if I'm delivering and using it in binary form.However this would mean that I have to put the compiled version as well as the code of that thirdparty into my repository. Not only would that make the checkout take ages, it would also be somewhat redundant.Are there any techniques or best practices on how to solve this issue? My project is available on Github if that matters.Update:Link to ProjectLink to Thirdparty | Linking against LGPL - How to share the code? | licensing;open source;legal;lgpl | The GNU FAQ says the following, which should pretty much answer your question:Can I make binaries available on a network server, but send sources only to people who order them?If you make object code available on a network server, you have to provide the Corresponding Source on a network server as well. The easiest way to do this would be to publish them on the same server, but if you'd like, you can alternatively provide instructions for getting the source from another server, or even a version control system. No matter what you do, the source should be just as easy to access as the object code, though. This is all specified in section 6(d) of GPLv3.The sources you provide must correspond exactly to the binaries. In particular, you must make sure they are for the same version of the programnot an older version and not a newer version.So, e.g. just put a link into an About-dialog of your program which should point to a server under your control or a versioning system like git (and probably github).Be careful about what the other answer suggests:just give a contact email for the source and auto reply with a link where you got the library from originally if you didn't modify it or a link to a zip in a dropbox with the modifications.This is basically the opposite from what the GNU-FAQ says. It seems like you are not allowed to only provide the source code on request (maybe if you only distribute your binaries on request but certainly not if you provide them on a webpage). Most likely you will never get in trouble if you do what ratchet freak suggests, but that doesn't mean that it is the right way.A linked entry about version control systems the the FAQ-section cited above, says:Users should be provided with clear and convenient instructions for how to get the source for the exact object code they downloadedthey may not necessarily want the latest development code, after all.So make sure you comply with this by, for example, specifying the program's current version number in the About-dialog and setting concurrent tags in the git repository.And at the end the obligatory I am not a lawyer note ;) |
_codereview.149549 | I want to encode unicode codepoints to utf8 manually. I wrote the following C# code. I testet it with some cases I know but I would like to know if its correct for all inputs. I know that Unicode codepoints are undefined beyond 10FFFFhex but I dont care about that. Therefore the output of my method might be more than 4 bytes.private byte[] CodePointToUtf8 (int codepoint){ if (codepoint < 0x80) { return new byte[]{ (byte)(codepoint) }; } else if (codepoint < 0x800) { return new byte[]{ (byte)(0xC0 | (codepoint << 21 >> 27)), (byte)(0x80 | (codepoint << 26 >> 26)) }; } else if (codepoint < 0x10000) { return new byte[] { (byte)(0xE0 | (codepoint << 16 >> 28)), (byte)(0x80 | (codepoint << 20 >> 26)) , (byte)(0x80 | (codepoint << 26 >> 26)) }; } else if (codepoint < 0x200000) { return new byte[] { (byte)(0xF0 | (codepoint << 11 >> 29)), (byte)(0x80 | (codepoint << 14 >> 26)), (byte)(0x80 | (codepoint << 20 >> 26)) , (byte)(0x80 | (codepoint << 26 >> 26)) }; } else if (codepoint < 0x4000000) { return new byte[] { (byte)(0xF8 | (codepoint << 6 >> 30)), (byte)(0x80 | (codepoint << 8 >> 26)), (byte)(0x80 | (codepoint << 14 >> 26)), (byte)(0x80 | (codepoint << 20 >> 26)) , (byte)(0x80 | (codepoint << 26 >> 26)) }; } else { return new byte[] { (byte)(0xFC | (codepoint << 1 >> 31)), (byte)(0x80 | (codepoint << 2 >> 26)), (byte)(0x80 | (codepoint << 8 >> 26)), (byte)(0x80 | (codepoint << 14 >> 26)), (byte)(0x80 | (codepoint << 20 >> 26)) , (byte)(0x80 | (codepoint << 26 >> 26)) }; }}Bonus question: Is there an build in way to do that? | C# Encode Unicode Codepoints to UTF8 Manually | c#;unicode;utf 8 | Yes, the code is correct for all valid code points. I was first confused about the double shifts, since I have never seen them before, but they do their job well. Other authors typically do a single >> followed by a bit mask, e.g. (codepoint >> 12) & 0x3F to skip the 12 bits to the right and take the next 6 bits. That way, the numbers can be verified more easily, since they are smaller. Plus, all the 01xxxxxx bytes have the same bitmask.Your code omits some validity checks:codepoint could be < 0codepoint could be between 0xD800 and 0xDFFFOther than these, it is perfect.I know for sure that this conversion is built-in into C#, I just don't know where. Try loading a file into a string using the UTF-8 encoding. During that loading, the built-in conversion code gets called. |
_unix.208514 | I am setting up a workstation with RHEL 6.6. When I doping server1it said ping: unknown host server1. However I can ping server1 with IP address xx.xx.xx.xxx.It seems to me /etc/resolv.conf will be rewritten by NetworkManager.I do add these in my /etc/sysconfig/network-scripts/ifcfg-eth0:DNS1=xx.xx.xx.xxxDNS2=xx.xx.xx.xxxDOMAIN=xxx.xxx.xxAny suggestion what might went wrong? | ping: unknown host | rhel | null |
_webmaster.1504 | I found this blank theme, but I was wondering if there are any other themes that provide a template for custom theme development.I'm looking for something that, out of the box, provides a very simple theme with validating HTML (XHTML1.1, HTML 4.1 Strict, or HTML5) and CSS (CSS2 or CSS3). Then, I want to build on this theme to make a custom WordPress theme for my personal site/blog.I've never developed a WordPress theme, but armed with the documentation and a basic knowledge of HTML and CSS and a bit of PHP experience, I should be able to make something that's my own. | Are there any WordPress themes optimized as a starting point for custom theme development? | wordpress;theme | This should be just what you're looking for: http://nathanstaines.com/archive/starkers-html5-v3 |
_softwareengineering.319606 | What is the essence of dependency injection? Is it the idea of dynamically swapping out/in core logical/structural aspects of a program at runtime?Traditionally, this is done in code via some DI container. For example, using Structure Map in C#:container.For<ICacheService>().Use<InMemoryCache>();However, I've written several programs which inject code via configuration, in XML. Something like:<cacheServiceProvider use=My.Namespace.InMemoryCache, MyAssembly/>That config is iterated at startup, and the various classes are instantiated for use throughout the program.Is it fair to say that this is a form of DI? Dependency Injection by Configuration? Or does DI require configuration in code and the use of some container system?Are their other philosophical or conventional aspects required to say something is dependency injected, or am I completely misunderstanding this? | How broad is the definition of dependency injection? | dependency injection | null |
_unix.303656 | I have a .jar file which I run like this:java -jar server.jar 4242So I have a script java-server.sh to launch it:#!/bin/shjava -jar server.jar 4242 &server.jar should start working on system boot, so I tried:Adding @reboot /home/user/java-server.sh to crontab -eAdding bash java-server.sh || exit 1 to rc.localAdding java-server.sh to /etc/init.dNone of which work. If I log into the system and launch my script I works like clockwork until I log out. What is the problem here? | Debian Linux - run script/app on boot | debian;boot;java;startup | You should call your script will full path, for example put in /etc/rc.local: bash /usr/local/bin/java-server.sh > /tmp/java-server.log 2>&1if your script is in /usr/local/bin, of course... This will also create a log file to debug other potential problems. (Note that in production you should never create such log files in /tmp for security reasons, but in /var/log with proper permission, rettention and log rotating, but this is simplified for purposes of answer) |
_datascience.8655 | I'm looking to use a tree kernel (e.g. Zelenko et al., 2003, Moschitti 2006, etc.) for text classification in Python. However, I'm still a little unclear on the implementation. Is there an existing implementation (in any language) that I could use as a reference, or is there a 3rd-party tree kernel library I could use? | Implementation of Tree Kernels in Python | machine learning;python;statistics;nlp | null |
_computerscience.3700 | So I was reading this, I sort of got the reason why there are a lot more games on Microsoft windows than on any other OS. The main issue presented was that Direct3D is preferred over OpenGL. What I don't understand is why would any developer sacrifice compatibility? That is simply a financial loss to the company. I understand that OpenGL is kind of a mess, but that should hardly be a issue for experts. Even if it is, I think that people would go a extra mile than to incur a financial loss. Also if I'm not wrong then many cross platform applications use both Direct3D and OpenGL. I think they switch between the APIs. This is weird as they can just use OpenGL, why even care about Direct3D? So the question is, are there any technical issues with OpenGL or is there any support that Direct3D provides that OpenGL lacks?I am aware that this question might be closed as being off-topic or too broad, I tried my best to narrow it down. | Is there any reason to prefer Direct3D over OpenGL? | opengl;direct3d | About the fact that there are more games for Windows, some reasons areWindows has the majority of the market and in the past to develop cross platform games was more complicated than it is today.DirectX comes with way better tools for developing (e.g. debugging)Big innovations are generally first created/implemented in DirectX, and then ported to/implemented in OpenGL. As for Windows vs Linux, you have to consider that when there is an actual standard due to marketing and historical reasons (for that see https://softwareengineering.stackexchange.com/questions/60544/why-do-game-developers-prefer-windows, as I said in the comments), it has its inertia.The inertia thing is very important. If your team develop for DirectX, targeting 90% of the market (well... if you play games on pc you probaly have windows, so... 99% of the market?), why would you want to invest in OpenGL? If you already develop in OpenGL, again targeting 99% of the market, you will stick to it as long as you can. For exampe Id Tech by Id Software is an excellent game engine (powering the DOOM series) that uses OpenGL.About the topic of your discussion, a comment.As of today, there are many many APIs, and a common practice is to use a Game Engine that abstracts over them. For example, consider thatOn most mobile platform you have to use OpenGl ES.On PC you can use both DirectX and OpenGLI think on XBOX you have to use DirectX.I think that on PS you use their own API. With old hardware you use DirectX9 or OpenGL 3, or OpenGL ES 2.With more recent hardware you can (and want to) use DirectX 11, OpenGL 4, OpenGL ES 3.Recently, with the advent of the new low overhead APIs - whch is a major turning point for graphical programming - there are DirectX 12 for Windows and XBOX, Metal for iOS and Vulkan (the new OpenGL) for Windows and Linux (including Android and Tizen).There still are games that only target Windows and XBOX, but IMHO today that can only be marketing choice. |
_unix.258797 | I have some arbitrary data as an output of a command (e.g. a fragment of a binary data put out using tail). I want to feed it to another command/program which allows only a file as an argument (e.g. rawtopng [filein] [fileout]), does not support dash (-) argument, and I cannot make a temporary file in between. How can I do it in bash?Will something like rawtopng <(tail myfile) fileout work? | How to pipe data from one command to another command which allows only a file as an argument? | bash;shell script;pipe;stdin | null |
_unix.215019 | I have a system with 1 GB of physical RAM. Right now, free shows the following memory usage: total used free shared buffers cachedMem: 1026360 863660 162700 0 0 50216-/+ buffers/cache: 813444 212916Swap: 5242876 500648 4742228So except the block cache, 813 MB are used. /proc/meminfo (which I'll post at the bottom due to length) tells me that, of this, 283 MB are mapped into userland processes (AnonPages + Mapped), and that 127 MB are used by the kernel (Slab + KernelStack + PageTables).That still leaves ~400 MB unaccounted for, however. Are my conceptions of how the system uses memory somewhat correct? Is there a way to tell what half of my memory is used for?MemTotal: 1026360 kBMemFree: 193768 kBBuffers: 0 kBCached: 28932 kBSwapCached: 101208 kBActive: 178816 kBInactive: 182476 kBActive(anon): 167196 kBInactive(anon): 168184 kBActive(file): 11620 kBInactive(file): 14292 kBUnevictable: 9848 kBMlocked: 9848 kBSwapTotal: 5242876 kBSwapFree: 4739272 kBDirty: 24 kBWriteback: 0 kBAnonPages: 268280 kBMapped: 14832 kBShmem: 280 kBSlab: 111828 kBSReclaimable: 27432 kBSUnreclaim: 84396 kBKernelStack: 2280 kBPageTables: 13200 kBNFS_Unstable: 0 kBBounce: 0 kBWritebackTmp: 0 kBCommitLimit: 5756056 kBCommitted_AS: 1506036 kBVmallocTotal: 34359738367 kBVmallocUsed: 145004 kBVmallocChunk: 34359581976 kBHardwareCorrupted: 0 kBAnonHugePages: 0 kBHugePages_Total: 0HugePages_Free: 0HugePages_Rsvd: 0HugePages_Surp: 0Hugepagesize: 2048 kBDirectMap4k: 79808 kBDirectMap2M: 968704 kB | What does Linux spend memory on other than userland, caches and slab? | linux;memory | null |
_scicomp.7688 | DisclaimerIn the process of typing up this question, I determine its solution. Since I went through the trouble of typing up the question in its entirety, I will post its answer as well. It may help out others who find themselves in the same predicament. Think of this as a sort of blog-post, if you will.The GoalConsider the mixed boundary value problem\begin{align}\frac{d}{dx}\left(k(x)\frac{du}{dx}\right)=f \text{ in }\Omega\\u=P \text{ at } x=0\\\frac{du}{dx}=T \text{ at } x=1\end{align}where $P$ and $T$ are constants and $f$ is a source term.I'm using finite differences and my goal is to impose the boundary condition at $x=1$ in such a way as to achieve second order accuracy. Assume that the grid has $N+1$ equispaced points (including the boundary points) given as $x_0,x_1,...,x_N$My ApproachAt the right boundary, use a 2nd order centered difference for the boundary condition\begin{equation}\frac{u_{N+1}-u_{N-1}}{\Delta x}=T\end{equation}and the 2nd derivative operator as:\begin{align}\frac{k_{N+\frac{1}{2}}\frac{u_{N+1}-u_{N}}{\Delta x} -k_{N-\frac{1}{2}}\frac{u_{N}-u_{N-1}}{\Delta x}}{\Delta x}=f_i\end{align}We can solve for the ghost point $U_{N+1}$ in the 1st equation, substitute it into the 2nd equation and simplify.The ProblemUsing this discretization requires the evaluation of $k_{N+\frac{1}{2}}=k(x_N+\frac{\Delta x}{2})$, which is outside of the domain! In general, $k(x)$ is only defined within the domain and I can't/shouldn't use values outside of it. Thus, I don't think this is the right approach to achieve 2nd order accuracy. What else can I do in this case? | Finite Difference Method Neumann Boundary Condition with Variable Coefficients | finite difference;boundary conditions | null |
_cogsci.12890 | Nerves can detect pressure, temperature, light (eyes), sound, friction- at least. Does each sensation have its own neurotransmitter? I'm only a little familiar with neurotransmitters. This page pretty well sums up what I know about neurotransmitters.So it seems like its a combination of neurotransmitters that flow from any single perception area. | Are there specific neurotransmitters for specific sensations? | neurobiology;neuro transmitters | No. For example, the neurotransmitter at the first stage of auditory processing (the inner hair cell VII cranial nerve synapse) and visual processing (rod and cone synapses with a bipolar cells) is glutamate. |
_unix.244066 | Let's say I have a bunch of .jpg files which I want to convert to .png. The file structure is as follow:00-01.jpg 00-02.jpg 00-03.jpg 00-04.jpg 00-05a.jpg00-05b.jpg01-01.jpg 01-02.jpg 01-03a.jpg01-03b.jpg01-04a.jpg01-04b.jpgSo now I want to rename 00-01.jpg to ACDfff001.png then 00-02.jpg to ACDfff002.png and so on. However when I reach 00-05a.jpg and 00-05b.jpg I want to name these as ACDfff005a.png respectively ACDfff005b.png. The final result e.g should be as:00-01.jpg -> ACDfff001.png00-02.jpg -> ACDfff002.png00-03.jpg -> ACDfff003.png00-04.jpg -> ACDfff004.png00-05a.jpg -> ACDfff005a.png00-05b.jpg -> ACDfff005b.png01-01.jpg -> ACDfff006.png01-02.jpg -> ACDfff007.png01-03a.jpg -> ACDfff008a.png01-03b.jpg -> ACDfff008b.png01-04a.jpg -> ACDfff009a.png01-04b.jpg -> ACDfff009b.pngIs this possible in bash or python? | How to rename bulk of jpg files to png using convert | bash;python;rename | Here's a starting point; it assumes that the indexes only go up to 9; you'll have to extend it if that's not true.#!/bin/bashindex=0lastseq=for file in *.jpgdo base=$(basename $file .jpg) lastchar=${base: -1:1} if [[ $lastchar =~ [[:digit:]] ]] then index=$((index + 1)) newname=$(printf ACDfff%03d $index) lastseq=$lastchar else seclast=${base: -2:1} if [[ $seclast != $lastseq ]] then index=$((index + 1)) lastseq=$seclast fi newname=$(printf ACDfff%03d%s $index $lastchar) fi echo mv $file ${newname}.pngdone |
_softwareengineering.283906 | I'm attempting to refactor what is becoming a very large method -- currently 350 or so lines -- that contains a high degree of cyclomatic complexity. I understand and ascribe to the theories that methods should be short and that concerns should be separated, and I've been reading over things like this and this among others. I'm struggling to refactor my method, though, for a couple of reasons. To help illustrate these, first here is a simplified example of what the method looks like before refactoring:private static void ProcessMessage(Message toProcess){ var processingIssues = new StringBuilder(); var transformedAttachments = new List<TransformedAttachmentData>(); foreach (var attach in toProcess.Attachments) { //in reality there is quite a bit of nested logic here, //but I'll represent it as a single if-else block. if (true) { //in reality, a third-party library is used in multiple //levels of this logic hierarchy to produce the transformed data. transformedAttachments.Add(new TransformedAttachmentData(attach)); } else { processingIssues.AppendLine( string.Format(@Issue {0} occurred with + @attachment {1}., blah blah problem, attach.Name)); } } /* * do something else complex here with * processingIssues and validResults */}First, the very cyclomatic complexity which is concerning to me is born of a complicated set of business rules that need to be applied which together sum up to a couple shared sets of data (represented here as processingIssues and transformedAttachments). Basically what this means to me is that not only should I break the foreach out into its own method, but I should also further consider breaking the logic tree contained within it into additional methods in the interest of keeping my methods short. In other words, it would seem as though it's not enough just to break my current method into its two obvious outer-most parts: pre-processing and post-processing of the attachments, if you will. How far do I need to go with this given that I am dealing with a complicated logic tree with concerns that are not so separate from one another. In other words, if separation of concerns is one reason to refactor to smaller methods, but so is cyclomatic complexity -- both of which seem to be orthogonal concepts -- which is the right reason to refactor, and how should I do it in the latter case?Second, in order to separate out some of the concerns to separate methods, those separate methods will have to return multiple variables (again, processingIssues and transformedAttachments), both of which are only needed within the separate methods themselves, so I'm faced with the choice: use output parameters, or create a small class to wrap the return values. Which is better?Any guidance on this topic and my specific hang-ups would be much appreciated. | Refactoring long methods with a lot of cyclomatic complexity | c#;design;design patterns;refactoring;separation of concerns | Your scenario seems like you have placed an entire message processing subsystem inside a single function. In order to simplify the function, you will need to come up with an actual message processing subsystem consisting of several classes. Some, if not all, of these classes will need to be instantiated, allowed to run, and discarded on each invocation of your method.This will be a subsystem which will have some state and some classes implementing operators (the actual rules.) The issue of returning multiple results is transformed into the task of modifying more than one item of state of the subsystem, and the issue of various rules interacting with each other is also transformed into having some rules modifying the state of the subsystem while other rules look at this modified state in order to figure out what to do.Essentially, there would be a pretty close correlation between the set of local variables of your function and the set of member variables of the message processing subsystem class, though the subsystem might need to contain more member variables in order to capture information which is currently encoded in conditional branching (if statements) in your existing method.Needless to say, the total number of lines in such a subsystem might easily exceed your current 350 lines by a factor of 2 or 3, so, before you embark on such a refactoring, consider whether you really need it. |
_webapps.55238 | MATCH function does not appear to work at all.Given the following data:$7,109.19 | $867.19 | -$5,374.81 | -$11,616.81=MATCH(MAX(FILTER(B122:U122, B122:U122 < 0)),B122:U122) returns the error error: Did not find value -5374.810000000005How can it not match a field for a value generated purely out of values that exist in the array?All I really want to do is select a cell in a different row of the same column of the value that should be returned by that match call. Thoughts? | MATCH Function does not work | google spreadsheets | null |
_cs.56632 | I have been looking for a prototypical language for recursive languages (decidible) which is no context sensitive without success. For instance $a^*$ is prototypical of regular languages, $a^nb^n$ for context free languages and $a^nb^nc^n$ for context sensitive languages. I usually consider the language which is accepted by a universal Turing machine (UTM) as prototypical of recursively enumerable. However for the the recursive languages I don't have one. I used to think that $\{1^p | p \text { is prime}\}$ was recursive but verifying a number is prime can be done by a bounded Turing machine. I also had $\{1^{2^{n}}\}$ but again verifying this can be done by a bounded Turing machine. On the other hand, the other options I have found are computing Turing machines that requiere that the output of the computation to be store somewhere in the machine, however the output is no part of the accepted language which makes every of those language regular or context free so far. For instance the machine that sums two numbers represented by 1s and separated by a space, and puts the result after. In this case, the accepted language is actually $1^*B1^*$ which is regular! If we try to do it like verification if become context free $1^nB1^mB1^{n+m}$ but no recursive!So is it possible to talk about a recursive language which it might be regular in essence but since it is conditioned to do the computation and put a result in the output as a kind of recursive language? Those definitely can not be done in a bounded Turing machine. | Is there an example of a recursive language which is not context sensitive? | formal languages;turing machines;context sensitive | Here's a more formal proof, by the standard trick of diagonalization (it must be folklore, but I saw it recently here)Let $G_1, G_2, ...$ be some enumeration of context sensitive grammars (convince yourself that there are only countable many of them; Why can they be enumerated?),Let $x_1, x_2, \ldots,$ be enumeration of $\Sigma^*$ (i.e., $x_1=\epsilon$, $x_2=0$, $x_3=1$, $x_4=00$, etc. in the case of binary alphabet).Consider the language:$$L = \{ x_i \mid x_i \notin L(G_i)\}.$$Claim 1 $L$ is not context sensitive: if it was, there was a specific $G_j$ generating it, but $x_j\in L$ while $x_j \notin G_j$.Claim 2 $L$ is decidable: given $x_i$ we just check if $G_i$ generates it (this problem is known to be PSPACE complete, thus decidable). |
_unix.293271 | I have a laptop with Arch and i3 installed and a desktop with Win 7 installed.My goal is to run a VNC server on the laptop and connect to it from my Win 7 desktop via VNC viewer and be able to use my i3config that I have setup on the laptop itself.I have tigervnc installed on the laptop and TightVNC installed on my desktop. I am able to start a vncserver and then connect to it from the vncviewer, but here's the tricky part...I can't get i3 to work properly on my desktop. Once I am connected to the server it displays 4 xterm instances without any proper layout (scattered accross the screen in no order). Do I have to export my i3config somehow to the vncviewer?Unfortunately I am at work at the moment so I can't paste my .xstartup but I can do that once I get home.Have anyone of you gotten VNC to properly work with i3? If so, how?Just to clarify: I don't have any issues with connecting to the server, I just don't get the wm (in this case i3) to work.TLDR; How do I get i3 to work with a Windows 7 client using VNCviewer? | VNC server on Arch with i3 and VNC viewer on Win 7 | arch linux;windows;vnc;i3 | I found another solution to this.I used x0vncserver instead (which is included in the tigervnc package).You can start the server via x0vncserver -display :0 -passwordfile ~/.vnc/passwd. |
_unix.307768 | as title. I've searched the net but found nothing useful? I've also looked at this link: man smb.confand I honestly don't know what to look for. Nothing obvious stands out.Thank you | Is it possible to turn off the AD features of Samba4? If yes, how? | samba;samba4 | null |
_unix.36627 | I am behind a proxy server in my college. It uses a simple username and password authentication. And i connect to the proxy server to port 3128. now i want to telnet simply to say any website on the internet like$ telnet www.google.com 80this gives me error telnet: could not resolve www.udacity.com/80: Name or service not knownHow can I define the proxy settings for telnet? I have already set environment variables http_proxy and HTTP_PROXY. Also have applied system wide proxy. | How to telnet via proxy authentication? | authentication;proxy;telnet | You can use Proxychains for this.First install proxychains, using the command:$ apt-get install proxychainsThen configure your proxy settings in /etc/proxychains.conf file.Add at last, these lines for HTTP and HTTPS proxy.http proxy-ip proxy-port username passwordhttps proxy-ip proxy-port username passwordNow you can do telnet by using the following command:$ proxychains telnet www.google.com 80 |
_webapps.37037 | I am in France for the holiday, and the internet connection is not that great. Actually, I have to select 240p for my YouTube videos.I am following a YouTube course. While a poor video quality is acceptable, a poor audio quality is more of a problem. Is there a way to have high quality audio despite low quality video on YouTube? | YouTube: Low quality video but high quality sound | youtube;video;audio;quality | No this isn't possible, seeing that the video and audio are linked when they stream. To get the highest quality sound you need the highest quality video.Source: http://evolver.fm/2011/02/08/how-to-get-better-sound-on-youtube/ |
_webapps.57244 | I started programming just a few weeks ago, got a grasp on the concepts and been evolving on it, since I have certain activities with spreadsheets, I decided to take it to the next level and got stuck on how to make a formula.I'm manually gathering all the data and I need to keep it as it is, since it's important for the analysis to know if a team is playing at home or not.Right now, I have something like this it would be A1, B1, C1 and D1. For example: | Newcastle | 1 | 2 | Liverpool I'm analyzing one club at time. So I need to know if the team on A1 or D1 is the team that I'm analyzing, then I need it to check how many points this team got from the match, so it needs to recognize what the result on B1/C1 is, and which team owns the result. The team on A1 owns the result on B1, and the team on D1 owns the result on C1.I hope it's enough to enlight whoever can help me. Maybe there are better functions to use than IF like I said in the title, if you can point it out, it would be also great. Right now I'm trying to work with nested IF functions. | Using if (or other function) to recognize a string and sum values | google spreadsheets;formulas | Please try: =if(B1=C1;1;if(B1>C1;0;3)) IF the team to be analysed is in F1 then in E1 and copied down: if(and(F$1=A1,B1>C1),3,if(and(or(F$1=A1,F$1=D1),C1=B1),1,if(and(F$1=D1,C1>B1),3,if(and(F$1=A1,B1>C1),3,0)))) might suit. It is the nature of spreadsheets that locations (cell references) are very significant and with the limited information in the question difficult to optimise what appears an ugly formula. |
_softwareengineering.262885 | This page descibes one important difference between Factory Method and Abstract Factory:http://architects.dzone.com/articles/factory-method-vs-abstractThe difference, according to this page, is that in Factory Method pattern the Creator (i.e. the entity creating new objects) and the Client (i.e. the entity using the Creator) are the same class. More precisely, this pattern only defines a method, so the rest of the class is the Client. In Abstract Factory however, the Creator and the Client are separate classes. The Creator's only purpose is to create objects so only a separate class can be the Client.Is this distinction correct? If so, why can't the Creator method in the Factory Method be put in a separate class? Would it create any problems? Similarly, why can't the Creator class in the Abstract Factory be the same class as the Client? Would this create any problems?Update:Just as a side note: it's SHOCKING to me too see that when I ask about such well known and (what should be) well defined design patterns I get actually contradictory answers. And it's not just this thread - the more and more I ask people (or search online resources) about the basic design patterns the more I start to think that people don't actually TRULY understand them even though they're using them on a daily basis and they believe they understand them. | Client vs Creator in Factory Method and Abstract Factory patterns | design patterns;factory method | null |
_codereview.100399 | I've been reading Dive Into Python and I needed to actually program something before I forget everything I learned. So, this is my first Python project (apart from trying the basics and playing with console).I first wrote this using lots of globals but that looked stupid so I rewrote it as a class. It was more-or-less main loop that called restart_game() which reset variables. But, I had self everywhere (eg. before every x, is this normal?) and that seemed weird so I rewrote it. Now I have run_game() which runs single game and is called from infinite loop.Still, this being my first real Python program, I'm sure there's room for improvement.snake.py'''Simple snake game using pygame.'''import pygameimport random# R G BWHITE = (255, 255, 255)BLACK = ( 0, 0, 0)RED = (255, 0, 0)GREEN = ( 0, 210, 0)DARK_GREEN = ( 0, 155, 0)DARK_GRAY = ( 40, 40, 40)BG_COLOR = BLACKHEAD_COLOR = GREENSNAKE_COLOR = DARK_GREENFONT_SIZE = 36# (dx, dy)LEFT = (-1, 0)RIGHT = (1, 0)UP = (0, -1)DOWN = (0, 1)key_mapping = { pygame.K_LEFT : LEFT, pygame.K_a : LEFT, pygame.K_RIGHT : RIGHT, pygame.K_d : RIGHT, pygame.K_UP : UP, pygame.K_w : UP, pygame.K_DOWN : DOWN, pygame.K_s : DOWN }class Snake(): Simple snake game. title - game title width - window width height - window height cell_size - size of one tile height and width need to be multiples of cell_size game_speed - must be >1 def __init__(self, title=Snake, width=640, height=480, cell_size=20, game_speed=8): self.width = width self.height = height self.cell_size = cell_size if height % cell_size != 0 or width % cell_size != 0: raise ValueError(height and width need to be multiples of cell_size) self.game_speed = game_speed if game_speed < 1: raise ValueError(game_speed must be bigger than 0) pygame.init() self.font = pygame.font.Font(None, FONT_SIZE) self.clock = pygame.time.Clock() self.display = pygame.display.set_mode((width, height)) pygame.display.set_caption(title) self.display.fill(BG_COLOR) def loop_games(self): Start new game and keep restarting until player quits. while True: self.run_game() def run_game(self): Run one game. row_count = self.height/self.cell_size col_count = self.width/self.cell_size x, y = self.get_starting_point() snake = [(x, y), (x - 1, y), (x - 2, y)] dx, dy = RIGHT apple_x, apple_y = self.generate_apple() while True: current_dx, current_dy = dx, dy for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() raise SystemExit(0) elif event.type == pygame.KEYDOWN: if event.key in key_mapping: new_dx, new_dy = key_mapping[event.key] # So you can't go from right to left and eat yourself. # You can't check against new_dx/new_dy because it # could be changed multiple times (eg. going right # and pressing up and left quickly). if new_dx != -current_dx and new_dy != -current_dy: dx, dy = new_dx, new_dy # move head x += dx; y += dy snake.insert(0, (x, y)) if x == apple_x and y == apple_y: apple_x, apple_y = self.generate_apple() else: # remove last part of snake snake.pop() self.display.fill(BG_COLOR) # apple apple_rect = pygame.Rect(apple_x * self.cell_size, apple_y * self.cell_size, self.cell_size, self.cell_size) pygame.draw.rect(self.display, RED, apple_rect) # body game_over = False for snake_x, snake_y in snake[1:]: body_rect = pygame.Rect(snake_x * self.cell_size, snake_y * self.cell_size, self.cell_size, self.cell_size) pygame.draw.rect(self.display, SNAKE_COLOR, body_rect) # border pygame.draw.rect(self.display, DARK_GRAY, body_rect, 1) if x == snake_x and y == snake_y: game_over = True # head head_rect = pygame.Rect(x * self.cell_size, y * self.cell_size, self.cell_size, self.cell_size) pygame.draw.rect(self.display, HEAD_COLOR, head_rect) pygame.display.flip() self.clock.tick(self.game_speed) if x < 0 or x >= col_count \ or y < 0 or y >= row_count \ or game_over: self.show_game_over() return def show_game_over(self): Show game over text. text = self.font.render(Game Over, True, WHITE) text_rect = text.get_rect() text_x = self.width / 2 - text_rect.width / 2 text_y = self.height / 2 - text_rect.height / 2 self.display.blit(text, (text_x, text_y)) pygame.display.flip() pygame.time.wait(300) def generate_apple(self): Generate new apple coordinates (x, y). return (random.randrange(0, self.width / self.cell_size), random.randrange(0, self.height / self.cell_size)) def get_starting_point(self): Return starting location of snake's head (x, y). return (random.randrange(5, (self.width / self.cell_size) - 5), random.randrange(5, (self.height / self.cell_size) - 5))if __name__ == '__main__': snake = Snake() snake.loop_games() | Simple Snake with pygame | python;python 3.x;pygame;snake game | null |
_softwareengineering.326229 | I am recently developing multi-tents cloud application that can help to generate classes and dbcontext dynamically for other ASP MVC projects.How can I do this task from my application to another projects with updating the DB for the new projects. | Entity framework code first for another project | c#;entity framework;code generation | null |
_softwareengineering.211683 | I appreciate all help and feedback. Parts bolded are critical parts if this is too verbose. Perhaps it will help to mention I am a green developer. I have found some useful info from related questions posted here and on Stack Overflow but nothing that felt 100%.BackgroundCurrently at work we are developing a web application with strict constraints set forth by the client. Normally we are a Rails shop, but the client really wanted to work with us. Thus to fit into their architecture we will be using ASP.NET. We are not very experienced with ASP.NET but some of the team including myself have used .NET for desktop applications.This application is three tiered and includes:Public facing server(s)Web services server(s)Data server(s)The client is expecting high demand and they may have multiple servers in any one of the tiers. There is a firewall between every tier. From my understanding this is a very common set up. A core goal is to minimize trips over the wire from the public facing server to the database.The ProblemHow do we handle user authentication without hampering performance on an N-Tier application with potentially many servers at each layer?What We've Done so FarWe toyed with the idea of using view state but ultimately felt like this would be a poor idea. Of course we are not opposed to re-visiting view state, but feel that view state offers no benefits over cookies and simply makes it harder for a user to have multiple tabs of our application open. I have been exploring the path of using the default session state with a custom implemented session store. The default session state tends to generate multiple requests going over the wire. Logging in and out this is okay, but when the user is using the app we do not want this. The custom session store helps minimize impact, but not by enough.Conclusion & Possible IdeaSince trips to the database will be inevitable on almost all requests once inside the application, perhaps giving the user a key on successful login is the best way to go. Then when the user requests a new page, or posts a new page we could send that key with the related SQL transaction for the request and validate the key. I believe this will simplify the code base immensely. So to re-iterate the problem: How do we handle user authentication without hampering performance on an N-Tier application with potentially many servers at each layer? Does the idea above sound like a solid implementation?Thanks,Jonathon | Implementing User Authentication on an N-Tier Web Application | asp.net;asp.net mvc;authentication;n tier | null |
_unix.104255 | I want to show the online users using the who command but I want to have a unique output and not show any duplicates. I piped the output into awk but I am not very familiar with that, is this the right way and how to proceed? | Print unique of who command | awk;sort;who | It's easier to just do it with sort: who | sort -u -k1,1The -u flag asks for unique lines (suppress duplicates). The key flag (-k) says to only consider the first word in each line for purposes of sorting and uniqueness. |
_cs.16515 | I've just began studying Artificial Intelligence and am wondering why the reachable state space of an 8-puzzle is $9!/2$. I see that the number of permutations of the tiles is $9!$ but it is not immediately obvious why half the possible states of the puzzle are unreachable at any given state. Can anyone elaborate?An image of an 8-puzzle for reference with a random configuration on the left and the goal state on the right: | Reachable state space of an 8-puzzle | artificial intelligence | This is an expansion of this presentation.Because the state graph consists of two disconnected components of equal size.Without loss of generality we can assume that the target state is $1\;2\;3\;...\;15\;\Box$. 1 2 3 4 5 6 7 8 9 10 11 1213 14 15 *Given a state $S$ a permutation inversion is a tile $T_i$ that is placed after $T_j$ but $i < j$; this happens when (a) $T_i$ is in the same row of $T_j$, but on its right, or (b) $T_i$ is in a lower row: . . . . . . . . 3 . . 1 . 7 . . . . . . . 5 . . . . . . . . . . (a) (b)We define $N_j$ as the number of tiles $T_i$, $i < j$ that appears after $T_j$.For example, in the state: 1 2 3 4 5 10 7 8 9 6 11 1213 14 15 *we have that after $T_{7}$ there is one tile ($T_6$) that should be before it, so $N_7=1$; after $T_{10}$ there are four tiles ($T_7, T_8, T_9, T_6$) that should be before it, so $N_{10}=4$.Let $N$ be the sum of all $N_i$ and the row number of the empty tile $T_{\Box}$$$N = \sum_{i=1}^{15} N_i + row(T_{\Box})$$In the example above we have: $N = N_7 + N_8 + N_9 + N_{10} + row(T_{\Box}) = 1 + 1 +1 + 4 + 4=11$We can notice that when the empty tile is moved horizontally $N$ doesn't change; if we move the empty tile vertically $N$ changes by an even quantity.For example: . . . . . . . . . . 2 3 . . * 3 4 5 * . 4 5 2 . . . . . . . . .$N' = N + 3 \mbox{ (2 is placed after 3,4,5)} - 1 \mbox{ (empty tile is moved up)} = N + 2$ . . . . . . . . . . * 4 . . 3 4 2 5 3 . 2 5 * . . . . . . . . .$N' = N + 1 \mbox{ (2 is placed after 3)} - 2 \mbox{ (4,5 are placed after 3)} + 1 \mbox{ (empty tile is moved down)} = N$So $N \bmod 2$ is invariant under any legal move of the empty tile.We can conclude that the state space is split in two disconnected halves, one having $N \bmod = 0$ and the other having $N \mod 2 = 1$.For example the following two states are not connected: 1 2 3 4 1 2 3 4 5 6 7 8 5 6 7 8 9 10 11 12 9 10 11 1213 14 15 * 13 15 14 * N = 4 N = 5 |
_codereview.38608 | I'm creating a custom MembershipProvider for an ASP.NET MVC5 application and am wanting to know if this code is acceptable for creating hashed and salted passwords. Is there anything I can do to improve it?EncodePassword is passed the plaintext password from the override functions. I picked 38 hash iterations arbitrarily and I honestly don't know if it's even necessary or valuable. Should it be higher?_machineKey is auto generated by ASP.NET for each machine/VM the software runs on. I will probably remove this to allow a distributed system and use an application key instead. Though, looking through the documentation for HMACSHA1, would it even seem like this key may be necessary? EncodePassword() result will be stored directly in the database. private bool CheckPassword(string password, string dbpassword) { var salt = GetSalt(dbpassword); password = EncodePassword(password, salt); if (password == dbpassword) { return true; } return false; } private string EncodePassword(string password, string salt = ) { if (string.IsNullOrEmpty(salt)) salt = CreateSalt(); var hash = new HMACSHA1 { Key = HexToByte(_machineKey.ValidationKey) }; var bytePassword = hash.ComputeHash(Encoding.Unicode.GetBytes(password + salt)); for (int i = 0; i < 38; i++) { bytePassword = hash.ComputeHash(bytePassword); } return String.Format({0}:{1}, bytePassword, salt); } private static string CreateSalt(int size = 64) { using (var rng = new RNGCryptoServiceProvider()) { var buff = new byte[size]; rng.GetBytes(buff); return Convert.ToBase64String(buff); } } private static string GetSalt(string password) { var passwordSplit = password.Split(':'); if (passwordSplit.Length == 2) { return passwordSplit[1]; } return String.Empty; } | Is this password hashing acceptable for a custom MembershipProvider? | c#;asp.net;security;cryptography | This is a pretty good start: you've got salting done pretty well (RNGCryptoServiceProvider is one of the most common recommended was to generate a salt), and the idea of using multiple iterations is a good one.However, doing 38 iterations of HMAC SHA1 yourself is not really going to help you much. The point of iterations is to slow down someone who is trying to brute-force passwords by making it take longer to do so. SHA1 is designed to be fast (it has to be in order to be used for message authentication at scale), so doing it multiple times doesn't slow you down all that much.Instead, consider using an algorithm purpose-built for password hashing, like PBKDF2, bcrypt, or scrypt. They are built on the same cryptographic hash functions, but are tuned for the specific purpose of password hashing. (They also typically recommend more than 1000 iterations, significantly more than your 38.) The easiest thing to do is to use a library like CryptSharp, SimpleCrypto.net, BCrypt.net, or many others.UPDATE PBKDF2 is built in to the .NET Framework using the Rfc2898DeriveBytes class. Here is how to use it (based on your EncodePassword function:private string EncodePassword(string password, string salt = ){ int numIterations = 1000; if (string.IsNullOrEmpty(salt)) salt = CreateSalt(); using (var pbkdf2 = new Rfc2898DeriveBytes(password, Encoding.UTF8.GetBytes(salt), numIterations)) { var hash = pbkdf2.GetBytes(64); return String.Format({0}:{1}, Convert.ToBase64String(key), salt); }}Another thing you could do to future-proof your hashing is to store the number of iterations and the encryption method along with the password. That way, if you decide to change the number of iterations used (for example, you may wish to do so if/when computing power gets to the point that a few thousand iterations isn't slow enough) you won't have to invalidate all existing passwords all at once. For example, PHP's password_hash function (which uses bcrypt, not PBKDF2 - but the principle is the same) stores a code representing the hash function used and the number of iterations along with the salt and the password. (For an easy look at how they do it, see this implementation.)(A general word of advice: it is very tempting to roll your own password encryption. Resist the urge and Just Don't Do It.) |
_webapps.25206 | Google Maps used to show street names, all the way down to minor back roads if you zoomed in enough. Now, those seem to be gone. Is is possible that I've accidentally changed a setting that displays street names, or is this some bewildering new feature of some sort? In response to the comments, here's a screenshot: ...and my browser info: Google Chrome 18.0.under Mac OSX 10.6.8. Street labels sometimes appear at different zoom levels, but not always. | How can I get Google Maps to show street names? | google maps | Judging by the screenshot (the zoom slider), you have WebGL enabled. It renders the visuals slightly differently and might bring some artifacts. (On my computer, the loading/rendering process looks strange but the end result is always working fine.)To turn off WebGL in Google Maps, open the site and look at the lower left corner of the screen (bottom of the side bar). There's the button labeled Classic - click it.Note that disabling WebGL will also disable some of the features, such as 3D buildings and 45 imagery. |
_codereview.97946 | Parent has list of Children. I only have access to the list of children. I need to get list of unique parents from the List of Children. Is there a better/faster/more efficient way of doing it than this?var temp = new HashSet<Parent>( (from child in program.Children select child.Parent).ToList()); | Get list of unique parents from childrens list | c#;linq | Your use of var is good, but names like temp is meaningless. It's a temp what exactly? A more descriptive name is in order here. The call to ToList appears to be redundant. Hashset's constructor takes an IEnumerable<T> and Linq queries that return collections already return one.I would also break the query away from the ctor for readability purposes. var parents = from child in program.Children select child.Parent;var distinctParents = new HashSet<Parent>(allParents);However, it's all kind of moot if you use the method syntax snippet that @RobH posted. var parents = program.Children.Select(c => c.Parent).Distinct(); |
_webapps.2596 | I often have large chunks of text (like code or some data) that I want to do a diff on but am too lazy to create two new files, run diff on them both, and then scan the output. Are there any good webapps that show you diffs? What about ones specifically for code? Or ones that do it completely in-browser to respect your privacy? | What are some good choices for doing diffs between text documents? | webapp rec;offline;diffs | Quick Diff Online Tool |
_unix.289767 | Outside tmux I use ctrl-k to erase the line in my terminal with zsh from the cursor to end of line. When I'm in tmux it doesn't work. Below is my tmux.conf:set-option -g prefix C-a# From: https://goo.gl/LmdY5Kset -g set-titles onset -g set-titles-string #Tset -g status-right '%Y%m%d | %H:%M 'setw -g mode-keys vibind C-a last-windowbind | split-window -hbind - split-window -vbind m command-prompt -p join pane from: join-pane -s '%%'#bind s command-prompt -p send pane to: join-pane -t '%%'bind s choose-sessionbind a send-prefix# Make tmux forward-word and backward-word with CTRL+arrow# See http://stackoverflow.com/a/15988701/1679629set-window-option -g xterm-keys onWhat is going on and how to fix that? | tmux ctrl-k to erase the line from cursor to end of line | zsh;tmux | null |
_unix.10040 | So I have a small little Ubuntu server set up, with some rather large files that I've allowed a few people to copy from their putty window.Anyways 2 questions:Lets say a person on windows wants to copy a file using putty from an Ubuntu server. how would they do it? and what directory would it default too? (what would the command be even? would I use SCP?)Second question: is there like a limit? these are mostly 1-2gb files. would that cause any issues? Thanks | SSH Copy Limit? | ssh;file sharing;cp | You can try PSCP which comes as part of the PuTTY distribution.The usage of pscp is:pscp [user@]host:source targetFor example, from a Windows cmd prompt, type the following command to transfer a file to your C: drive.pscp username@host:/path/to/file.txt C:\temp\file.txtI don't believe there is a file size limit. |
_unix.138104 | I am working on a script to sort my downloads folder by the date the files were created. This is the script I am using:#!/bin/bashcd ~/Downloadsfor FILENAME in *do if [[ -f $FILENAME ]]; then date=$(ls -l $FILENAME | tr -s ' ' | cut -d ' ' -f 6 | tr -d '.') mkdir -vp $date find . -maxdepth 1 -type f -name $FILENAME -exec mv {} $date \; fidonecd -The name of the folder created by this script is just Jun which leads me to believe there is some sort of conversion going on somewhere.If I do just a ls -l test0 | tr -s ' ' | cut -d ' ' -f 6 | tr -d '.'the date shows 19062014 correctly.This is the result of a bash -x of the script:sigurd@Goliath ~ -> bash -x clean+ cd /home/sigurd/Downloads+ for FILENAME in '*'+ [[ -f test0 ]]++ ls -l test0++ tr -s ' '++ cut -d ' ' -f 6++ tr -d .+ date=Jun+ mkdir -vp Junmkdir: created directory 'Jun'+ find . -maxdepth 1 -type f -name test0 -exec mv '{}' Jun ';'+ for FILENAME in '*'+ [[ -f test1 ]]++ ls -l test1++ tr -s ' '++ cut -d ' ' -f 6++ tr -d .+ date=Jun+ mkdir -vp Jun+ find . -maxdepth 1 -type f -name test1 -exec mv '{}' Jun ';'+ cd -/home/sigurdThe functionality I'm looking for is that the script should move files into folders named 19_06_2014, 20_06_2014 etc. based on when the file was created. | Strange formatting of date in bash script | bash;shell script;ls;date;timestamps | Wild guess: you have an alias for ls that's being used when you try the command interactively, and that alias isn't used in the script. Something like this, perhaps?alias ls=ls --full-timeNote that conventional wisdom says that trying to parse ls is a bad idea. Assuming you're on a Linux machine, something like this might be preferable:stat $FILENAME | awk '/^Modify: /{print $2}'EDIT: Or, as Stphane points out below, using find with -printf is even better. The output of stat is slightly easier to predict than ls, but -printf allows for an output format that's entirely controlled by you. |
_unix.340777 | I am running BackBox Linux version 4.6.Trying to install GdMap version 0.8.1.I've entered:./configureand then:makeand this is what I got:make all-recursive make1: Entering directory /home/wh1t3ni9ht/Desktop/New Folder/gdmap-0.8.1'Making all in srcmake[2]: Entering directory/home/wh1t3ni9ht/Desktop/New Folder/gdmap-0.8.1/src' gcc -DHAVE_CONFIG_H -I. -I.. -DGDMAP_LOCALE_DIR=\/usr/local/share/locale\ -DPACKAGE_DATA_DIR=\/usr/local/share/gdmap\ -pthread -I/usr/include/gtk-2.0 -I/usr/lib/i386-linux-gnu/gtk-2.0/include -I/usr/include/atk-1.0 -I/usr/include/cairo -I/usr/include/gdk-pixbuf-2.0 -I/usr/include/pango-1.0 -I/usr/include/gio-unix-2.0/ -I/usr/include/freetype2 -I/usr/include/glib-2.0 -I/usr/lib/i386-linux-gnu/glib-2.0/include -I/usr/include/pixman-1 -I/usr/include/libpng12 -I/usr/include/harfbuzz -DGTK_DISABLE_DEPRECATED -I/usr/include/libxml2 -g -O2 -W -Wall -D_GNU_SOURCE -Wno-pointer-sign -MT gdmap-gui_support.o -MD -MP -MF .deps/gdmap-gui_support.Tpo -c -o gdmap-gui_support.o test -f 'gui_support.c' || echo './'gui_support.c gui_support.c: In function on_ebox_enter: gui_support.c:88:3: warning: implicit declaration of function GTK_WIDGET_SENSITIVE [-Wimplicit-function-declaration] if (GTK_WIDGET_SENSITIVE(label)) { ^ gui_support.c: In function ui_create_event_label: gui_support.c:167:3: warning: implicit declaration of function GTK_OBJECT_FLAGS [-Wimplicit-function-declaration] GTK_WIDGET_SET_FLAGS(ebox, GTK_CAN_FOCUS); ^ In file included from /usr/include/gtk-2.0/gtk/gtkcontainer.h:35:0, from /usr/include/gtk-2.0/gtk/gtkbin.h:35, from /usr/include/gtk-2.0/gtk/gtkwindow.h:36, from /usr/include/gtk-2.0/gtk/gtkdialog.h:35, from /usr/include/gtk-2.0/gtk/gtkaboutdialog.h:32, from /usr/include/gtk-2.0/gtk/gtk.h:33, from gui_support.c:10: /usr/include/gtk-2.0/gtk/gtkwidget.h:459:80: error: lvalue required as left operand of assignment #define GTK_WIDGET_SET_FLAGS(wid,flag) G_STMT_START{ (GTK_WIDGET_FLAGS (wid) |= (flag)); }G_STMT_END ^ gui_support.c:167:3: note: in expansion of macro GTK_WIDGET_SET_FLAGS GTK_WIDGET_SET_FLAGS(ebox, GTK_CAN_FOCUS); ^ make[2]: * [gdmap-gui_support.o] Error 1 make[2]: Leaving directory /home/wh1t3ni9ht/Desktop/New Folder/gdmap-0.8.1/src'make[1]: *** [all-recursive] Error 1make[1]: Leaving directory/home/wh1t3ni9ht/Desktop/New Folder/gdmap-0.8.1' make: * [all] Error 2What should I do? | Error with make and sudo make install command in terminal | compiling | You can install GdMap from Terminalsudo apt-get install gdmap -y-y parameter automatically accepts dependencies. |
_unix.73862 | I've attempted to write a small script that will by default open emacs withemacs -nw fooby simply typingemacs fooand when I want a window typingemacs foo &The script I attempted to write looks like this#!/bin/bashif [ -z $2 ]; then emacs -nw $1else emacs $1 &fiThe problem I'm running into is that when I try to run the script nothing happens, as if I just hit enter.Would a more experienced person please advice how to make this script properly? | Script for opening emacs in two different ways | bash | The problem with the script is that if you call it either way (with and without &, it sees only one parameter. bash has already used the & to put the process in the background. If you would try the fg after starting with emacs foo & you should see emacs with no window, as with the first option. The second option never gets executed, and it should not have an &. What is needed is that the script tests if it runs in the background and decides on that. In a C program or in Python I would test if the program group and the terminal foreground process group are the same, but I do not know how to do that in bash shell (Chris Down answer indicates it can be done).Your invocation strongly implies you want to call this script emacs in that case make sure to put the full path to the 'real' emacs in there, to prevent recursion.If you can live with a Python script to do the job:import osimport sysimport subprocessSTDOUT_FILENO=1emacs_cmd = ['/usr/bin/emacs']if os.getpgrp() == os.tcgetpgrp(STDOUT_FILENO): emacs_cmd.append('-nw')emacs_cmd.extend(sys.argv[1:])subprocess.call(emacs_cmd)It allows you to specify multiple filenames (and additional emacs options) on the commandline. |
_webapps.65576 | I want to share a calendar with 3 or 4 other people. I am looking for the simplest approach; one user is highly non-technical. I tried using Google Calendar but she would keep adding events to her personal calendar thinking it was the shared one. Under the My Calendars heading, I selected to only display the shared calendar but it appears Google Calendar by default re-shows the personal calendar after a new event is created. Can this be changed? Is there a simpler alternative to Google Calendar? | Want Google Calendar to only display 1 shared calendar for highly non-technical user | google calendar | null |
_codereview.36951 | I've just created a small class to reverse date in PHP. I'd like to show to someone to see if it's good or not. If I can improve it or not. So, here is the code.<?php/** * Reverse date and hour */class ReverseDate{ var $date; var $hour; var $error; /** * Checks if the date has hours */ function exec($data = null, $timestamp = false, $debug = false) { $this->date = $data; // Checks if the date is not null if (empty($this->date)) { // Debug - not activated buy default $this->error = 'Date is null.'; $this->debug($debug); return false; } // Verify the date to brazilian or international format $braRegExp = '/^([0-9]{2}[\-|\/|\.]{1}[0-9]{2}[\-|\/|.]{1}[0-9]{4})/'; $othRegExp = '/^([0-9]{4}[\-|\/|\.]{1}[0-9]{2}[\-|\/|.]{1}[0-9]{2})/'; if (!preg_match($braRegExp, $this->date)) { if (!preg_match($othRegExp, $this->date)) { // Debug - not activated buy default $this->error = 'Invalid date.'; $this->debug($debug); return false; } else { // Fix the day lenth for brazilian dates $d2len = 2; } } else { // Fix the year lenth for brazilian dates $d2len = 4; } // Get the date spliter (. or / or -) $s = preg_replace('/[a-zA-Z0-9]/', '', $this->date); $s = substr($s, 0, 1); // Explode the date into an array $d = explode($s, $this->date); // Checks if the date has hours if (strlen($d[2]) > 4) { // Get the hour $this->hour = trim(substr($d[2], $d2len, strlen($d[2]))); // This is the year withou the hour $d[2] = explode(' ', $d[2]); $d[2] = $d[2][0]; } // Reverse the date $this->date = array_reverse($d); // Join the array $data = implode($s, $this->date); // Join date and hour $this->date = trim($data . ' ' . $this->hour); // Return if ($timestamp) { // Timestamp return strtotime($this->date); } else { // Or the date return $this->date; } } // Debug function debug($val = false) { // Checks if the val is true if ( $val ) { // Kills the script exit($this->error); } }}And then use it:$reverseDate = new ReverseDate();$data = $reverseDate->exec('06/12/2013 17:30', false, true);echo $data . '<br>'; // 2013/12/06 17:30$data = $reverseDate->exec('2013/12/01 08:25:10', false, true);echo $data . '<br>'; // 01/12/2013 08:25:10$data = $reverseDate->exec('06/12/2013 17:30', true, true);echo $data . '<br>'; // 1386347400$data = $reverseDate->exec('2013-12-01', false, true);echo $data . '<br>'; // 01-12-2013 17:30I believe it is gonna make my life really easier. So, any improvements? | Class: Reverse date in PHP | php | I'll comment on the general appearance and structure of your code, show you some problems with it and then throw it out and present you with an easier implementation with the caveat that it behaves slightly differently.You'll notice that I use a modified K&R style with the opening braces on the same line, this is only the style I choose because I do not know of an official style-documentation for PHP and I have adopted the Java style for my PHP projects.Also, your brace-style does change half-way through.Let's have a look at the first few lines to start with:/** * Reverse date and hour */class ReverseDate{ // ...snip /** * Checks if the date has hours */ function exec($data = null, $timestamp = false, $debug = false) {The following problems here:The class has a function nameThe function is not staticThe function has a completely irrelevant nameThe parameters are not well namedThe documentation is plain out wrong.The first few questions that are raised are:Why is this called exec()? (Remember that exec is a pretty negative word in the PHP world, same as eval or system)It does check something?What is $data?What is $timestamp?What is $debug?If you're going to create helper classes it should be clear that this is a helper class./** * A small helper class for working with Dates. */class DateHelper {At the moment you also need to create an instance of your class just to use one function, it should be static (and have correct documentation)./** * Reverses the date part of the given DateTime-String. The DateTime-String * needs to be in the format Y/m/d h:i:s. * @var string $datetime * @return string */static function reverseDate($datetime) {$this->date = $data;Is this a typo?You should also not make variables more accessible then necessary. $this->date is never used outside of the exec() function, so it's scope should be limited to that function.$s = preg_replace('/[a-zA-Z0-9]/', '', $this->date);Whenever you have the urge to use one-letter-variable names, take a deep breath and ask yourself:What does this variable hold?And then you name it according to what it holds.Your function does either return a string or an int based on a parameter passed in, that's bad. That is ambiguity you should avoid.This function does return a datetime-string with the date part reversed, except if a parameter is passed in, then it does return an int/timestamp.So code would look like this:$reverseDate = new ReverseDate();$data = $reverseDate->exec('06/12/2013 17:30', $timestamp, false);Quick: What value does $data hold?Someone unfamiliar with the internals of this function would say 2013/12/06 17:30 and that's a problem.function debug($val = false){ // Checks if the val is true if ( $val ) { // Kills the script exit($this->error);You should not hide calls to exit or die in a function which does not clearly state that this will happen.Personally I think this function does too much and tries too hard. Always keep in mind that you should write code for the problem you face right now.Here is a much simplified solution (with caveats, follows):/** * A helper class for Date and Time. */class DateHelper { /** * Reverses the date part of the given DateTime-String. The DateTime-String * needs to start with the date string, otherwise this will fail. * @var string $datetime * @return string */ static function reverseDate($datetime) { // Will hold the result of the match. $result = NULL; // Match this against what we've got. // // ([0-9]+) The first part (year?) // ([^0-9]{1}) Separator // ([0-9]+) The second part (month?) // ([^0-9]{1}) Separator // ([0-9]+) The third part (day?) // (.*) Everything else. if (preg_match(/^([0-9]+)([^0-9]{1})([0-9]+)([^0-9]{1})([0-9]+)(.*)/, $datetime, $result) === 0) { // Chicken out if there were 0 matches. // preg_match does handle NULL for us. return false; } // Now we put it together backwards. return $result[5] . $result[4] . $result[3] . $result[2] . $result[1] . $result[6]; }}This does not have neither your error handling nor your debug support and especially not the tag parameter. Ideally you would add this Helper class to your project, write a few unittests for it and be done with it.Is there a problem with your error handling? No, not at all, but it's absolutely unnecessary in this implementation. Compare these use cases:$reverseDate = new ReverseDate();$data = $reverseDate->exec($input, false, true);if (!$data) { // Error handling goes here. $reverseDate->debug();}With this:if (!($date = DateHelper::reverseDate($input))) { // Error handling goes here. die(Parsing of . ($input === NULL ? NULL : '$input') . failed.);}There's no need for fine grained error messages, as looking at the passed in value should be enough to determine why the parsing failed.Is there a problem with your debug parameter? Yes! If you need a function to behave differently whenever you want to debug it or not, and especially need a parameter for this, then there's something wrong with your design of said function. Also your parameter does not change the behavior of the function at all, it changes the behavior of a completely different function, which is evil (speaking from a design point of view). |
_unix.281955 | I have a Debian 8 test server that has only root. I have configured it to send emails with https://wiki.amahi.org/index.php/Gmail_As_Relay_On_Ubuntu by making use of a new gmail account eg [email protected]. That email has as name atux t. The thing is that when I send emails from the Debian box it only appears as: rootHow do i get rid of the root and make it appear with the name I want? | Postfix smarthost sends as root | email;postfix | null |
_softwareengineering.140550 | I need to create a REST web service to manage user submitted images and displaying them all in a website. There are multiple websites that are going to use this service to manage and display images. The requirements are to have 5 pre-defined image sizes available.The 2 options I see are the following:The web service will create the 5 images, store them in the file system and and store the URL's in the database when the user submits the image. When the image is requested, the web service will return an array of URLs. I see this option to be a little hard on the hard drive. The estimates are 10,000 users per site, and lets say, 100 sites. The heavy processing will be done when the user submits the image and each image is going to be pulled from the File System.The web service will store just the image that the user submits in the file system and it's URL in the database. When the user request images, the web service will get the info from the DB, load the image on memory, create its 5 instances and return an object with 5 image arrays (I will probably cache the arrays). This option is harder on the processor and memory. The heavy processing will be done when the images get requested. A plus I see for option 2 is that it will give me the option to rewrite the URL of the image and make them site dependent (prettier) than having a image repository for all websites. But this is not a big deal. What do you think of these options? Do you have any other suggestions? | Storing images in file system and returning URLs or virtually resizing and returning byte arrays? | design;asp.net;web services;asp.net mvc;image manipulation | Definitely use a file store, whether that's a classic CDN, a cloudy one, or a roll-your-own. I also wouldn't bother storing all 5 image sizes. Create the scaled images on the fly, at first access (i.e. if the DB query for a particular image and size returns NULL for the URL, scale the larger image down, and return the newly created URL, then store it for future references).Don't bother too much about hard drives. There's already a very effective file cache in every relevant OS, and you're going to be hard-pressed to beat that. Furthermore, you'd planning to service a million users. You can quote storage at a reasonable $1.00 per user and have plenty of money to play with.Don't worry about the URL pretty-ness. Our filestore is known as download.<OurCompanyName>.com, even though it's actually hosted by a well-known CDN company. |
_unix.25601 | This is mostly out of curiosity, I'm trying to understand how event handling workson a low level, so please don't reference me to a software that'll do it for me.If for example I want to write a program in C/C++ that reacts to mouse clicks,I assume I need to use a system call to hook some function to the kernel, or maybe you need to just constantly check the status of the mouse, I don't know.I assume it's possible since just about everything is possible in C/C++, being so low level, I'm mostly interested in how it works, even though I'll probably never have to implement it myself.The question is how it works in linux, are there certain system calls, c libraries, etc.? | How do mouse events work in linux? | linux;devices;input | If you're writing a real-world program that uses the mouse in Linux, you're most likely writing an X application, and in that case you should ask the X server for mouse events. Qt, GTK, and libsdl are some popular C libraries that provide functions for accessing mouse, keyboard, graphics, timers, and other features needed to write GUI programs. Ncurses is a similar library for terminal applications.But if you're exploring your system, or you can't use X for whatever reason, here is how it works at the kernel interface.A core idea in the UNIX philosophy is that everything is a file. More specifically, as many things as possible should be accessible through the same system calls that you use to work with files. And so the kernel interface to the mouse is a device file. You open() it, optionally call poll() or select() on it to see if there's incoming data, and read() to read the data.In pre-USB times, the specific device file was often a serial port, e.g. /dev/ttyS0, or a PS/2 port, /dev/psaux. You talked to the mouse using whatever hardware protocol was built into the mouse. These days, the /dev/input/* subsystem is preferred, as it provides a unified, device-independent way of handling many different input devices. In particular, /dev/input/mice will give you events from any mouse attached to your system, and /dev/input/mouseN will give you events from a particular mouse. In most modern Linux distributions, these files are created dynamically when you plug in a mouse.For more information about exactly what you would read or write to the mouse device file, you can start with input/input.txt in the kernel documentation. Look in particular at sections 3.2.2 (mousedev) and 3.2.4 (evdev), and also sections 4 and 5. |
_webmaster.25265 | I heard about Joomla, Drupal, Wordpress, etc. but I don't know about their detailed features. I am looking for a content management system meeting the following requirements:Possibility to add simple text pages, with internal and external links (more or less the same features as a wiki)Possibility to add complex JavaScript content pages (i.e., the content of the page is entirely determined by JavaScript, except the page frame itself, menu, headers, footers...)Good back-up system. Something like export/import in svn.Possibility to have a good control on HTML keywords associated with each page.Multi-user, with some access control for editingGood community support.Which framework is best suited for the above requirements? Points 2, 3 and 6 are the most important. | Looking for a CMS for specific requirements (Javascript, import/export...) | javascript;cms;keywords;backups | For this, I would lean towards Drupal. Let me address each of your points as best I can, realizing that we have converted our development shop from custom .NET apps to the Drupal framework because of the flexibility we like to provide to our webmasters/customers. We have used Drupal for both hosting and dyanmic internal intranets where every user can be a poster of pages/information.Drupal Gardens can give you a quick demo of your own Drupal 7 site for free and is a good location to test a simple feature set for a site of this nature.1 Possibility to add simple text pages, with internal and external links (more or less the same features as a wiki)Drupal pages can be simple or complex. This can be done in many ways.2 Possibility to add complex JavaScript content pages (i.e., the content of the page is entirely determined by JavaScript, except the page frame itself, menu, headers, footers...)Drupal will let you insert JavaScript into a node for complex things. However, this is not normal for most sites. This requirement would be a challenge for all three CMS systems depending on what you'd like to accomplish here.3 Good back-up system. Something like export/import in svn.For Drupal, you can use SVN against the site, but you need to think differently about CMS systems. For a CMS the framework is your code, i.e. the process for displaying content. For Drupal the real data exists in MySQL, so MySQL backups are needed. Lastly, with Drupal, you can turn on revisions which will keep copies of the content of a page as it is edited.4 Possibility to have a good control on HTML keywords associated with each page.Drupal has a module with lets you manage keywords in a different fashion for pages and stories stored in the system. You can customize each page if needed. Having a module implement keyword management has been very slick for us. The module to accomplish this is called Nodewords.5 Multi-user, with some access control for editingA complete user system is built into Drupal and modules exist to further extend the security of the system. Editing can be controled and if you are familiar with CKEditor, it is one of many HTML editors that are supported in Drupal.6 Good community support.Drupal community support is great. I have been able to find plenty of information to migrate from .NET to a PHP content management platform. |
_webapps.35483 | When adding an image, sometimes I'll drag in the wrong screenshot or realize I have a better one to add. Would be nice to be able to edit and delete images just like you can with text comments. Know of any way to do that? Or if they're planning on adding that ability in the future? | Is there a way to edit or delete uploaded images on a Trello card? | trello | null |
_scicomp.4722 | Hello scicomp community,I have worked in the area of graph algorithms using frameworks such as NetworkX (Python), JUNG and YFiles (Java). I am now entering the area of parallel and high perfomance computing. For a new project, I am looking for a C++ graph library with the following features:has an intuitive interface that enables algorithm developmentsupports dynamic operations: e.g. arbitrary node/edge insertions and deletionssupports parallelization: e.g. shields the programmer from issues arising with multithreadinghas a low memory overhead and is suitable for high performance computingPlease suggest some libraries and discuss these criteria as well as pros and cons. | I am looking for a parallel dynamic graph library in C++ | algorithms;parallel computing;libraries;graph theory | null |
_softwareengineering.267321 | I have two designs which achieve the same result.-------Design AMainClass has a List and two methods. The methods create an autonomous object and is added to the list. The reason for the superclass, B and C are similar and I will be adding more subclasses. Furthermore, I can take advantage of polymorphism later on.-------Design Bmainclass has two methods. The method creates a aggregation link with MiddleClass and directly calls Mainclass methods - which returns an autonomous object of class b/c.Unlikely A, B benefits from a higher degree of (loose)coupling from the MainClass, where the MiddleClass acts handles information from the inheritance hierarchy to the mainclass - And of course, the more subclasses I add, the mainclass will not have any additional links to the hierarchy, instead, it's all dealt with by middleclass.However, I am not sure if I am just over-engineering the design or if it's a better design. What do you guys think is the better design and why? | Which design is better? [MainClass] -> [Class] OR [MainClass] -> [MiddleClass] -> [Class] | design | In both designs, MainClass has to know about ClassB and ClassC (and any future derived classes) to provide the methods to create and add new list elements. This makes that with the current interface for users of MainClass the first design is the simplest design and the best of the two.However, it is possible to create a better design by decoupling MainClass and MiddleClass.MainClass only needs to provide a method to add (already created) items to the list.MiddleClass is actually a factory class, as already noted in the comments, and should be made available to the user to create the items that should be added to the list.This way, MainClass doesn't need to be updated if new classes are added to the hierarchy, but only MiddleClass. |
_unix.226923 | Is there a way to update tmux window attributes based on command exit status? Similar to activity monitoring, I would like the title to change color when a command exits, say, green for success and red for failure. I've hacked something together using PROMPT_COMMAND (which goes in ~/.bashrc), but it's not entirely satisfactory. It doesn't play well with activity monitoring (i.e. the red/green can't be seen unless activity monitoring is disabled) and the color change is sticky; it maintains state after you visit the window instead of returning to the default like other tmux monitoring does.function set_color_from_return_code { local bg_color=$([ $? == 0 ] && echo green || echo red) tmux set-window-option -t${TMUX_PANE} window-status-bg $bg_color # &> /dev/null}PROMPT_COMMAND=set_color_from_return_codeEdit: Specifically, I'm using tmux as the backend for byobu, so I'm adding the byobu tag, as a byobu-specific solution is fine by me. | Monitor exit code in tmux | tmux;bashrc;byobu | null |
_unix.118754 | CentOS 6.x I'm confused on when exactly files I place in /tmp/ are deleted./etc/cron.daily/tmpwatch has the following:#! /bin/shflags=-umc/usr/sbin/tmpwatch $flags -x /tmp/.X11-unix -x /tmp/.XIM-unix \ -x /tmp/.font-unix -x /tmp/.ICE-unix -x /tmp/.Test-unix \ -X '/tmp/hsperfdata_*' 10d /tmp/usr/sbin/tmpwatch $flags 30d /var/tmpfor d in /var/{cache/man,catman}/{cat?,X11R6/cat?,local/cat?}; do if [ -d $d ]; then /usr/sbin/tmpwatch $flags -f 30d $d fidoneThe section in line 5 that reads -X '/tmp/hsperfdata_*' 10d /tmp leads me to believe that files I place in /tmp/ will remain for 10 days (assuming they aren't locked during deletion of course or the directory is mounted on a tmpfs file system). Is that correct? | When exactly does tmpwatch clear out files I place in /tmp? | centos;tmp | On CentOS 6, it would seem that tmpwatch is basing it's decision to delete on when a file was last accessed (atime). If it's been 10 days (10d) or more then it will be deleted when tmpwatch runs.From the tmpwatch man page: By default, tmpwatch dates files by their atime (access time), not their mtime (modification time). If files aren't being removed when ls -l implies they should be, use ls -u to examine their atime to see if that explains the problem.Also from the man page: The time parameter defines the threshold for removing files. If the file has not been accessed for time, the file is removed. The time argument is a number with an optional single-character suffix specifying the units: m for minutes, h for hours, d for days. If no suffix is specified, time is in hours. |
_codereview.14389 | I have written this sample code to fetch a web page in C++ using libcurl. Please review it.#include <iostream>#include <iostream>#include <string>#include <exception>extern C{#include <curl/curl.h>#include <stdlib.h>}//Exception class for curl exceptionclass CurlException : std::exception{public: CurlException(std::string message):m_message(message) { } CurlException(CURLcode error) { m_message = curl_easy_strerror(error); } const char* what() throw() { return m_message.c_str(); } ~CurlException() throw() { }private: std::string m_message;};//A tiny wrapper around Curl C Libraryclass CppCurl{public: CppCurl(std::string url) throw (CurlException) { m_handle = curl_easy_init(); if ( m_handle == NULL ) throw CurlException(Unable to initialize curl handler); if ( url.length() == 0 ) throw CurlException(URL can't be of zero length); m_url = url; } std::string Fetch() throw (CurlException) { SetOptions(); SendGetRequest(); return m_data; } ~CppCurl() throw() { curl_easy_cleanup(m_handle); }private: void SetOptions() throw (CurlException) { CURLcode res; //set the url res = curl_easy_setopt(m_handle, CURLOPT_URL, m_url.c_str()); if ( res != CURLE_OK) throw CurlException(res); //progress bar is not require res = curl_easy_setopt(m_handle, CURLOPT_NOPROGRESS, 1L); if ( res != CURLE_OK ) throw CurlException(res); //set the callback function res = curl_easy_setopt(m_handle, CURLOPT_WRITEFUNCTION, CppCurl::WriteDataCallback); if ( res != CURLE_OK ) throw CurlException(res); //set pointer in call back function res = curl_easy_setopt(m_handle, CURLOPT_WRITEDATA, this); if ( res != CURLE_OK ) throw CurlException(res); } void SendGetRequest() { CURLcode res; res = curl_easy_perform(m_handle); if ( res != CURLE_OK ) throw CurlException(res); } static size_t WriteDataCallback(void *ptr, size_t size, size_t nmemb, void* pInstance) { return (static_cast<CppCurl*>(pInstance))->write_data(ptr, size, nmemb); } size_t write_data(void* ptr, size_t size, size_t nmemb) { size_t numOfBytes = size * nmemb; char *iter = (char*)ptr; char *iterEnd = iter + numOfBytes; //while ( iter != iterEnd ) //{ // cout<<*iter; // iter ++; //} m_data += std::string(iter, iterEnd); return numOfBytes; } CURL *m_handle; std::string m_url; std::string m_data;};int main(){ try { CppCurl ob(http://kodeyard.blogspot.in/); std::cout<<ob.Fetch(); std::cout<<std::endl; } catch ( CurlException e) { std::cerr<<Exception thrown...<<std::endl; std::cerr<<e.what()<<std::endl; } return 0;}This is also here in the blog. | Tiny Curl C++ wrapper | c++;curl | null |
_softwareengineering.26033 | I'd like to get a sense for the range of complexity that algorithms fall into. I think it would be interesting and helpful for those, like me, trying to better understand how algorithms are formulated and how to deconstruct them.Can you offer a basic algorithm with explanation, an intermediate algorithm with explanation, and maybe an expert level one (with or without) an explanation? | An example of a beginner-level Algorithm, intermediate level Algorithm and a complex/expert level Algorithm? | algorithms | null |
_softwareengineering.338035 | Representation 1 - Multi walk treetypedef struct multiWalkTreeNode{ struct multiWalkTreeNode * parent; void *item; struct multiWalkTreeNode **childPointer;}Node;typedef struct multiWalkTree{ Node *root; int size; /*Number of nodes in the tree*/}Tree;Pictorial view:Representation 2 - LCRS treetypedef struct SiblingTreeNode{ struct SiblingTreeNode *parent; void *item; struct SiblingTreeNode *firstChild; struct SiblingTreeNode *nextSibling;}Node;typedef struct LCRSTree{ Node *root; int size;}Tree;Pictorial view:Representation 3 - Tree using list(How to name this tree?)typedef struct DListNode{ int item; struct DListNode *next; struct DListNode *prev;}DListNode;typedef struct DList{ //Circular DListNode *head; int size;}List;typedef struct treeNode{ struct treeNode *parent; void * item; List *childList; /* Sentinel node is created on initial construction of a List */}Node;typedef struct treeUsingList{ Node *root; int size;}Tree;Pictorial view:Parent pointer is introduced to perform DFS without recursion or explicit stack.Please confirm the correctness of representation.Question:1) Do we have any name for tree in Representation 3?2) For insert/delete/find operations, which representation performs better?3) Are there any other representations for rooted tree, that can enhance performance? | Rooted tree - Representation & Performance | c;data structures;trees | Here are some considerations:In #1, you aren't capturing a size of the childPointer array, so you cannot know how many children there are.Your code for #3 uses void *item in the text, but Node *item in the diagram. Further, the items labeled sentinel have (struckthru) item, next and prev, but should (to match the text) have head and size .None of these data structures are optimized for find operations, so among these, the fewer data structures the better, within a small margin (as none is great for find). If find is the primary concern I'd move to a totally different data structure (e.g. B-Tree or balanced binary tree, or anything else)!The #3 choice, I see as basically broken. It uses a doubly linked list, which at first blush might imply some improvement for large numbers of children regarding insert/delete. However, observe that the parent pointers from the nodes only refer to other tree nodes, and not also to the position in the doubly linked list (which themselves do not offer a parent pointer). So a full traversal of immediate children is still necessary, just like in option #2, and, the doubly linked list offers no improvement, just more maintenance required and space taken (all bad).Workload is going to be the primary concern here regarding which is best for performance. Regular trees (not one of your options) would be the best for insertion if there are, say, two or fewer children. For huge numbers of children, a doubly linked list might be better, but not if implemented as #3. |
_codereview.150660 | Description:Youre given the pointer to the head node of a linked list and a specific position. Counting backwards from the tail node of the linked list, get the value of the node at the given position. A position of 0 corresponds to the tail, 1 corresponds to the node before the tail and so on.Code:int GetNode(Node head,int n) { // This is a method-only submission. // You only need to complete this method. Node current = head; int count = 0; while (current != null) { count++; current = current.next; } current = head; for (int i = 0; i < count - n - 1; i++) { // extra -1 to avoid going out of linked list. current = current.next; } return current.data;} | Get nth node from end in a linked list | java;algorithm;programming challenge;linked list | Instead of a count variable and reusing current,I think it's neater to use two pointers:Node runner = head;for (int i = 0; i < n; i++) { runner = runner.next;}Node current = head;while (runner.next != null) { runner = runner.next; current = current.next;}return current.data;Other than that, your implementation is fine, except for a few tiny style points that are barely worth mentioning, but here we go anyway:The commented out instructions about method-only submissions are unnecessaryAdd a space after commas in parameter list |
_softwareengineering.348876 | Suppose I have low level classes A, B, and C that are independent of each other. The functions in them take some input and does some computation and returns some output.Now suppose I want to create an executable where it read in some data and output some statistics with the flow of input->A.func1->B.func1->C.func1->outputThere are two options for me to handle this, Create a high level class called ABC. It does no computation, it simply receives the input from the main function, parses the input and pass it into A.func1, and forward the output of A.func1 into B.func1, and forward the output of B.func1 into C.func1, and output it to the main function.In the main function, directly parse the input itself, pass it into A.func1 and then B.func1 and then C.func1 and then save the output.If class ABC does some computation internally while calling functions from A, B, and C, it's a no brainer that ABC class should exist. However, I am having a hard time to justify the need of a ABC class since it's just calling functions from low level class without any additional computation. It also means if we want to create 10 executables that are using the functions from the low level classes with different combination and order, we will have 10 of these high level classes. However, I heard people said having a high level ABC class is better because Why should main() be short?Which approach is better? | Single function from a high level class VS Multi functions from low level classes | design;code quality;class design | Neither 1. nor 2. is always better. Here is how I would typically make the decision:start without an additional class ABC and call functions from A, B and C directly from main. If the orchestration logic is very simple, no need to change it.as soon as the logic in main becomes more complex, needs unit tests or has to be reused somewhere else, refactor. For example parsing looks like a task on its own, it could be placed in a separate class.as a result of the refactoring, you may end up with a separate class ABC (hopefully with a more descriptive name). Maybe you end up only with a class orchestrating A and B, a parsing class, some output processing class, and let the calls to C separated. This depends on the details of your situtation.However, I would typically not make this decision up-front, I think it is much better to decide during the refactoring process. The driving forces here should beforming better abstractionstestabilityreusability.For very simple programs, it is perfectly possible you have all the abstractions you need in main, don't need to write tests which require a separate class ABC, and you don't need to reuse anything. If that is the case, stay with option 2. |
_webapps.73056 | I am using the URL https://www.facebook.com/sharer/sharer.php?u=http://example.com/ to allow users to share my website by sending users browsing my site to the aforementioned link. However, after updating my page Open Graph HTML my page is not scraped and the content displayed in the Facebook Content sharer does not update.What should I do? | Facebook sharer.php not updating shared information after page update | facebook;html | According to this page: https://developers.facebook.com/docs/plugins/share-button, normally, Facebook only scrapes your site for Open Graph information once a day. You need to manually go to the Facebook Debugger Tool https://developers.facebook.com/tools/debug/ and paste your URL into the box and click on the Debug button and then on the Fetch new scrape information button each time you update your page's Open Graph information to see the updates in the Facebook sharer page once you update your HTML.There is also one particular Facebook scraper bug to watch out for. Sometimes, even when the Open Graph Image and related information specified in the head section of an HTML page is correct, upon hitting the Fetch new scrape information you may get the following error message:og:image could not be downloaded or is too smallIf your image fits the Facebook guidelines and you're still getting this message, then just hit the Fetch new scrape information button a few more times and it will go away (or, even if it does not, you can safely ignore the message).Also, when embedding your Facebook sharing URL inside HTML, remember to URL-encode it. For your example, the HTML should be something like:<ahref=https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Fexample.com%2Ftarget=_blank> <img src=share-button.png alt=Share on Facebook /></a>If after doing these things, the sharing feature still won't work, then paste the following link in the Facebook Debugger Tool (with the fbrefresh=CAN_BE_ANYTHING query string field) and click on the Debug button to clear the cache, then paste http://www.example.com/ into the field to reload the OG data into the Facebook servers:http://www.example.com?fbrefresh=CAN_BE_ANYTHING |
_unix.11063 | I am essentially trying to assing certain portions of the output of a shell command to mulitple variables, but I don't know how to do that.For simplicity's sake, assume that the command on the shell, when executes, printsone two three fourwhich can be simulated with aecho one two three four(although the actual comannd is different)Now, I'd like to assign the second and fourth word of the output (in this case two and four) to the variables w1 and w2.I thought I could use the read command like so:echo one two three four | awk '{print $2 $4}' | read w1 w2but this doesn't work, probably because the read command is executed in a sub-process.So, how would I go about to achieve what I am after? | How to assign values to multiple variables in command line with bars | shell;bash | This doesn't work because the read runs in a child process which cannot affect the parent's environment.You have a few options:You can convert your command to:w1=$(echo one two three four | awk '{print $2}')w2=$(echo one two three four | awk '{print $4}')Alternatively, change IFS and use set:OIFS=$IFSIFS=' 'set -- $(echo one two three four | awk '{print $2 $4}')IFS=$OIFSw1=$1 w2=$2or a Here String:read w1 w2 w3 w4 <<< one two three four |
_webapps.66506 | Is there a way to change my Spotify login from using Facebook to using just email and password? | How to change Spotify Facebook login to email login | login;spotify | null |
_codereview.111392 | I have written a simple pager in C. It works fine for most things, but I'd like to know how it can be improved. Specific things I'm looking for are if there are size and/or speed improvements to be made, as I have noticed that it sometimes performs slowly (but that might be my slow computer ;-), and usability. This obviously uses (n)curses.#include <stdio.h>#include <unistd.h>#include <stdlib.h>#include <string.h>#include <curses.h>#include <stdbool.h>/* * some.c - A small and simple pager written by Daniel Roskams */void view_file(char *, int, int);/* * A function to view files. This does most of the work here. It returns on * error. */void view_file(char *file, int row, int col){ int fch; /* file character */ int uch; /* user character */ int x; /* not used currently */ int y; FILE *fp; (void) col; /* keep the compiler happy */ if (strcmp(file, -) == 0) { fp = stdin; } else if ((fp = fopen(file, r)) == NULL) { perror(file); endwin(); printf(\n); return; /* error */ } while ((fch = fgetc(fp)) != EOF) { /* Get current x/y coordinates of cursor */ getyx(stdscr, y, x); (void) x; /* if we printed a screenful of stuff */ if (y == (row - 1)) { refresh(); attron(A_BOLD); printw([return or spacebar to advance, q to quit]); attroff(A_BOLD); for (;;) { uch = getch(); switch (uch) { case 'q': fclose(fp); endwin(); putchar('\n'); return; case '\n': case ' ': break; default: continue; } break; } /* Clear the screen and go to the beginning */ clear(); move(0, 0); } else { /* Print out the character */ printw(%c, fch); } } (void) getch(); if (fp != stdin) { fclose(fp); } return;}int main(int argc, char *argv[]){ int row, col; int i; /* initialise curses */ initscr(); /* start curses mode */ noecho(); /* don't echo typed stuff */ raw(); /* don't generate escape chars */ /* make everything reverse video-ish */ if (has_colors()) { assume_default_colors(COLOR_BLACK, COLOR_WHITE); start_color(); } getmaxyx(stdscr, row, col); /* find screen size */ if (argc < 2 && !isatty(fileno(stdin))) { view_file(-, row, col); } for (i = 1; i < argc; i++) { view_file(argv[i], row, col); } endwin(); return 0;}Something nice to note is that this compiles with no warnings using this command:$ clang -Oz -Weverything -o some some.c -lcurses | Simple pager in C | c;file;pagination;curses | Overall, I'd say this code seems pretty straightforward and is easy to read. My main concern is the performance. You're reading a file in one character at a time and that's going to be slow.Rather than using fgetc(), I recommend using getline() instead. It's a standard function that reads an entire line at a time.The other concern I have is what happens when a line is longer than the width returned by getmaxyx()? Does it wrap? Does it overwrite the last character? Does it just not print because it's off screen? Whatever it does, it seems like you should be handling it in some way, or at the least document that you want the standard behavior, and what that behavior is. If someone updates this to use something other than curses in the future, they may want to keep the same behavior, which might not be the default in this hypothetical new library. |
_cs.51611 | I am studying CFL at the moment and I found this confusing.What I've just read is that, $L=\{ww\}$ is not a CFL. The proof showed it by using pumping lemma for CFL. ($w=0^n1^n0^n1^n$) and I fully understood the proof.Here comes the question.I understand that $L1=\{ww^R\}$ can be constructed by NPDA, and thus a CFL.However, if I use pumping lemma for this, i.e., $w=0^n1^n1^n0^n$, I can show that this specific sentence does not satisfy pumping lemma as well.Pumping lemmaLet $L1$ be a CFL. Then, there exists n such that for any $w L$ and $|w|\geq n$, $w$ can be decomposed as $w=uvxyz$ such that1) $|vxy|\leq n$2) $|vy| \geq 1$3) $w_i=uv^ixy^iz$ $L1$, for all $i \geq 0$By setting $w=0^n1^n1^n0^n$ and if $v,y$ $0^+$ in the first half, regardless of how many times I pump, $ww^R$ does not belong to $L1$ anymore. Thus, since the pumping lemma should be satisfied for every possible case, I can conclude that it is not CFL.Note again that I know $L1$ can be designed with NPDA. What is my mistake while proving using pumping lemma?I am really confused about this.Can anyone answer my question?My first guess is...In order to show a language is CFL, I should first try to construct a PDA accepting the language, and if it is not possible, I should show that it is not a CFL by using pumping lemma.However, what if I could not find a PDA although there exists one?P.S. I actually posted this question yesterday with not much detailed explanation, therefore I posted again.Thanks in advance | L=ww is not a CFL | formal languages;pumping lemma | null |
_unix.158650 | How can I find the value before the word free?top -n1 | grep Mem Mem: 2054968k av, 2034120k used, 20848k free, 0k shrd, 186768k buffFirst I tried top -n1 | grep Mem | awk '{print $7}'but this isnt good because the free value (here, 20848k) can be in different fields. Sometimes it's field 6, others field 7 and so on.I need this to work on both Linux and Solaris. | sed + find value before word in line | text processing;sed;awk;solaris | awk -v RS=[, ] '/free/{print a}{a=$0}'ExplanationSet the record separator to , and space, so the number preceding every string is a record in itself, and so is the string.Having everything as its own record, awk will process every item one by oneFor all the records before free it will ignore the {print a} because the condition doesn't match, and it will skip to {a=$0} which will store the currently processed record in variable aOnce /free/ is matched, awk will just {print a} where a contains the record right before the match |
_softwareengineering.250688 | I have come from a transaction script world and I am just starting to take a look at DDD. I am unsure of the correct way to integrate a DDD design with database persistence. This is what I have:A service class called OrganisationService whose interface contains methods for retrieving and saving away instances of Organisation domain objects. Organisation is an aggregate root and has other data related to it: Members and Licenses. EF6 database first DBContext is used within the OrganisationService to retrieve OrganisationDB entities and the related MemberDB and LicenseDB entities. These all get transformed into their domain object class equivalents when retrieved by the OrganisationService and loaded into the Organisation domain object. This object looks like so:public class Organisation{ public IList<Member> Members { get; set; } public IList<License> Licenses { get; set; }}I am not using the Repository pattern in the OrganisationService...I am using EF itself as the Repository as it seems that EF6 has largely made repository redundant now.At this point in the design the Organisation domain object is anaemic: it looks like the EF POCO Organisation class. The OrganisationService class looks a lot like a Repository!Now I need to start adding logic. This logic includes managing an Organisations Licenses and Members. Now in the transaction script days I would add methods into the OrganisationService for handling these operations and call into a Repository to interact with the DB, but with DDD I believe this logic should be encapsulated within the Organisation domain object itself...This is where I am unsure of what I should be doing: I will need to persist this data back to the database as part of the logic. Does this mean I should use DbContext within the Organisation domain object to do this? Is using the repository/EF within the domain object bad practice? If so, where does this persistence belong?public class Organisation{ public IList<Member> Members { get; set; } public IList<License> Licenses { get; set; } public void AddLicensesToOrganisation(IList<License> licensesToAdd) { // Do validation/other stuff/ // And now Save to the DB??? using(var context = new EFContext()) { context.Licenses.Add(... } // Add to the Licenses collection in Memory Licenses.AddRange(licensesToAdd); }}Should I instead just be mutating the Organisation domain object in memory and then pushing it back to the OrganisationService for persistence? Then I have to track what actually changed on the object (which is what EF does to its own POCOs! I am kind of coming to feel that EF isn't just a repository replacement, but also could be the domain layer!)Any guidance here is appreciated. | Should I use the repository in the Domain Object or push the Domain Object back to the Service Layer? | domain driven design | You can take either approach and have it work well - there are, of course, pros and cons.Entity Framework is definitely intended to suffuse your domain entities. It does work well when your domain entities and data entities are the same classes. It's much nicer if you can rely on EF to keep track of the changes for you, and just call context.SaveChanges() when you're finished with your transactional work. It also means that your validation attributes don't have to be set twice, once on your domain models and once on your persisted entities - things like [Required] or [StringLength(x)] can be checked in your business logic, allowing you to catch invalid data states before you try to do a DB transaction and get an EntityValidationException. Finally, it's quick to code - you don't need to write a mapping layer or repository, but can instead work directly with the EF context. It's already a repository and a unit of work, so extra layers of abstraction don't accomplish anything.A downside to combining your domain and persisted entities is that you end up with a bunch of [NotMapped] attributes scattered throughout your properties. Often, you will want domain-specific properties which are either get-only filters on persisted data, or are set later in your business logic and not persisted back into your database. Some times, you'll want to express your data in your domain models in a way that doesn't work very well with a database - for example, when using enums, Entity will map these to an int column - but perhaps you want to map them to a human-readable string, so you don't need to consult a lookup when examining the database. Then you end up with a string property which is mapped, an enum property which isn't (but gets the string and maps to the enum), and an API which exposes both! Similarly, if you want to combine complex types (tables) across contexts, you may wind up with a mapped OtherTableId and an unmapped ComplexType property, both of which are exposed as public on your class. This can be confusing for someone who isn't familiar with the project, and unnecessarily bloats your domain models.The more complex my business logic/domain, the more restrictive or cumbersome I find combining my domain and persisted entities to be. For projects with short deadlines, or that don't express a complex business layer, I feel that using EF entities for both purposes is appropriate, and there's no need to abstract your domain away from your persistence. For projects which need maximum ease-of-extension, or that need to express very complicated logic, I think you're better off separating the two and dealing with the extra persistence complexity.One trick to avoiding the trouble of manually tracking your entity changes is to store the corresponding persisted entity ID in your domain model. This can be filled automatically by your mapping layer. Then, when you need to persist a change back to EF, retrieve the relevant persistent entity before doing any mapping. Then when you map the changes, EF will detect them automatically, and you can call context.SaveChanges() without having to track them by hand.public class OrganisationService{ public void PersistLicenses(IList<DomainLicenses> licenses) { using (var context = new EFContext()) { foreach (DomainLicense license in licenses) { var persistedLicense = context.Licenses.Find(pl => pl.Id == license.PersistedId); MappingService.Map(persistedLicense, license); //Right-left mapping context.Update(persistedLicense); } context.SaveChanges(); } }} |
_unix.172117 | I have a tab delimited file in which in every line I have this:K00001;K00004;K00008 0 0 34 0 0 0 0 0 0 0 0 0 0 0 0 0 36 0 0 52 0 0 0 6 0I would like to have one row with a unique code and the same sequence of numbers like this:K00001 0 0 34 0 0 0 0 0 0 0 0 0 0 0 0 0 36 0 0 52 0 0 0 6 0 K00004 0 0 34 0 0 0 0 0 0 0 0 0 0 0 0 0 36 0 0 52 0 0 0 6 0 K00008 0 0 34 0 0 0 0 0 0 0 0 0 0 0 0 0 36 0 0 52 0 0 0 6 0 | repeat a line, splitting one field | text processing;awk;perl | null |
_unix.238722 | I just implemented a few lines into my .vimrc that changes the color scheme from SolarizedDark to SolarizedLight based on the time of day. Solarized light during the day, solarized dark during the nightlet hour = strftime(%H)if 6 <= hour && hour < 18 set background=lightelse set background=darkendifIs it possible to do this for tmux and OS X terminal as well? | How can I change my tmux color scheme based on the time of day? | terminal;vim;tmux | null |
_codereview.129828 | As I am a novice, I was keen to solve the task, so now I want to optimize the code.Sub AddOlEObject() Dim mainWorkBook As Workbook Set mainWorkBook = ActiveWorkbook Sheets(SingleProfile).Activate Folderpath = C:\Users\sandeep.hc\Pics Set fso = CreateObject(Scripting.FileSystemObject) NoOfFiles = fso.GetFolder(Folderpath).Files.Count Set listfiles = fso.GetFolder(Folderpath).Files For Each fls In listfiles strCompFilePath = Folderpath & \ & Trim(fls.Name) If strCompFilePath <> Then If (InStr(1, strCompFilePath, jpg, vbTextCompare) > 1 _ Or InStr(1, strCompFilePath, jpeg, vbTextCompare) > 1 _ Or InStr(1, strCompFilePath, png, vbTextCompare) > 1) Then counter = 29 counter1 = counter1 + 1 Call insert(strCompFilePath, counter, counter1) 'Sheets(SingleProfile).Activate counter1 = counter1 + 17 End If End If NextmainWorkBook.SaveEnd SubFunction insert(PicPath, counter, counter1)'MsgBox PicPath With ActiveSheet.Pictures.insert(PicPath) With .ShapeRange .LockAspectRatio = msoFalse .Width = 875 .Height = 300 End With .Left = ActiveSheet.Cells(counter, counter1).Left .Top = ActiveSheet.Cells(counter, counter1).Top .Placement = 1 .PrintObject = True End WithEnd FunctionBased on Comments Optimized codeSub AddImage2()Dim rgTarget As RangeDim RowI As Long, ColumnI As Long Folderpath = C:\Users\sandeep.hc\Pics Set fso = CreateObject(Scripting.FileSystemObject) NoOfFiles = fso.GetFolder(Folderpath).Files.Count Set listfiles = fso.GetFolder(Folderpath).Files For Each fls In listfiles strCompFilePath = Folderpath & \ & Trim(fls.Name) If strCompFilePath <> Then If (InStr(1, strCompFilePath, jpg, vbTextCompare) > 1 _ Or InStr(1, strCompFilePath, jpeg, vbTextCompare) > 1 _ Or InStr(1, strCompFilePath, png, vbTextCompare) > 1) Then RowI = 29 ColumnI = ColumnI + 1 Set rgTarget = Cells(RowI, ColumnI) Application.ActiveSheet.Shapes.AddPicture strCompFilePath, False, True, rgTarget.Left, rgTarget.Top, 875, 400 ColumnI = ColumnI + 17 End IfEnd IfNextEnd Sub | Importing JPG, JPEG, and PNG images from a folder to an Excel worksheet | beginner;vba;excel;image;file system | I will summarize what I said before (and add a few new ones):Use Option Explicit at the top of your module. It helps you to prevent mistakes and forces you to declare the variablesinstead of Instr use Right as in If Right(strCompFilePath,4)=.jpg rename counter and counter1 so it is clear what they are (row and column indices)Declare insert as a Sub and not a Function.instead of passing the row and column index to the insert function/sub and then using the ActiveSheet pass the cell as a Range to the insert function/sub. (Instead of Activesheet you can use cell.Worksheet to get the right sheet) possibly rename insert so you don't confuse it with Pictures.insertadd the option savewithfile := true to the Pictures.Insert method so the pictures will stay in the file even if you send it somewhere.as it is now, you don't really need NoOfFiles and mainWorkBook instead of the FileSystemObject I would use Dir. See this for more on that. |
_opensource.4371 | So when I tried to signed the CLA for my company, it failed and Google told me that Please have an authorized executive sign this document. ...To me it's not quite clear their definition of authorized executive. How do I get autorized if I am the only employee or I am the boss. By default, Google use Docusign for digital signature and I just signed the default signature (which is generated by Docusign automatically)So here's my question:How do you signed it? It would be really great if someone has experience on this.There is a required field title which is unclear to me. What kind of information should I fill in this field. ( I filled in Mr)https://cla.developers.google.com/clas/new?domain=DOMAIN_GOOGLE&kind=KIND_CORPORATE | Google voided Corporate Contributor License Agreements | open source definition | null |
_softwareengineering.329338 | Our team develops an application. As this application intended to run on Debian, we've done it in a proper Debian way - via .deb packages. This app is written in C++/Python and versioned using Git.We have a private Debian repo where I place snapshot and release versions (approach taken from Java world):appname-1.2-SNAPSHOT.debappname-1.2.1.debNow some of developers have branched, have writen code and finally are creating pull requests. By pull request I want to trigger the testing of his work - make sure it is not so bad to go to master branch.So I am creating the VM and.. what should I install from Debian repo before triggering the test? What is the best practice? | How to define the .deb-packages name to reflect the Git branch | continuous integration;continuous delivery;devops | null |
_vi.11212 | I'm trying to make autocompletion work in vim with youcomplete me plugin. It works find with langs, say, javascript or python but when i try it on c# see the following error:ConnectionError: HTTPConnectionPool(host='localhost', port=52234): Max retries exceeded with url: /autocomplete (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x10b3ee790>: Failed to establish a new connection: [Errno 61] Connection refused',))full log:2017-01-30 01:13:46,452 - ERROR - Exception from semantic completer (using general): Traceback (most recent call last): File /Users/smooth/.vim/bundle/YouCompleteMe/third_party/ycmd/ycmd/../ycmd/handlers.py, line 104, in GetCompletions .ComputeCandidates( request_data ) ) File /Users/smooth/.vim/bundle/YouCompleteMe/third_party/ycmd/ycmd/../ycmd/completers/completer.py, line 218, in ComputeCandidates candidates = self._GetCandidatesFromSubclass( request_data ) File /Users/smooth/.vim/bundle/YouCompleteMe/third_party/ycmd/ycmd/../ycmd/completers/completer.py, line 234, in _GetCandidatesFromSubclass raw_completions = self.ComputeCandidatesInner( request_data ) File /Users/smooth/.vim/bundle/YouCompleteMe/third_party/ycmd/ycmd/../ycmd/completers/cs/cs_completer.py, line 125, in ComputeCandidatesInner completion_type ) ] File /Users/smooth/.vim/bundle/YouCompleteMe/third_party/ycmd/ycmd/../ycmd/completers/cs/cs_completer.py, line 447, in _GetCompletions completions = self._GetResponse( '/autocomplete', parameters ) File /Users/smooth/.vim/bundle/YouCompleteMe/third_party/ycmd/ycmd/../ycmd/completers/cs/cs_completer.py, line 588, in _GetResponse response = requests.post( target, data = parameters, timeout = timeout ) File /Users/smooth/.vim/bundle/YouCompleteMe/third_party/ycmd/third_party/requests/requests/api.py, line 107, in post return request('post', url, data=data, json=json, **kwargs) File /Users/smooth/.vim/bundle/YouCompleteMe/third_party/ycmd/third_party/requests/requests/api.py, line 53, in request return session.request(method=method, url=url, **kwargs) File /Users/smooth/.vim/bundle/YouCompleteMe/third_party/ycmd/third_party/requests/requests/sessions.py, line 468, in request resp = self.send(prep, **send_kwargs) File /Users/smooth/.vim/bundle/YouCompleteMe/third_party/ycmd/third_party/requests/requests/sessions.py, line 576, in send r = adapter.send(request, **kwargs) File /Users/smooth/.vim/bundle/YouCompleteMe/third_party/ycmd/third_party/requests/requests/adapters.py, line 437, in send raise ConnectionError(e, request=request)ConnectionError: HTTPConnectionPool(host='localhost', port=52234): Max retries exceeded with url: /autocomplete (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x10b3ee790>: Failed to establish a new connection: [Errno 61] Connection refused',))2017-01-30 01:13:46,947 - INFO - Received event notification2017-01-30 01:13:46,947 - DEBUG - Event name: FileReadyToParse2017-01-30 01:13:46,947 - INFO - Adding buffer identifiers for file: /Users/smooth/.vim/bundle/YouCompleteMe/third_party/ycmd/ycmd/tests/cs/testdata/testy/Program.cs2017-01-30 01:13:46,947 - INFO - Starting OmniSharp server2017-01-30 01:13:46,947 - INFO - Loading solution file /Users/smooth/.vim/bundle/YouCompleteMe/third_party/ycmd/ycmd/tests/cs/testdata/testy/testy.sln2017-01-30 01:13:46,947 - INFO - using port 522342017-01-30 01:13:46,949 - INFO - Received event notification2017-01-30 01:13:46,949 - DEBUG - Event name: InsertLeave2017-01-30 01:13:46,949 - INFO - Adding ONE buffer identifier for file: /Users/smooth/.vim/bundle/YouCompleteMe/third_party/ycmd/ycmd/tests/cs/testdata/testy/Program.csI did everything as it says in install manualC# support: install Mono with Homebrew [24] or by downloading the Mono Mac package [26] and add '--omnisharp-completer' when calling './install.py'.but it's not working. My environment is:VimversionVIM - Vi IMproved 8.0 (2016 Sep 12, compiled Jan 28 2017 00:47:01)MacOS X (unix) versionIncluded patches: 1-243Compiled by HomebrewclangApple LLVM version 8.0.0 (clang-800.0.42.1)Target: x86_64-apple-darwin16.4.0 | ConnectionError: HTTPConnectionPool(host='localhost', port=52234): Max retries exceeded with url | plugin you complete me | null |
_softwareengineering.87070 | Our team of 10 developers meet weekly. The meetings are rather boring and not particularly useful. What format/agenda do you utilize to have good meetings?We meet weekly in the conference room with pizza provided. The format is we go around the room and list the status of various tasks we are working on and discuss tasks for the next week. Managers will provide an overview of upcoming projects and priorities for the coming months and year ahead.Update The goal of these meeting is more or less - general team building, to share the knowledge of what everyone is working on, and to keep everyone aware of shifting company initiatives. It is not to formally 'hand out' work assignments (that is done via other means). | How to run developer team meetings? | management;communication;meetings;team building;team | null |
_softwareengineering.275832 | We have huge modules in our project, each module has a bunch of user-stories, each story contains developer tasks. Actually, we take tasks from multiple modules, since we have some core module features and optional.Each developer task I should review and merge into master.So, basically it is just project-task-subtask, right? But it doesn't fit our case.Each project has it's own board - we need one board, actuallySub-tasks cannot have status beside completed/not. So, sub-task is completed, but not reviewed, but PM sees it like this part is done and ready to be tested and touched. Waiting for whole user story to be completed isn't acceptable every time.I know it is not a resource to find apps, but I dunno where I can ask this questions. | Agile tools, can't find any that suits my case or I'm wrong somewhere? | agile;scrum;kanban | It sounds like you're thinking about what a project is differently to how most of this kind of software does. As a result, you're also breaking down other pieces differently.In a tool like Jira:A project is an entire piece of software - a product. So in your case, you have one project.Modules within a piece of software are called components. In your case, each of the modules would line up 1-to-1 with a component.Stories (developer tasks) belong to a project, and can be associated with 1 or more components. Each story has it's own state (open, in progress, done, closed; these are configurable in Jira), and follows a predefined workflow. In your case, a task and a story are equatable.A story can be broken down in to sub-tasks. Each sub-task (like a story) has it's own state, following a predefined workflow.A backlog is a collection of stories which need working on. In Jira, this is defined by a filter over all stories in the system.A scrum board is a team's view on a product backlog, showing which stories from that backlog are being worked on in the current sprint. The scrum board has a swimlane (row) for each story, and a column for each state, with stories and subtasks appearing in the appropriate columns.A large internal project within the product is an epic. An epic can have any number of stories in it.If you were to use a tool like Jira, you would have a single project, with a scrum board and backlog per team. Stories would be associated with the modules, and work on them would follow the normal workflow. You could easily divide your teams and backlogs along module boundaries by using an appropriate filter when creating a backlog; eg only those stories associated with this module |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.