id
stringlengths 5
27
| question
stringlengths 19
69.9k
| title
stringlengths 1
150
| tags
stringlengths 1
118
| accepted_answer
stringlengths 4
29.9k
⌀ |
---|---|---|---|---|
_webmaster.77143 | I recently canceled my AdSense account and I want to re-apply for a new one, with a different email.My payee name and other informations will be exactly the same as my canceled account. Can I open a new AdSense account using the same information? My previous account no longer exists.If I can, how long I have to wait after canceling it? | I have canceled my AdSense account. Can I apply for a new account? | google adsense;google adsense policies;accounts | null |
_cs.19664 | (I'm aware that software questions are better suited for stackoverflow, but since DFAs are not something that software developers usually care about, I hope it's alright if I ask here.)I'm currently working on a project to do with regular overapproximations for context free languages. For this purpose, I need to implement stuff that requires me to represent regular languages in a minimized form, intersect them, complement them, etc. - i.e. everything that's easy and quick to do with DFAs. However, I'm having a hard time finding still-maintained libraries for DFAs in C++. I could find libfa which does everything quite nicely, but that's as far as I've gotten. Grail hasn't been maintained in 15+ years and the download link is dead. FAdo seemed interesting initially, but it's in Python and I can't determine whether there's a way to use it as a C++ library, or whether it offers the functionality I mentioned above (the Docs are a bit slim).Do you know of C(++) libraries for DFAs that offer minimization, intersection and complementation that are free for academic use? I'd like to have at least one alternative to libfa that I can use. | C(++) library for DFAs - free for academic use | reference request;automata;finite automata;mathematical software | I don't know of a full blown library, but based on [1] there is a really fast practical C++ implementation available from the author's homepage here.[1] Valmari, Antti. Fast brief practical DFA minimization. Information Processing Letters 112.6 (2012): 213-217. |
_unix.96663 | I'm trying to install slime on a debian wheezy distro 64 bit called Crunchbang, trying to install common lisp, followed this tutorial, although the title says it's for windows, I installed it on linux and slime seems to work perfectly (or so i think).However, I see this errorCannot open slime-helper.el so i ran emacs --debug-init and got this error`Should I care about it? And if so, how to fix it?note that i have sbcl, not clisp, and that my .emacs fle looks like this(load (expand-file-name ~/quicklisp/slime-helper.el))(setq inferior-lisp-program sbcl)(require 'slime)(slime-setup '(slime-fancy)) | Cannot open slime-helper.el | debian;emacs;crunchbang;lisp | The error says that the file /home/elie/quicklisp/slime-helper.el does not exist.So, does it? What do you see when you do ls /home/elie/quicklisp/slime-helper.el?Incidentally, you do not need expand-file-name in load. |
_unix.268315 | I am trying to run Logic application to talk to my logic analyzer, and I observe the following behavior, after I install the rules under the driver../Logic ./Logic: cpp_libs/libc.so.6: version `GLIBC_2.18' not found (required by /usr/lib/x86_64-linux-gnu/libstdc++.so.6)sudo bash./Logic ./Logic: cpp_libs/libc.so.6: version `GLIBC_2.18' not found (required by /usr/lib/x86_64-linux-gnu/libstdc++.so.6)sudo ./Logic # Application runsWhat is the cause for this strange behavior?I am running Ubuntu 14.04. | Why does Logic Application not work except directly under sudo? | bash;ubuntu;sudo | null |
_unix.36886 | I've seen this answer:Preserve bash history in multiple terminal windowsThis works for history, but I'm wondering if there is way to extend this so pressing up is shared as well? | Is there a way to make the history when pressing up in bash shared between shells? | bash;command history | null |
_cs.79925 | I'm trying to solve the excersice from Knuth's ConcreteMathematics:A Double Tower of Hanoi contains 2n disks of n different sizes, two ofeach size. As usual, we're required to move only one disk at a time, without putting a larger one over a smaller one.How many moves does it take to transfer a double tower from one peg toanother, if disks of equal size are indistinguishable from each other?My solution was like this. Let $n$ be the number of disks ofdifferent sizes and $X_n$ - number of moves. The first few solutionsare:$n = 0$ $X_n = 0$$n = 1$ $X_n = 2$$n = 2$ $X_n = 6$$n = 3$ $X_n = 14$Recurrence is $X_n = 2X_{n-1} + 2$We can add $2$ to both sides:$X_n+2 = 2X_{n-1} + 4$let $Y_n = X_n + 2$, then$Y_n = 2Y_{n-1}$$Y_n = 2^n$$X_n = 2^n - 2$The problem is that the correct solution is $2^{n+1} - 2$, but Icannot find an error in my approach. | Solve X(n) = 2X(n-1) + 2 recurrence relation | recurrence relation | Your $Y_0$ is probably wrong. $Y_0$ must be equal to $X_0+2=0+2=2$. Then $Y_n=2^{n+1}$ and hence $X_n=2^{n+1}-2$. Please double check. |
_webmaster.86223 | I'm having a lot of trouble with something that should be simple. I don't want my development site indexed by Google. According to Google's instructions, and just about everything else I can find says to block this through robots.txt. I set this up correctly months ago, but my development sites still show up. When I log into Google Webmasters and use their robots.txt tester, it shows my site and every URL I've tested should be completely blocked. User-agent: *Disallow: /As an extra measure, I added a simple .htpasswd to the website too, but cached pages still showed up. I went through each and every page and removed it using the Google removal tool - most of them disappeared temporarily but week after week more and more pages pop up as being indexed. I've tried to use Wordpress settings to disallow robots, and I've tried including page-specific code in the header too. This has been going on for quite some time.Long story short, this is starting to drive me crazy as I feel like I've tried everything I can to stop Google from indexing my site, but they won't. Can anyone think of what I could have done wrong? | Why does my staging site show up in Google even though my robots.txt file shouldn't allow it? | seo;google;google search console;robots.txt;noindex | null |
_unix.374236 | How can I search lines in a text file for a pattern between two positions and print the entire row where that pattern is found? I am working with fixed-width files. I understand how to supply a list of lengths for each field to awk, but I am only interested in searching a single field for the pattern. Is there a simpler solution that does not involve specifying the length for each field?Here is a single line of text from the file. How can I find all lines that have 'Cook Co. IL' between positions 18 and 57 and not elsewhere in the line?17 031 1602 1600 Cook Co. IL 047 011 9999 9999 Bradley Co. TN 16 | Search lines in text file for pattern between two positions and print entire row | text processing;awk;grep | awk solution:awk 'substr($0,18,57-18)~/Cook Co\. IL/' filesubstr(string, start [, length ]) Return a length-character-long substring of string, starting at character number start. |
_webmaster.3909 | Have some ideas, but for now I'm going to leave it description as the question.If you have any questions, just ask -- thanks!!UPDATES: Guidelines:Workflow makes the most frequent tasks easy, and less frequent tasks achievable.Workflow covers 80% of the tasks.Solutions use smart default settings.Focus of the Question: The focus is the production of front interfaces; HTML, CSS, JS, generic content/graphic source, etc. Also, I figure that if the workflow required a CMS that the template would be based on existing one implementable on a given system. Again, thanks for any and all post!! -- Any real answers will get an up vote by me, and I will select an answer. Cheers! | What's the best workflow for creating websites fast & cheap, but that work as needed? | website design;web development;process | To expand a bit on John Conde's reply: Good, fast, cheap. Pick any two.I'd say that a static site built on a free web template with minor customizations (colors, column widths, background images) will suffice for 80-90% of small businesses. Get the client to fill out some kind of questionnaire, then do most of the thinking for them and show them your work every week or so for their feedback. If you want to produce fast and cheap websites, that's as much workflow as you and they usually need to consider; otherwise, the website will not be fast, and if it's cheap then it probably means you lost money for the amount of effort you put into it. Most clients who who care about implementing workflow on their website are not in the we want a site fast and cheap camp.Edit: do you mean the workflow that you use to create the website, or the workflow that the client uses to achieve his business tasks with the website? |
_cstheory.36687 | There are quite a lot papers describing near-linear algorithms. They are usually iterative, with linear complexity of one iteration. Others have $O(n\log^k n)$ time compexity.I'm failed to find a decent source with the definition of near-linear time, which covers both types. Please, help me find one. | Definition of near-linear algorithm | time complexity;definitions | null |
_unix.383239 | I've created with Yocto a Linux image for an IMX6 device.I've modified the /etc/network/interface file in order to setup usb0 and wlan0.No problem with usb0, it's correctly setup at boot time. It does not work as expected for wlan0.My /etc/network/interface looks like:auto usb0iface usb0 inet static address 192.168.1.1 broadcast 192.168.1.255 netmask 255.255.255.0auto wlan0iface wlan0 inet dhcp wpa-conf /etc/wpa_supplicant.confThe wpa_supplicant.conf looks like:network={ ssid=my_own_ssid psk_mgmt=NONE}Having that done, if I tried:ifup wlan0I get:udhcpc (v1.24.2) startedSending discover...Sending discover...Sending discover...No lease, failingSame thing if I do:/etc/init.d/S40network restartHowever, I type the following command before:wpa_supplicant -B -iwlan0 -c /etc/wpa_supplicant.conf -Dwextifup wlan0It works.I'm not a Linux expert, but I was understanding that wpa_supplicant was called by /etc/network daemon.How can I do to have wlan0 setup at boot time ? Any suggestion is welcome.Z. | Configure wlan0 interface at boot time | network interface;wpa supplicant;wlan | null |
_softwareengineering.33402 | Okay, this is one of those little things that always bugged me. I typically don't abbreviate identifiers, and the only time I use a short identifier (e.g., i) is for a tight loop. So it irritates me when I'm working in C++ and I have a variable that needs to be named operator or class and I have to work around it or use an abbreviation, because it ends up sticking out. Caveat: this may happen to me disproportionately often because I work a lot in programming language design, where domain objects may mirror concepts in the host language and inadvertently cause clashes.How would you deal with this? Abbreviate? (op) Misspell? (klass) Something else? (operator_) | What do you do when your naming convention clashes with your language? | naming | Accept that you might have to make minor changes to your naming convention, such as adding capitalization. It's better to accept this as soon as possible so all subsequent code is consistent.Consider being more specific. Keywords tend to be quite broad, so narrowing class down to demonstrationClass not only works around the issues but also increases readability. |
_webapps.29282 | My Gmail account does not have the select all checkbox, so I have to select one by one.Is there any other way to delete all my spam messages? | Why doesn't my Gmail account have the select all option? | gmail | null |
_unix.115398 | I am connected to a Freebsd 10 -STABLE server with SSH from my office box but when I trying to work inside the session I encounter these problems:although I did chsh for every user in said server to /usr/local/bin/bash; whenever I ssh to server I get:sh (the default Bourne shell in FreeBSD) supports command-line editing. Just``set -o emacs'' or ``set -o vi'' to enable it. in my ssh session I can't go to end of a line by End key or beginning of a line by Home key. instead I get ~ character. all and all the environment I feel in the SSH session is primitive and hard to navigate.the echo $SHELL returns /usr/local/bin/bash. the ps -ef|grep $$ returns:2010 0 S 0:00.03 TERM=xterm PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/games:/usr/local/s and echo $0 returns su | Setting the bash SHELL for remote openSSH connections? | shell;ssh;freebsd;openssh | null |
_codereview.71026 | In a bigger project of mine I'm using angular to create a dropdown menu dynamically and then toggling a dropdown menu for some of the menu items. This is why I got a function that toggles the dropdown menus for only the items that should actually have one. However, I feel like I should try to DRY this out a bit since I'll be repeating the same function even more than what I've done so far. How can I improve this code? Should I create a self invoking function or something similar? Here's the functions (they're part of a controller object that I left out): init: function() { menuController.toggleDropDown('msg'); menuController.toggleDropDown('mypages'); menuController.toggleDropDown('tools'); menuController.toggleDropDown('administration'); menuController.toggleDropDown('contactinfo'); menuController.toggleDropDown('utbildning'); menuController.toggleDropDown('surveys'); menuController.toggleDropDown('help'); }, toggleDropDown: function (id) { $('#main-menu' + ' #' + id + '').hover(function() { $('#' + id + ' ul').stop().slideToggle(); }); } | Toggle dropdown menus for different menu items with Jquery | javascript;beginner;jquery;object oriented | I think you can use html attribute to group it.eg.<div data-toggle=dropdown> or<a data-toggle=dropdown> or whateverand then$('#main-menu [data-toggle=dropdown]').hover(function(e) { $(e.currentTarget).find('ul').stop().slideToggle();}); |
_unix.312261 | I'm having difficultly finding an explanation for allowing the OS default copy/paste capabilities (i.e. highlight a portion of text and then use standard shortcut or right click menu) and allow mouse scrolling at the same time. Mouse mode turns on tmux's own copy/paste system, but leaving it off removes the mouse scrolling. As I'm switching between an IDE, browser, and terminal with tmux I would like the controls to be consistent between all of them. Is there a way to have the standard OS copy/paste controls while also allowing the mouse to scroll in tmux?(Note: I originally asked, but deleted, this question on SO. I decided it was more appropriate here.) | tmux mouse scrolling without altering copy/paste? | tmux;clipboard;scrolling | It depends on whether you are relying upon tmux to interpret the wheel-mouse, or not. If that's tmux — no, you cannot, because tmux would only see the wheel mouse events if it turned on the terminal's mouse operations.Without turning on the mouse operations, some terminals may send up/down cursor keys to the application when it has switched to the alternate screen. VTE (gnome-terminal) has done that unconditionally for a few years. The same feature is an option(alternateScroll) in xterm. tmux switches to the alternate screen if the terminal description has that in the terminfo smcup and rmcup capabilities. While in the alternate screen, normally (except for this fairly recent up/down cursor feature), the wheel mouse would have no effect on the terminal.So... you can get some limited use of the wheel mouse while running tmux, and it depends on the terminal and how it is configured. |
_codereview.35251 | I did most of my PHP coding back with PHP 4, and among the projects I did was a popular pagination class. I've been meaning to bring it up to date with PHP 5 and OOP practices. I've also been working on updating my database code, using PDO over the deprecated mysql* functions. What I'd like from you is your input and feedback about my updates.Pagination Classclass Paginator{ public $items_per_page; public $total_items; public $current_page; public $num_pages; public $mid_range; public $limit; public $limit_start; public $limit_end; public $return; public $querystring; public $ipp_array; public $get_ipp; public $get_page; public function __construct($total,$mid_range=7,$ipp_array=array(10,25,50,100,'All')) { $this->total_items = $total; $this->mid_range = $mid_range; $this->ipp_array = $ipp_array; $this->items_per_page = (isset($_GET['ipp'])) ? $_GET['ipp'] : $this->ipp_array[0]; $this->get_ipp = isset($_GET['ipp']) ? $_GET['ipp'] : NULL; $this->get_page = isset($_GET['page']) ? (int) $_GET['ipp'] : 1; $this->default_ipp = $this->ipp_array[0]; if($this->get_ipp == 'All') { $this->num_pages = 1; } else { if(!is_numeric($this->items_per_page) OR $this->items_per_page <= 0) $this->items_per_page = $this->ipp_array[0]; $this->num_pages = ceil($this->total_items/$this->items_per_page); } $this->current_page = (isset($_GET['page'])) ? (int) $_GET['page'] : 1 ; // must be numeric > 0 if($_GET) { $args = explode(&,$_SERVER['QUERY_STRING']); foreach($args as $arg) { $keyval = explode(=,$arg); if($keyval[0] != page And $keyval[0] != ipp) $this->querystring .= & . $arg; } } if($_POST) { foreach($_POST as $key=>$val) { if($key != page And $key != ipp) $this->querystring .= &$key=$val; } } if($this->num_pages > 10) { $this->return = ($this->current_page > 1 And $this->total_items >= 10) ? <a class=\paginate\ href=\$_SERVER[PHP_SELF]?page=.($this->current_page-1).&ipp=$this->items_per_page$this->querystring\>Previous</a> :<span class=\inactive\ href=\#\>Previous</span> ; $this->start_range = $this->current_page - floor($this->mid_range/2); $this->end_range = $this->current_page + floor($this->mid_range/2); if($this->start_range <= 0) { $this->end_range += abs($this->start_range)+1; $this->start_range = 1; } if($this->end_range > $this->num_pages) { $this->start_range -= $this->end_range-$this->num_pages; $this->end_range = $this->num_pages; } $this->range = range($this->start_range,$this->end_range); for($i=1;$i<=$this->num_pages;$i++) { if($this->range[0] > 2 And $i == $this->range[0]) $this->return .= ... ; // loop through all pages. if first, last, or in range, display if($i==1 Or $i==$this->num_pages Or in_array($i,$this->range)) { $this->return .= ($i == $this->current_page And $this->get_page != 'All') ? <a title=\Go to page $i of $this->num_pages\ class=\current\ href=\#\>$i</a> \n:<a class=\paginate\ title=\Go to page $i of $this->num_pages\ href=\$_SERVER[PHP_SELF]?page=$i&ipp=$this->items_per_page$this->querystring\>$i</a> \n; } if($this->range[$this->mid_range-1] < $this->num_pages-1 And $i == $this->range[$this->mid_range-1]) $this->return .= ... ; } $this->return .= (($this->current_page < $this->num_pages And $this->total_items >= 10) And ($this->get_page != 'All') And $this->current_page > 0) ? <a class=\paginate\ href=\$_SERVER[PHP_SELF]?page=.($this->current_page+1).&ipp=$this->items_per_page$this->querystring\>Next</a>\n:<span class=\inactive\ href=\#\>Next</span>\n; $this->return .= ($this->get_page == 'All') ? <a class=\current\ style=\margin-left:10px\ href=\#\>All</a> \n:<a class=\paginate\ style=\margin-left:10px\ href=\$_SERVER[PHP_SELF]?page=1&ipp=All$this->querystring\>All</a> \n; } else { for($i=1;$i<=$this->num_pages;$i++) { $this->return .= ($i == $this->current_page) ? <a class=\current\ href=\#\>$i</a> :<a class=\paginate\ href=\$_SERVER[PHP_SELF]?page=$i&ipp=$this->items_per_page$this->querystring\>$i</a> ; } $this->return .= <a class=\paginate\ href=\$_SERVER[PHP_SELF]?page=1&ipp=All$this->querystring\>All</a> \n; } $this->return = str_replace('&','&',$this->return); $this->limit_start = ($this->current_page <= 0) ? 0:($this->current_page-1) * $this->items_per_page; if($this->current_page <= 0) $this->items_per_page = 0; $this->limit_end = ($this->get_ipp == 'All') ? (int) $this->total_items: (int) $this->items_per_page; } public function display_items_per_page() { $items = NULL; natsort($this->ipp_array); // This sorts the drop down menu options array in numeric order (with 'all' last after the default value is picked up from the first slot if(is_null($this->get_ipp)) $this->items_per_page = $this->ipp_array[0]; foreach($this->ipp_array as $ipp_opt) $items .= ($ipp_opt == $this->items_per_page) ? <option selected value=\$ipp_opt\>$ipp_opt</option>\n:<option value=\$ipp_opt\>$ipp_opt</option>\n; return <span class=\paginate\>Items per page:</span><select class=\paginate\ onchange=\window.location='$_SERVER[PHP_SELF]?page=1&ipp='+this[this.selectedIndex].value+'$this->querystring';return false\>$items</select>\n; } public function display_jump_menu() { $option=NULL; for($i=1;$i<=$this->num_pages;$i++) { $option .= ($i==$this->current_page) ? <option value=\$i\ selected>$i</option>\n:<option value=\$i\>$i</option>\n; } return <span class=\paginate\>Page:</span><select class=\paginate\ onchange=\window.location='$_SERVER[PHP_SELF]?page='+this[this.selectedIndex].value+'&ipp=$this->items_per_page$this->querystring';return false\>$option</select>\n; } public function display_pages() { return $this->return; }}Sample Instantiation<?phpinclude('paginator.class.php');try { $conn = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass'); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $num_rows = $conn->query('SELECT COUNT(*) FROM City')->fetchColumn(); $pages = new Paginator($num_rows,9,array(15,3,6,9,12,25,50,100,250,'All')); echo $pages->display_pages(); echo <span class=\\>.$pages->display_jump_menu().$pages->display_items_per_page().</span>; $stmt = $conn->prepare('SELECT City.Name,City.Population,Country.Name,Country.Continent,Country.Region FROM City INNER JOIN Country ON City.CountryCode = Country.Code ORDER BY City.Name ASC LIMIT :start,:end'); $stmt->bindParam(':start', $pages->limit_start, PDO::PARAM_INT); $stmt->bindParam(':end', $pages->limit_end, PDO::PARAM_INT); $stmt->execute(); $result = $stmt->fetchAll(); echo <table><tr><th>City</th><th>Population</th><th>Country</th><th>Continent</th><th>Region</th></tr>\n; foreach($result as $row) { echo <tr><td>$row[0]</td><td>$row[1]</td><td>$row[2]</td><td>$row[3]</td><td>$row[4]</td></tr>\n; } echo </table>\n; echo $pages->display_pages(); echo <p class=\paginate\>Page: $pages->current_page of $pages->num_pages</p>\n; echo <p class=\paginate\>SELECT * FROM table LIMIT $pages->limit_start,$pages->limit_end (retrieve records $pages->limit_start-.($pages->limit_start+$pages->limit_end). from table - $pages->total_items item total / $pages->items_per_page items per page);} catch(PDOException $e) { echo 'ERROR: ' . $e->getMessage();}?>Live DemosDemo 1Demo 2Areas of ConcernI noticed in my query that if I try to execute the SQL with:$stmt->execute( array(':start'=>$pages->limit_start,':end'=>$pages->limit_end) );I get an error unless I also use $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);. However I can get around that if I use bindParam instead:$stmt->bindParam(':start', $pages->limit_start, PDO::PARAM_INT);$stmt->bindParam(':end', $pages->limit_end, PDO::PARAM_INT);$stmt->execute();Should I be using $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE); or the separate bindParam calls?bindParam seems like a decent solution, whereas using ATTR_EMULATE_PREPARESseems a little hacky.Within the class, am I setting the visibility (public, private, protected) of my parameters and methods properly?If you see anything that jumps out at you like what in the world was he thinking?, you can assume that I was dealing with something I hadn't done before. Any tips or suggestions overall would be appreciated. | Critique Requested on PHP Pagination Class | php;object oriented;classes;pdo;pagination | null |
_unix.227373 | Is there a portable way of handling NULL characters in shell?A typical example would be splitting the output of find ... -print0 with shell (and shell only) either in a pipe or in a command substitution result. By portable I mean ideally something that shells not as powerful as e.g. bash or zsh wouldn't choke on. Is this possible in a bare POSIX shell (any POSIX version)? | Handling NULL characters in shell | shell;binary | POSIX doesn't envision the standard utilities to deal with text embedding null characters. The -print0 option you use with find is itself a GNU extension unsupported by POSIX.One way to deal with a flow of data containing nulls with POSIX shell scripting would be to convert it first to real text with od and process that text instead.In any case, if you have GNU find, you likely have other GNU utilities that haven't that limitation in the first place. |
_codereview.13949 | I have written code exclusively in both C and C++. I see clear advantages in both and therefore have recently began using them together. I have also read, what I would consider, outrageous comments claiming that to code in C is outright dumb, and it is the language of past generations. So, in terms of maintenance, acceptance, common practice and efficiency; is it something professionals on large scale projects see/do?Here's an example snippet:I obviously need to #include both <stdio.h> and <iostream>.#define STRADD , #include <stdio.h>#include <stdlib.h>#include <iostream>#include <fstream>#include <iomanip>#include <string>#include Struct.h#include Rates.h#include Taxes.husing namespace std; And later I utilize functions like...void printHeading(FILE * fp){ fprintf(fp, Employee Pay Reg Hrs Gross Fed SSI Net\n); fprintf(fp, Name Rate Ovt Hrs Pay State Defr Pay\n); fprintf(fp, ==================================================================================\n); return;}and..void getEmpData(EmpRecord &e){ cout << \n Enter the employee's first name: ; getline(cin, e.firstname); cout << Enter the employee's last name: ; getline(cin, e.lastname); e.fullname = e.lastname + STRADD + e.firstname; //Fullname string creation cout << Enter the employee's hours worked: ; cin >> e.hours; while(e.hours < 0) { cout << You did enter a valid amount of hours!\n; cout << Please try again: ; cin >> e.hours; } cout << Enter the employee's payrate: ; cin >> e.rate; while(e.rate < MINWAGE) { cout << You did enter a valid hourly rate!\n; cout << Please try again: ; cin >> e.rate; } cout << Enter any amount to be tax deferred: ; cin >> e.deferred; while(e.deferred < 0) { cout << You did enter a valid deferred amount!\n; cout << Please try again: ; cin >> e.deferred; } cin.ignore(100, '\n'); return;}Thanks in advance! | What are the draw backs, if any, in using C and C++ together? Is doing so considered correct by the large? | c++;c | null |
_cstheory.7168 | I'm considering the problem of recognizing a language (over alphabet 0-9 and space) containing strings like 1 2 3 4 5 6 and 14 15 16 17 but not 1 3. This came up while working on a common parsing task where elements needed to be in an ordered list. It struck me that while parsing the rest of that language was regular, this part was clearly irregular -- it can recognize, for example, the language A1A2 where A is an arbitrary string 0-9. In fact it seems to be content-sensitive (and not context-free by the pumping lemma).My first question: is there a (reasonably well-known, i.e. not defined just for this problem) class of languages between context-sensitive and context-free that describes its expressive power better? I've read about Aho's indexed languages, but it's not obvious (to me!) that these are even in that class, powerful though it is.My second question is informal. It seems that this language is easy to parse, and yet it is very high on the hierarchy. Is it common to come across similar examples and is there a standard way of dealing with them? Is there an alternate grouping of classes of languages that is incompatible with inclusion on the 'usual' ones?My reason for thinking this is easy: the language can be parsed deterministically, by reading until you get to the end of the first number, checking if the next number follows, and so forth. In particular it can be parsed in O(n) time with O(n) space; the space can be reduced to $O(\sqrt n)$ without too much trouble, I think. But it's hard enough to get that kind of performance with regular languages, let alone context-free. | What kind of language is needed to recognize an ordered list? [multihead automata, apparently] | fl.formal languages | It sounds like what you are looking for are multihead automata (in your case, 1-way 2-head deterministic finite automata should suffice). I'm not really an expert on these, but google turns up some interesting surveys on this language hierarchy, such asMarek Chrobak: Hierarchies of one-way multihead automata, http://www.sciencedirect.com/science/article/pii/0304397586900939This also gives one answer to your second question: The hierarchy of n-head automata lies across the Chomsky hierarchy. |
_codereview.141688 | ChallengeFind all possible moves for a knight on an empty chessboard.SpecificationsThe first argument is a path to a file.The file contains multiple lines.Each line is a test case representing the position of the knight in CN form.C is a letter from a to h and denotes a column.N is a number from 1 to 8 and denotes a row.For each test case, print all positions for the next move of the knight ordered alphabetically. Sample Inputg2 a1 d6 e5 b1Sample Outpute1 e3 f4 h4 b3 c2 b5 b7 c4 c8 e4 e8 f5 f7 c4 c6 d3 d7 f3 f7 g4 g6 a3 c3 d2SourceMy Solution#include <stdio.h>#include <stdlib.h>#define LINE_LENGTH 5#define BOARD_LENGTH 8#define MOVE_BUFFER 24int rows[] = {1, 2, 3, 4, 5, 6, 7, 8};char cols[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'};char moves[MOVE_BUFFER];int move_iter = 0;char num_convert(int *n) { for (int i = 0; i < BOARD_LENGTH; i++) { if (*n == rows[i]) { return cols[i]; } }}int alpha_convert(char *c) { for (int i = 0; i < BOARD_LENGTH; i++) { if (*c == cols[i]) { return rows[i]; } }}void add_moves(int c, int n1, int n2) { if (c >= 1 && c <= 8) { if (n1 >= 1) { moves[move_iter++] = num_convert(&c); moves[move_iter++] = n1 + '0'; moves[move_iter++] = ' '; } if (n2 <= 8) { moves[move_iter++] = num_convert(&c); moves[move_iter++] = n2 + '0'; moves[move_iter++] = ' '; } }}char* valid_moves(char position[]) { int C = alpha_convert(&position[0]); int N = atoi(&position[1]); add_moves(C - 2, N - 1, N + 1); add_moves(C - 1, N - 2, N + 2); add_moves(C + 1, N - 2, N + 2); add_moves(C + 2, N - 1, N + 1); moves[move_iter - 1] = '\0'; move_iter = 0; return moves; }int main(int argc, char *args[]) { if (argc < 2) { fprintf(stderr, File path not provided. Exiting...\n); return 1; } if (argc > 2) { puts(Excessive arguments, only the first will be considered.); } FILE *file = fopen(args[1], r); if (file == NULL) { perror(Error); return 1; } char position[LINE_LENGTH]; while (fgets(position, LINE_LENGTH, file)) { puts(valid_moves(position)); } fclose(file);} | All the knight moves in all the right places | beginner;c;programming challenge | Joshua: What's the difference?Computers sometimes have a hard time to differentiate between things that are apples and oranges to us, some examples are:if this is a game or if this is realthermonuclear war and a game of chesschar and intYou have two functions converting from char to int and back:char num_convert(int *n) { for (int i = 0; i < BOARD_LENGTH; i++) { if (*n == rows[i]) { return cols[i]; } }}int alpha_convert(char *c) { for (int i = 0; i < BOARD_LENGTH; i++) { if (*c == cols[i]) { return rows[i]; } }}This is not necessary in C, because char and int are kind of the same thing. You can do regular calculations with characters just like you do with integers. Once in character, stay in character.So when it comes to playing the game of converting between both types, I'd have to say the only winning move is not to play.the mysterious void add_moves()I have no idea what this function does.void add_moves(int c, int n1, int n2) { if (c >= 1 && c <= 8) { if (n1 >= 1) { moves[move_iter++] = num_convert(&c); moves[move_iter++] = n1 + '0'; moves[move_iter++] = ' '; } if (n2 <= 8) { moves[move_iter++] = num_convert(&c); moves[move_iter++] = n2 + '0'; moves[move_iter++] = ' '; } }}Why are there two n but only a single c? What do those values represent?They are apparently boundary checked, too. Then there's this code block that's pretty much duplicated for both n, which is bad. if (n1 >= 1) { moves[move_iter++] = num_convert(&c); moves[move_iter++] = n1 + '0'; moves[move_iter++] = ' '; }After all, something is somehow added to moves, which justifies the name add_moves(). But it's not immediately clear to me what's going on in that function and I feel like too much is going on.a hint in char* valid_moves()This function takes away a bit of the mystery from what add_moves() is doing. As it calls it with different possible moves of the knight.add_moves(C - 2, N - 1, N + 1);add_moves(C - 1, N - 2, N + 2);add_moves(C + 1, N - 2, N + 2);add_moves(C + 2, N - 1, N + 1);This is not very intuitive. Why do I only see 4 lines here? The knight can do 8 moves in general. Now it is clear why add_moves() takes two n values as parameters, but only one c.This distribution of logic doesn't appear to be plausible. It's like some part of the movement is calculated in one place while the other happens later. If the concerns of the functions were more clearly separated, it would be easier to understand them.I gave it a try myself. Here's how I did it:Position typeThis is all about positions, so let's create a type for that.typedef struct { signed char column; int row;}Position;We're not in oop land, but we still group data together if it belongs together. This helps a lot when passing it around.disclaimer: I often see type names like position_t and I absolutely hate that, which is why I'm not using it. Your naming convention may vary.relative knight moves as positionsIs 5 meters an absolute position or a difference between two positions? It can very well be both! In the same idea, let's create an array of Position that represent the relative movements a knight can perform.Position allKnightMovesInAlphabeticalOrder[] = { {-2, -1}, {-2, +1}, {-1, -2}, {-1, +2}, {+1, -2}, {+1, +2}, {+2, -1}, {+2, +1} };#define numberOfKnightMoves 8As you can see, -2 is a perfectly fine signed char value. 1If you are uncomfortable reusing the Position type which from its name might suggest to be an absolute position, you can always typedef it to a Move type, which makes the intention more clear.position checkA handy helper function could solve the sub-problem of whether a certain position is on the board or not.bool positionIsInChessboard(Position *position){ return position->column >= 'a' && position->column <= 'h' && position->row >= 1 && position->row <= 8;}You need to #include <stdbool.h> for bool. If you don't want that, you should be able to use _Bool as a return type.making a moveAnother helper function that simply adds two positions together.void addTwoPositions(Position *a, Position *b, Position *result){ result->column = a->column + b->column; result->row = a->row + b->row;}Again, as a Position might represent a relative movement, this starts to make sense I hope. If not, recall how a 2D vector in math might represent a fixed point or the difference between two points. This is the same idea.putting it all together#include <stdio.h>#include <stdbool.h>typedef struct { signed char column; int row;}Position;Position allKnightMovesInAlphabeticalOrder[] = { {-2, -1}, {-2, +1}, {-1, -2}, {-1, +2}, {+1, -2}, {+1, +2}, {+2, -1}, {+2, +1} };#define numberOfKnightMoves 8bool positionIsInChessboard(Position *position){ return position->column >= 'a' && position->column <= 'h' && position->row >= 1 && position->row <= 8;}void addTwoPositions(Position *a, Position *b, Position *result){ result->column = a->column + b->column; result->row = a->row + b->row;}int main (){ Position testPositions[] = { {'g', 2}, {'a', 1}, {'d', 6}, {'e', 5}, {'b', 1} }; int numberOfTestPositions = sizeof(testPositions)/sizeof(Position); Position result; for(int testPositionIndex = 0; testPositionIndex < numberOfTestPositions; testPositionIndex++) { printf(%c%d:\t, testPositions[testPositionIndex].column, testPositions[testPositionIndex].row); for(int moveIndex = 0; moveIndex < numberOfKnightMoves; moveIndex++) { addTwoPositions(&testPositions[testPositionIndex], &allKnightMovesInAlphabeticalOrder[moveIndex], &result); if(positionIsInChessboard(&result)) { printf(%c%d , result.column, result.row); } } printf(\r\n); }}I hard coded the test positions into main() for brevity. the basic idea for every test case is to iterate over all the possible knight moves, perform them via addTwoPositions() and then check the validity of the result with positionIsInChessboard().I do not build up a buffer as you do in your code simply because that isn't necessary.Here's what I get as a result in terminal:$ ./chess g2: e1 e3 f4 h4 a1: b3 c2 d6: b5 b7 c4 c8 e4 e8 f5 f7 e5: c4 c6 d3 d7 f3 f7 g4 g6 b1: a3 c3 d2 1 thanks @Daniel Jour for pointing out that plain char has an unspecified signedness, which may vary across platforms and compilers.For me, I get the same output for any of the three versions char, signed char or unsigned char. It's still good practice to use signed char as it makes it more obvious that a Position might be a relative position. |
_codereview.82374 | I need to observe a ConcurrentQueue, but to minimize the resources I want to pause the Thread if the Queue is empty and resume it from another Thread if there is a new Entry in the Queue. I implemented a pausing and an resuming of a thread like this:My Worker, where the DoWork() method is called in a new Thread, looks like this:public static class Worker{ public static bool Running = true; public static void DoWork() { while (Running) { try { Thread.Sleep(Timeout.Infinite); } catch (ThreadInterruptedException) { DoActualWork(); } } } private static void DoActualWork() { //Do something }}I start the thread like this:Thread workerThread = new Thread(Worker.DoWork);workerThread.Start();I interrupt the Thread like this:workerThread.Interrupt();I stop the Thread like this:Worker.Running = false;Everything is working as expected but I'm not sure if this is how it should be implemented.Is this best practice? What can go wrong?Is there a problem with the static class and the members? (It have to be static because the Thread have to be interrupted by different Threads) | Is it ok to use Thread.Sleep and Thread.Interrupt for pausing and resuming Thread like this? | c#;multithreading | This is pretty bad.Instead why not use BlockingCollection. Then the loop will be:try{ while(true) { doSomethingWith(queue.Take()); }}catch(InvalidOperationException e){ // ignore and cleanup}And to stop the thread you need to call CompleteAdding() on the queue. |
_unix.206001 | Is there any way to read files from the virtual /proc directory using smbclient?No root access. Both server and client are Debian Linux machines. Server is running Samba 3. Smbclient version is 4.0.6-DebianCopying files from servers /proc filesystem with get /proc/cpuinfo in smbclient's interactive mode result in an empty file being copied. | Is there any way to read files from the virtual /proc directory using smbclient? | linux;samba;proc | null |
_codereview.8648 | Please critique my word frequency generator. I am a beginner programmer so any criticism are welcome.Original Code: http://pastebin.com/rSRfbnCtHere is my revised code after the feedback:import string, time, webbrowser, collections, urllib2def timefunc(function): def wrapped(*args): start = time.time() data = function(*args) end = time.time() timetaken = end - start print Function: +function.__name__+\nTime taken:,timetaken return data return wrapped@timefuncdef process_text(text_file): words = text_file.read().lower().split() words = [word.strip(string.punctuation+string.whitespace) for word in words] words = [word for word in words if word]#skips ''(None) elements return words@timefuncdef create_freq_dict(wordlist): freq_dict = collections.Counter(wordlist) return freq_dict@timefuncdef create_sorted_list(freqdict): sorted_list = [(value,key) for key,value in list(freqdict.items())]#list() provides python 3 compatibility sorted_list.sort(reverse=True) return sorted_list@timefuncdef write_results(sorted_list): text_file = open('wordfreq.txt','w') text_file.write('Word Frequency List\n\n') rank = 0 for word in sorted_list: rank += 1 write_str = [{0}] {1:-<10}{2:->10}\n.format(rank, word[1],word[0]) text_file.write(write_str) text_file.close()## The Brothers Grimm## This file can be obtained from Project Gutenberg:## http://www.gutenberg.org/cache/epub/5314/pg5314.txtweb_file = urllib2.urlopen('http://www.gutenberg.org/cache/epub/5314/pg5314.txt')wordlist = process_text(web_file)freqdict = create_freq_dict(wordlist)sorted_list = create_sorted_list(freqdict)results = write_results(sorted_list)webbrowser.open('wordfreq.txt')print END | Word frequency generator in Python | python;strings | import string, time, math, webbrowserdef timefunc(function, *args): start = time.time() data = function(*args) end = time.time() timetaken = end - startI'd recommend calling this time_taken as its slightly easier to read. print Function: +function.__name__+\nTime taken:,timetakenPrint already introduces newlines and combines different pieces. Take advantage of that. print Function: , function.__name__ print Time Taken: , time_takenThat's easier to follow return datadef process_text(filename):You never use filename in here, but you do use fin which is the same thing. typo? t = []Not a very descriptive name. I suggest coming up with something clearer for line in fin: for i in line.split():i usually means index which its not here word = i.lower() word = word.strip(string.punctuation) if word != '': t.append(word) return tI'd do this as words = fin.read().lower().split() words = [word.strip() for word in words] words = [word for word in words if word] return wordsI think its easier to follow and probably more efficientdef create_freq_dict(wordlist): d = dict()d is not a very good name. Usually dicts are created with {} not dict(). No difference, but the first is generally preffered for word in wordlist: if word not in d.keys(): d[word] = 1 else: d[word] += 1Use d = collections.defaultdict(int) or d = collections.Counter(). Both will make it easier to count up like this. See the python documentation for collections. You should actually be able to write this function in one line return ddef sort_dict(in_dict): t = [] for key,value in in_dict.items(): t.append((value, key))in_dict.items() is a list already, there is no reason to copy the elements into the list. (NOTE: in Python 3.x in_dict.items() is no longer a list). Even if it wasn't a list you could do: t = list(in_dict.items())Which would do the same thing your code does t.sort(reverse=True) return tI'd implement this function asreturn sorted(in_dict.items())The sorted function takes anything sufficiently list-like and produces a sorted list from it.def write_results(sorted_list):sorted_list isn't a great name. It would be better to give an indication of what's in the list. fout = open('wordfreq.txt','w') fout.write('Word Frequency List\n\n') r = 0 for i in sorted_list: r += 1Use for r, (key, value) in enumerate(sortedlist): That way you don't need to manage r yourself, and you can refer the value as value rather then the harder to read i[1]. fillamount = 20 - (len(i[1]) + len(str(r)))Some of the those parens are unnecessary. write_str = str(r)+': '+i[1]+' '+('-' * (fillamount-2))+' '+str(i[0])+'\n'Multiplication has precedence, you don't need the parens to make that happen. Also, python has a method ljust which does this for you write_str = (str(r) + ': ' + i[1]).ljust('-', 20) + str(i[0]) + '\n'You may also want to consider using string formatting rather then adding strings write_str = ('%d: %s' % (r, i[1])).just('-', 20) + '%d\n' % i[0]I think its easier to follow, although I'd probably split across several lines fout.write(write_str) fout.close()## The Brothers Grimm## This file can be obtained from Project Gutenberg:## http://www.gutenberg.org/cache/epub/5314/pg5314.txtfin = open('c:\Python27\My Programs\wx\grimm.txt')fin presumable stands for file in. Give a name that indicates what's actually in it ike grim_textwordlist = timefunc(process_text,fin)freqdict = timefunc(create_freq_dict,wordlist)sorted_list = timefunc(sort_dict,freqdict)results = timefunc(write_results,sorted_list)Very nicewebbrowser.open('wordfreq.txt')That's a slightly unusual use of a webbrowserprint END |
_codereview.132839 | I am a newbie coder and I'm trying to learn good coding habits. I'm making a Simon Says game challenge from Free Code Camp in Angular JS.CodepenI have an array that keeps random integers between 1-4:var simonSays = [];This is how I'm currently animating and playing sounds. I've read that you're not to manipulate the DOM using Angular. But how would I handle it for my game?var counter = 0, //for looping thru simon's array innerTimeOutSecs = 1000, //time during each iteration outerTimeOutSecs = 500, //time before next iteration simonTurn = false; //if simon is playing, player cannot interrupt simonfunction animateSimonSays() { simonTurn = true; $timeout(function() { var simon = simonSays[counter]; //find the current pad and current audio to light up/play var currentPad = document.getElementById(pad + simon); var currentAudio = document.getElementById(pad + simon + _audio); angular.element(currentPad).addClass(lightUpPad); currentAudio.play(); $timeout(function() { currentAudio.pause(); //stop audio currentAudio.currentTime = 0; angular.element(currentPad).removeClass(lightUpPad); //'turn off' pad //get ready for the next simon counter++; if (counter < simonSays.length) { //recursion fail condition animateSimonSays(); } else { counter = 0; simonTurn = false; } }, innerTimeOutSecs); //how long to stay 'lit' }, outerTimeOutSecs); //how long before the next simon}It's dirty but it works for my app. All the examples I found online were jQuery so I couldn't really follow their methodology.var app = angular.module('App', []);app.controller('MainCtrl', ['$scope', '$timeout', function($scope, $timeout) { var simonSays = [], //push what simon says copy = [], // compare user answer to simon answer counter = 0, //for looping thru simon's array innerTimeOutSecs = 1000, //time during each iteration outerTimeOutSecs = 500, //delay in resetting to original state of pad and call next pad simonTurn = false, //if simon is playing, play cannot interrupt simon currentResponse = true; //used to compare user answer to simon $scope.count = 0; //number of rounds $scope.isStrict = false; //is strict mode on/off $scope.startGame = function() { //start button calls restart restart(); } function restart() { //initialize game by setting values in array to empty and start a new round simonSays = []; $scope.count = 0; newRound(); } function newRound() { //begin next round if ($scope.count === 20) { //victory alert if player reaches 20 steps alert(Congratulations. You win!); restart(); return; } $scope.count++; //increase round by one if ($scope.count % 5 === 0) { innerTimeOutSecs -=100; outerTimeOutSecs -=50; } simonSays.push(Math.floor(Math.random() * 4 + 1)); //add random step to the end copy = simonSays.slice(0); animateSimonSays(); } function animateSimonSays() { //light works and sound //TODO: speedup animations after every 5 'count' simonTurn = true; //simon is playing, user cannot play function again by pressin start $timeout(function() { //outertimeout var simon = simonSays[counter]; //setting up iteration of array var currentPad = document.getElementById(pad + simon); //setting up light show for each var currentAudio = document.getElementById(pad + simon + _audio); //setup audio angular.element(currentPad).addClass(lightUpPad); //opacity change currentAudio.play(); //audio starts $timeout(function() { //inner timeout currentAudio.pause(); //stop sound currentAudio.currentTime = 0; //set audio back to start position angular.element(currentPad).removeClass(lightUpPad); //return to original opacity counter++; //setting up next iteration in array if (counter < simonSays.length) { //test for recursiveness animateSimonSays(); //calling recursive function for next iteration } else { //if counter reaches end.. counter = 0; //reset counter simonTurn = false; //simon turn over } }, innerTimeOutSecs); //how long it stays lit }, outerTimeOutSecs); //next pad } //three possible situations //1.user click wrong pad --> call animate again (last round) //2.user click right pad but seq not finish --> do nothing //3.user pick right pad and end of seq --> new round function checkResponse() { if (!currentResponse) { // case 1 var buzzer = document.getElementById(buzzer); buzzer.play(); if ($scope.isStrict) { //strict mode restarts game $timeout(function() { buzzer.pause(); buzzer.currentTime = 0; restart(); }, 1000); return; } $timeout(function() { buzzer.pause(); buzzer.currentTime = 0; copy = simonSays.slice(0); animateSimonSays(); }, 1000); } else if (currentResponse && copy.length === 0) { //case 3 $timeout(newRound, 1000); } } $scope.registerClick = function(padId) { if (simonTurn) return; //click does not register during simon turn //var currentPad = document.getElementById(pad + padId); var currentAudio = document.getElementById(pad + padId + _audio); currentAudio.play(); $timeout(function() { currentAudio.pause(); currentAudio.currentTime = 0; }, 500); var desiredResponse = copy.shift(); //pop out first index of the array var actualResponse = padId; currentResponse = desiredResponse === actualResponse; //compare click and simon checkResponse(); }}]);.wrapper { position: relative; width: 640px; margin: 0 auto;}.back { position: absolute; top: 170px; width: 640px; height: 640px; z-index: 0; background-color: #000; border-radius: 310px;}.pad { width: 300px; height: 300px; float: left; z-index: 1; margin: 10px; -ms-filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=60); filter: alpha(opacity=60); opacity: 0.6; cursor: pointer;}.pad:active { -ms-filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=100); filter: alpha(opacity=100); opacity: 1;}.shape1 { border-top-left-radius: 300px; background-color: green;}.shape2 { float: left; border-top-right-radius: 300px; background-color: red; clear: right;}.shape3 { float: left; border-bottom-left-radius: 300px; background-color: yellow; clear: left;}.shape4 { float: left; border-bottom-right-radius: 300px; background-color: blue;}.circle { position: absolute; top: 195px; left: 195px; width: 250px; height: 250px; background: #000; border-radius: 125px; z-index: 10;}.simon { text-align: center; color: white; font-family: Impact; font-size: 5em; margin-top: 25px;}.startButton { width: 25px; height: 25px; border-radius: 50%; background: red; margin-left: 25%; margin-top: 10px;}.strictButton { width: 25px; height: 25px; border-radius: 50%; background: #ffff00; margin-top: 8px; margin-left: 10px;}.strictIndicator { height: 7px; width: 7px; background-color: #32050C; border-radius: 50%; margin-left: 20px; margin-top: -5px;}.strictIndicator-on { background-color: #DC0D29;}.lightUpPad { opacity: 1;}.count { text-align: center; width: 60px; height: 50px; background-color: #32050C; border-radius: 10px; margin-left: 15px; color: #DC0D29; font-size: 2.5em; border: 2px solid #222;}.controllabel { text-align: center; text-transform: uppercase; color: #fff;}.countlabel { margin-left: 15px;}.buttonlabel { margin-top: 13px;}.controls { float: left; margin-left: 13px;}.strictlabel { margin-top: 13px;}<script src=https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js></script><audio preload=auto id=pad1_audio><source src=https://s3.amazonaws.com/freecodecamp/simonSound1.mp3 type=audio/mp3></audio><audio preload=auto id=pad2_audio><source src=https://s3.amazonaws.com/freecodecamp/simonSound2.mp3 type=audio/mp3></audio><audio preload=auto id=pad3_audio><source src=https://s3.amazonaws.com/freecodecamp/simonSound3.mp3 type=audio/mp3></audio><audio preload=auto id=pad4_audio><source src=https://s3.amazonaws.com/freecodecamp/simonSound4.mp3 type=audio/mp3></audio><audio preload=auto id=buzzer><source src=http://soundbible.com/mp3/Basketball Buzzer-SoundBible.com-1863250611.mp3 type=audio/mp3></audio><div ng-app=App ng-controller=MainCtrl> <div class=wrapper> <div class=back> <div id=pad1 class=pad shape1 ng-click=registerClick(1)> </div> <div id=pad2 class=pad shape2 ng-click=registerClick(2)> </div> <div id=pad3 class=pad shape3 ng-click=registerClick(3)> </div> <div id=pad4 class=pad shape4 ng-click=registerClick(4)> </div> <div class=circle> <div class=simon>simon</div> <div class=controls> <div class=count>{{count}}</div> <div class=controllabel countlabel>COUNT</div> </div> <div class=controls> <button class=startButton ng-click=startGame()></button> <div class=controllabel buttonlabel>START</div> </div> <div class=controls> <div ng-class=isStrict ? 'strictIndicator-on' : '' class=strictIndicator></div> <button class=strictButton ng-click=isStrict = !isStrict></button> <div class=controllabel strictlabel>STRICT</div> </div> </div> </div> </div></div> | Animate and play sounds in Simon Says 'the Angular way' | javascript;recursion;angular.js;dom;simon says | null |
_reverseengineering.6634 | I've been reverse engineering a PE executable and I came across a behavior that I can't understand. The executable uses both shell32.dll and profapi.dll. I see that shell32.dll delay loads a function in profapi.dll using an ordinal value (I verified this by looking at the delay load import table of shell32.dll). However, profapi.dll does not export any functions as it doesn't even have an export table. I'm examining the delay import and export sections of these DLLs using the Python library pefile. I'm using profapi.dll version 6.1.7600.16385 (as reported by the file properties) on Windows 7.From what I understand, to load a function by ordinal or name from profapi.dll, you still need access to profapi.dll's export table. Is there another way through which profapi.dll could expose the addresses of its functions, or am I missing something?EDIT: It looks like it was an issue with pefile parsing the DLL. I was indeed able to examine the export section using IDApro. I am leaving the question up to highlight what looks like a potential bug in pefile. I am using pefile version 1.2.10-139. | Delay imported function not in export table | dll;pe | profapi.dll should certainly have an Export Table. For example, here's the Export Table from profapi.dll version 6.3.9600.16384:There is an export table in .text at 0x10001000The Export Tables (interpreted .text section contents)Export Flags 0Time/Date stamp 52157da7Major/Minor 0/0Name 00001060 profapi.dllOrdinal Base 101Number in: Export Address Table 0000000e [Name Pointer/Ordinal] Table 00000000Table Addresses Export Address Table 00001028 Name Pointer Table 00000000 Ordinal Table 00000000Export Address Table -- Ordinal Base 101 [ 0] +base[ 101] 2b24 Export RVA [ 1] +base[ 102] 25c2 Export RVA [ 2] +base[ 103] 3cd9 Export RVA [ 3] +base[ 104] 1089 Export RVA [ 4] +base[ 105] 4a8b Export RVA [ 5] +base[ 106] 49b2 Export RVA [ 6] +base[ 107] 42ae Export RVA [ 7] +base[ 108] 4643 Export RVA [ 8] +base[ 109] 45ce Export RVA [ 9] +base[ 110] 4592 Export RVA [ 10] +base[ 111] 3dc3 Export RVA [ 11] +base[ 112] 4318 Export RVA [ 12] +base[ 113] 428d Export RVA [ 13] +base[ 114] 3bcd Export RVAI just checked version 6.1.7600.16385 from Windows 7 and confirmed that it too has an Export Table, from which it exports 6 functions by ordinal. If the Python library you're using isn't seeing these functions then it's due to a bug in the Python library (or potentially your usage of it).For what it's worth, this is a known issue in older versions of the pefile library and was fixed about a year ago. Perhaps you're using an outdated version? |
_softwareengineering.257488 | It seems to be accepted that computers that have been powered on for a long time and have any sort of complex software (ie and OS) running on them they tend to develop random errors and problems. Turning the device off and back on powers off the machine and destroys all volatile memory, generally fixing the problem. First, am I just imagining that or is it accepted? Is there a better description or a word/phrase for it?Second, how do servers deal with this. They are generally 24/7/365 machines. Though multiple machines serving the same page could be turned off individually, is this done in that situation? | How do web servers deal with issues that arise when a machine has been on for a long time? | web;hardware | It might be the accepted norm if you are accustomed to running hardware and software that isn't that stable. But I haven't observed a particular trend of servers running poorly after extended uptime in my career. I've run many a Solaris, Linux or BSD server well past 1000 day uptime and more than a handful have made it to the 1400-1500 day mark. I would update Apache or apply other patches without patching the kernel and just keep trucking. (NOTE: I don't advocate that this as a sys-admin practice, but there are systems that customer's don't want rebooted unless there is a problem).As to how it is done in web servers that just serve pages, you are correct, a page can and is often served by redundant servers and even a content delivery network. Taking down a node shouldn't impact your site if you have redundancy and caches. High availability is all about redundancy. It isn't so important to keep a single node healthy for extended runtimes for a static web site. You really shouldn't need to depend on a single web server today when a Linux VM can be had for $5 a month at Digital Ocean and a 2 node load-balanced Linux setup can be put together for cheap.The shift for the past 10 years has been toward many cheap servers. Back in the 1998-2000 time frame at IBM we were already running massively distributed web farms with 50-100 nodes serving up a single site (Olympics, Wimbledon, US Open, Masters), and now it is commonplace since companies like Google and Facebook published a lot of literature on this technique. |
_cstheory.21503 | There has been a few questions (1, 2, 3) about transitive completion here that made me think if something like this is possible:Assume we get an input directed graph $G$ and would like to answer queries of type $(u,v)\in G^+$?, i.e. asking if there exists an edge between two vertices in the transitive completion of a graph $G$? (equivalently, is there a path from $u$ to $v$ in $G$?).Assume after given $G$ you are allowed to run preprocessing in time $f(n,m)$ and then required to answer queries in time $g(n,m)$.Obviously, if $f=0$ (i.e. no preprocessing is allowed), the best you can do is answer a query in time $g(n)=\Omega(n+m)$. (run DFS from $u$ to $v$ and return true if there exists a path).Another trivial result is that if $f=\Omega(min\{n\cdot m,n^\omega\})$, you can compute the transitive closure and then answer queries in $O(1)$.What about something in the middle? If you are allowed, say $f=n^2$ preprocessing time, can you answer queries faster than $O(m+n)$? Maybe improve it to $O(n)$?Another variation is: assume you have $poly(n,m)$ preprocessing time, but only $o(n^2)$ space, can you use the preprocessing to answer queries more efficient than $O(n+m)$?Can we say anything in general about the $f,g$ tradeoff that allows answering such queries?A somewhat similar tradeoff structure is considered in GPS systems, where holding a complete routing table of all pairwise distances between locations is infeasible so it's using the idea of distance oracles which stores a partial table but allow significant query speedup over computing the distance of the whole graph (usually yielding only approximated distance between points). | Computing a transitive completion / path existance oracle | graph theory;graph algorithms;space time tradeoff;transitive closure | Compact reachability oracles exist for planar graphs,Mikkel Thorup: Compact oracles for reachability and approximate distances in planar digraphs. J. ACM 51(6): 993-1024 (2004)but are hard for general graphs (even sparse graphs)Mihai Patrascu: Unifying the Landscape of Cell-Probe Lower Bounds. SIAM J. Comput. 40(3): 827-847 (2011)Nevertheless, there is an algorithm that can compute a close-to-optimal reachability labeling Edith Cohen, Eran Halperin, Haim Kaplan, Uri Zwick: Reachability and Distance Queries via 2-Hop Labels. SIAM J. Comput. 32(5): 1338-1355 (2003)Maxim A. Babenko, Andrew V. Goldberg, Anupam Gupta, Viswanath Nagarajan: Algorithms for Hub Label Optimization. ICALP 2013: 69-80Building on the work of Cohen et al. and others, there is quite a bit of applied research (database community) see e.g.Ruoming Jin, Guan Wang: Simple, Fast, and Scalable Reachability Oracle. PVLDB 6(14): 1978-1989 (2013)Yosuke Yano, Takuya Akiba, Yoichi Iwata, Yuichi Yoshida: Fast and scalable reachability queries on graphs by pruned labeling with landmarks and paths. CIKM 2013: 1601-1606 |
_softwareengineering.263196 | I'd like to create a developer task collector where I'd put all issues that I see need some work but are not User Story related (e.g. fix some not visible quirks in startup animation, scan code with lint, enable EasyTracker in application, clean unused resources, etc.).I don't know when we'll have time to work all those issues, maybe next Sprint we'll do one of them and two Sprints later we'll work one etc.How to deal with it in Scrum/Sprint planning? Also should Product Owner decide what to do and when? | How to work on not User Story related tasks | agile;scrum;product owner;jira | null |
_codereview.136220 | I'm writing a MVC app, I've put effort into writing index.php since it must be the entrance point (like main for C and Java) imho.I would like to ensure if someone who were to work on this file wouldn't be confused. require_once 'App/config.php'; //main constants are defined hererequire_once 'App/autoload.php';if(strpos(URL,'error/')) goto start;try{ Connection::set(DBMS,HOST,PORT,DB_NAME,DB_USER,DB_PWD,$PDO_OPTIONS); DAO::init();}catch(Exception $e){ if(!PROD){ //if the app is online PROD=TRUE throw $e; }else header('location: '.WEBROOT.'error/503/',503); exit;}session_start();if(!isset($_SESSION['user'])) $_SESSION[user] = new Guest;start: try{ extract($_GET); unset($_GET); if(isset($controller, $action, $params)) Dispatcher::dispatch($controller, $action, $params); else if (isset($controller, $action)) Dispatcher::dispatch($controller, $action); else if (isset($controller, $params)) Dispatcher::dispatch($controller, NULL, $params); else if (isset($controller)) Dispatcher::dispatch($controller); else Dispatcher::dispatch(); echo Dispatcher::deliver(); //output the response }catch(Throwable $t){ if(!PROD) throw $t; else if($t instanceof TypeError && strpos($t->getTrace()[0],'Dispatcher.php')) header('location: '.WEBROOT.'error/400/',400); else if(strpos($t->getMessage(),'not found')) header('location: '.WEBROOT.'error/404/',404); else header('location: '.WEBROOT.'error/503/',503); } | index.php implementation | php;mvc | null |
_softwareengineering.273981 | Problem Statement:I have a tree with node values ( i , j ) where i , j < 1. The children of each node take on the values (i - 1, j), (i - 1, j - 1), and (i, j - 1) respectively. Now, i and j have constraints where they cannot be less than zero, so, given i (or j WLOG) == 0 for a node, its only child becomes (0, j - 1) (assuming j > 0).These nodes represent the indices of a matrix, and what the children represent are either the index to the West, the North, or the North West of the currently selected index. (Notice 0 either represents the West edge or the North edge of the matrix)I have written a recursive algorithm that will produce the number of different directions you can walk to get from node_0 (i, j) to the beginning.def backtrackrecursion( currentnode, counter ): if currentnode.getindex() == (0 , 0): return counter++ if currentnode.geti() > 0: currentnode.addchild(Node(index=(i - 1, j))) if currentnode.getj() > 0: currentnode.addchild(Node(index=(i, j - 1))) if currentnode.getindex() >= ( 1 , 1 ): currentnode.addchild(Node(index=(i - 1, j - 1))) for child in currentnode.getchildren(): counter += backtrackrecursion(child, counter) return counterI understand why this works. My girlfriend wrote another algorithm, and to my astonishment, it works as well.def btr(cnode, cou): if cnode.getindex() == ( 0 , 0 ): return cou++ if cnode.getindex() != (0 , 0): cou = btr(cnode.inddecr( -1, 0), cou) + btr(cnode.inddecr(0, -1), cou) + btr(cnode.inddrec( -1 , -1 ), cou) return counow I might have missed a property in her class that deletes all children with index i or j < 0, but shouldn't this be an infinite call? Where is the logic that I am missing? | Why does this recursion method work? I have explored it for a day or two, and I cannot figure out why | recursion | null |
_unix.138398 | I have file with 200 lines.I need to extract lines from 10 to 100 and put them into a new file.How do you do this in unix/Linux?What are the possible commands you could use? | How to get lines 10 to 100 from a 200 line file into a new file | text processing;sed;tail;head | null |
_codereview.31770 | So a page where I do a search based on a bunch of filters but all of them are optionals.I have my controller here:def distribution begin @service_request = ServiceRequest.find(params[:id]) @claimed, @unclaimed = 0, 0 @conditions = ContractorSearchConditions.new() @conditions.zipcode = @service_request.zipcode.to_s @conditions.search_terms = params[:filters].present? && params[:filters][:keywords].present? ? params[:filters][:keywords] : 'general' params[:filters].present? && params[:filters][:proximity].present? ? @conditions.mile_radius = params[:filters][:proximity] : params[:filters].present? && params[:filters][:results].present? ? @conditions.page_size = params[:filters][:results] : @conditions.page = 1 @contractors = Contractor.search(@conditions) @contractors.each do |contractor| if contractor.uid == 26 @unclaimed = @unclaimed+ 1 else @claimed = @claimed+ 1 end end rescue => e flash[:error] = #{e} redirect_to :action => :edit end endAnd my struct here:class ContractorSearchConditions < Struct.new(:search_terms, :state, :zipcode, :lat, :lng, :mile_radius, :account_type, :page, :page_size) #convert zipcode into lat, lon, and state def prepare zip = ZipCode.find(zipcode) self.state.nil? ? self.state = zip.state : self.state = self.state self.lat.nil? ? self.lat = zip.latitude.to_f : self.lat = self.lat.to_f self.lng.nil? ? self.lng = zip.longitude.to_f : self.lng = self.lng.to_f self.mile_radius.nil? ? self.mile_radius = 15 : self.mile_radius = self.mile_radius.to_i self.page_size.nil? ? self.page_size = 50 : self.page_size = self.page_size.to_i self.page.nil? ? self.page = 1 : self.page = self.page endendandThe thing is that my struct will be used in different controller across the app so I went to check the params and set default ones.But I'm quite not happy with the all my line of if.Any idea how I could make it better ?Edit:New distribution method: begin @service_request = ServiceRequest.find(params[:id]) if params[:filters].nil? params[:filters] = Hash.new params[:filters] = {:mile_radius => 15, :page_size => 50, :search_terms => 'general', :score => 100} end @conditions = ContractorSearchConditions.new(params[:filters]) @conditions.zipcode = @service_request.zipcode.to_s @contractors = Contractor.search(@conditions) @claimed, @unclaimed = 0, 0 @contractors.each do |contractor| if contractor.uid == 26 @unclaimed = @unclaimed+ 1 else @claimed = @claimed+ 1 end rescue => e flash[:error] = #{e} redirect_to :action => :edit end endand here is the view:<fieldset> <div class=row> <div class=form-group col-lg-12> <%= f.label :keywords, Keywords, :class => 'control-label' %> <%= f.input :keywords, :required => true, :label => false, :as => :string, :input_html => {:class => 'form-control', :maxlength => 255, :value => params[:filters][:keywords]}, :no_wrapper => true %> <hr> </div> </div> <div class=row> <div class=form-group col-lg-2> <%= f.label :results, # Results, :class => 'control-label' %> <%= f.input :results, :required => true, :label => false, :input_html => {:class => 'form-control', :value => params[:filters][:results]}, :no_wrapper => true, :as => :number %> </div> <div class=form-group col-lg-2> <%= f.label :proximity, Proximity, :class => 'control-label' %> <%= f.input :proximity, :required => true, :label => false, :input_html => {:class => 'form-control', :value => params[:filters][:proximity]}, :no_wrapper => true, :as => :number %> </div> </div> </fieldset>and my struct:class ContractorSearchConditions < Struct.new(:search_terms, :state, :zipcode, :lat, :lon, :mile_radius, :account_type, :page, :page_size) #convert zipcode into lat, lon, and state def prepare zip = ZipCode.find(zipcode) self.lat = (lat.nil? ? zip.latitude : lat).to_f self.lon = (lon.nil? ? zip.longitude : lon).to_f self.state = (state.nil? ? zip.state : state).to_s self.mile_radius = (mile_radius.nil? ? '15' : mile_radius).to_i self.page_size = (page_size.nil? ? 50 : page_size).to_i self.page = (page.nil? ? 1 : page).to_i self.search_terms = (search_terms.nil? ? 'general' : search_terms).to_s endend | Improve a list of if | ruby;ruby on rails | Many things here.Style considerationsFirst, in ruby conditionals are expressions, so instead of :self.lat.nil? ? self.lat = zip.latitude.to_f : self.lat = self.lat.to_fyou can do :self.lat = self.lat.nil? ? zip.latitude.to_f : self.lat.to_fyou can also get rid of self when not assigning :self.lat = lat.nil? ? zip.latitude.to_f : lat.to_fyou can also group statements :self.lat = (lat.nil? ? zip.latitude : lat).to_falso, this is roughly equivalent to :self.lat ||= zip_latitudeself.lat = lat.to_fDesign considerationsYour controller is too fat. especially this : @conditions = ContractorSearchConditions.new() @conditions.zipcode = @service_request.zipcode.to_s @conditions.search_terms = params[:filters].present? && params[:filters][:keywords].present? ? params[:filters][:keywords] : 'general' params[:filters].present? && params[:filters][:proximity].present? ? @conditions.mile_radius = params[:filters][:proximity] : params[:filters].present? && params[:filters][:results].present? ? @conditions.page_size = params[:filters][:results] : @conditions.page = 1Basicly all of this should be in the body of ContractorSearchConditions#initialize method (give up the struct, use a real class : too much logic is attached to this entity to be a simple bag of data), so that you can do :@conditions = ContractorSearchConditions.new( params[:search_conditions] )To be continued I will come back when i have more time to analyze your logic, but here's a hint : when you have a lot of conditionals, it usually means you failed to capture a concept / mechanism as an object. Find out what concept(s) it is and you should be able to clean this. EDIT : RefactoringLet's analyze this bit of code : @conditions.search_terms = params[:filters].present? && params[:filters][:keywords].present? ? params[:filters][:keywords] : 'general' params[:filters].present? && params[:filters][:proximity].present? ? @conditions.mile_radius = params[:filters][:proximity] : params[:filters].present? && params[:filters][:results].present? ? @conditions.page_size = params[:filters][:results] : @conditions.page = 1first, we will use real ifs and proper indentation to see clear in this mess : if params[:filters].present? && params[:filters][:keywords].present? @conditions.search_terms = params[:filters][:keywords] else @conditions.search_terms = 'general' end if params[:filters].present? && params[:filters][:proximity].present? @conditions.mile_radius = params[:filters][:proximity] end if params[:filters].present? && params[:filters][:results].present? @conditions.page_size = params[:filters][:results] else @conditions.page = 1 endStill ugly, but more clear. Something important now stands out... Do you see it ? if params[:filters].present? # side note : here we use presence from ActiveSupport, # which returns the object itself if it is not blank, or nil. @conditions.search_terms = params[:filters][:keywords].presence @conditions.mile_radius = params[:filters][:proximity].presence @conditions.page_size = params[:filters][:results].presence end @conditions.search_terms ||= 'general' @conditions.page = 1 unless @condition.page_sizeThe whole logic has, in fact, two purposes : initialize the @conditions object using params[:filters]set default values if necessaryAll of this should be the responsibility of ContractorSearchConditions#initialize. class ContractorSearchConditions # here are defaults values, all contained in a constant. # Thanks to this, everyone that looks at that class knows # what to expect as default values with this object. # DEFAULTS = { search_terms: :general, page: 1, page_size: 50, # those values are hard to find miles_radius: 15 # in the code you posted... not anymore ! }.freeze def initialize( params = {} ) # the magic happen here. We have default values, # but let the caller override them : options = DEFAULTS.merge( params || {} ) filters = options.delete( :filters ){ {} } assign_attributes( options ) filters.each{|name, value| apply_filter( name, value )} end # use the attributes accessor to assign all values. # the benefit here is that each accessor encapsulates # rules about what is a valid value to assign, how to coerce it, etc. # one could also easily filter which attributes can be assigned this way, # la attr_accessible # def assign_attributes( attributes ) attributes.each{|attr,value| public_send #{attr}=, value } end # example of custom writer with safety nets all over the place : # def page=( value ) return @page if value.blank? @page = value.to_i rescue NoMethodError raise ArgumentError, invalid value '#{value}' for page end # we can do something somewhat similar with filters : # def apply_filter( name, value ) public_send #{name}_filter, value rescue NoMethodError raise ArgumentError, unknown filter '#{name}' end # example of filter : # def proximity_filter( value ) self.mile_radius = value # this seems dumb, but would be really useful if you have complex behavior # like multiparameter filters, etc. endendWhat ? but this is far more complex !yes... and no.This implementation provides encapsulation of data and behavior, and ensures that your object always initializes with default, sensible values, in a consistent state. This is the heart of OOP! This also means you won't have to repeat this code over and over if you need it in another controller : in other words, reusability. this is a lot of logic, but you're doing many things ! In fact, if you want this to be pure, outrageously OO code, you would have to create one object for each responsibility (SRP) :extract parameters from a hash map them to a set of attributescoerce all values and guard against meaningless onesetc.For now, you've stuffed a lot of logic in the controller. This works for small projects, but can quickly become a code swamp in bigger ones. The whole process you perform should have a dedicated place to live ! That's why many people (me included) would use some sort of ContractorSearch object that would represent... a search (duh) and that you would be able to manipulate like, say, an ActiveModel object. A (bit outdated) example of such approach can be seen in railscasts #111. This even allows you to easily save your searches !i admit i have a tendency to overengineer. My implementation may be too much, but you get the spirit... |
_unix.194850 | I am copying files from my SD card to my Ubuntu server via Windows 7 using a network drive.The problem is that sometimes, 2 files out of 150, are corrupted during transfer.See here 2 example files in hex compare, left side original, right side how it is stored on server. They differ in ~10kB. In the second example you can see 00's added.I don't know what could cause this. So i am asking for any advice how to narrow down the possible error source.I think it is not the hardware itself, because 2 drives are affected.Network connection is also not the issue, this is cable bound and i had never problems on that level.My wife has the feeling that sometimes the bug also appears when working on files in Picasa. But i can't say that for sure.My guess is, that it is some sort of race condition bug on either ext4 fs or samba or mount.Here some system information, which might help:The affected drives are: UUID=bc57f0fd-c16d-450e-83aa-4b7faace655c /media/FOTOS2/ ext4 defaults 2UUID=aacc7c57-8997-42c3-a2fc-648fe5a9009c /media/WDRED2TB/ ext4 defaults 2Here the complete fstab file:# /etc/fstab: static file system information.## Use 'blkid' to print the universally unique identifier for a# device; this may be used with UUID= as a more robust way to name devices# that works even if disks are added and removed. See fstab(5).## <file system> <mount point> <type> <options> <dump> <pass># / was on /dev/sda2 during installationUUID=9978d40a-b90d-49e1-ab7a-002cc0577120 / ext4 errors=remount-ro 0 1# /boot/efi was on /dev/sda1 during installationUUID=AA12-9F54 /boot/efi vfat defaults 0 1# swap was on /dev/sda3 during installationUUID=bba8a1b5-a7da-44a2-a220-23a69c73e6ab none swap sw 0 0UUID=bc57f0fd-c16d-450e-83aa-4b7faace655c /media/FOTOS2/ ext4 defaults 2UUID=aacc7c57-8997-42c3-a2fc-648fe5a9009c /media/WDRED2TB/ ext4 defaults 2UUID=ba87bd76-a34a-45a5-8268-4de331ebf72f /media/RAID/ ext4 defaults 0 2Here the 'mount' output/dev/sde2 on / type ext4 (rw,errors=remount-ro)proc on /proc type proc (rw,noexec,nosuid,nodev)sysfs on /sys type sysfs (rw,noexec,nosuid,nodev)none on /sys/fs/cgroup type tmpfs (rw)none on /sys/fs/fuse/connections type fusectl (rw)none on /sys/kernel/debug type debugfs (rw)none on /sys/kernel/security type securityfs (rw)none on /sys/firmware/efi/efivars type efivarfs (rw)udev on /dev type devtmpfs (rw,mode=0755)devpts on /dev/pts type devpts (rw,noexec,nosuid,gid=5,mode=0620)tmpfs on /run type tmpfs (rw,noexec,nosuid,size=10%,mode=0755)none on /run/lock type tmpfs (rw,noexec,nosuid,nodev,size=5242880)none on /run/shm type tmpfs (rw,nosuid,nodev)none on /run/user type tmpfs (rw,noexec,nosuid,nodev,size=104857600,mode=0755)none on /sys/fs/pstore type pstore (rw)/dev/sde1 on /boot/efi type vfat (rw)/dev/sdc1 on /media/FOTOS2 type ext4 (rw)/dev/sdb1 on /media/WDRED2TB type ext4 (rw)/dev/md0p1 on /media/RAID type ext4 (rw)systemd on /sys/fs/cgroup/systemd type cgroup (rw,noexec,nosuid,nodev,none,name=systemd)gvfsd-fuse on /run/user/1000/gvfs type fuse.gvfsd-fuse (rw,nosuid,nodev,user=piotre)The system is apiotre@SERVER:~$ uname -aLinux SERVER 3.13.0-46-generic #79-Ubuntu SMP Tue Mar 10 20:06:50 UTC 2015 x86_64 x86_64 x86_64 GNU/Linuxdumpe2fs gives for one of the drives:Filesystem volume name: WDRED2TBLast mounted on: /media/WDRED2TBFilesystem UUID: aacc7c57-8997-42c3-a2fc-648fe5a9009cFilesystem magic number: 0xEF53Filesystem revision #: 1 (dynamic)Filesystem features: has_journal ext_attr resize_inode dir_index filetype needs_recovery extent flex_bg sparse_super large_file huge_file uninit_bg dir_nlink extra_isizeFilesystem flags: signed_directory_hashDefault mount options: (none)Filesystem state: cleanErrors behavior: ContinueFilesystem OS type: LinuxInode count: 122101760Block count: 488378385Reserved block count: 24418919Free blocks: 36947951Free inodes: 121834982First block: 0Block size: 4096Fragment size: 4096Reserved GDT blocks: 907Blocks per group: 32768Fragments per group: 32768Inodes per group: 8192Inode blocks per group: 512RAID stride: 1Flex block group size: 16Filesystem created: Wed May 1 12:47:05 2013Last mount time: Tue Apr 7 15:27:31 2015Last write time: Tue Apr 7 15:27:31 2015Mount count: 169Maximum mount count: 25Last checked: Mon Jul 21 21:11:14 2014Check interval: 15552000 (6 months)Next check after: Sat Jan 17 20:11:14 2015Lifetime writes: 2513 GBReserved blocks uid: 0 (user root)Reserved blocks gid: 0 (group root)First inode: 11Inode size: 256Required extra isize: 28Desired extra isize: 28Journal inode: 8Default directory hash: half_md4Directory Hash Seed: 9e898ed8-9275-4e6f-9dd6-431190f4b932Journal backup: inode blocksJounaleigenschaften: journal_incompat_revokeJournalgrsse: 128MJournal-Lnge: 32768Journal-Sequenz: 0x00028de6Journal-Start: 1First i tried modifying smb.conf (sync always and strict sync) but it did not help.Here the current smb.conf[global]workgroup=WORKGROUPserver string=%h server (Samba, Ubuntu)netbios name=SERVERdns proxy=nolog file=/var/log/samba/log.%mmax log size=1000syslog=0panic action=/usr/share/samba/panic-action %dserver role=standalone servermap to guest=bad userusershare allow guests=yessecurity=shareforce user=nobodyguest account=nobodysocket options = TCP_NODELAY IPTOS_LOWDELAY SO_RCVBUF=65536 SO_SNDBUF=65536strict syn = yessync always = yes | find the cause of file corruption when copying files to a network share on an Ubuntu machine | ubuntu;filesystems;samba;ext4;corruption | null |
_unix.63133 | Yesterday I was freely able to ssh into server box-a, and it seemingly froze on me today so I killed my putty instance. I am now unable to ssh into it. It ssh's but the prompt does not appear. I am able to ssh using a different username, and then if i try to su into my user it hangs as well:ssh notme@box-abox-a:/home/notme> su myuserPassword:and just hangs. Why could this be (on bash)?Debug output:ld-chhfemd01: ssh -vvv ld-chhfemd02OpenSSH_4.3p2, OpenSSL 0.9.8e-fips-rhel5 01 Jul 2008debug1: Reading configuration data /etc/ssh/ssh_configdebug1: Applying options for *debug3: cipher ok: aes128-cbc [aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour,aes192-cbc,aes256-cbc]debug3: cipher ok: 3des-cbc [aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour,aes192-cbc,aes256-cbc]debug3: cipher ok: blowfish-cbc [aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour,aes192-cbc,aes256-cbc]debug3: cipher ok: cast128-cbc [aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour,aes192-cbc,aes256-cbc]debug3: cipher ok: arcfour [aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour,aes192-cbc,aes256-cbc]debug3: cipher ok: aes192-cbc [aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour,aes192-cbc,aes256-cbc]debug3: cipher ok: aes256-cbc [aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour,aes192-cbc,aes256-cbc]debug3: ciphers ok: [aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour,aes192-cbc,aes256-cbc]debug2: ssh_connect: needpriv 0debug1: Connecting to ld-chhfemd02 [10.32.242.71] port 22.debug2: fd 3 setting O_NONBLOCKdebug1: fd 3 clearing O_NONBLOCKdebug1: Connection established.debug3: timeout: 30000 ms remain after connectdebug1: identity file /home/myuser/.ssh/identity type -1debug3: Not a RSA1 key file /home/myuser/.ssh/id_rsa.debug2: key_type_from_name: unknown key type '-----BEGIN'debug3: key_read: missing keytypedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug3: key_read: missing whitespacedebug2: key_type_from_name: unknown key type '-----END'debug3: key_read: missing keytypedebug1: identity file /home/myuser/.ssh/id_rsa type 1debug1: identity file /home/myuser/.ssh/id_dsa type -1debug1: loaded 3 keysdebug1: Remote protocol version 2.0, remote software version OpenSSH_4.3debug1: match: OpenSSH_4.3 pat OpenSSH*debug1: Enabling compatibility mode for protocol 2.0debug1: Local version string SSH-2.0-OpenSSH_4.3debug2: fd 3 setting O_NONBLOCKdebug1: SSH2_MSG_KEXINIT sentdebug1: SSH2_MSG_KEXINIT receiveddebug2: kex_parse_kexinit: diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1debug2: kex_parse_kexinit: ssh-rsa,ssh-dssdebug2: kex_parse_kexinit: aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour,aes192-cbc,aes256-cbcdebug2: kex_parse_kexinit: aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour,aes192-cbc,aes256-cbcdebug2: kex_parse_kexinit: hmac-md5,hmac-sha1,hmac-ripemd160,[email protected],hmac-sha1-96,hmac-md5-96debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,hmac-ripemd160,[email protected],hmac-sha1-96,hmac-md5-96debug2: kex_parse_kexinit: [email protected],zlib,nonedebug2: kex_parse_kexinit: [email protected],zlib,nonedebug2: kex_parse_kexinit:debug2: kex_parse_kexinit:debug2: kex_parse_kexinit: first_kex_follows 0debug2: kex_parse_kexinit: reserved 0debug2: kex_parse_kexinit: diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1debug2: kex_parse_kexinit: ssh-rsa,ssh-dssdebug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arc\four,[email protected]: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arc\four,[email protected]: kex_parse_kexinit: hmac-md5,hmac-sha1,hmac-ripemd160,[email protected],hmac-sha1-96,hmac-md5-96debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,hmac-ripemd160,[email protected],hmac-sha1-96,hmac-md5-96debug2: kex_parse_kexinit: none,[email protected],zlibdebug2: kex_parse_kexinit: none,[email protected],zlibdebug2: kex_parse_kexinit:debug2: kex_parse_kexinit:debug2: kex_parse_kexinit: first_kex_follows 0debug2: kex_parse_kexinit: reserved 0debug2: mac_init: found hmac-md5debug1: kex: server->client aes128-cbc hmac-md5 [email protected]: mac_init: found hmac-md5debug1: kex: client->server aes128-cbc hmac-md5 [email protected]: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sentdebug1: expecting SSH2_MSG_KEX_DH_GEX_GROUPdebug2: dh_gen_key: priv key bits set: 135/256debug2: bits set: 514/1024debug1: SSH2_MSG_KEX_DH_GEX_INIT sentdebug1: expecting SSH2_MSG_KEX_DH_GEX_REPLYdebug3: check_host_in_hostfile: filename /home/myuser/.ssh/known_hostsdebug3: check_host_in_hostfile: match line 79debug3: check_host_in_hostfile: filename /home/myuser/.ssh/known_hostsdebug3: check_host_in_hostfile: match line 79debug1: Host 'ld-chhfemd02' is known and matches the RSA host key.debug1: Found key in /home/myuser/.ssh/known_hosts:79debug2: bits set: 522/1024debug1: ssh_rsa_verify: signature correctdebug2: kex_derive_keysdebug2: set_newkeys: mode 1debug1: SSH2_MSG_NEWKEYS sentdebug1: expecting SSH2_MSG_NEWKEYSdebug2: set_newkeys: mode 0debug1: SSH2_MSG_NEWKEYS receiveddebug1: SSH2_MSG_SERVICE_REQUEST sentdebug2: service_accept: ssh-userauthdebug1: SSH2_MSG_SERVICE_ACCEPT receiveddebug2: key: /home/myuser/.ssh/identity ((nil))debug2: key: /home/myuser/.ssh/id_rsa (0x2ac6af877020)debug2: key: /home/myuser/.ssh/id_dsa ((nil))debug1: Authentications that can continue: publickey,passworddebug3: start over, passed a different list publickey,passworddebug3: preferred gssapi-with-mic,publickey,keyboard-interactive,passworddebug3: authmethod_lookup publickeydebug3: remaining preferred: keyboard-interactive,passworddebug3: authmethod_is_enabled publickeydebug1: Next authentication method: publickeydebug1: Trying private key: /home/myuser/.ssh/identitydebug3: no such identity: /home/myuser/.ssh/identitydebug1: Offering public key: /home/myuser/.ssh/id_rsadebug3: send_pubkey_testdebug2: we sent a publickey packet, wait for replydebug1: Server accepts key: pkalg ssh-rsa blen 149debug2: input_userauth_pk_ok: SHA1 fp f1:2c:f7:09:b6:b7:ff:83:c5:e7:98:da:f4:fe:ea:66:05:32:f7:9cdebug3: sign_and_send_pubkeydebug1: read PEM private key done: type RSAdebug1: Enabling compression at level 6.debug1: Authentication succeeded (publickey).debug1: channel 0: new [client-session]debug3: ssh_session2_open: channel_new: 0debug2: channel 0: send opendebug1: Entering interactive session.debug2: callback startdebug2: x11_get_proto: /usr/bin/xauth list unix:18.0 2>/dev/nulldebug1: Requesting X11 forwarding with authentication spoofing.debug2: channel 0: request x11-req confirm 0debug2: client_session2_setup: id 0debug2: channel 0: request pty-req confirm 0debug3: tty_make_modes: ospeed 38400debug3: tty_make_modes: ispeed 38400debug3: tty_make_modes: 1 3debug3: tty_make_modes: 2 28debug3: tty_make_modes: 3 127debug3: tty_make_modes: 4 21debug3: tty_make_modes: 5 4debug3: tty_make_modes: 6 0debug3: tty_make_modes: 7 0debug3: tty_make_modes: 8 17debug3: tty_make_modes: 9 19debug3: tty_make_modes: 10 26debug3: tty_make_modes: 12 18debug3: tty_make_modes: 13 23debug3: tty_make_modes: 14 22debug3: tty_make_modes: 18 15debug3: tty_make_modes: 30 0debug3: tty_make_modes: 31 0debug3: tty_make_modes: 32 0debug3: tty_make_modes: 33 0debug3: tty_make_modes: 34 0debug3: tty_make_modes: 35 0debug3: tty_make_modes: 36 1debug3: tty_make_modes: 37 0debug3: tty_make_modes: 38 1debug3: tty_make_modes: 39 0debug3: tty_make_modes: 40 0debug3: tty_make_modes: 41 0debug3: tty_make_modes: 50 1debug3: tty_make_modes: 51 1debug3: tty_make_modes: 52 0debug3: tty_make_modes: 53 1debug3: tty_make_modes: 54 1debug3: tty_make_modes: 55 1debug3: tty_make_modes: 56 0debug3: tty_make_modes: 57 0debug3: tty_make_modes: 58 0debug3: tty_make_modes: 59 1debug3: tty_make_modes: 60 1debug3: tty_make_modes: 61 1debug3: tty_make_modes: 62 0debug3: tty_make_modes: 70 1debug1: Sending environment.debug3: Ignored env GREP_COLORdebug3: Ignored env HOSTNAMEdebug3: Ignored env _debug2: channel 0: request shell confirm 0debug2: fd 3 setting TCP_NODELAYdebug2: callback donedebug2: channel 0: open confirm rwindow 0 rmax 32768debug2: channel 0: rcvd adjust 2097152Last login: Wed Jan 30 14:38:32 2013 from ld-chhfemd01.rocks.comKickstart-Installed Fri Oct 12 17:17:04 CDT 2012Red Hat Enterprise Linux Server release 5.8 (Tikanga)so it seems to log in but then hang. | I hang when I try to ssh into a machine with my username (or su to my user) | linux;ssh | null |
_webmaster.104679 | We recently moved our domain from monomachines.com --> supplychimp.comFollowed all the recommendations from various blog posts and told Google in Webmaster Tools that MonoMachines is now SupplyChimp. 301 redirects are all setup and working properly.The Issue:Google is using our OLD company/domain name for the new website.If you look at the indexed pages using site:supplychimp.com Google is using the wrong name. Anyone know how/why Google is using our old name? It's been 3 months now! | Old domain name appended to page titles in Google SERP | google search;301 redirect;serps;title | null |
_webmaster.7274 | Suppose I'm buying ads for keyword x and suddenly x becomes the biggest thing in the world. Will my budget run down faster? Will the price stay at the same rate I purchased that keyword on or will change with the popularity? | Peaking keywords on Google AdWords | seo;google adsense;keywords | As more people bid on an phrase the higher the cost of the phrase will be. So, yes, if that phrase becomes very popular your budget will run down faster as you can expect more bidders to enter that market. |
_vi.9783 | I have several useful search, search and replace and global commands written in my personal Vim reference. How can I easily turn some of them into one macro without recording (retyping everything)? | How to turn several commands into a macro without recording? | macro | Well, if you want turn them into a macro specifically, then this is pretty easy to do. The thing you need to know about macro registers is that they are exactly the same as text registers that you cut/copy/paste from. So if you had the following text on a line:iHello<esc>And you wanted to turn this into a macro, you could just go to the beginning of the line, type aD (delete line into register 'a'). Now, you can type @a and this will run that text as a macro, exactly the same as if you had recorded it. There's an even easier way to do the same thing, which is to directly assign the register. For example::let @a=iHello\<esc>or:call setreg('a', iHello\<esc>)But I'm guessing there is a simpler way to do what you want. If you just have some functions, or sets of keystrokes that you would like to be able to easily call, you could just make a new mapping. Preferably with <leader> to avoid conflicting with other mappings. Like this answer said, leader is essentially a namespace for your own mappings. I would add something like this to your .vimrcnnoremap <leader>h iHello<esc>However, if you would really prefer a macro, you could simply add let @a or setreg like I demonstrated. |
_codereview.106102 | Problem StatementYou are given time in AM/PM format. Convert this into a 24 hour format.Note Midnight is \$ 12:00:00AM \$ or \$ 00:00:00 \$ and 12 Noon is \$ 12:00:00PM. \$Input FormatInput consists of time in the AM/PM format i.e. hh:mm:ssAM or hh:mm:ssPM where \$ 01 \le hh \le 12 \$, \$ 00 \le mm \le 59 \$, \$ 00 \le ss \le 59 \$Output FormatYou need to print the time in 24 hour format i.e. hh:mm:ss where\$ 00 \le hh \le 23 \$, \$ 00 \le mm \le 59 \$, \$ 00 \le ss \le 59 \$Sample Input\$ 07:05:45PM \$Sample Output\$ 19:05:45 \$Solutionclass AbsTime(object): def __init__(self, hh, mm=0, ss=0, pm=False): self.hh = hh self.mm = mm self.ss = ss self.pm = pm def add(self, time): self.hh += time.hh self.mm += time.mm self.ss += time.ss if self.ss >= 60: self.ss -= 1 self.mm += 1 if self.mm >= 60: self.mm -= 1 self.hh = self.hh % 24 return self def midnight(self): return not self.pm and str(self) in ['00:00:00', '12:00:00'] def noon(self): return self.pm and str(self) == '12:00:00' def __str__(self): return {0:02d}:{1:02d}:{2:02d}.format(self.hh, self.mm, self.ss) def get(self): if self.midnight(): return AbsTime(0) if self.noon(): return AbsTime(12) if self.pm: if self.hh == 12: hh = self.hh else: hh = self.hh + 12 return AbsTime(hh, self.mm, self.ss) else: return AbsTime(self.hh % 12, self.mm, self.ss) @classmethod def create_from_string(cls, time): pm = True if time[-2:] == 'PM' else False hh, mm, ss = map(int, time[:-2].split(':')) return cls(hh, mm, ss, pm)def main(time): if time == '00:00:00': return time abstime = AbsTime.create_from_string(time) return abstime.get()if __name__ == '__main__': TIME = raw_input().strip() print main(TIME) #print main('00:00:00') #00:00:00 #print main('12:00:00PM') #12:00:00 #print main('12:00:00AM') #00:00:00 #print main('02:00:00PM') #14:00:00 #print main('02:00:00AM') #02:00:00 #print main('11:59:00AM') #11:59:00 #print main('12:59:00PM') #12:59:00 #print main('01:00:00PM') #13:00:00 #print main('11:59:59PM') #23:59:59 #print main('12:59:59AM') #00:59:59It really took me a while to do this simple solution, its fast when we do just structural programming but once I thought to step into OOP world things really got confusing. How can I improve this design? | Time Conversion Python implementation | python;object oriented;programming challenge;python 2.7 | null |
_softwareengineering.279773 | For a software project I am working on, we have a 'dev => QA => production' methodology. That is, we create a release candidate (deployed to Artifactory), give it to QA (deploy to QA systems and a QA backend/application server) who takes a week or so to look at it, and if they it's ok, we make a production release.Now, I come from an embedded/native app background, not as much Java/systems/CI. And I am accustomed to revision control organized with all releases tagged (in this case, the production release tags are always just copies of an RC tag). branches/1.2 branches/1.3 tags/1.2.0-rc tags/1.2.0 tags/1.3.0-rc tags/1.3.1-rc tags/1.3.1However, several team members state that this doesn't work well with Maven (and maybe Jenkins too). Instead, they suggest: branches/1.2.0-rc branches/1.3.0-rc branches/1.3.1-rc tags/1.2.0 tags/1.3.1I am arguing that a release candidate should not be a branch, as we need to deliver a known entity to QA (as opposed to a continuous integration/deployment situation where we might cut the production release directly from our development line without waiting for QA). The fact that several developers are checking code into the RC branch, and there is little control around it, has caused issues.Could somebody please explain if there's something about Maven or Jenkins that would make the second way better? Is there anything that makes the first way more difficult to implement? | Conventions for revision control with Maven/Jenkins | java;svn;maven;jenkins | null |
_webmaster.50136 | Customers to my website who are from the USA need to pay more P&P then UK customers. How do I make a PayPal button which charges a different amount depending on the country the user is from? | PayPal buy now button to charge different amount depending on the country the user is from | paypal;internationalization | null |
_unix.90446 | I have a remote Linux server and I use it to run some very long tasks using SSH. It works great, but, of course, if the connection dies for some reason, the task dies.Specifically, I'm running something like this:[myName@localStation]$ ssh john_doe@myRemoteServerPassword: *****[john_doe@remoteServer]$ ./myVeryLongTask.script > myOutputLog.txtIs there a way to tweak the SSH connection in such a way that, if the network connection fails, the task keeps running? | How to run script using SSH from remote computer and avoid its interruption if remote computer goes offline | bash;ssh | You need to read up on the screen command (here's a quick google result)Screen allows you to leave a remote connection running and come back to it for reasons exactly as you describe. It's also useful for running unattended jobs or keeping sessions open indefinitely.'man screen' for more infoEDIT: Here's a better link to a HOWTO: screen: Keep Your Processes Running Despite A Dropped Connection |
_softwareengineering.184815 | Im trying to create an SMS gateway .. I have a request coming in from a client (web form or API or database record) that I need to process and forward on to a 3rd Party API - or SMS provider. So that things would be simpler going forward I decided to create an interface that each provider implementation would implement :interface SMSProvider public method sendSMS(sendTo,message) public method sendWakeup(sendTo)I thought this would be my best way forward because then I wouldn't have to change my code when sending to a different provider - i knew that when i create my provider i just call the method to perform the function with the normal parameters and everything is good ... Well until I have a new provider that requires new parametersnew provider requires - sendTo - message - sendFrom - validityPeriodSo now what do i do ? how can i now use my interface ? when the new provider needs extra parameters ? | Class inheritance and extra parameters | object oriented;interfaces | The usual practice in this case is to wrap arguments of interface methods into abstract classes and have implementing classes instantiate certain variation of the abstraction. So,interface SMSProviderpublic method sendSMS(SMSMessage)public method sendWakeup(WakeupMessage)class SMSProvider1public method sendSMS(Provider1SpecificSMSMessage)public method sendWakeup(Provider1SpecificWakeupMessage)class SMSProvider2public method sendSMS(Provider2SpecificSMSMessage)public method sendWakeup(Provider2SpecificWakeupMessage)abstract class SMSMessagestring sendTostring messageclass Provider1SpecificSMSMessage :: SMSMessage/*fields from base class plus customizations*/class Provider2SpecificSMSMessage :: SMSMessage/*fields from base class plus customizations*/[Sorry, not sure what language you're dealing with] |
_codereview.160484 | I have written an implementation for sentence generation using Markov Chains. Would be great if you could review it. #!/usr/bin/env python# -*- coding: utf-8 -*-import osimport randomfrom markovipy.utils import get_word_listfrom markovipy.utils import list_to_tuplefrom markovipy.constants import PUNCTUATIONSclass MarkoviPy: def __init__(self, filename=, markov_length=2): starting_word: keeps track of the words from which sentences would be starting out. TODO: - instead of storing final_mapping and middle_mapping on memory, put them on a tiny DB(Sqlite comes to my mind) :type markov_length: <int> defaults to 2 :type filename: <str> defaults to an empty string self.starting_words = [] self.middle_mapping = {} self.final_mapping = {} self.words_list = [] self.markov_length = markov_length if os.path.exists(filename): self.filename = filename else: raise FileNotFoundError(Please enter a valid file name for corpus) def _normalise_mapping(self): creates the self.final_mapping with the final probabilities in similar structure { ... ('with',): {'Till': 0.2, 'a': 0.2, 'darkness': 0.2, 'such': 0.2, 'whispering': 0.2}, ('word',): {',': 0.6666666666666666, 'within': 0.3333333333333333}, ('word', ','): {'Swaddled': 0.5, 'unable': 0.5}, ... } :return: for word_tuple, probable_word in self.middle_mapping.items(): total = sum(probable_word.values()) self.final_mapping[word_tuple] = dict([(k, v / total) for k, v in probable_word.items()]) def _build_middle_mapping(self, word_history, next_word): Adds next_word to the list of possible next words after the sequence presented in word_history. maps the occurrence of the words after one another in a <dict> called 'middle_mapping'. This would just be a <dict> which would contain a - <tuple> as the key, inside the <tuple> you would be having the sequence of the words one after the another - and the value would be <dict> eg: word_history = [it, rained, on] and next_word = a, then it will create a mapping where for the sequences [it, rained, on], [it, rained], [rained, on] and [on]. The next word for them would be a Something like this self.middle_mapping -> {('Once', 'upon'): {'a': 1.0}, ('upon',): {'a': 1.0}} Finally,method builds something like this inside self.middle_mapping { ... ('youth',): {',': 1.0, '.': 5.0, 'about': 1.0, 'and': 4.0, 'is': 1.0, 'saint': 1.0, 'stirred': 1.0, 'was': 1.0}, ('youth', ','): {'a': 1.0}, ... } :param word_history: <list> of contiguous words :param next_word: next word in the sequence of the <list> word_history :return: while len(word_history) > 0: key = list_to_tuple(word_history) if key not in self.middle_mapping: self.middle_mapping[key] = {} self.middle_mapping[key][next_word] = 1.0 else: if next_word in self.middle_mapping[key]: self.middle_mapping[key][next_word] += 1 else: self.middle_mapping[key][next_word] = 1.0 word_history = word_history[1:] def _iterate_through_word_list(self): Picks out pair of words with accordance to the length of the markov chain to be created and passes the chain as a list and the next word to self._build_middle_mapping() :return: self.words_list = get_word_list(self.filename) self.starting_words.append(self.words_list[0]) for i in range(1, len(self.words_list) - 1): if i < self.markov_length: word_history = self.words_list[:i + 1] elif i >= self.markov_length: word_history = self.words_list[i - self.markov_length + 1:i + 1] next_word = self.words_list[i + 1] # if the last word was a period, add the next word to self.starting_word if word_history[-1] == . and next_word not in list(PUNCTUATIONS): self.starting_words.append(next_word) self._build_middle_mapping(word_history, next_word) self._normalise_mapping() def _next(self, prev_list): Decides on the next word to be selected for :param prev_list: :return: <str> probabilty_sum = 0.0 next_word = index = random.random() # Shorten prevList until it's in mapping while list_to_tuple(prev_list) not in self.final_mapping: prev_list.pop(0) # Get a random word from the mapping, given prevList for k, v in self.final_mapping[list_to_tuple(prev_list)].items(): probabilty_sum += v if probabilty_sum >= index and next_word == : next_word = k break return next_word def generate_sentence(self): Returns a generic sentence using markov chains :return: <str> Generated sentence self._iterate_through_word_list() # Start with a random starting word current_word = random.choice(self.starting_words) sent = current_word.capitalize() prev_list = [current_word] # Keep adding words until we hit a period while (current_word != .): current_word = self._next(prev_list) prev_list.append(current_word) # if the prevList has gotten too long, trim it if len(prev_list) > self.markov_length: prev_list.pop(0) if (current_word not in list(.,!?;)): sent += # Add spaces between words (but not punctuation) sent += current_word return sentEDIT: Github linkhttps://github.com/prodicus/markovipy | Sentence generation using Markov Chains | python;markov chain | null |
_cs.19049 | For my homework I have a problem that I can't solve and it makes me wonder about 2 different MST:Let $G=(V,E)$ be a graph that has a minimum spanning tree $T$.I want to find another minimum spanning tree $T'$ that has at least 1 different edge $e'$ such that the weight of $e'$ is differ from any weight of edges in $T$.If $T'$ doesn't exist I can claim that every 2 different MST must have the same weight for each edge. My intuition says that this claim is wrong but on the other hand I can't find example of $T'$ to contradict this claim. | Find a diffrent minimal spanning tree for a graph | algorithms;graph theory;graphs;spanning trees | You cannot find such a MST. Every two minimal spanning trees must have the same multiset of edge-weights.Actually you can find the proof in the link that Raphael added:Do the minimum spanning trees of a weighted graph have the same number of edges with a given weight? |
_unix.40378 | I'm working on a VPS which I can control with PuTTY and FreeNX.I don't have enough RAM for Gnome, so I want fluxbox to start by default instead of Gnome. how do I do that? | how do I enable fluxbox instead of Gnome by default in Ubuntu | ubuntu;gnome;fluxbox | null |
_cstheory.9186 | Colloquially, the definition of the matrix-multiplication exponent $\omega$ is the smallest value for which there is a known $n^{\omega}$ matrix-multiplication algorithm. This is not acceptable as a formal mathematical definition, so I guess the technical definition is something like the infimum over all $t$ such that there exists a matrix-multiplication algorithm in $n^t$.In this case, we cannot say there is an algorithm for matrix-multiplication in $n^{\omega}$ or even $n^{\omega + o(1)}$, merely that for all $\epsilon > 0$ there exists an algorithm in $n^{\omega + \epsilon}$. Often, however, papers and results which use matrix-multiplication will report their cost as simply $O(n^{\omega})$.Is there some alternate definition of $\omega$ that permits this usage? Are there any results that guarantee that an algorithm of time $n^{\omega}$ or $n^{\omega + o(1)}$ must exist? Or is the usage $O(n^{\omega})$ simply sloppy? | Definition of matrix-multiplication exponent $\omega$ | ds.algorithms;linear algebra | null |
_unix.101193 | I have Ubuntu installed on a Raspberry pi. I have a normal user pi, but I forgot the password. However, I do have root access.How would I change pi's password using root? | change regular user's password with root access | ubuntu;password | Simply do :passwd usernamein your case passwd pi |
_unix.222538 | I spent quite some time tracking down a problem in production recently, where a database server disappearing would cause a hang of up to 2 hours (long wait for a poll() call in the libpq client library) for a connected client. Digging into the problem, I realized that these kernel parameters should be adjusted way down in order for severed TCP connections to be noticed in a timely fashion:net.ipv4.tcp_keepalive_time = 7200net.ipv4.tcp_keepalive_probes = 9net.ipv4.tcp_keepalive_intvl = 75net.ipv4.tcp_retries2 = 15The four values above are from an Ubuntu 12.04 machine, and it looks like these defaults are unchanged from current Linux kernel defaults.These settings seem to be heavily biased towards keeping an existing connection open, and being extremely stingy with keepalive probes. AIUI, the default tcp_keepalive_time of 2 hours means when we're waiting for a response for a remote host, we will wait patiently for 2 hours before initiating a keepalive probe to verify our connection is still valid. And then, if the remote host does not respond to a keepalive probe, we retry those keepalive probes 9 times (tcp_keepalive_probes), spaced 75 seconds apart (tcp_keepalive_intvl), so that's an extra 11 minutes before we decide the connection is really dead.This matches what I've seen in the field: for example, if I start a psql session connected to a remote PostgreSQL instance, with some query waiting on a response, e.g.SELECT pg_sleep(30);and then have the remote server die a horrible death (e.g. drop traffic to that machine), I see my psql session waiting for up to 2 hours and 11 minutes before it figures out its connection is dead. As you might imagine, these default settings cause serious problems for code which we have talking to a database during, say, a database failover event. Turning these knobs down has helped a lot! And I see that I'm not alone in recommending these defaults be adjusted.So my questions are: How long have the defaults been like this?What was the original rationale for making these TCP settings the default?Do any Linux distros change these default values?And any other history or perspective on the rationale for these settings would be appreciated. | How were these Linux TCP default settings decided? | linux;tcp;history | RFC 1122 specifies in section 4.2.3.6 that the keep-alive period must not default to less than two hours. |
_codereview.166038 | I made a function that takes an argument x and returns True if x is a prime number and False if x is a non-prime number.I am a beginner and think the code can be improved. I had to add the else statement because for is_prime(2), I kept getting None instead of True. I think this was because when x is 2, list_n = range(2,2) prints []. Are there ways I could change this so there is not a separate else statement?def is_prime(x): list_n = range(2,x) if x <= 1: return False elif x-1>2: for n in range(len(list_n)): list_n[n] = x % list_n[n] for n in list_n: if n == 0: return False for n in list_n: if n > 0: return True else: return True | Determine if number is a prime number | python;beginner;primes | null |
_unix.367641 | I have a lot of music in a tree under one directory, saved in whatever format I initially got it in, for quality. I have a second directory tree which is similar in structure, but with all files in a lossy-compressed format playable by my phone, and with occasional metadata changes (e.g. removing embedded covers to save space).It occurs to me that for a significant portion of the music, there is no difference between the two instances - generally when the distributed version was only available as mp3/ogg and didn't have embedded covers. Hard drive space may be cheap, but that's no reason to waste it. Is there a way to script:Check for identical files in two directoriesWhenever identical files are found, replace one with a hardlink to the otherWithout e.g. taking the time to get a full diff, in the interest of timeBut still without the risk of accidentally deleting a copy of two non-identical files, which is a remote but nonzero chance if I were to e.g. just compare hashes? | Convert identical files to hardlinks | files;diff;hard link;hashsum;disk cleanup | null |
_unix.205428 | I just bought a raspberry pi and want to start using it as a NAS. I'm fairly new to this, but I've gotten this far..I've got an external hard drive (freshly formatted NTFS) connected with a USB cable to my raspberry pi and am connected through SSH terminal (I dont have an external display to use).Everytime my pi reboots I have to remount the drive in order to use it. I added this line to /etc/fstab file /dev/sda1 /media/NAS ntfs-3g defaults 0 0For as far as I understand, thats all I need to make my raspberry pi auto mount my USB hard drive as soon as it reboots.What am I doing wrong? | USB hard drive doesn't auto mount | automounting | null |
_cs.40275 | Given an un-rooted tree with N nodes, numbered from 1 to N. Each edge of the tree has a positive integer, associated with it. We need to calculate the number of unordered pairs (S, T) of tree's nodes such that the greatest common divisor of all the integers associated with the edges of the path between S and T is equal to one. Of course, we consider only the pairs where S isn't equal to T.But main problem is N (Number of nodes in tree is 100000) So is their any better solution than O(N^2) as I currently have O(N^2) approach to do this problem using LCA between 2 nodes of tree.So given a tree with N nodes and N-1 edges can we have a better algorithm ? | Count pairs of nodes in a tree that are connected by a path whose labels have gcd 1 | algorithms;trees;counting | null |
_cstheory.5695 | One of the amazing things about computer science is that the physical implementation is in some sense irrelevant.People have successfully built computers out of several different substrates -- relays, vacuum tubes, discrete transistors, etc.People may soon succeed in building Turing-complete computers out of non-linear optical materials, various biomolecules, and a few other substrates.In principle, it seems possible to build a billiard-ball computer.However, the physical substrate is not completely irrelevant.People have found that certain sets of components -- in particular,diode-resistor logic --are incomplete: no matter how many of them you connect to a power supply and to each other, there are certain very simple things that it cannot do.(The diode-resistor logic can implement AND, OR, but fails to implement NOT).Also, certain ways of connecting components -- in particular, single-layer perceptrons -- are incomplete: there are certain very simple things that they cannot do.(A single-layer perceptron can implement AND, OR, NOT, but fails to implement XOR).Is there a less-awkward phrase for physical things out of which one can build a Turing machine?Or for the opposite, physical things that, no matter how many of them one has, cannot form a Turing machine?For a while I used the phrase functionally complete set or universal set of gates -- or, when speaking to mathematicians, physical things that can implement a functionally complete set -- but I've been told that isn't quite correct.Some sets of components can implement a functionally complete set;and yet it is not possible to build a Turing-complete machine entirely out of these components.For example, light bulbs and manually-operated 4-way light switches can implement a functionally complete set (AND, OR, NOT, XOR, etc.);and yet it is not possible to build a Turing-complete machine entirely out of light switches and light bulbs, since the (electrical or optical) output of one cannot be fed into the (mechanically rotating) input of the next.related: Is there an official name for a notion of reusably universal? and Is there a name for chips out of which one can build a CPU? | Is there a name for physical things out of which one can build a Turing machine? | computability;turing machines;terminology;physics;natural computing | I believe an appropriate term is a Turing Machine physical implementation.The main problem with any implementation is how to provide infinite tape or in a more abstract level, infinite memory. An easy solution to this problem is to use a special symbol to indicate the last tape square. When a Turing Machine reaches it, it enters a special state which requires user intervention, who is supplying extra tape. Then, the TM can continue its operation. Unfortunately, such implementations being physical involve physics. If the universe is finite and due to the Planck scale, there is a finite amount of tape available. This is where problems arise that perhaps cannot be answered by computer scientists but by physicists. Note that physicists have not reached a conclusion on those matters, which are considered major open problems of the magnitude of $P \neq NP$, so it would be unlikely that a computer scientist would resolve them.You can read more in Scott Aaronson's paper NP-complete Problems and Physical Reality , especially in the Analog and Relativity computing section.You can also find a lego implementation (with finite tape) in the following page: http://legoofdoom.blogspot.com/ |
_softwareengineering.147698 | I have read different opinions about the singleton pattern.Some maintain that it should be avoided at all costs and othersthat it can be be useful in certain situations.One situation in which I use singletons is when I need a factory(let's say an object f of type F) to create objects of a certain class A.The factory is created once using some configuration parameters and thenis used each time an object of type A is instantiated. So every part ofthe code that wants to instantiate A fetches the singleton f and createthe new instance, e.g.F& f = F::instance();boost::shared_ptr<A> a = f.createA();So the general my scenario is thatI need only one instance of a class either for optimization reasons (I do not need multiple factory objects) or for sharing common state (e.g. the factory knows how many instances of A it can still create)I need a way to have access to this instance f of F in different places of the code.I am not interested in the discussion whether this pattern is good or bad,but assuming I want to avoid using a singleton, what other pattern can I use?The ideas I had were (1) to get the factory object from a registry or(2) to create the factory at some point during program start up and thenpass the factory around as a parameter.In solution (1), the registry itself is a singleton, so I have just shiftedthe problem of not using a singleton from the factory to the registry.In case (2) I need some initial source (object) from which the factory objectcomes so I am afraid that I would again fall back to another singleton(the object that provides my factory instance).By following back this chain of singletons I can maybe reduce the problemto one singleton (the whole application) by which all other singletonsare directly or indirectly managed.Would this last option (using one initial singleton that creates all otherunique objects and injects all other singletons at the rightplaces) be an acceptable solution?Is this the solution that is implicitly suggested when one advises not touse singletons, or what are other solutions, e.g. inthe example illustrated above?EDITSince I think the point of my question has been misunderstood by some,here is some more information. As explained e.g. here, the wordsingleton can indicate (a) a class with a single instance object and(b) a design pattern used to create and access such an object.To make things clearer let us use the term unique object for (a) andsingleton pattern for (b). So, I know what the singleton patternand dependency injection are (BTW, lately I've been using DI heavilyto remove instances of the singleton pattern from some code I am working on).My point is that unless the whole object graph is instantiated froma single object living on the stack of the main method, there will always bethe need to access some unique objects through the singleton pattern.My question is whether having the complete object graph creation andwiring depend on the main method (e.g. through some powerful DI frameworkthat does not use the pattern itself) is the onlysingleton-pattern free solution. | Alternatives to the singleton pattern | design patterns;programming practices;anti patterns;singleton | Your second option is a fine way to go -- it's a kind of dependency injection, which is the pattern used to share state across your program when you want to avoid singletons and global variables.You can't get around the fact that something has to create your factory. If that something happens to be the application, so be it. The important point is that your factory shouldn't care what object created it, and the objects that receive the factory shouldn't depend on where the factory came from. Don't have your objects get a pointer to the application singleton and ask it for the factory; have your application create the factory and give it to those objects that will need it. |
_softwareengineering.326135 | I have some SQL commands that I am trying to figure out the best way to have them in code so that:1. They are very readable2. They would be easy to update3. They won't be performance overhead due to many string construction. I have something like the following that did not turn out too good. public class SQLHandler { private static final String CUSTOMER_TABLE = customer_table; private static final String CUSTOMER_ID = id; private static final String CUSTOMER_FIRST_NAME = first_name; private static final String CUSTOMER_LAST_NAME = last_name; private static final String CUSTOMER_TELEPHONE = customer_telephone; private static final String REP_ID = customer_representative_id; private static final String REP_TABLE = representative_table; private static final String REP_ID = id; private static final String REP_FIRST_NAME = first_name; private static final String LAST_LAST_NAME = last_name; private static final String DEPT_ID = rep_dep_id; public static ArrayList<Representatives> getRepresentatives(int customerId) { StringBuilder sb = new StringBuilder(); sb.append(SELECT) .append(REP_TABLE).append(.).append(REP_ID) .append(,) .append(REP_TABLE) .append(.) .append(REP_FIRST_NAME).append( FROM) .append(CUSTOMER_TABLE).append( JOIN ).append(REP_TABLE) .append(ON).append(REP_TABLE).append(.) .append(REP_ID).append(=).append(CUSTOMER_TABLE) .append(.).append(REP_ID) .append( AND) .append(CUSTOMER_TABLE).append(.).append(CUSTOMER_ID) .append(=).append(String.valueOf(customerId)); // do query } } As you can see none of the (3) are met.I can't easily update the query and if I saw it again I wouldn't remember exactly what was it.How can I improve this? (Couldn't format it properly in post) | How to create multiline strings for sql queries that are readable, maintainable and fast? | java;performance;clean code;strings | null |
_vi.3814 | I recently realized that my vimrc is now more than 400 lines long (which IMO is too much I'll try to reduce that) and to make it easier to navigate, read and edit it I decided to investigate the concept of folding in vim (which I wasn't familiar with).I tried to set the folding method to indent but I didn't like the result (It was too messy mostly because a great part of my vimrc isn't really indented). I also tried to set foldmethod to expr and syntax but I wasn't able to fold anything properly.Here using diff as folding method doesn't seem relevant. (Or if it is I didn't understand how to use it)So for now I'm using the marker method which doesn't totally satisfy me because of the {{{ and }}} markers which I found noisy in the file.So I'd like to know if there are best practices or common guidelines about properly folding a vimrc. Note 1: As we all know SO isn't a forum and isn't made to collect personal opinions and that's not what I'm looking for: of course I guess some people has their preferences but I'd like to know why using markers (for example) improves the readability more than using indent.Note 2: Also my main goal is to make my vimrc as clear as possible so if other best practices exists to create a nice vimrc I'm curious about it.Edit 1: I should have precised that my vimrc is already subdivided in sections (and sometimes subsection) the main ones being general optionsplugins (containing a subsection for each plugin and its configuration)mappingsnavigation (also containing subsection)coloretc...And it's this structure which made me thought of folding: I feel that being able to output only the section I'm interested in at a certain point is something pretty convenient.Edit 2: Answer mentioning subdivisions of the vimrc in several files are valid, but as a personal preference I'd rather use folding because I think it is easier to maintain only one file in the git repo containing my dotfiles. That is only a personal preference and I'm aware that is it possible to also use this approach but I'd prefer to use folding. | Is there a best practice to fold a vimrc file | vimrc;folding | null |
_unix.184749 | I will need to install a custom application as a service on a RHEL 6.2 box this weekend. Will I be able to do this with sudoer powers or will I need the root password for anything? | Will I be able to install a service as a sudoer? | rhel;sudo;root;services | null |
_reverseengineering.8911 | I've written a simple code to get a student information like name and ID, but in the code when I want to get input the interrupt doesn't work I mean int 21h/ah=0AhIt pauses when the interrupt is reached but just accepts Enter from keyboard not any number or characters, here my code :stack segment dw 128 dup (?)stack endsdata segment name0 db 30,?,30 dup('$') id0 db 10,?,10 dup('$') menu db 1-Enter student name:,0Dh,0Ah db 2-Enter student ID:,0Dh,0Ah db 3-Printing the student name and ID:,0Dh,0Ah, db 4-Exit,0Dh,0Ah db Please Select :,'$' selection db 1,?,4 show0 db (s)he is ,'$' show1 db his/her ID ,'$' ; address1 db 2 dup(?) ; address2 db 2 dup(?)data ends code segmentstart:; set segment registers: mov ax, data mov ds, ax ;mov ax, data1 mov es, ax push bp mov bp,sp xor cx,cxloop1: ;cx is reserved push offset menu call print lea dx,selection mov ah,0Ah int 21h ; <----- doesn't work lea bx,selection mov cl,[bx+2] cmp cl,1 je getname_scope cmp cl,2 je getid_scope cmp cl,3 je showinforet0: cmp cl,4 jne loop1 jmp exit getname_scope: mov bx, offset name0 push bx call Get jmp ret0 getid_scope: lea bx,id0 push bx call Get jmp ret0 showinfo: push offset show0 call print push offset name0+2 call print push offset show1 call print push offset id0+2 call print jmp ret0exit: ; wait for any key.... mov ah, 1 int 21h pop bp mov ax, 4c00h ; exit to operating system. int 21h code endsproc Get near push bp mov bp,sp lea dx,[bp+4] mov ah,0Ah int 21h pop bp retGet endpproc print near push bp mov bp,sp mov dx,[bp+4] mov ah, 9 int 21h pop bp ret end start ; set entry point and stop the assembler.what's wrong with the code ? how to | Why int 21h/ ah=0Ah doesn't work in emu86 | assembly | null |
_softwareengineering.66740 | What language should I seek to learn if I would like to develop for Windows? Not command-line stuff (obviously, I guess) but with Windows Forms and such? I've used C before (when working with Rockbox), but that's it. Up until now, I've used Autoit (for basic, simple stuff), but I'm looking for something that has more flexibility and is popular inside of the PC software industry. Plus, I didn't like how easy it was to crack Autoit programs. I'm also a web developer/designer, just to throw that out there.Thanks in advance! | What language should I seek to learn if I would like to develop for Windows? | programming languages;windows | C#I recommend C# as the language to learn. The syntax is C-like, which will help you get started.The language is object-oriented, and it's good to learn that way of thinking.Visual Studio Express is a free download, so it doesn't cost much to start.There are lots of open source projects in C# to look at and learn from.It's applicable to web-sites or standalone applications.If you want to get funky, there are lots of nice features to the language, like lambdas to bend your mind. |
_codereview.93147 | I am programming a graphical text adventure using python. The game is playable, but I am not sure whether the code is well-suited for newcomers (code smells / quirks / general readability). Here's the main script:import timeimport sysimport printerfrom rooms import *from _player import PlayerVER = 0.01SCENES = {0 : Lobby(), 1 : LivingRoom(), 2 : Bathroom()}player = Player()def run(start_at=None): Starts the game if not start_at: scene = SCENES[0] else: scene = SCENES[start_at] scene.init_player(player) while 1: new_scene = scene.run() if new_scene != None: scene = SCENES[new_scene] scene.init_player(player)if __name__ == __main__: run() | Run loop for a text-based adventure game | python;adventure game | null |
_unix.261121 | Everywhere I look I see that screen is for keeping a session open so that you can come back to it after disconnection. But this doesn't seem to be the case for a system that I ssh to. Do I understand correctly, that the sysadmins have crippled nohup and screen? Is there a way to circumvent this?Here is a test I did (perhaps the problem is me):mira1:~> screen -S test COMMENT: I did ctrl-a ctrl-d[detached from 54211.test]mira1:~> logoutConnection to mira1.**** closed.me:~ me$ ssh me@mira1.***Last login: Tue Feb 9 23:21:57 2016 from client*****mira1:~> screen -lsNo Sockets found in /var/run/screen/S-me.Edit:The screen is still there after detaching it and before logging out. As in:mira1:~> screen -S test[detached from 59923.test]mira1:~> ls -ltr /var/run/screen/S-me/total 0prw------- 1 me URP_dse 0 Feb 9 23:39 59923.testmira1:~> Edit 2 for Gile's questions:Here is ssh session #1mira1:~> screen -lsThere is a screen on: 59923.test (09/02/16 23:39:26) (Detached)1 Socket in /var/run/screen/S-me.mira1:~> screen -r[detached from 59923.test]ssh session #2mira1:~> screen -lsThere is a screen on: 59923.test (09/02/16 23:39:26) (Detached)1 Socket in /var/run/screen/S-me.ssh sesssion #1 againmira1:~> logoutConnection to mira1.**** closed.client-10-129-225-10:~ me$ ssh session #2 again (screen gone)mira1:~> screen -lsNo Sockets found in /var/run/screen/S-me. | Circumvent deletion of screen session and nohup processes on logout | ssh;gnu screen;nohup | null |
_softwareengineering.309565 | I am working on a C# programming project in Visual Studio. I have created various VS library projects inside the VS solution containing the various components of the solution. Without giving it too much thought, I have put the factories for these components into their corresponding VS projects.I have now needed to reuse one of these components inside another VS solution and realized that having the factory inside the components VS project may not be the correct way, since in the new project I have different requirements for the factory to construct the object (e.g. parameters, etc.). So this would suggest, that the factory should not form part of the components VS project.On the other hand factories appear to be very closely bound to the components/objects they construct. For me this raises the question, where I should put them:Should factories be part of the solution using the components library or should it be part of the library? | Project structure: Where to put object factories | c#;visual studio;factory | TLDRIt depends on how configurable and extendable you want to have the reusable library (project), without touching it.In the end you either have factories in the library itself, or the library does not have them and the client (the user) of the library is responsible for creating them and instantiating the library himself.Longer answerNo matter how object oriented your code is, a part of OO code will always have to be procedural. The part where the object graph is constructed, the newing of the classes.When dealing with construction of classes belonging to another project (this will usually be some common library which contains code useful throughout more projects), you usually have two options how to expose the project to the outer world.For this demostration purpose I chose the cache layer, which, from my experience, usually has very similar API throghout many different projects, only the configuration is different.1. Creating a public endpoint of the library to expose itIf you were to follow this ideology, all the classes inside your cache library project would be set to internal except one class, perhaps a YourNamespace.Library.Cache class, which would be set to public, thus if you were to use the cache library, the only class you would have publicly access to is one single endpoint.The YourNamespace.Library.Cache class constructor could look like this:public class Cache : CachingInterface{ public Cache(string configuration) { // this is where the magic happens }}Not saying very much, is it? What exactly is the magic I am talking about?Notice the configuration string as a parameter. It is a variable in which you define what you want to have, you insert your configuration, and this one public endpoint, the YourNamespace.Library.Cache class, will, in its constructor, parse this string, extract the data it needs from it, and based on the user input construct everything necessary.Inside this constructor the Cache endpoint will instantiate the factories belonging to the cache project, it will the use those to instantiate the correct implementations.In your main project, the code then could be as simple as this:var cache = new YourNamespace.Library.Cache(type:redis,connection:[schema:tcp,host:localhost,port:3000,database:master],options:[replication:true]);By parsing the string, the constructor will then see, you want to cache to redis, and provided the configuration, it will use the configuration and pass it onto the internal classes of the cache library, which know what to do with it.Be aware the configuration does not need to be a string, you may use whatever you want.The placement of the factoriesWhen using this approach, the factories are inside the cache project. In fact, the one public endpoint, the Cache class, acts as a factory itself.The project itself calls new on desired object based on the configuration string and after the construction of the endpoint, should it not throw an exception, you are set to use all the functionality of the library.The goodthe construction of a very complex library is simplified to one single endpoint, which only requires some configuration (be it a string, an array,...) described in documentationyou do not expose the internal parts of the library, so as long as you do not change the endpoint, you can optimize it, release new versions and the clients of this library need not to change anything in their codeThe badif someone uses your library and wants to add his custom caching mechanism (perhaps a faster Redis driver or a completely new caching mechanism), he has to contact the owner of the library the add ityou need to create thorough documentation, so people know, how to use the endpoint and what configuration it offers2. Exposing everything inside the library and letting the client of the library decide what he wants to constructUsing this approach, (almost) all classes inside the cache library will be set to public, all the interfaces, all the implementations, everything.Besides the unit tests part of the cache library, there will probably be no usage of the new keyword inside the cache library. The library itself will not construct anything, it will only provide constructors and methods with predefined types of parameters, to let you know which exact class you will need if you want to instantiate a class.The placement of the factoriesConsidering the cache library itself does not construct anything, the only place where you will have the factories is your main project, or the project of the client using the library.The client himself will be responsible for constructing the object graph, by newing the dependencies, until he creates the final object representing the cache itself.The goodthe library is very easily extendable by the end user, would he want to use some custom implementation of a part of the library, he simply needs to adhere to the contract presented by the type of an object a class requires for its construction, perhaps by implementing an interface or extending a classthe creator of the library itself does not need to create a lot of documentation describing the construction, because by following the dependency injection principle, it is always pretty clear, which other classes you need in order to construct the class you desirethe client may very easily manipulate concrete implementations to make the library suitable for the project he is using it inThe badthe construction in client code may become (really) uglyYou are likely to see something like this in the client code:var depOne = new One();var depTwo = new Two(depOne);var depThree = new Three(depTwo);var depFour = new Four(depThree);// ...var depTwentySeven = new TwentySeven(depTwentySix);var cache = new Cache(depTwentySeven);This is an extreme example, the amount of dependencies would probably vary, based on the type of cache you would like to construct, but it can happen.because the client is responsible for creating all the dependencies, some of them may use the first pattern I am describing in this example for construction, meaning the client of the cache library is forced to check the documentation of the third party library to know how he is supposed to construct the dependency for the cache library.SummaryBefore diving in, you should decide, what it is you want.If you want to encapsulate the library and want to have it its own environment and hide its complexity behind a simple abstraction layer, I would say go with a variation the first approach.I would also use the first approach when I wanted to reflect all the internal changes in the library in all the projects where the library is used.If you want the library to be easily extendable and you are likely to provide custom implementations, go with approach number two, where the library is not responsible for the construction, but gives clues on how the construction should happen.But be aware, that change in the library will most likely need more change in the client code.There is also always the third approach, which is a result of combining the first and second together, where then there are factories in both the library itself and also the client code. |
_codereview.157562 | Just looking for some feedback regarding how to optimize my code. It works, but just want some feedback on how to improve the solution.Requirements:Prompt for and read a number between 1 and 5. Repeat this step until the input is 1..5.Repeat the following multiple times according to the number read in step 1.a. Read in a list of integers ending with a 0. The 0 marks the end ofthe input and is not considered part of the listb. Print the largest and smallest integers in the list.c. If only a zero appears in the list, print an error messageCODE:import java.util.ArrayList;import java.util.Collections;import java.util.Scanner;public class SIMPLE_NUMBER_PROGRAM { public static void main(String[] args) { int input = prompt(); ArrayList<Integer> inputList; inputList = new ArrayList(); Integer min; Integer max; if (input == 0 && inputList.isEmpty()) { System.out.println(error: empty list!); } else { while (input < 1 && input != 0 || input > 5 && input != 0) { input = prompt(); } while (input >= 1 && input <= 5) { inputList.add(input); input = prompt(); } min = Collections.min(inputList); max = Collections.max(inputList); System.out.println(Min: + min + \n + Max: + max); } } private static int prompt() { Scanner sc = new Scanner(System.in); System.out.println(Enter a number: ); return sc.nextInt(); }} | Read numbers between 1 and 5, then print the minimum and maximum | java;beginner | You really only need 1 while loop that loops on the condition that your input != 0. Then as you get your input you either add it to your list if the input is between 1-5, ignore all other values and when a 0 is entered the looping exits and you can determine max,min if possible. Try this ArrayList<Integer> inputList = new ArrayList(); Integer min; Integer max; int input = -1; while(input != 0) { input = prompt(); if(input > 0 && input < 6) { inputList.add(input); } } if(inputList.size() == 0) System.out.print(Error, No Valid Numbers Entered); else { min = Collections.min(inputList); max = Collections.max(inputList); System.out.println(Min: + min + \n + Max: + max); } |
_webapps.31284 | I just had this question. The title really just says it allif I import email from another account (not a Gmail one) into Gmail, will old sent email also get imported? And will it appear as sent in Gmail? | If I import email from another email account into Gmail, will sent email also be imported? And will appear as sent in Gmail? | gmail;email;import | null |
_cstheory.13943 | Is there a linear time in-place riffle shuffle algorithm? This is the algorithm that some especially dextrous hands are capable of performing: evenly dividing an even-sized input array, and then interleaving the elements of the two halves.Mathworld has a brief page on riffle shuffle. In particular, I'm interested in the out-shuffle variety which transforms the input array 1 2 3 4 5 6 into 1 4 2 5 3 6. Note that in their definition, the input length is $2n$.It's straightforward to perform this in linear time if we've got a second array of size $n$ or more handy. First copy the last $n$ elements to the array. Then, assuming 0-based indexing, copy the first $n$ elements from indices $[0,1,2,...,n-1]$ to $[0, 2, 4,...,2n-2]$. Then copy the $n$ elements from the second array back to the input array, mapping indices $[0,1,2,...,n-1]$ to $[1,3,5,...,2n-1]$. (We can do slightly less work than that, because the first and last elements in the input do not move.)One way of attempting to do this in-place involves the decomposition of the permutation into disjoint cycles, and then rearranging the elements according to each cycle. Again, assuming 0-based indexing, the permutation involved in the 6 element case is$$\sigma=\begin{pmatrix} 0 & 1 & 2 & 3 & 4 & 5 \\0 & 2 & 4 & 1 & 3 & 5\end{pmatrix}=\begin{pmatrix}0 \end{pmatrix} \begin{pmatrix}5 \end{pmatrix} \begin{pmatrix}1 & 2 & 4 &3 \end{pmatrix}.$$As expected, the first and last elements are fixed points, and if we permute the middle 4 elements we get the expected outcome.Unfortunately, my understanding of the mathematics of permutations (and their $\LaTeX$) is mostly based on wikipedia, and I don't know if this can be done in linear time. Maybe the permutations involved in this shuffling can be quickly decomposed? Also, we don't even need the complete decomposition. Just determining a single element of each of the disjoint cycles would suffice, since we can reconstruct the cycle from one of its elements. Maybe a completely different approach is required.Good resources on the related mathematics are just as valuable as an algorithm. Thanks! | Linear time in-place riffle shuffle algorithm | ds.algorithms;time complexity | The problem is surprisingly non-trivial. Here is a nice solution by Ellis and Markov, In-Situ, Stable Merging by way of the Perfect Shuffle (section 7). Ellis, Krahn and Fan, Computing the Cycles in the Perfect Shuffle Permutation succeed in selecting cycle leaders, at the expense of more memory. Also related is the nice paper by Fich, Munro and Poblete, Permuting In Place, which gives a general $O(n\log n)$ time algorithm for the oracle model. If only an oracle for the permutation is available, the algorithm requires logarithmic space; if we also have an oracle for the inverse, it requires constant space.Now for Ellis and Markov's solution. First, suppose $n = x+y$. Then computing the perfect shuffle of order $n$ reduces to computing the perfect shuffle of orders $x$ and $y$, with a rotation preceding them. Here is a proof by example ($n=5$, $x=3$, $y=2$):$$\begin{array}{cc}012\mathbf{345} & \mathbf{67}89 \\012\mathbf{567} & \mathbf{34}89 \\051627 & 3849\end{array}$$Ellis and Markov found an easy way to compute the perfect shuffle when $n=2^k$, using constant space and linear time. Using this, we obtain an algorithm for computing the perfect shuffle for arbitrary $n$. First, write $n = 2^{k_0} + \cdots + 2^{k_w}$ using the binary encoding of $n$, and let $n_i = 2^{k_i} + \cdots + 2^{k_w}$. Rotate the middle $n_0$ bits, shuffle the right-hand $2^{k_0}$ bits. Ignoring the righthand $2^{k_0}$ bits, rotate the middle $n_1$ bits, and shuffle the right-hand $2^{k_1}$ bits. And so on. Note that rotation is easy since the first few elements rotated function as cycle leaders. The total complexity of rotation is $O(n_0 + \cdots + n_w) = O(n)$, since $n_{t+1} < n_t/2$. The total complexity of the inner shuffles is $O(2^{k_0} + \cdots + 2^{k_w}) = O(n)$.It remains to show how to compute the perfect shuffle when $n=2^k$. In fact, we will be able to identify cycle leaders, following classical work on necklaces (Fredricksen and Maiorana, Necklaces of beads in $k$ colors and $k$-ary de Bruijn sequences; Fredricksen and Kessler, An algorithm for generating necklaces of beads in two colors).What is the connection? I claim that the shuffle permutation corresponds to right shifting of the binary representation. Here is a proof by example, for $n=8$:$$\begin{array}{cccccccc}000 & 001 & 010 & 011 & 100 & 101 & 110 & 111 \\000 & 100 & 001 & 101 & 010 & 110 & 011 & 111\end{array}$$Therefore, to find cycle leaders, we need to find one representative out of each equivalence class of the rotation of binary strings of length $k$. The papers mentioned above give the following algorithm for generating all cycle leaders. Start with $0^k$. At each step, we are at some point $a_1 \ldots a_k$. Find the maximal index $i$ of a zero bit, divide $k$ by $i$ to obtain $k = d\cdot i + r$, and let the following point be $(a_1\ldots a_{i-1}1)^d a_1\ldots a_r$. Whenever $r = 0$, the new string is a cycle leader.For example, when $n=16$ this generates the sequence$$\mathbf{0000}, \mathbf{0001}, 0010, \mathbf{0011},\mathbf{0101}, 0110, \mathbf{0111}, \mathbf{1111}.$$The cycle leaders are highlighted. |
_webmaster.9271 | I have a domain name which has a relevantly top searched keyword in it. I have not used this for over a year but I plan on doing so soon. Where is the best place to put it up for auction or see if anyone would like to buy it? (I am in the UK) and also Is there a way I can generate revenue from this unused domain name because at the moment I'm just paying for the domain name costs. | Selling/Generating Revenue from Unused Domain Names | domains;advertising | There are services that you park your domain on their server and you split the revenue with them earned from the ads they place on it. I never used these kinds of services so I can't give a recommendation as to a good one but I'm sure you cn find a bunch with a search or two.To sell a domain see these sites (from this previous answer):Snapnames.comSedo.comGodaddy.com AuctionsAuctionpus.comEbay.comLatonas.comAfternic.comDomainmonkey.comBido.comDomaintools.comGreatdomains.com (Part Of Sedo)Namejet.comSnapnames.comWinyourdomain.comYou can also try to sell it via the specialized forums (incomplete list):dnforum.comnamepros.comdomainforums.com |
_webapps.51513 | Lately whenever I send a gmail to others, a unknown yahoo email address (in my name) also accompanies my gmail, such that my friends receive at their end this yahoo email address. Thus when they send a reply message, it is sent to this Yahoo address too. I am unable to de-activate this Yahoo account as I cannot answer the 2 so-called security answers they require eg what is the nickname of your eldest child. Can you help? Thanks | Why Gmail sent has an unknown Yahoo account accompanying it | gmail | null |
_codereview.18771 | I have a list of images that are used as links and at the bottom of each image there is another image to show/hide. So far all the images show at the same time because they have the same class.Is there any way to get around that? I don't know how to give them all the unique ID. <div id=nav> <ul> <li id=one ><a href=#><img src=mikesfamilyborder.png class=first /><p><img src=mikesfamilybordername.png class=name/></p></a></li> <li id=two><a href=# ><img src=bradsfamilyborder.png class=first /><p><img src=bradsfamilyname.png class=name/></a></p></li> <li id=three><a href=# ><img src=brennerfamilyborder.png class=first /><p><img src=ryanbfamilyname.png class=name/></a></p></li> <li id=four><a href=# ><img src=ryanfamilyborder.png class=first /><p><img src=ryanlfamilyname.png class=name/></a></p></li> <li id=five><a href=# ><img src=missydadfamilyborder.png class=first /><p><img src=lackeysname.png class=name/></a></p></li> <li id=six><a href=# ><img src=libbyfamilyborder.png class=first /><p><img src=libbysname.png class=name/></a></p></li> </ul> <p> Click Picture for Family page</p></div> JavaScript:$('.name').hide();$(.first).hover(function() { $(.name).stop().show();}, function() { $(.name).stop().hide();}); | Show/hide image in each list individually with same class | javascript;jquery;html | You need to find the .name item that is in the same block of HTML as the one being hovered. One way to do that is to go up the parent chain from the one begin hovered to get the li tag and then use .find() from thereto find that .name item in that block. You can use this code to do that:$('.name').hide();$(.first).hover(function() { $(this).closest(li).find(.name).stop(true).show();}, function() { $(this).closest(li).find(.name).stop(true).hide();}); |
_webapps.93223 | I'd like to see the number of my Twitter impressions during some time without taking me into account. Is it possible? | How to make Twitter Analytics don't take me into account? | twitter | null |
_softwareengineering.119147 | There are many resources on general project management, but are there any specifically for non-technical people for software project management, covering topics such as requirements gathering, use cases and general architecture? | Any good resources for a non-technical guy to learn software project management? | project management | null |
_cstheory.17328 | The Bentley-Saxe trick allows us to go from a static decomposable problem to a problem admitting insertions, where the insertion time is off the optimal time by a factor of $\log n$. Is this tight ? Or alternately, is there a more restricted subclass for which you can get insertion time $P(n)/n$ (amortized or worst-case) even if $P(n) = O(n\log n)$ ? Here, $P(n)$ is the time to compute the result statically. | Optimal insertion times in insertion-only data structures beyond Bentley-Saxe | ds.data structures;dynamic algorithms | Think about your question in reverse: suppose you have a dynamic data structure for some problem does that imply that you can solve it statically, faster by a log? Why should it? And in fact it is not true.Consider range counting in one-dimensional intervals, in a comparison model of computation. That is, the data is a set $S$ of numbers, the query is an interval $[\ell,r]$, and the answer to a query is the size of $S\cap[\ell,r]$. Statically, you can solve it in $O(\log n)$ query time by storing $S$ as a sorted array and using binary search, in preprocessing time $P(n)=\Theta(n\log n)$. Dynamically, you can still solve it in $O(\log n)$ query time by using balanced binary search trees, with insertion time $O(\log n)=O(P(n)/n)$. |
_softwareengineering.52515 | How do you handle incomplete feature requests, when the ones asking for the feature cannot possibly write a complete request?Consider an imaginary situation. You are a tech lead working on a piece of software that revolves around managing profiles (maybe they're contacts in a CRM-type application, or employees in an HR application), with many operations being directly or indirectly performed on those profiles — edit fields, add comments, attach documents, send e-mail...The higher-ups decide that a lock functionality should be added whereby a profile can be locked to prevent anyone else from doing any operations on it until it's unlocked — this feature would be used by security agents to prevent anyone from touching a profile pending a security audit.Obviously, such a feature interacts with many other existing features related to profiles. For example:Can one add a comment to a locked profile?Can one see e-mails that were sent by the system to the owner of a locked profile?Can one see who recently edited a locked profile?If an e-mail was in the process of being sent when the lock happened, is the e-mail sending canceled, delayed or performed as if nothing happened?If I just changed a profile and click the cancel link on the confirmation, does the lock prevent the cancel or does it still go through?In all of these cases, how do I tell the user that a lock is in place?Depending on the software, there could be hundreds of such interactions, and each interaction requires a decision — is the lock going to apply and if it does, how will it be displayed to the user? And the higher-ups asking for the feature probably only see a small fraction of these, so you will probably have a lot of questions coming up while you are working on the feature.How would you and your team handle this? Would you expect the higher-ups to come up with a complete description of all cases where the lock should apply (and how), and treat all other cases as if the lock did not exist? Would you try to determine all potential interactions based on existing specifications and code, list them and ask the higher-ups to make a decision on all those where the decision is not obvious? Would you just start working and ask questions as they come up?Would you try to change their minds and settle on a more easily described feature with similar effects?The information about existing features is, as I understand it, in the code — how do you bridge the gap between the decision-makers and that information they cannot access? | Specifying and applying broad changes to a program | team;features;specifications | null |
_codereview.27177 | I want to implement in my code a cache mechanism with a fixed duration. For example an iframe will be cached for one hour, or a script file will be cached for 24 hours.This is how I implemented it, with a rounded timestamp (simplified code assuming that the url doesn't have any query or hash part):var duration=86400000; // example for 1 day = 86400000 millisecondsurl=url+?_ts=+ getTimeStamp(duration);function getTimeStamp(roundTime) { var timeStamp=new Date().getTime(); if (roundTime) {timeStamp=Math.floor(timeStamp/roundTime);} return timeStamp;}My questions:Are there any traps to watch for, or is the above code going to work just fine in all situations (dynamic script tag, iframe, ajax)?Is there a better way to do it, for example with a JavaScript library? | Cache mechanism with duration | javascript;ajax;cache | null |
_webmaster.77700 | I have a company website for our Internet agency for over 5 years. It holds blog posts, content pages, and our portfolio mainly.One of our biggest competitors, with mainly the same company activities as we have, went bankrupt because it lost 2 of its biggest clients. I bought their domain from the curator, and it's now ours. I don't have their old website.The domain has a lot of relevant incoming links, and a high domain authority. Besides that I can see that it also still has a lot of traffic from people that know the old company and look to render its services.I changed the DNS so it's the same as my website, so:www.example.com/portfolio.html = www.competitors-example.com/portfolio.htmlAnd I check incoming links to the new domain and redirect them to relevant pages on my site.But is this right? Or should I redirect it to my domain so the address bar says: www.example.com?In short: How do I use the domain so it doesn't hurt but helps my website's SEO? | How can I use a competitor's domain that I purchased? | seo;domains;redirects | I changed the DNS so it's the same as my websiteDoes this mean your website is now displaying on their domain? If so undo this ASAP, as this will create a duplicate of your site, which could have na adverse effect on your sites ranking.You should 301 redirect their domain to your domain. Where possible redirect pages on their site to relevant pages on your site, or to the nearest relevant page.www.competitors-example.com/prices.html301 redirects to www.example.com/our-prices.htmlIf no relevant page exists, 301 redirect the page to the home page.Before doing this though, I would investigate their back links to make sure there are no potentiality bad bad links present, as they could pass over to your domain and cause issues. As well as your own common sense, there are tools on the market to help identify bad badlinks. You could then do a link disavow in Google Webmaster Tools, on your domain to exclude any such backlinks.Doing all of the above will pass over most of the SEO authority to your site and will also make sure people land on your site when accessing the old domain. |
_unix.220264 | I am a newbie in OpenWrt development. I have a problem in my router when I try to upgrade my router (TP-Link TL-WDR-3600) to openwrt firmware via web ui. Now my router is bricked and I can't connect the router via WebUI (192.168.1.1), putty and WinSCP. I checked the ipconfig command incommand prompt. But the Default gateway is missing.Finally I try to connect via USB to serial cable using putty. But the putty is shown a blank screen for a long time. ( 30 minutes ).I am really hopeless, I think my router is seriously crashed.Could you please suggest any advice? | OpenWrt bricked router is not connected via USB to serial cable | ssh;putty;openwrt;router;telnet | null |
_webapps.56578 | I have these cells A1 through A7:Mary SusieJaneMarySusieElizabethMaryI want to get the names that do not appear multiple times, so my results should be Jane and Elizabeth. I don not want Susie or Mary because they appeared multiple times.How do I do this? | Find items that are not duplicates | google spreadsheets | null |
_webapps.11836 | Is there an open source asset management tool for controlling an organization'sassetsconsumables and equipment ?I was checking Asset Manager, it is a commercial windows application but I would prefer a web based application. | Asset Management web application? | inventory | Should check GLPI which's a free software webapps for managing IT ressources HTH, |
_cs.72318 | As a computer science student I consider is essential to completely understand how a Turing machine is defined.What mathematical knowledge is required in order to understand the formal definition of a Turing Machine, as explained in this Wikipedia link. | What is the knowledge required to understand the formal definition of a Turing Machine? | turing machines | null |
_unix.149771 | When a user process invokes malloc(n), are there any physical pages allocated to the process? I believe No since malloc allocates from the heap. Is this correct? | Malloc and Paging | virtual memory | For Linux, I believe the short answer to your question is usually no physical pages are allocated. This is called memory overcommit and you can find tons of documentation on it. Unix variants have had different policies about actual physical page allocation at malloc-time. 4BSD-based systems traditionally did not overcommit, which in combination with the chill program (can't find a reference) was endless fun. chill allocated and held as much memory as it could. Because SunOS (4.2BSD-based) always allocated physical pages for any malloc(), a mere user could allocate all RAM and cause everyone else to page endlessly.For linux you can find out what your system's policy is: cat /proc/sys/vm/overcommit_memory should give out a 0, 1 or 2 with the meanings heuristic overcommit, always overcommit and never overcommit respectively. |
_webmaster.54281 | Upon reading over this question is lengthy so allow me to provide a one sentence summary: I need to get Google to de-index URLs that have parameters with certain values appendedI have a website example.com with language translations.There used to be many translations but I deleted them all so that only English (Default) and French options remain.When one selects a language option a parameter is aded to the URL. For example, the home page:https://example.com (default)https://example.com/main?l=fr_FR (French)I added a robots.txt to stop Google from crawling any of the language translations:# robots.txt generated at http://www.mcanerin.comUser-agent: *Disallow: Disallow: /cgi-bin/Disallow: /*?l=So any pages containing ?l= should not be crawled. I checked in GWT using the robots testing tool. It works.But under html improvements the previously crawled language translation URLs remain indexed. The internet says to add a 404 to the header of the removed URLs so the Googles knows to de-index it.I checked to see what my CMS would throw up if I visited one of the URLs that should no longer exist.This URL was listed in GWT under duplicate title tags (One of the reasons I want to scrub up my URLS)https://example.com/reports/view/884?l=vi_VN&l=hy_AMThis URL should not exist - I removed the language translations. The page loads when it should not! I played around. I typed example.com?whatever123It seems that parameters always load as long as everything before the question mark is a real URL.So if Google has indexed all these URLS with parameters how do I remove them? I cannot check if a 404 is being generated because the page always loads because it's a parameter that needs to be de-indexed. | De-index URL parameters by value | google search console;indexing;google index;url parameters | null |
_codereview.8198 | So say I have a method that does a bunch of stuff, and I want to refactor this method to take a different type of parameter:public object A(MyObject a){ // does a bunch of crap with a // then calls another method this.B(a);}Now even method B() does a lot of crap with that same Object a. What if I want an endpoint that takes a SecondObject b. What I just did was basically duplicate all the methods and change the parameter type, but now I'm sitting with basically a bunch of duplicate code here. What's the best way to refactor this so that all my methods can take a different set (not just a different type) of parameters and reduce duplicity?Thanks.Edit:Example,private Chatham.Panda.WCF.DataContracts.IInstrument FillHistoricInstrumentRates( Chatham.Panda.WCF.DataContracts.IInstrument instrument, Chatham.Enumerations.BidMidAsk valuationPrice, DateTime rateCutoffDate, bool loadRates, FillInstrumentRates recursiveDelegate) { if (instrument == null) { throw new ArgumentNullException( instrument, RateAcqusitionService.SetInstrumentHistRates's 'instrument' argument is null); } // Compound Instruments Chatham.Panda.WCF.DataContracts.CompoundInterestRateInstrument compoundInstrument = instrument as Chatham.Panda.WCF.DataContracts.CompoundInterestRateInstrument; if (compoundInstrument != null) { foreach (Chatham.Panda.WCF.DataContracts.IInstrument i in compoundInstrument.ChildInstruments) { recursiveDelegate(i); return compoundInstrument; } } // Simple Instruments Chatham.Panda.WCF.DataContracts.SimpleInterestRateInstrument simpleInstrument = instrument as Chatham.Panda.WCF.DataContracts.SimpleInterestRateInstrument; if (simpleInstrument != null) { // Set Rates for each Component foreach (Chatham.Panda.WCF.DataContracts.Component component in simpleInstrument.Components) { this.FillHistoricComponentRates( component, valuationPrice, rateCutoffDate, loadRates ); } return instrument; } throw new NotSupportedException( string.Format( Instrument with type '{0}' currently not supported, instrument.GetType().FullName) ); }Now I want to change this method so that it takes a List<ScheduleRow> rows, as well as some other random properties including within the Chatham.Panda.WCF.DataContracts.IInstrument instrument, instead of passing the whole instrument across the wire, but if I just create another method with all this code in it and different parameters, it won't look TOO much different, and have plenty of duplicate code.Then I'd also be doing things like calling:this.FillHistoricComponentRates( component, valuationPrice, rateCutoffDate, loadRates );With a list of rows instead of the entire component, which leads to THAT method being changed in the same exact fashion, so on and so on... | Refactoring different type of param to reduce duplicate code | c#;.net | null |
_codereview.109278 | I attempted this problem from the ieeextreme, and I got timeout for just over 40% of the cases. Now that the competition is over, I was wondering what could be improved.The problem is as follows:Given a grid of size R, C1 <= r <= 12, 1 <= c <= 10^6Apply one of 3 commands 'a', 'r', or 'q''a', x1, y1, x2, y2: add one to each element of the subgrid formed by the co-ordinates given'r', x1, y1, x2, y2: remove one from each element of the subgrid formed by the co-ordinates given'q', x1, y1, x2, y2: output the sum of the elements in the subgrid formed by the co-ordinates givenI gave a naive solution as seen below, where I simulated the grid with a 2d array, and applied each operation as it came. I also tried to implement an array of fenwick trees, but that solution gave more timeouts, so I believe there are a lot more add and remove commands than query.Code:#include <cmath>#include <cstdio>#include <vector>#include <iostream>#include <algorithm>using namespace std;void inp(int &n) { n = 0; int ch = getchar_unlocked(); while(ch < '0' || ch > '9') { ch = getchar_unlocked(); } while(ch >= '0' && ch <= '9') { n = (n<<3)+(n<<1) + ch-'0', ch=getchar_unlocked(); } } int grid[13][1000001];int main() { int R, C; inp(R); inp(C); for(int i = 0; i < R; ++i) { for(int j = 0; j < C; ++j) { grid[i][j] = 0; } } int Q; inp(Q); while(Q--) { char o; int x1, y1, x2, y2; cin >> o; inp(x1); inp(y1); inp(x2); inp(y2); if(o == 'a') { for(int i = x1; i <= x2; ++i) { for(int j = y1; j <= y2; ++j) { ++grid[i][j]; } } } else if(o == 'r') { for(int i = x1; i <= x2; ++i) { for(int j = y1; j <= y2; ++j) { --grid[i][j]; } } } else { int count = 0; for(int i = x1; i <= x2; ++i) { for(int j = y1; j <= y2; ++j) { count += grid[i][j]; } } cout << count << endl; } } return 0;}EDIT: This is the solution with the fenwick tree, which gave more timeouts#include <cmath>#include <cstdio>#include <vector>#include <iostream>#include <algorithm>using namespace std;#define LSOne(S) (S & (-S))int ft[13][1000003];int size = 1000003;int sum(int i, int b) { int sum = 0; for (; b; b -= LSOne(b)) sum += ft[i][b]; return sum;}int sum(int i, int a, int b) { return sum(i, b) - (a == 1 ? 0 : sum(i, a - 1));}void update(int i, int k, int v) { for (; k <= size; k += LSOne(k)) ft[i][k] += v;}void inp( int &n ) { n=0; int ch=getchar_unlocked();; while( ch < '0' || ch > '9' ){ ch=getchar_unlocked(); } while( ch >= '0' && ch <= '9' ) n = (n<<3)+(n<<1) + ch-'0', ch=getchar_unlocked(); } int main() { int R, C; inp(R); inp(C); size = C; int Q; inp(Q); while(Q--) { char o; int x1, y1, x2, y2; cin >> o; inp(x1); inp(y1); inp(x2); inp(y2); if(o == 'a') { for(int i = x1; i <= x2; ++i) { for(int j = y1; j <= y2; ++j) { update(i, j, 1); } } } else if(o == 'r') { for(int i = x1; i <= x2; ++i) { for(int j = y1; j <= y2; ++j) { update(i, j, -1); } } } else { int count = 0; for(int i = x1; i <= x2; ++i) { count += sum(i, y1, y2); } cout << count << endl; } } return 0;} | Block Art - IEEEXtreme 9.0 | c++;programming challenge;time limit exceeded | Fenwick treesIt's too bad you didn't print your Fenwick tree solution, because there was probably something wrong with it if it gave your more timeouts than the brute force solution that you provided.Assuming you had an array of 12 Fenwick trees (because the rows are limited to 12), each add/remove operation should only take up to \$O(r \log c)\$ time, compared to \$O(r*c)\$ time of the brute force solution. Each query should take also take \$(r \log c)\$ time instead of \$O(r*c)\$ time.2-d Fenwick treeThere also exists a 2-d version of the fenwick tree, which is perfectly suited to this problem. It should be slightly faster at \$O(\log r * \log c)\$ time. Here is a sample implementation of a 2-d Fenwick tree. However, since r in your case is 12, it's unclear whether this would actually be faster than the array of Fenwick trees or not.Edit: Comments on your 2nd solutionYou didn't implement the Fenwick tree correctly. When you updated it, you did this: if(o == 'a') { for(int i = x1; i <= x2; ++i) { for(int j = y1; j <= y2; ++j) { update(i, j, 1); } } }What it should have looked like is this: if(o == 'a') { for(int i = x1; i <= x2; ++i) { update(i, y1, 1); update(i, y2+1, -1); } }Notice the lack of a loop across the y values. The same thing applies to the remove operation. |
_unix.115212 | I am configuring an openvpn server on a new centos 6.5. But the main problem is that selinux is blocking openvpn to use the default port tcp 1194.The following is the sealert -a /var/log/audit/audit.logSELinux is preventing /usr/sbin/openvpn from name_bind access on the tcp_socket .***** Plugin bind_ports (92.2 confidence) suggerisce ************************Se you want to allow /usr/sbin/openvpn to bind to network port 7505Quindi you need to modify the port type.Fai# semanage port -a -t TIPO_PORTA -p tcp 7505dove TIPO_PORTA una delle seguenti: openvpn_port_t, http_port_t.I am sorry, as u see the sealert is translated in italian. Anyway should I follow the advice like this:# semanage port -a -t vpn -p udp 1194or there are other more clean way to open the openvpn default port ? | SELinux is preventing /usr/sbin/openvpn from name_bind access on the tcp_socket | centos;selinux;openvpn | That's actually the best error message I've seen. It tells you exactly what's wrong and how to fix it. I don't see any kind of problem if you really want to allow openvpn use port 1194.BTW, to make errors in english you can use LANG=C before the commands (not sure if you can with auth.log). |
_unix.167339 | I have a buildroot package that I need to build. When I issue the 'make' command, it runs until it errors out with lutimes undeclared. After lengthy research, it appears that uClibc needs to be patched to include the definition of lutimes before my build will complete.I found this patch, but being new to Linux, I do not know how to apply it:ucLibc Mailing List Archive - June 2010, Post 44113Can anyone help me properly apply this patch ? I'm very new to Linux and I've never applied a patch before. | Applying patch to the uClibc | compiling;patch;buildroot | Have in mind that Patches are per source code revision, and after 4 years of changes in the source code, this patch may be outdated and may need recreation from scratch.First thing you should do is check the official documentation.http://buildroot.uclibc.org/downloads/manual/manual.html#_providing_patchesYou should pay attention to the following two categories:17.1.2. Within Buildrootand17.2. How patches are appliedGive it a try and let us know if you face any issues |
_unix.245037 | I created a systemd file unit (Centos 7) and I wanted to save the Python output to a file but the service won't start with the below code.[root@static ~]# cat /etc/systemd/system/pykms.service[Unit]Description=PY-KMSAfter=network.target[Service]Type=simpleUser=rootExecStart=/usr/bin/python2.7 /usr/local/py-kms-master/server.py 192.168.1.100 1688 -v > /usr/local/py-kms-master/pykmsss.log[Install]WantedBy=multi-user.targetNOTE: if I delete the line after > above, then everything works fine but I want to save the logs to a file.systemctl status pykms -l [root@static ~]# systemctl status pykms -lpykms.service - PY-KMS Loaded: loaded (/etc/systemd/system/pykms.service; enabled) Active: active (running) since Tue 2015-11-24 20:54:28 IRST; 2s ago Main PID: 2788 (server.py) CGroup: /system.slice/pykms.service 2788 /usr/bin/python2.7 /usr/local/py-kms-master/server.py 192.168.1.100 1688 -vNov 24 20:54:28 server.de systemd[1]: Starting PY-KMS...Nov 24 20:54:28 -server.de systemd[1]: Started PY-KMS. | Saving process output to a file in systemd unit file | linux;centos;files;python;systemd | null |
_codereview.85149 | I am wanting to encrypt a password and decrypt a password using PHP. Is this a safe method?$pass = password//encrypt password$salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.');$salt = sprintf($2a$%02d$, 10) . $salt;$hash = crypt($pass, $salt);//decryption in second programif(crypt($pass, $hash) == $hash){ echo you are in;} | Encrypting and decrypting passwords in PHP | php;cryptography;authentication;hashcode | As KIKO Software and the documentation for crypt said, password_hash() is encouraged. It's safer (it applies multiple rounds of hashing, thus increasing the time it takes to decrypt the hash), and it will manage salts for you, which means that your code will be simpler. If for some reason you do not want to use password_hash, note the warning from the crypt documentation:Warning When validating passwords, a string comparison function that isn't vulnerable to timing attacks should be usedYou are not doing that, you are just using ==. hash_equals would be one such timing safe function. |
_unix.330125 | I was following this instruction on this site to installing tesseract: https://github.com/tesseract-ocr/tesseract/wiki/Compilinggit clone https://github.com/tesseract-ocr/tesseract.gitcd tesseract./autogen.sh./configuremakesudo make installsudo ldconfigBut there is a problem in the last line and I got this error messages when I tried ldconfig:/sbin/ldconfig.real: /usr/local/lib is not a known library type/sbin/ldconfig.real: /usr/local/lib/pkgconfig is not a known library typeWhat's that error meaning and how can I fix it?This is the content of /etc/ld.so.conf.d/libc.conf :# libc default configuration/usr/local/lib | /sbin/ldconfig.real: /usr/local/lib is not a known library type | configuration;shared library;error handling | null |
_webmaster.56663 | We currently use Schema.org for our rich snippets in Google. I want to add Open Graph along with that, so other social signals will recognize our site better. If I add OG to our existing schema, will that have any effect on our current rich snippets? | Schema.org & Open Graph | seo;google search;rich snippets;open graph protocol;schema.org | Open Graph data is completely separate from structured data. There are so many sites using both the features without any issue. Here is a link from a Moz community question just like a one you asked. |
_webapps.81177 | I want to replace Mailbox with something similar in pure Gmail. But I miss the way Mailbox shows the conversation count next to each folder.Is there a way to do this for Gmail? | Make Gmail show conversation count? | gmail | null |
_scicomp.2421 | As an assignment in college, I did a 1d simulation.The problem statement was to solve 1d shock tube problem involving compressible ideal gas as working fluid.For this problem, I solved system of Eulers equations using Roe's Riemann solver.I want to know, to solve the Euler's equations in 2 or 3 dimensions, where should I start?Which is the test problem, i should consider first?(Please don't suggest commercial solvers. I want to write my own code)just I need some help in writing my own code.What are the good resources that introduce 2d problem in the most practical way? | Euler equations in 2d | numerics;fluid dynamics | null |
_softwareengineering.180996 | I have an open source project that uploads files to DropBox among several file hosts. Right now I am screen scraping for DropBox. To use their API, I have to hardcode a SECRET KEY provided by them to me for OAuth authentication. But I'm afraid that the key won't be secret if it is visible plainly for anyone to see.It is 'possible' for someone malicious to use my key to upload a virus to a user's account (who already allowed access to my app) that will spread to their pc (if they had desktop sync enabled) and to others' pc (if they had shared folders) and so on. :OI found this unanswered question that has the same problem as mine.But I would like to know generally how one would hide confidential data in an open source project.I have one idea.Have a placeholder in the source code like <SECRET KEY HERE> and fill it only when building binary for release? (yuck!)Any decent idea? | How can I hide confidential data in my open source project? | open source | null |
_reverseengineering.15756 | For example I have eax 7c9100a4 -> ntdll.RtlCreateHeapI can get reg value in my plugin but I can't get the api nameHow can get the correct api name from the address? | How to get API name from address in registry value in IDA plugin | ida;idapro plugins | NameEx(BADADDR, GetRegValue(EAX)) |
_unix.333791 | I am unable to use the morse utility, both in GUI and non-GUI terminal:# echo word | morseCould not initialize audio: Connection refusedCan't access speaker.Why do I have this error and how to use morse with alsamixer?From /usr/share/doc/morse/README:Currently supported devices: X11: The X11 window system. (Warning: not all X11 implementations handle duration and frequency of beeps properly!) Linux: The IBM PC console speaker. OSS: Open Sound System /dev/dsp device. Also works with the newer ALSA Linux sound system using the legacy OSS device. PA: PulseAudio using the pulse-simple client API. ALSA: ALSA Linux sound system /dev/snd/* device. | Cannot use morse: Could not initialize audio | audio;alsa | null |
_unix.3947 | I want to duplicate a directory on an FTP server I'm connected to from my Mac via the command-lineLet's say I have file. I want to have files2 with all of file's subdirectories and files, in the same directory as the original. What would be the simplest way to achieve this?(Im a complete newbie to the UNIX command line, so sorry if the question is not clear enough; please ask for any clarification needed.)EDIT:With mget and mput you could download all files and upload them again into a different folder but this is definitely NOT what i want/need (I started this question trying to avoid duplicating with this download upload method from the dektop client) | Easiest way to duplicate directory over FTP | file transfer;ftp;remote;file copy | What you have is not a unix command line, what you have is an FTP session. FTP is designed primarily to upload and download files, it's not designed for general file management, and it doesn't let you run arbitrary commands on the server. In particular, as far as I know, there is no way to trigger a file copy on the server: all you can do is download the file then upload it under a different name.Some servers support extensions to the FTP protocol, and it's remotely possible that one of these extensions lets you copy remote files. Try help site or remotehelp to see what extensions the server supports.If you want a unix command line, you need remote shell access, via rsh (remote shell) or more commonly in the 21st century ssh (secure shell). If this is a web host, check if it provides ssh access. Otherwise, contact the system administrator. But don't be surprised if the answer is no: command line access would be a security breach in some multi-user setups, so there may be a legitimate reason why it's not offered. |
_unix.275914 | Creating AD 2003 domain using Samba-4.3.4 with internal DNS. ISC-DHCP as a server. On Debian.DNS updates comes only from DHCP-server.What tool do I have to use to clear old DNS records, or what mechanizm is used to detect and (maybe) automatically clear such records? | Samba4 DNS - clear old DNS records | debian;dns;isc dhcpd;samba4 | null |
_unix.102237 | Is there a good alternative (free software) for Crashplan for UNIX desktops?There is a plethora of backup systems out there, but there doesn't seem to be one that rivals with Crashplan.The specifications are:continuous, seemless backupintuitive desktop user interfacebackups to remote servers (aka the cloud), local hard drives, friendsincremental backupsencryption for remotesoptionally: go back in timeSimilar questions:Easy incremental backups to an external drive - no desktop interface, no remote servereasy rsync solution with file manager (thunar or nautilus or) - simply a workaroundComparison of backup tools - on askubuntu.com | crashplan desktop alternative? | backup;free software | I do not know of any free software continuous backup solution. An interesting design was written up by liw which seems to correspond to what you are looking for, but that design has yet to be implemented.Nevertheless, here are what are the interesting free software backup alternatives right now.Dej dup is a frontend for duplicity so it supports incremental and encrypted backups. It can also keep previous backups. It has some remote servers options and integrates well with the desktop.Obnam is quite interesting and seems to fulfill all requirements but the desktop support.Bup and Attic are also interesting alternatives, both of which are really high performance (so that you can run backups frequently, although not continuously) but only Bup have some (third-party) GUI. Note that Attic is an abandoned project, with a more active fork called Borg and Bup is self described as 'very early version'.Timevault is one alternative, but it has been unmaintained for a while, and backups only on local filesystems.Back in time is an alternative that seems to be more maintained but has similar limitations.Flyback is yet another alternative.git-annex, while not a complete backup solution, is a nice solution for large file collections, and seemlessly integrates with git, rsync and other tools. It can easily track multiple copies and make sure that you have more than N (configurable) copies of your data. The downside is that the UI is limited and it will fail backing up certain files, like .git directories, ironically enough.camlistore is similar to git-annex, but is mostly aimed at developers at the time of writing. |
_webmaster.89669 | Can we get the revenue generated by (the ads on) each of the individual URLs on my website? Other than, you know, by adding URL channels manually at both Adsense and Ad Exchange and then summing up the revenues. I know that the SlotRenderEndedEvent of the GPT API can give me information as far as the line item id, service that rendered the ad slot etc. Can it, may be, give more info like the pricing rule used (at adx) etc - so that I can get an estimate on the revenue?Any other new solution is also fine - as long as it's not adding URL channels manually. (There is no API to add URL channels to Adx).PS: I do not have Google Analytics Premium, so I cannot connect DFP to GA. | Is there a way to get DFP revenue/cpm by URL? | google adsense;google dfp;doubleclick ad exchange | AFAIK you won't get any pricing data from the event. But you can get the line item and potentially other useful info from the event. You can query the DFP reporting (even without premium) to get the impressions/revenue for that line item. If you have other key-value data you pass through, you can get more detailed info about revenue broken apart by the different KV. |
_unix.42223 | Let's say I have a script:#!/bin/bashecho $1if [[ ! $1 ]];thenecho Truefiexport ABC=/home/aashishABC is not available after the execution of this script. How can I make that variable persist after the execution as well? | How can I set environment variable permanently through shell script? | shell script;environment variables | source it into current shell session. |
_codereview.166050 | I have a system that parses a mathematical expression String, creates a derivative expression tree, and reconstructs the derived expression into a new String. I am looking for a method to shorten my code/organize it/make it more abstract.Here is what one of my classes looks like. This is the Product class, one of several subclasses of the BinaryOperator class, a subclass of the Expression class. As you can see, it applies differentiation rules and re-write rules:Product.javapublic class Product extends BinaryNode { public Product(Expression left, Expression right) { super(left, right, BinaryOperator.MULTIPLY); } @Override public Expression derive() { Expression l = left.derive(); Expression r = right.derive(); return new Sum( new Product(l, right), new Product(left, r) ); } @Override public Expression reduce() { Expression l = left.reduce(); Expression r = right.reduce(); // C*C ==> C // x*C ==> C*x if(l instanceof Constant || r instanceof Constant) { if(l.getType().equals(1)) { // Ex: 1*5 (polish: 15*) ==> 5 return r; } if(r.getType().equals(1)) { // Ex: 5*1 (polish: 51*) ==> 5 return l; } if(l.getType().equals(0)) { // Ex: 0*5 (polish: 05*) ==> 0 return l; } if(r.getType().equals(0)) { // Ex: 5*0 (polish: 50*) ==> 0 return r; } if(l instanceof Constant && r instanceof Constant) { // Ex: 5*5 (polish: 55*) ==> 25 return new Constant(l.getValue() * r.getValue()); } if(!(l instanceof Constant)) { // Ex: x*5 (polish: x5*) ==> 5*x Expression tmp = l; l = r; r = tmp; } } // Ex: x^2 * C ==> C * x^2 if(l instanceof Exponent) { Expression tmp = l; l = r; r = tmp; } // C*x*C*x ==> (C*C)*(x*x) if(r instanceof Product && l instanceof Product) { } // C*x*C ==> (C*C)*x if(r instanceof Product) { if (l instanceof Constant) { if (r.getLeftChild() instanceof Constant) { // Ex: 4*4*x (polish: 44x**) ==> 16*x return new Product( new Constant(l.getValue() * r.getLeftChild().getValue()), r.getRightChild() ); } if (r.getRightChild() instanceof Constant) { // Ex: 4*x*4 (polish: 4x4**) ==> 16*x return new Product( new Constant(l.getValue() * r.getRightChild().getValue()), r.getLeftChild() ); } } } // C*x*C => (C*C)*x if(l instanceof Product) { if (r instanceof Constant) { if (l.getLeftChild() instanceof Constant) { // Ex: 4*x*4 (polish: 4x*4*) ==> 16*x return new Product( new Constant(r.getValue() * l.getLeftChild().getValue()), l.getRightChild() ); } if (l.getRightChild() instanceof Constant) { // Ex: x*4*4 (polish: x4*4*) ==> 16*x return new Product( new Constant(r.getValue() * l.getRightChild().getValue()), l.getLeftChild() ); } } } if(r instanceof Quotient) { Expression numerator; if(r.getLeftChild().getType().equals(1)) { numerator = left; } else { numerator = new Product( left, r.getLeftChild() ); } return new Quotient( numerator, r.getRightChild() ); } return new Product(l, r); } @Override public double getValue() { if(left instanceof Constant) return left.getValue(); if(right instanceof Constant) return right.getValue(); return 0; }}I found this, and was thinking that I could have a Rewrite class and a Rules class that recursively analyzes and compares trees while looking for patterns.Example: \$x^2 \cdot x^2 \rightarrow x^4\$ | Computer Algebra System that computes symbolic derivatives | java;expression trees | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.