id
stringlengths 5
27
| question
stringlengths 19
69.9k
| title
stringlengths 1
150
| tags
stringlengths 1
118
| accepted_answer
stringlengths 4
29.9k
⌀ |
---|---|---|---|---|
_opensource.2611 | Say I'm maintaining a GPLv3 project on Github with a LICENSE file, code headers and all. Now, a few folks made some code enhancements and sent me a pull-request. Does that automatically mean that they agree to contribute under GPLv3 terms, or, do I have to do make some kind of separate agreement with each contributor? The latter is not only cumbersome, but practically impossible as projects become large. What is the usual practice in this regard for projects like Wordpress, Drupal, Debian, Linux kernel, etc.? Do they all make formal agreements with the devs?I had a look at this recently posted question which explored this same area, but didn't answer this exact question I have.Most importantly, if today I accept someone's pull-request, can they come back five years down the line saying, Hey, I didn't intend this to be GPLed all those years ago, so I want to assert my rights now. | When folks send me pull-requests on Github, what are their copyright/licensing terms by default? | copyright;license notice;contributor agreements | null |
_scicomp.265 | I will start with my personal experience in our lab. Back in the ifort 9 and 10 days, we used to be quite aggressive with the optimizations, compiling with -O3 and processor specific flags (-xW -xSSE4.2 for example). But starting with ifort 11, we started to notice: 1. some inconsistencies in the results (because semantics were not preserved) 2. smaller gains compared to -O2. So currently, we usually simply compile with -O2 and -xhost. Do you have better suggestions with ifort 11? Will this change once again as we transition to ifort 12? Thanks in advance. | Intel Fortran Compiler: tips on optimization at compilation | performance;hpc;compiling;fortran | We strongly recommend all our users start with -O3 -xHost -ipo for both ifort 11 and ifort 12. If there are particular floating point transformations enabled by O3 that affect the precision of some of your computations, you can turn those specifically off with -fp-model precise -fp-model except (or, more drastically, -fp-model strict) while retaining the other optimizations O3 enables, such as loop blocking for cache, loop fusion and unrolling, and memory access optimizations. I'd advise trying the floating point model stuff on individual files and finding out where it makes a difference, rather than turning it off globally; it can be a ~15% speed bump, and you want to be able to keep that where it doesn't affect your calculations. If you're not sure where the precision is being affected, you can play with turning on and off the floating point model flags for those files, or playing with rounding modes.We recently gave a short talk to our users about optimization flags, focusing on the gnu and intel compilers for x86; you can see the slides from that talk here.Incidentally, while we're talking about choosing optimization flags for your code, every now and then it's also worth looking at the output of -vec-report to see where the compiler attempted to vectorize a loop and couldn't; sometimes there are small changes you can make to your loop which can result in vectorization being possible (which can be a 4x speedup). Similarly for the more general -opt-report. |
_unix.192409 | Using the shared /tmp directory is known to have lead to many security vulnerabilities when predictable filenames have been used. And randomly generated names aren't really nice looking.I am thinking that maybe it would be better to use a per user temporary directory instead. Many applications will use the TMPDIR environment variable in order to decide where temporary files goes.On login I could simply set TMPDIR=/temp/$USER where /temp would then have to contain a directory for each user with that directory being writable to that user and nobody else.But in that case I would still like /temp to be a tmpfs mountpoint, which means that the subdirectories would not exist after a reboot and need to be recreated somehow.Is there any (de-facto) standard for how to create a tmpfs with per user subdirectories? Or would I have to come up with my own non-standard tools to dynamically generate such directories? | Per user tmpfs directories | security;fhs;tmpfs | null |
_reverseengineering.3026 | I want to make a program that can intercept events (something like OnClickFolder as well as OnClickFile). Is there a way Spy++ or similar programs can do this? | How to use Spy++ to find OnClickFolder or OnClickFile events in Windows Explorer? | windows | Yes, Spy++ can detect folder- and file-clicks in shell windows. Just make sure you're monitoring the right process (typically Explorer.exe). |
_codereview.75314 | Over the course of the past month I've worked on a little visualizer to show how different algorithms are sorted. I'm pretty happy with how it turned out but would be interested in any feedback pertaining to the design of it or the coding.I'm still a bit of a novice to Swing, so I'd love some feedback on my usage:public class SortPanel extends JPanel {private ArrayList<Integer> list;private ArrayList<Colors> colorList;private int hPad;private int hRatio = 10; // ratio between width of bars and paddingprivate int width;private int vPad = 5;private int index;private int line;private float vScale;private String name, message;public SortPanel(String name) { super(); list = new ArrayList<Integer>(); colorList = new ArrayList<Colors>(); this.name = name; message = ; index = 0; line = 0;}/*...Variety of setters and getters to manipulate the list of numbers...*/public void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D) g; g2d.clearRect(0, 0, this.getWidth(), this.getHeight()); g2d.drawString(name, 5, this.getHeight() - 30); g2d.drawString(message,5,this.getHeight() - 15); if (this.getListSize() > 0) { hPad = this.getWidth() / ((hRatio + 1) * list.size() + 1); vScale = (this.getHeight() - 2 * vPad - g2d.getFont().getSize() - 50) / (float) list.get(this.getMaxIndex()); g2d.drawRect(0, 0, this.getWidth(), this.getHeight()); width = hRatio * hPad; int y = vPad + 20; g2d.setColor(Colors.TARGET.get()); g2d.drawLine(0, y+Math.round(line*vScale), this.getWidth(), y+Math.round(line*vScale)); for (int i = 0; i < list.size(); i++) { int x = hPad * ((hRatio + 1) * i + 1); g2d.setColor(colorList.get(i).get()); g2d.fillRect(x, y, width, Math.round(list.get(i) * vScale)); if (i == index) { // index marker g2d.setColor(Color.RED); g2d.fillOval((2 * x + width) / 2 - 5, 5, 10, 10); } } }}}This was also my first time using an enum. I wanted to make it easier to quickly get the Color I needed. Does this way provide less overhead and work more efficiently?import java.awt.Color;public enum Colors {INACTIVE(191, 191, 191), SORTED(87, 232, 14), TARGET(255, 0, 0), ACTIVE(8,8,8), LOWER(12,94,245), UPPER(205,21,0);private final Color col;Colors(int r, int g, int b) { col = new Color(r, g, b);}public Color get() { return col;}}I also used Threads for the first time here, so this is probably one of my main areas to look at.public QuickSortThread(SortPanel sp, long msdelay) { super(sp, msdelay); sp.setIndex(-1); } public int partition(ArrayList<Integer> nums, int a, int b) { if (started) { int pivot = nums.get(b); sp.setLine(pivot); sp.setColorRange(a, b, Colors.ACTIVE); sp.setColor(b, Colors.TARGET); int greater = a; sp.setMessage(Moving elements before/after index + greater + if they are < or > + pivot + .); for (int i = a; i < b && started; i++) { sp.setIndex(i); while (paused) { try { Thread.sleep(10); } catch (Exception e) { e.printStackTrace(); } } if (nums.get(i) < pivot) { sp.setColor(i, Colors.LOWER); sp.swap(i, greater); greater++; sp.setMessage(Moving elements before/after index + greater + if they are < or > + pivot + .); } else { sp.setColor(i, Colors.UPPER); } sp.repaint(); try { Thread.sleep(msdelay); } catch (Exception ex) { ex.printStackTrace(); } } sp.swap(greater, b); sp.repaint(); try { Thread.sleep(msdelay); } catch (Exception ex) { ex.printStackTrace(); } return greater; } return -1; } public void quickSort(ArrayList<Integer> nums, int a, int b) { sp.setColorRange(0, Colors.INACTIVE); sp.repaint(); if (a < b + 1 && started) { int pivot = partition(nums, a, b); quickSort(nums, a, pivot - 1); quickSort(nums, pivot + 1, b); } } public void run() { quickSort(list, 0, list.size() - 1); if (started) { sorted = true; sp.setLine(0); sp.setMessage(Sorted!); sp.setColorRange(0, Colors.SORTED); sp.setIndex(-1); sp.repaint(); } if (checkAllSorted() && started) { MainWindow.this.start(); } }}One thing I couldn't figure out was reducing the repeated Thread.sleep() blocks to methods. When I did so they stopped working. General OOP advice is also appreciated.Here is a Gist of my code, and here is an executable jar. | Sorting Algorithm Visualizer | java;algorithm;object oriented;swing;concurrency | First of all, nice effort.Some of the things that I can say about is - Visibility of the UIThere have been suggestions that for Swing we should use something like SwingUtilities.invokeLater() for making the UI visible.So instead of using public MainWindow() { ... frame.add(buttonPanel); frame.add(numbersPane); frame.setVisible(true);}...public static void main(String[] args) { MainWindow mw = new MainWindow();}you can use something like - public MainWindow() { ... frame.add(buttonPanel); frame.add(numbersPane);}public void startDisplay() { frame.setVisible(true);}...public static void main(String[] args) { final MainWindow mw = new MainWindow(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { mw.startDisplay(); } });}Invocation of UI calls on a separate threadWhenever you're calling sp.repaint();, you're doing it on a separate thread. Shouldn't you do it on the Event Dispatcher Thread (EDT)?Also I couldn't get the purpose of Thread.sleep(msdelay); after every call to repaint. Could you maybe add some more description as to why you've done that?Instead of sp.repaint(), do something like this - SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { sp.repaint(); }});and then add a breakpoint at sp.repaint() and even public void actionPerformed(ActionEvent event) { ... } to see how exactly the code is run on EDT.Separation of Code and UIEverything is dumped in a single class MainWindow. Why not separate theimplementations of SelectionSortThread, InsertionSortThread etc., after allyou have already made separate classes for them.The entire implementation of Selection Sort has been done inside of run().Please separate them as you have done in case of Merge Sort (mergeSort() and merge()).Store the instance of SortPanel that you pass to the constructor.So instead of -class SelectionSortThread extends SortThread { public SelectionSortThread(SortPanel sp, long msdelay) { super(sp, msdelay); } ...}Have something like - class SelectionSortThread extends SortThread { private SortPanel selectionSortPanel; public SelectionSortThread(SortPanel sp, long msdelay) { super(sp, msdelay); selectionSortPanel = sp; } ...}Try to implement an MVC sort of thing.Documentation and Nomenclature.Adding documentation would be nice.for e.g. I didn't know what the method paintComponent() did, later I realized that the method was initially declared in JComponent and you have overridden it. You could have just included the tag - @OverrideThe variables - list and colorList are quite confusing. Give them a proper descriptive name like unsortedList etc.Clean CodeI have moved some code around (I didn't have enough time to fork your repository, will do that later), so that it appears cleaner. Here is an example how you can abstract repeating code into new methods./** Merging */public void merge(ArrayList<Integer> nums, int a, int mid, int b) { if (this.mainWindow.started) { int[] lower = new int[mid - a]; int[] upper = new int[b - mid]; int index = a; int i, j; for (i = 0; index < mid; i++, index++) lower[i] = nums.get(index); for (j = 0; index < b; j++, index++) upper[j] = nums.get(index); initialSP(a, mid, b); sleepThread(msdelay); i = 0; j = 0; index = a; while (i < lower.length && j < upper.length) { while (this.mainWindow.paused) sleepThread(10); if (lower[i] < upper[j]) { nums.set(index, lower[i]); changeSP(lower[i], index, Colors.LOWER); i++; } else { nums.set(index, upper[j]); changeSP(upper[j], index, Colors.UPPER); j++; } index++; sleepThread(msdelay); } while (i < lower.length) { while (this.mainWindow.paused) sleepThread(10); nums.set(index, lower[i]); changeSP(lower[i], index, Colors.LOWER); i++; index++; sleepThread(msdelay); } while (j < upper.length) { while (this.mainWindow.paused) sleepThread(10); nums.set(index, upper[j]); changeSP(upper[j], index, Colors.UPPER); j++; index++; sleepThread(msdelay); } }}private void sleepThread(long msdelay) { try { Thread.sleep(msdelay); } catch (Exception ex) { ex.printStackTrace(); }}private void initialSP(int a, int mid, int b) { sp.setColorRange(0, Colors.INACTIVE); sp.setColorRange(a, mid, Colors.LOWER); sp.setColorRange(mid, b, Colors.UPPER); sp.setMessage(Merging values from index + a + to + (b - 1) + in order.); try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { sp.repaint(); } }); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); }}private void changeSP(int line, int index, Colors color) { sp.setLine(line); sp.setColor(index, color); try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { sp.repaint(); } }); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); }} |
_cstheory.8298 | I'm interested in open questions from the book Approximation Algorithms for NP-Hard Problemss dedicated to k-clustering. They are:Is Euclidean max cut solvable in polynomial time? If not, how well can it be approximated?Does the problem minimizing the sum of distances from points to their cluster centers has good approximation algorithm ? | k-clustering problems | ds.algorithms;approximation algorithms;clustering | null |
_cs.54621 | Taken from Wikipedeia:A simple voting game, taken from Game Theory and Strategy by Phillip D. Straffin:[6; 4, 3, 2, 1]The numbers in the brackets mean a measure requires 6 votes to pass, and voter A can cast four votes, B three votes, C two, and D one. The winning groups, with bolded swing voters, are as follows:AB, AC, ABC, ABD, ACD, BCD, ABCDUsing a non-trivial structure, we know that ABCD will always be a member of the set of winning groups. Also, we know that if AB is a winning group, then ABC and ABD are also winning groups. In other words, the set of winning groups AB, ABCD is invalid. Thus, any member of the set, besides ABCD, can be constructed by removing a single element from another set in the group. (Edit: While this is true, it gives the wrong impression.)In the beginning, the goal was to generate the set of possible winning groups for a given number of players. Using three players as an example, the set of winning groups is:{1, 2, 3}{1, 2, 3}, {1, 2}{1, 2, 3}, {1, 2}, {1}{1, 2, 3}, {1, 2}, {2}{1, 2, 3}, {1, 2}, {1}, {2}{1, 2, 3}, {1, 3}{1, 2, 3}, {1, 3}, {1}{1, 2, 3}, {1, 3}, {3}{1, 2, 3}, {1, 3}, {1}, {3}{1, 2, 3}, {2, 3}{1, 2, 3}, {2, 3}, {2}{1, 2, 3}, {2, 3}, {3}{1, 2, 3}, {2, 3}, {2}, {3}{1, 2, 3}, {1, 2}, {1, 3}{1, 2, 3}, {1, 2}, {1, 3}, {1}{1, 2, 3}, {1, 2}, {1, 3}, {2}{1, 2, 3}, {1, 2}, {1, 3}, {3}{1, 2, 3}, {1, 2}, {1, 3}, {1}, {2}{1, 2, 3}, {1, 2}, {1, 3}, {1}, {3}{1, 2, 3}, {1, 2}, {1, 3}, {2}, {3}{1, 2, 3}, {1, 2}, {1, 3}, {1}, {2}, {3}# and so on...This is doable through a relatively simple algorithm as thankfully offered here.(Edit: That algorithm does what was requested, but, per my oversight, generates false positives, e.g. {{1, 2}, {1, 3}, {1, 2, 3}, {1, 2, 3, 4}}.)However, I want to only generate one set per isomorphic group. For example, the sets {1, 2, 3}, {1, 2} and {1, 2, 3}, {1, 3} are the same if we swap the labels of 2 and 3. This is the primary goal.The secondary goal is to only generate the sets of winning groups that could be realized through a voting structure. Using a four player system and a maximum of 20 votes per person, I found sets of winning groups that satisfied the above criteria, but could not be realized. (Edit: See previously mentioned false positives and the answer below.) | Enumeration of winning coalitions | algorithms;enumeration;voting | You are asking two questions:How to count winning groups up to isomorphism?Which winning groups are realizable as winning coalitions?From the point of view of winning groups, we can assume that each voter always casts all her votes, and the resulting games is known as a weighted voting game.Counting winning groupsYour concept of winning group is a same as a monotone Boolean function or an upset. The number of monotone Boolean functions up to permutation is enumerated in the sequence A003182, and grows pretty quickly. For $n=7$ the number is already pretty large: 490,013,148. It's probably not too helpful to list all of them. It is even non-trivial just to calculate the number, see this paper.You can find all the 16351 non-constant monotone Boolean functions for $n=6$ listed here as sets of minterms, which are (in your parlance) minimal winning coalitions. The minterms form what is known as an antichain, a collection of sets none of which is a subset of another.Which winning groups are achievable?Let $S_1,S_2$ be two sets of voters. A swap consists of taking some $x \in S_1 \setminus S_2$ and some $y \in S_2 \setminus S_1$, and forming the new sets $S_1 - x + y, S_2 - y + x$ (that is, we exchange two voters, taking care not to have the same voter twice in any of the sets). Given several sets $S_1,\ldots,S_k$ of voters, a trade is the result of applying arbitrarily many swaps, resulting in a new $k$-tuple $T_1,\ldots,T_k$.(Alternatively, $T_1,\ldots,T_k$ is a trade of $S_1,\ldots,S_k$ if the multisets $S_1 \cup \cdots \cup S_k$ and $T_1 \cup \cdots \cup T_k$ are the same.)Let $W$ be a set of winning coalitions. We say that $W$ is trade robust if whenever $S_1,\ldots,S_k \in W$, in any trade $T_1,\ldots,T_k$ obtained from $S_1,\ldots,S_k$ at least one of the $T_i$ is in $W$. It is easy to see that every set of winning coalitions arising from weighted voting games is trade robust (exercise). Amazingly, Taylor and Zwicker showed that the converse holds as well. |
_softwareengineering.316320 | Is there a general term for the code that sets the parameters of statements require some kind of initialization or bounds? Examples:C:for (x=0; x<y; ++i) switch (controlling_variable)SystemVerilog:foreach (array[i])case (someVar)Python:while foo():for x in y:All of these examples have some statement followed by some code that defines the parameters. Is there a specific name for code that controls the behavior of the statement? For example, would it be correct to just use controlling expression for the examples where only one expression is required, and controlling clause for those that use more?Just to be clear: I'm not asking for suggestions or ideas about what to call these sections of code. I'm asking if there is already a standard name or phrase that should be used. Answers should cite language specifications or formal syntax/grammar descriptions to support their conclusions. It may well be the case that there isn't one is the correct answer. | Is there a language agnostic term for statement parameters? | terminology;language specifications | null |
_unix.348419 | I'm using this sed command to delete the word --More-- :sed 's/--More--\s*/ /' tabladetallada.datthe original file looks like this:Device ID: BIOTERIO IP address: 148.228.83.189Interface: GigabitEthernet1/0/6, Port ID (outgoing port): GigabitEthernet0/1 --More-- Device ID: N7K-LAN(JAF1651ANDL) IP address: 148.228.4.192Interface: GigabitEthernet1/0/1, Port ID (outgoing port): Ethernet7/23Device ID: LAB_PESADO IP address: 148.228.131.130Interface: GigabitEthernet1/0/11, Port ID (outgoing port): GigabitEthernet0/1 IP address: 148.228.131.130Device ID: Arquitectura_Salones IP address: 148.228.135.61Interface: GigabitEthernet1/0/9, Port ID (outgoing port): GigabitEthernet0/49 IP address: 148.228.135.61Device ID: CIVIL_253 IP address: 148.228.132.253 --More-- Interface: GigabitEthernet1/0/4, Port ID (outgoing port): GigabitEthernet1/0/52 IP address: 148.228.132.253Device ID: Arquitectura IP address: 148.228.134.253Interface: GigabitEthernet1/0/3, Port ID (outgoing port): GigabitEthernet0/1 IP address: 148.228.134.253Device ID: ING_CIVIL IP address: 148.228.133.251Interface: GigabitEthernet1/0/7, Port ID (outgoing port): GigabitEthernet0/2 IP address: 148.228.133.251Device ID: ING_CIVIL_DIR IP address: 148.228.4.188Interface: GigabitEthernet1/0/10, Port ID (outgoing port): GigabitEthernet0/2Device ID: Ingenieria_Posgrado IP address: 148.228.137.253Interface: GigabitEthernet1/0/8, Port ID (outgoing port): GigabitEthernet0/1 IP address: 148.228.137.253Device ID: Biblio_Barragan IP address: 148.228.136.61Interface: GigabitEthernet1/0/2, Port ID (outgoing port): GigabitEthernet0/1 IP address: 148.228.136.61Device ID: Electronica_Edif_3 --More-- IP address: 148.228.130.253Interface: GigabitEthernet1/0/5, Port ID (outgoing port): GigabitEthernet0/1 IP address: 148.228.130.253Once the word is deleted the white spaces after it are still thereHow can I delete them?Device ID: BIOTERIO IP address: 148.228.83.189Interface: GigabitEthernet1/0/6, Port ID (outgoing port): GigabitEthernet0/1 Device ID: N7K-LAN(JAF1651ANDL) IP address: 148.228.4.192Interface: GigabitEthernet1/0/1, Port ID (outgoing port): Ethernet7/23Device ID: LAB_PESADO IP address: 148.228.131.130Interface: GigabitEthernet1/0/11, Port ID (outgoing port): GigabitEthernet0/1 IP address: 148.228.131.130Device ID: Arquitectura_Salones IP address: 148.228.135.61Interface: GigabitEthernet1/0/9, Port ID (outgoing port): GigabitEthernet0/49 IP address: 148.228.135.61Device ID: CIVIL_253 IP address: 148.228.132.253 Interface: GigabitEthernet1/0/4, Port ID (outgoing port): GigabitEthernet1/0/52 IP address: 148.228.132.253Device ID: Arquitectura IP address: 148.228.134.253Interface: GigabitEthernet1/0/3, Port ID (outgoing port): GigabitEthernet0/1 IP address: 148.228.134.253Device ID: ING_CIVIL IP address: 148.228.133.251Interface: GigabitEthernet1/0/7, Port ID (outgoing port): GigabitEthernet0/2 IP address: 148.228.133.251Device ID: ING_CIVIL_DIR IP address: 148.228.4.188Interface: GigabitEthernet1/0/10, Port ID (outgoing port): GigabitEthernet0/2Device ID: Ingenieria_Posgrado IP address: 148.228.137.253Interface: GigabitEthernet1/0/8, Port ID (outgoing port): GigabitEthernet0/1 IP address: 148.228.137.253Device ID: Biblio_Barragan IP address: 148.228.136.61Interface: GigabitEthernet1/0/2, Port ID (outgoing port): GigabitEthernet0/1 IP address: 148.228.136.61Device ID: Electronica_Edif_3 IP address: 148.228.130.253Interface: GigabitEthernet1/0/5, Port ID (outgoing port): GigabitEthernet0/1 IP address: 148.228.130.253 | Delete white spaces after certain character | awk;sed;grep;perl | The substitution should look likes/--More-- */ /ors/--More--[[:blank:]]*/ /sed does not know about \s for space but treats it as a literal s.* (space + *) will match zero or more spaces.[[:blank:]]* will match zero or more spaces or tabs. |
_unix.97001 | I get thunderbird popup notifications in Awesome Window Manager that when clicked, are supposed to focus the message to which the notification corresponds.However, this does not work in awesome when thunderbird is on another tag.So, to clarify, clicking on the T-bird notification should switch to the tag where T-bird is running, and focus T-bird.Anyone know if this can be made to work?% awesome --version && thunderbird --version && cat /etc/issue 2>&1awesome v3.5.1 (Ruby Tuesday) Build: Sep 12 2013 20:14:11 for x86_64 by gcc version 4.8.1 (nobody@) Compiled against Lua 5.2.2 (running with Lua 5.2) D-Bus support: Thunderbird 24.0Arch Linux \r (\l) | Clicking on thunderbird notifications does not focus client | awesome;thunderbird | null |
_webmaster.77160 | I've created a BlueSpice MediaWiki site that I only want visible to users that are logged in. This works fine by creating Read permission only for Users as described here.All this works fine until I try and add two-factor authentication, which when logging in, goes to a second page to get the token at http://wiki.domain.com/index.php/Special:TwoFactorAuth/auth but this page fails to load due to no read permission:Please log in to view other pages.So how can I make this one page special and readable by all?A similar issue exists for the special page http://wiki.domain.com/index.php/Special:RequestAccount that gets added with the ConfirmAccount extension, so more generally, a set of special pages needs to be readable when not logged in, and the remaining that show information such as page names and user names should not be readable. | How to allow MediaWiki non-users to only read some wiki pages related login and account creation? | mediawiki;authentication;permissions | Use wgWhitelistRead in your LocalSettings.php configuration file. |
_codereview.121789 | Here is a function in a django rest api, that takes data in json and registers a category for a given website. I'd like to merge two try...except parts that check 'site_id' and 'category_id' but I am not sure how to do it. Also any other suggestion to make it pythonic is appreciated:@myql_view(['POST']) def register_category(request): try: site_id = request.data['site_id'] except Exception as e: print('Request error or missing site_id:', e) return Response(status=status.HTTP_400_BAD_REQUEST) try: category_id = request.data['category_id'] except Exception as e: print('Request error or missing category_id', e) return Response(status=status.HTTP_400_BAD_REQUEST) cursor = connection.cursor() try: cursor.execute('INSERT INTO productCategory (site_id, category_id) VALUES (%s, %s)', [site_id, category_id]) except Exception as e: print('Could not register product', e) return Response(status=status.HTTP_409_CONFLICT) finally: cursor.close() return Response(status=status.HTTP_200_OK) | improvement of a database register function | python;django | You can actually merge them pretty easily. They're very similar, with just a minor difference in the strings that determine what key failed. But luckily you can get the bad key by using the message attribute of the exception:]try: site_id = request.data['site_id'] category_id = request.data['category_id'] except Exception as e: print('Request error or missing {}:'.format(e.message), e) return Response(status=status.HTTP_400_BAD_REQUEST) Now they both work the same except that the missing key is taken out of your exception e and formatted into the message you print for the user. I also think you should except KeyError, not just any old Exception. Using the latter would mask typos, while the former deals specifically with the typeof exception you expect to appear. |
_unix.192540 | I have been trying to format my 640GB external Hard Drive in command-line and can't seem to get it working. I have done the following in order:sudo fdisk /dev/sda(Deleted any partitions, created a new partition, toggled partition type (tried multiple, but not sure the best?), then wrote the partition and printed to make sure it was correct.I then created the ext4 filesystem using: sudo mkfs.ext4 /dev/sda1I tried to mount the partition using: sudo mount -t ext4 /dev/sda1 /mnt/640-hdd -o gid=XXXX,uid=XXXXI then was given a mount error: mount: wrong fs type, bad option, bad superblock on /dev/sda1, missing codepage or helper program, or other error In some cases useful info is found in syslog - try dmesg | tail or soAny recommendations?FSTAB info:/dev/sda1 /mnt/640-hdd ext4 defaults,uid=bwhite94,gid=bwhite94 0 0 | Debian..Can't format and mount external HDD | debian;ext4;raspbian;fdisk;mkfs | null |
_unix.78689 | I am trying to open Firefox in CentOS, but I'm getting the following message:Firefox is already running but is not respondingand Firefox doesn't open. I tried this in command line: kill Firefoxbut it didn't work. Also, I don't know in which directory I must execute the right commands.How can I fix this? | Fix firefox is already running issue in Linux | process;kill;firefox | First find the process id of firefox using the following command in any directory:pidof firefoxKill firefox process using the following command in any directory:kill [firefox pid]Then start firefox again.Or you can do the same thing in just one command.As don_crissti said:kill $(pidof firefox) |
_unix.21478 | I typically dual boot my laptop betwen a Win7 and Ubuntu partition, but keep a spare partition for playing around with new distros. Earlier this week, I decided to try out Debian Squeeze.For the most part, the install has gone smoothly. However, the wireless is not working, and this is apparently a well known issue for Debian. The thing is, my wireless card apparently requires the iwlagn firmware iwlwifi-5000-5.ucode. I downloaded the updated 0.33 package that supposedly includes this firmware and installed it using the package manager.It still isn't working, as dmesg | grep firmware returns 'looking for firmware v5, found v0'This laptop is over 2 years old and I have zero problems with networking in Ubuntu Maverick. Any solutions? | Resolving Debian wireless issue | debian;wifi | null |
_webmaster.96824 | Say we had a website which on every page had a meta title of the followingProduct Name Blah Blah Blah | CompanyName.comHowever we felt that CompanyName.com was not really our identity and we wanted to change it to be without the .com and adding a space in the company name which matched our social media, Google Products and company names.Could we do one of the following below, and would it hit our SEO rankings if we changed it on all pages immediately?Product Name Blah Blah Blah | Company NameAlso, would we have to have a space after the pipe and before Company Name, or would the following also work? - That way we save a few more pixels.Product Name Blah Blah Blah |Company Name | Does changing company/brand name in title have SEO issues? | seo;title | null |
_unix.164396 | I've gone to my router settings and added port forwarding for port 22 to my linux machine. However, when I now type ssh @ from another computer (the terminal of my mac), it says operation timed out. I've used grep Port /etc/ssh/sshd_config to confirm that port 22 is infact the port ssh uses on my linux. Am I missing some thing? | Can't ssh to my ubuntu machine using global ip address | ssh | null |
_unix.138520 | I got my config files in /etc folder all messed up because I did not take care of shell expansion while doing rsync:rsync --progress --delete -avhHe ssh /etc/logrotate.d/{httpd,mariadb,php-fpm,ppp,wpa_supplicant,yum} [email protected]:/etcI think the problem is that the '.' following logrotate got expanded and subsequently some folders such as /etc/httpd got deleted.I want to learn from this mistake by doing it correctly. How do I prevent shell expansion when rsync multiple files with ssh? | rsync --delete deleted most files in the destination directory, why? | rsync | That command boils down to this:rsync --delete --recursive /etc/logrotate.d/{httpd,mariadb,php-fpm,ppp,wpa_supplicant,yum} [email protected]:/etcThe . in there has its literal meaning - it's part of the name - so that isn't the problem. The part in {} is subject to brace expansion: each comma-separated part gets expanded and concatenated to the part of that argument that came before (/etc/logrotate.d/). (It'd also get anything after, if there were anything: a{BC}d expands to aBd aCd).So this command is equivalent torsync --delete --recursive /etc/logrotate.d/httpd /etc/logrotate.d/mariadb /etc/logrotate.d/php-fpm /etc/logrotate.d/ppp /etc/logrotate.d/wpa_supplicant /etc/logrotate.d/yum [email protected]:/etcor to pick just one directory out so it's short:rsync --delete --recursive /etc/logrotate.d/httpd [email protected]:/etcrsync interprets the from location as a single entity, and if it doesn't end with a / it makes a new file or directory with just the last part of that name inside the given destination path: here, that's httpd. So this makes a /etc/httpd on the destination and copies the contents of /etc/logrotate.d/httpd into it.With --delete, it will then delete everything that wasn't in /etc/logrotate.d/httpd on the source. The problem since /etc/logrotate.d/httpd probably doesn't exist at all, copying it and deleting any files that weren't present on the source means deleting everything in all of those directories. If it did exist, its contents won't be the same as /etc/httpd, so (almost) everything will be deleted.So the problem is just that you have the logrotate.d part there at all, when you really meant to copy the same directories under /etc. What you probably meant was just:rsync --progress --delete -avhHe ssh /etc/{httpd,mariadb,php-fpm,ppp,wpa_supplicant,yum} [email protected]:/etcThat copies /etc/httpd and its contents to /etc/httpd on the destination, and so on. If you meant to copy things inside logrotate.d, put that in the path on both sides.One thing you may find useful is the -n or --dry-run option to rsync:-n, --dry-run perform a trial run with no changes madeThat will show you a preview of what would happen, but not actually make any changes on either end. You can use that to check it's what you want before running the real thing.You asked how to prevent shell expansion in the arguments you gave to rsync. As above, I don't think that's actually what you want given the problem you had, but if you do ever need to: brace expansions don't take place inside quotes, so a{BC}d stays as a{BC}d literally. |
_softwareengineering.215470 | I am in the final stages of development for my Revit plugin. This plugin is programmed in C#, and distributed via a DLL. One of the DLLs is an encrypted SQLite database (with proprietary data) that is in the form of a DLL. Currently, in development stages, the decryption key for the SQLite database is hardcoded in my main DLL (the program's DLL). For distribution, since DLLs are easily decompilable, I am in need of a new method to decrypt the DLL. My solution is to send our decryption keys from our servers securely to the host's computer.I was looking in POST, thinking it was more secure than GET, but upon research, it appears it's similarly insecure, only more obscure than GET. I also looked into HTTPS, but Hostgator requires extra money for HTTPS use.I am in need of some advice - are there any custom solutions I can do to implement this? | Safest way (i.e. HTTPS, POST, PGP) to send decryption keys through the web? | encryption | null |
_unix.388542 | I have just created a new directory called sync in the location /home/sync.I created the directory as user liam, I then done a chown -R rslsync:rslsync /home/sync. This changed the owner to user rslsync no problem. I added myself liam to the rslsync group. I then created another folder in the directory named test so the directory is now /home/sync/test. When I try to point my rslsync folder location to be /home/sync/test it tells me rslsync doesn't have write permissions to the folder. I run an ls -l and it shows root root.How does an owner of the top directory folder rslsync not have access to one of its sub folders thats created by another user thats even in the same group as itself? Am I missing something here?EDITdrwxr-xr-x. 3 rslsync rslsync 18 Aug 26 17:09 /home/syncdrwxr-xr-x. 2 root root 6 Aug 26 17:09 /home/sync/testWhen i created the folder test i used sudo as it wouldnt let me create it otherwise.Group liam shows as thisliam : liam wheel rslsync | Why cant owner of folder write to a folder created by a different user | permissions;group | null |
_webmaster.7970 | I know that Google has a duplicate content penalty for text, such as articles, etc.However, does Google apply this penalty to two identical designs, such as templates?I'm guessing that Google only cares about the content and not the internal markup/structure that makes up a web page, right? | Does Google consider a site's markup when filtering duplicate content? | seo;google;web development;search engines | null |
_codereview.127822 | I would like some feedback on my solution for the trip programming challenge. Please go through my code understanding that I am interested in interviewing for a dev position at some point and am also interested in competitive programming (I'm just getting started):'''@author: TeereraiThis code is intended to calculate the minimum that a number of students needs to exchange in order to get the ammounts that they spend to within one cent of each other. The idea is to calculate the average then round it up and down to the nearest cent. The next step is to calculate the cumulative absolute positive and negative difference for each ammount spen from the nearest rounded average spend and take the maximum between the cumulative positive and negative difference.'''import sysfrom sys import stdinimport mathfrom decimal import Decimaldef main(): num_students=int(stdin.readline()) #read number of students while num_students!=0: i=num_students total_spending=0 student_spending=[] # stores amount spend by each student pos_difference=0 # Keeps track of cumulative absolute difference between average spend and ammounts higher than the average. neg_difference=0 #Keeps track of cumulative negative difference. for i in range(i): current_spending=float(stdin.readline()) student_spending.append(current_spending) total_spending+=current_spending average_spending=total_spending/num_students #these following two variables account for the fact that we can never get to the exact average. lower_average_spending=math.floor(average_spending*100)/100 upper_average_spending=math.ceil(average_spending*100)/100 #As the challenge specifies, we are not aiming to get the ammount spend to the exact average but rather to either the nearest cent above and below it. for element in student_spending: if element>average_spending: pos_difference=pos_difference+element-upper_average_spending else: neg_difference=neg_difference+lower_average_spending-element amount_exchanged=Decimal(max(neg_difference,pos_difference)) amount_exchanged=round(amount_exchanged,2) print($,amount_exchanged,sep=) num_students=int(stdin.readline()) return main()sys.exit(0)p.s. the code works perfectly and has been accepted by the uva online judge. I am simply looking for advice. | The trip programming challenge | python;programming challenge | Readability countsYou follow PEP8 naming conventions but fail to follow layout ones. The result is a big block of code that get harder to read than necessary. Use spaces and blank lines to give the reader some rest.You should also get yourself familiar with the if __name__ == '__main__' idiom and remove some unnecessary stuff:return at the end of a function has no added value;same for sys.exit(0) at the end of a program.Break functionnality into tinier functionAs it stand, your main function does 3 things:Compute the required value;Parse the input for information about computing such value;Parse the input to repeat such computation for a number of trips.You should use 3 functions instead, each responsible of its own task. Or at least split the parse input for a trip and compute the value for this trip part into its own function.Define variables when you need themPython is a dynamic language, you don't need to define variables before using them, nor preallocate memory for them. Just declare a new variable when you need it.You should also aim at removing the number of intermediate variables that you use only once.Use builtinsinput, max, sum and list-comprehensions can help you express your thoughts in a more straighforward way.str.format can help you with rounding and formatting output.Proposed improvementsimport mathfrom decimal import Decimaldef compute_expenses_for_a_trip(students_count): students_spending = [float(input()) for _ in range(students_count)] average_spending = sum(students_spending) / students_count # these following two variables account for the fact that we can never get to the exact average. lower_average_spending = math.floor(average_spending * 100) / 100 upper_average_spending = math.ceil(average_spending * 100) / 100 pos_difference = sum(element - upper_average_spending for element in students_spending if element > average_spending) neg_difference = sum(lower_average_spending - element for element in students_spending if element < average_spending) return Decimal(max(pos_difference, neg_difference))def trip_programming_challenge(): while True: num_students = int(input()) # read number of students if not num_students: break amount_exchanged = compute_expenses_for_a_trip(num_students) print('${:.2f}'.format(amount_exchanged)) if __name__ == '__main__': trip_programming_challenge()I didn't enforce a line length of 80 characters but you might want to.I'm also unsure why you introduced Decimal that late into the computation. Either you use them all along or you remove them, but introducing them halfway through kind of defeat their purpose.Also note that the two summed differences are mainly proposed as an alternative syntax but since they iterate two times over the same list you may find your for loop faster. If it matters, profile and choose the best. |
_codereview.64224 | Is there a way to cut-off using div elements in my design or it is good enough? I use Boostrap CSS library.CSS:body { border: 3px solid black; min-width: 1800px;}#search_box { border: 3px solid red; background-color: white; color: black; text-align: left; margin-bottom: 15px; width: 40%;}#search_filter_border { border: 3px solid green; /*border: 1px outset gray;*/ float: left; padding: 10px; }#search_categories_filter { border: 3px solid blue; line-height: 20px; height: 420px; width: 250px; float: left; padding: 10px; margin: 5px 5px 5px 5px;}#search_additional_filters { border: 3px solid brown; width: 700px; float: left; padding: 10px; margin: 5px 5px 5px 5px;}#top20 { border: 3px solid gray; width: 650px; padding: 5px; margin: 5px 5px 5px 50px; float: left;}HTML:<div id=search_box> <h2> :</h2> <div id=searchKeyword class=input-group> <i class=glyphicon glyphicon-search input-group-addon></i> <input type=text class=form-control placeholder= ng-model=actionsQuery.searchText on-enter=queryResult()> <span class=input-group-btn> <button class=btn btn-primary type=button ng-click=queryResult()> </button> </span> </div></div><div id=search_filter_border> <div id=search_categories_filter> <label> :</label><br/> <button class=btn btn-link btn-mini ng-click=UpdateCheckBoxes()> <span ng-show=checkBoxesState> </span> <span ng-hide=checkBoxesState> </span> </button> <div class=row-fluid ng-repeat=at in actionsQuery.actionTypes> <div class=checkbox> <label><input type=checkbox ng-model=at.checked>{{at.Description}}</label> </div> </div> </div> <div id=search_additional_filters> <label tooltip-popup-delay='400' tooltip-placement=right tooltip= - , - > :</label> <div class=form-inline row role=form> <div class=col-sm-4> <div class=input-group> <label class=input-group-addon> </label> <input datepicker-popup class=form-control col-md-4 type=text ng-model=actionsQuery.fromDate is-open=fromDateOpen/> <i class=glyphicon glyphicon-calendar input-group-addon ng-click=toogleDatepicker($event, 'fromDateOpen')></i> </div> </div> <div class=col-sm-4> <div class=input-group> <label class=input-group-addon> </label> <input datepicker-popup class=form-control col-md-4 type=text ng-model=actionsQuery.toDate is-open=toDateOpen/> <i class=glyphicon glyphicon-calendar input-group-addon ng-click=toogleDatepicker($event, 'toDateOpen')></i> </div> </div> <div class=col-sm-4> <div class=input-group> <span class=input-group-addon><input type=checkbox ng-model=actionsQuery.isOpenDatesIncluded></span> <label class=form-control col-md-3>+ </label> </div> </div> </div> <br/> <!--, --> <div class=row> <div class=form-group col-sm-8> <label>:</label> <div class=input-group> <i class=glyphicon glyphicon-filter input-group-addon></i> <select class=form-control ng-model=actionsQuery.city ng-options=c as c.Name for c in cities></select> </div> <br/> <label> :</label> <div class=input-group> <i class=glyphicon glyphicon-filter input-group-addon> </i> <select class=form-control ng-model=actionsQuery.actionPlace ng-options=ap as ap.Name for ap in actionPlaces></select> </div> </div> </div> </div> <!-- --> <div class=row-fluid offset1> <table class=table table-striped table-condensed table-hover style=float: left><!--float: left Mozilla --> <tr ng-repeat=action in actionList> <td><img ng-src={{action.ActionLogoUrl?action.ActionLogoUrl:'/img/no_image.gif'}} /></td> <td> <div> <strong>{{action.Artist}}</strong> <span class=pull-right><a class=btn btn-link ng-click=showSeances(action) ng-hide=action.seances> </a></span> <span class=pull-right><a class=btn btn-link ng-click=hideSeances(action) ng-show=action.seances> </a></span> </div> <div class=text-success> {{action.ActionPlaceName}} <span ng-show=action.ETicketEnabled>0 class=label label-success>ET</span> </div> <!-- --> <table class=table table-striped ng-show=action.seances style=margin-bottom: 3px; margin-top: 10px;> <tr ng-class=getSeanceClasses(seance) ng-repeat=seance in action.seances> <td> <h5 class=checkbox>{{seance.title}}</h5> </td> <td> <span ng-show=seance.IsClosed></span> <span class=text-warning ng-show=seance.IsPaymentsReceived></span> </td> <td> {{seance.ActionInfo}} </td> <td> <a class=btn btn-link ng-href=/Order.aspx?ActionID={{action.Id}}&ActionDate={{seance.ActionDate}} target=_blank></a> </td> </tr> </table> <span><a class=btn btn-link ng-show=action.seances.length>seancesLimit ng-click=seancesLimit=seancesLimit+7> ...</a></span> </td> <td>{{action.BeginActionDate | date:'dd.MM.yyyy HH:mm'}}</td> </tr> </table> <input type=button class=btn value= ng-click=queryNext() ng-hide=isLastPage style=float: left/><!--float: left Mozilla --> </div></div><div id=top20 class=col-md-4 row-fluid ng-if=top20 && top20.length!=0> <label style=text-decoration: underline;>p 20:</label> <p ng-repeat=t in top20> <a class=btn-link ng-href=/Order.aspx?ActionID={{t.ActionID}} target=_blank>{{t.Artist}}</a> </p></div> | Can the number of div elements be reduced in this design? | html;css | null |
_vi.767 | In my default Vim settings I've enabled a gutter and line numbers. Sometimes I copy some lines to clipboard in order to paste somewhere else. Currently I need to disable line numbers and the gutter. Otherwise they are included selection and thus in the copied text. Then I select the lines with my mouse and copy them using CtrlShiftv. After copying I can re-enable line numbers and gutter again. Is it possible without disabling line numbers and gutter? | How to select and copy lines to clipboard which are selected by mouse without linenumbers and gutter? | cut copy paste;os clipboard;mouse | The trick is to enable the mouse with :set mouse=a.By default, Vim doesn't handle the mouse; the terminal emulator does, and from the terminal emulator's perspective it's all text, it can't distinguish between your number or gutter.gVim emulates a terminal emulator in many ways, and acts in the same way.Then enabling the mouse, it's Vim that does all the mouse handling, and Vim does know what your gutter is, and what your actual text buffer is, so it can handle selection more intelligently.Note that using set mouse=a has some side-effects; clicking anywhere in Vim will put the cursor there, and you can now scroll Vim buffers with your mouse wheel, instead of your terminal's scrollback (both can be considered either bugs or features, depending on your preferences). |
_unix.34973 | From what I can understand of LSB documentation, neither wget or netcat are standard tools always available in an LSB environment.Is there some other way to make a http request without being dependent on anything else than LSB?What would be the most safe tool to be dependent on if I want to make it as simple as possible for users of my tool? | bash script with network request in pure lsb environment | linux;networking;shell script;standard | I see that the LSB includes both Perl and Python...Python, at least, includes http tools in the standard library. I didn't investigate to see if the LSB mandates libwww-perl. If you don't want to write anything yourself and you're happy with output to stdout, you can do this:python -murllib http://example.com/And if you're feeling really motivated, you can write a simple http client in bash. |
_unix.359852 | I'm running a fully updated Arch Linux system. Two days ago Dolphin began having a strange problem that I haven't encountered in my ten years of using KDE.When I open any file by clicking on the file in Dolphin, the associated application opens as expected, but then the file panes* within Dolphin become unresponsive. Dolphin will then not open any more files. However, the Dolphin menus are still responsive.If I close Dolphin and reopen it, it will again open just one file and become unresponsive within the file panes.As a work-around I found that if I right click a file and select Open With... and then pick the application (even the default application), the problem does not happen. I can open as many files as I wish using the context menu and Open With.UPDATE: This only happens in one user profile. I created a new user and logged into KDE and the problem is not present for that new user.Any ideas as to what could be causing this?*NOTE: What I'm calling the file panes within Dolphin are the areas where files and directories are displayed. One Dolphin reference calls these areas the workspace. I typically run the split view, so there are two workspaces. To be totally accurate, the Places pane (bookmarks) and the Folders pane also become unresponsive. But the main menu works, shortcuts work, toolbar icons work, I can open a new tab, etc. The Dolphin app is not hung. Another note: when I open a new tab, the file panes are unresponsive in that new tab too.UPDATE2: I'm offering a bounty. The answer I'll accept for the bounty must point me to the configuration (or other) files that are causing the problem and point out the specific issues in those files. I want to accomplish 2 things: 1) fix the issue without blowing away the user, and 2) learn specifically what caused the problem. For the bounty, I will not accept any answer that is based on creating a new user account or similar. Thanks. | KDE Dolphin becomes unresponsive after opening any file | files;kde;gui;dolphin | null |
_unix.76100 | I have LUbuntu 13.04.Is it possible to change the keyboard on the operating system, so that when I press k for instance, the system will hear it as I actually typed m?Or any other key for that matter.The thing is that the keyboard really isn't setup the way I would want to have it. If I could change the OS's keyboard then my efficiency would increase big time, especially in the long run as I could for instance, slowly evolve my keyboard towards a more efficient setting, such as Dvorak.here | Change one typed key for another | debian;keyboard;key mapping | null |
_codereview.164410 | I've written a script to harvest Name and Phone number from yellowpage Canada under pizza category. The web page doesn't show its full content until scrolled downmost. In my crawler's every cycle, it fetches 40 records. I twitched a little in my loop which I've learnt lately to get the full content. Hope I did it the way it should be.import requestsfrom lxml import htmlBase_url=https://www.yellowpages.ca/search/si/{0}/pizza/Torontowith requests.session() as session: page_num=1 while True: response = session.get(Base_url.format(page_num)) if response.status_code==404: break tree = html.fromstring(response.text) for titles in tree.xpath(//div[@itemprop='itemListElement']): try: title = titles.xpath(.//h3[@itemprop='name']/a/text())[0] except IndexError: title= try: phone= titles.xpath(.//h4[@itemprop='telephone']/text())[0] except IndexError: phone= print(title,phone) page_num+=1 | Parser for a lazyloading yellowpage | python;python 3.x;web scraping | Applying PEP8 recommendations about naming and formatting,as well as wrapping the main logic in a main function and calling from within a if __name__ == '__main__': guard,the code would become easier to read and possible to import and test:import requestsfrom lxml import htmlurl_format = https://www.yellowpages.ca/search/si/{0}/pizza/Torontodef main(): with requests.session() as session: page_num = 1 while True: response = session.get(url_format.format(page_num)) if response.status_code == 404: break tree = html.fromstring(response.text) for titles in tree.xpath(//div[@itemprop='itemListElement']): try: title = titles.xpath(.//h3[@itemprop='name']/a/text())[0] except IndexError: title = try: phone = titles.xpath(.//h4[@itemprop='telephone']/text())[0] except IndexError: phone = print(title, phone) page_num += 1if __name__ == '__main__': main()I'm not a huge fan of using exceptions in situations that are not really exceptions, like here:try: title = titles.xpath(.//h3[@itemprop='name']/a/text())[0]except IndexError: title = What if a titles.xpath(...) call would raise an IndexError due to a bug? It would be inadvertently caught and unnoticed.Catching IndexError here is an indirect way of the real intention,which is getting the first title if it exists.It would be better to write the code in a way that expresses the intention directly, for example:for item in tree.xpath(//div[@itemprop='itemListElement']): title = get_first_or_empty(item, .//h3[@itemprop='name']/a/text()) phone = get_first_or_empty(item, .//h4[@itemprop='telephone']/text()) print(title, phone)Where get_first_or_empty is:def get_first_or_empty(item, xpath): matches = item.xpath(xpath) if matches: return matches[0] return |
_unix.132293 | I use a simple alias to enable the tracking of commands in one or many terminal window(s):alias trackmi='export PROMPT_COMMAND=history -a; $PROMPT_COMMAND'Then I just tail -f my .bash_history file in another terminal on the workspace to get immediate feedback. I have just enabled unlimited history and updated my history format (export HISTTIMEFORMAT=[%F %T] ) in .bashrc. Of course the history command displays the timestamps. But the format the history file per se is:#1401234303alias#1401234486cat ../.bashrc How can I have the Unix time converted and the whole command displayed on a single line just like with the history command, including numbering:578 [2014-05-27 19:45:03] alias579 [2014-05-27 19:48:06] cat ../.bashrc ...and follow that. Or find a way to continuously output the output of the history command to the terminal? | How to have command history with timestamps output to the terminal continuously? | bash;text processing;command history;date | With GNU awk:tail -fn+1 ~/.bash_history | awk ' /^#/{printf %-4d [%s] , ++n, strftime(%F %T, substr($0, 2)); next}; 1' |
_unix.283584 | I'm trying to write a one liner that sources aliases, then calls one of those newly sourced aliases. My one liner is basically:alias startEnv sourceAliasFile;runNewAliasSince I'm using csh, I can't make a function. When I run this, my source executes but my new alias doesn't exist yet and does not execute. Why does this not work and is there a way to get around it? | How to execute alias right after sourcing it in a one liner? | alias | null |
_unix.208979 | I was looking at SQL Server 2000 today, and it has an argument in the EXECUTE command called -DelBkUps for deleting backups that are of a certain age.Does Linux have any tools for deleting backups that become too old? I would assume it would be something that is run from a cron job of some sort, or maybe part of a larger set of tools like something in Backula. I'm certain that something along these lines could be done with bash, but I'm looking for something a little more pre-built and widely used. | Linux tools for deleting backups when they get too old? | backup;disk usage;disk cleanup | null |
_unix.252623 | I have succeded (full story here) on installing some ethernet card that, according to the docs, must be manually started:# modprobe e1000bpI would like this driver startup to be performed on boot time. What is the proper method to achieve this? I thought about adding the command to /etc/rc.local, but for PPTP or OpenVPN connections there are another methods that are supposed to be more clean, so I was wondering if the same could be told for the drivers startup. | What is the proper way to start a driver on boot? | linux;drivers;startup;modprobe | null |
_unix.283209 | I was wondering if it is safe to delete Xfce themes and/or icon themes that I don't use to save disk space. Additionally, is there a apt or other package manager command to do this? Also, just in case this is important, I'm running Ubuntu 16.04. Thanks. | Removing xfce icons and themes | ubuntu;xfce;theme;icons | There is no reason at all not to remove those unused themes and icon sets.You could remove the packages that installed them but those are all meta packages and do not install just one theme or icon set at a time. Therefore you need to check the content of the meta package to see what they install.I have no idea what package managers with a gui are installed on Ubuntu of any version anymore.The recommended way would be to rm the files from /user/share/themes or /icons using the cli.The not recommended way would be to open your file browser as root and delete them that way. If you are using Xubuntu you have an awful lot of Gnome things installed to make it work, like nautilus to run the desktop. If you installed the xfce-desktop to an ubuntu netinstall I am not sure what all is installed because it would be up to the Ubuntu folks what exactly was in that meta package. If it includes the xfce4-goodies you have a lot more theme and icons probably installed than a real xfce4 install would give you if unaltered from the xfce devs version.Themes are usually not that large a file. Your space saving will be pretty minimal.Icon sets are pretty large though so I would concentrate on those to start with.The problem with removing them manually is that the package that installed them is still installed. If you moved the ones you use to a safe place and then found the packages from Ubuntu repos that installed them and removed those you could then put those icons back in /usr/share/icons.That would work fine. Except that the package including the icons is probably part of a larger meta package and so removing that icon package will remove your, probably, entire desktop environment. You can break meta packages with;aptitude keep-allThis simply changes the state of packages installed in a meta package from auto to manual allowing you to remove them individually. This is not something that should really be used much. You can really screw up your package management system doing so.It does work though.Your best approach to a light system is to do a netinstall for only the basic system with no DE or any X11 packages at all and then build the system yourself using as few meta packages as possible. This is time consuming, requires a fairly large list of packages to install and is not real exciting to do. It is very satisfying to get that lighter, smaller installation.It is also much easier to do on just about any distro that is not Ubuntu or Ubuntu based.They repackage Debian packages for their repos. In doing so they create meta packages that use more than one Debian meta package meaning that a lot of desktop environments will, if removed, remove all X11 packages. While this makes it easier to install a desktop environment it also means it is much harder to remove package that you don't need at all. If you are running actual Ubuntu with the xfce desktop added I would recommend re installing using just the Xubuntu 16.04 because you have a lot more packages related to Ubuntu and its Unity DE using space than any number of xfce icons or themes that you are not using. |
_webmaster.88342 | I've added a side menu successfully but when i want to change the color of it it doesn't work.The mid of the menu is still another grey and i dont know what to do.Tried to add style=background-color: grey; but it didn't made any difference. The Site I'm talking about | How to define the background color of this side menu? | html;css;menu | If you want to change the middle grey colour, in the CSS look for the following block of code:.sidebar-nav li { text-decoration: none; color: #fff; background: rgba(255,255,255,0.2);}then change the background line to whatever colour you want using that syntax or using the normal syntax:background-color: #F5F5F5; |
_cstheory.16143 | (This essentially copies my unaswnered questionfrom math.stackexchange.com/questions/275685)I was reading http://arxiv.org/abs/1201.4995, and I thoughtback to a game I used to play, which is close to being coveredby Metatheorem 3 (on page 5), but does not have one-way paths.What is the computational complexity of the following problem?For an undirected graph G whose vertices have non-negative integer weights,for vertices s and t, is there a path from s to t such that the sum of the weightsof the vertices (including s) reached at any given point along it is alwaysgreater than the number of distinct edges traversed to get to that point?(The vertices are not counted with multiplicity either.) | complexity of games with just doors and keys | cc.complexity theory;graph algorithms | If I understand your question correctly, by path you mean that we build up a tree starting from s by always taking an edge adjacent to our current tree. This problem is NP-complete, the reduction is from SAT.The main part of the graph will consist of n cycles of length four attached to each other at vertices s=v0, v1, v2, .., vn. So from s we have two paths of length two to v1, from v1 two paths to v2 and so on. From vn there will be a path of length N+1 to t.We will have only enough weights to use one of each pair of paths and depending on which path we use, the value of the variable xi will be true or false. The weight in s is N+2n, where N is some big number.Each clause is represented by an additional vertex that is connected by a path of length N to the center vertex of the path that corresponds to its literals and it has value N+epsilon (I know we need integers, but we can multiply up and replace each edge by 1/epsilon edges), where 1/epsilon is the number of clauses. So we have to visit every clause-vertex to get to t. |
_softwareengineering.35159 | I recently started using Haskell Platform. I created a source file using Wordpad and named it add. I tried double clicking it so I can open it in ghci but I get<[1 of 1] Compiling Main (C:\add.hs,interpeted)C:\add.hs:1:6: parse error on input '\'Failed modules loaded: none.>What do I do so I can use my source file?. Should I use another text editor?. Thanks | Haskell Using Source File Problems | haskell | null |
_softwareengineering.86510 | So, HTML5 is the Big Step Forward, I'm told. The last step forward we took that I'm aware of was the introduction of XHTML. The advantages were obvious: simplicity, strictness, the ability to use standard XML parsers and generators to work with web pages, and so on.How strange and frustrating, then, that HTML5 rolls all that back: once again we're working with a non-standard syntax; once again, we have to deal with historical baggage and parsing complexity; once again we can't use our standard XML libraries, parsers, generators, or transformers; and all the advantages introduced by XML (extensibility, namespaces, standardization, and so on), that the W3C spent a decade pushing for good reasons, are lost.Fine, we have XHTML5, but it seems like it has not gained popularity like the HTML5 encoding has. See this SO question, for example. Even the HTML5 specification says that HTML5, not XHTML5, is the format suggested for most authors.Do I have my facts wrong? Otherwise, why am I the only one that feels this way? Why are people choosing HTML5 over XHTML5? | Why not XHTML5? | html;html5;xml;xhtml | null |
_codereview.95271 | I have a PupilService which is calling the PupilRepository.AttachPupil() method.I have an N to M relation between SchoolclassCode and Pupil.Technical logic:A pupil can be related to many SchoolclassCode like Math 7 a or English 8 c.Business logic:A pupil can be related only to SchoolclassCode like Math 7 a or English 7 c. That means it's not possible for a pupil to belong to 2 different class numbers.A pupil can only be attached to a smaller class number during the year (changes happen in mid-year) thus all higher class relations must be removed.The business logic from 1) and 2) should be put elsewhere. It just does not fit into the PupilService or another Repository method because by splitting up the tasks in finer grained method It would causes more queries to do the same job. Further more if I split up the business logic the repo.AttachPupil would only work the half if the repository would be called directly. I do not like that either.public async Task AttachPupil(int pupilId, int targetSchoolclassCodeId){ var pupil = new Pupil { Id = pupilId }; context.Pupils.Attach(pupil); var targetSchoolclassCode = await context.SchoolclassCodes.SingleAsync(s => s.Id == targetSchoolclassCodeId); await context.Entry(pupil).Collection(p => p.SchoolclassCodes).LoadAsync(); var existingLowerSchoolclasses = pupil.SchoolclassCodes.Where( s => s.SchoolclassNumber < targetSchoolclassCode.SchoolclassNumber); if (existingLowerSchoolclasses.Any()) { throw new PupilAdvancedNextSchoolclass(A pupil can only downgrade a class within a schoolyear); } else { foreach (var schoolclassCodeToDetach in existingLowerSchoolclasses) { // Detach pupil from higher SchoolclassCode classes e.g. class 9 pupil.SchoolclassCodes.Remove(schoolclassCodeToDetach); } // Attach Pupil to a lower class becaue his grades/marks are too bad e.g. in the mid-year to class 8 targetSchoolclassCode.Pupils.Add(pupil); await context.SaveChangesAsync(); }}How would you refactor this AttachPupil method so that the business logic is better separated from the data access logic? | Separate business logic from Data Access Logic in the repository | c#;repository | First of all I'd say that your foreach loop will never loop, because it is only reached when there are no elements in existingLowerSchoolclasses. In general I would recommend to re-think your datastructure, especially with a view towards next year and the year after. Because then you'll wish you had identified classes like English 8 c 2014 or Math 7 d 2015. This will make it easier to enforce the constraints you described. If you're concerned about the number of queries you could use a stored transaction. Even that feels old-fashioned, in some cases it still makes sense to guard the access to N:M relations with those things. The question is always: Is it really a domain problem, or is it caused by the fact that your data structure doesn't adhere enough to the domain? If you can answer that, you'll know where to put the Data Access Logic. Last of all let me be honest: Whenever I see a N:M relation I get very suspicious about it. In most real-world situations, there are no anonymous N:M relations. A student started a class at a certain time and left it at another, also different students could have different mentors within one course, and there might be much more attributes you might want to assign to that relationship in the future. Therefore I would advise you to remodel this relation, e.g. by introducing a ClassMembership entity. |
_unix.370064 | I'm trying to migrate my configuration from Nagios to Shinken. I have something like this.define hostgroup { hostgroup_name group3 alias Group 3 hostgroup_members group1, group2 members !member2}It seems that Shinken does not understand the ! symbol. How do I exclude members from a hostgroup? | How to exclude member from a hostgroup in Shinken? | configuration;nagios | null |
_unix.5300 | I need easily updatable troubleshooting LiveUSB distro. By troubleshooting I mean that it should not have nothing fancy (X is used o display gparted etc.) but should have access to file archivers/undeleting etc. tools.Unfortunately most LiveUSB distros are modified LiveCD ones so they assume sequential and slow base device (as opposed to USB flash disk which is fast compared to CD, have 0 latency and have much number of writes to it). The only method of updating is overwriting the previous content.I'd like to have 'easy' package manager on distro to allow installing tools I need and from time to time an update which would not destroy any customisation. On the other hand I still would like to have autodetection scripts etc. | Easily updatable troubleshooting LiveUSB distro | distros;live usb | null |
_cs.45249 | So here is the problem: There are n objects in a super market that you need to retrieve, then you need to go to the cashier register in the end. How do you find the best path of traversing the least distance to retrieve the objects and finally go to the cashier register?I could only find a brute force method of finding optimal path of each permutation of paths and seeing which overall distance covers the least traversing. But this implementation is O(n!). Is there a more efficient approach? | optimal path for traversing nodes | optimization;graph traversal;searching | null |
_unix.138669 | I am trying to login from cURL command line with the commandcurl --data username=user&password=pass&submit=Login http://www.ip.com:8080/LoginApplication/Login.jspAnd after that trying to access inner page usingcurl http://www.ip.com:8080/LoginApplication/Success.jspBut I am getting redirected to error page because of not logged in.What I am missing in my first command so that it can maintain the session?I have my website locally hosted | Login site using cURL | curl | Well, you'll need to store the session data in a cookie. You can use -c cookie_filename to create the cookie (add this to your login command). And then, for the other requests, you can read from the cookie with -b cookie_filename.In example:curl -s loginpage -c cookiefile -d user=myself&pass=securecurl -s secretpage -b cookiefileEDIT:Notice many times loginpage is not the page you open with your web browser where you introduce your user and password. You'll have to check where the form is posting that data to (search the <form> tag in the source code and the action=... attribute). So, for example, if you want to log in to http://criticker.com, loginpage is http://www.criticker.com/authenticate.php and not http://www.criticker.com/signin.php, which is the one you open with your browser.If you use Firefox, a plugin like Tamper may help you find the correct loginpage and all the data that is being posted to it (like hidden input fields in the form). |
_codereview.11474 | I have many-to-many mapping with extra columns in the join table. The table structure looks like this:table vendor{vendor_id, vendor_name, vendor_password, etc...}table student{student_id, student_name, student_password, etc..}table test{test_id, test_subject, test_price,test_level, etc..}Relations as follows:vendor to test --> many-to-manystudent to test --> many-to-manyThe link:table vendor_student_test{vendor_id, student_id, test_id, purchasedDate, assignedDate, writtenDate, result}I've created POJO classes as follows:Vendor.javapublic class Vendor { private Long vendorId; private String vendorName; private String vendorPassword; private Set<VendorStudentTest> tests; private boolean isVendorActivate; public boolean isVendorActivate() { return isVendorActivate; } public void setVendorActivate(boolean isVendorActivate) { this.isVendorActivate = isVendorActivate; } public Set<VendorStudentTest> getTests() { return tests; } public void setTests(Set<VendorStudentTest> tests) { this.tests = tests; } public Long getVendorId() { return vendorId; } public void setVendorId(Long vendorId) { this.vendorId = vendorId; } public String getVendorName() { return vendorName; } public void setVendorName(String vendorName) { this.vendorName = vendorName; } public String getVendorPassword() { return vendorPassword; } public void setVendorPassword(String vendorPassword) { this.vendorPassword = vendorPassword; }}Student.javapublic class Student { private Long studentId; private String studentName; private String studentPassword; private Set<VendorStudentTest> tests; public Set<VendorStudentTest> getTests() { return tests; } public void setTests(Set<VendorStudentTest> tests) { this.tests = tests; } public Long getStudentId() { return studentId; } public void setStudentId(Long studentId) { this.studentId = studentId; } public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } public String getStudentPassword() { return studentPassword; } public void setStudentPassword(String studentPassword) { this.studentPassword = studentPassword; }}Test.javapublic class Test{ private Long testId; private String testSubject; private int testTotalNoOfQuestions; private double testPrice; public Long getTestId() { return testId; } public void setTestId(Long testId) { this.testId = testId; } public String getTestSubject() { return testSubject; } public void setTestSubject(String testSubject) { this.testSubject = testSubject; } public int getTestTotalNoOfQuestions() { return testTotalNoOfQuestions; } public void setTestTotalNoOfQuestions(int testTotalNoOfQuestions) { this.testTotalNoOfQuestions = testTotalNoOfQuestions; } public double getTestPrice() { return testPrice; } public void setTestPrice(double testPrice) { this.testPrice = testPrice; } public int getTestLevel() { return testLevel; } public void setTestLevel(int testLevel) { this.testLevel = testLevel; } public Set<Question> getTestQuestions() { return testQuestions; } public void setTestQuestions(Set<Question> testQuestions) { this.testQuestions = testQuestions; } private int testLevel; private Set<Question> testQuestions;}VendorStudentTest.javapublic class VendorStudentTest { private VendorStudentTestPK vendorStudentTestPK; private Date assignedDate; private Date purchasedDate; private Date writtenDate; private double result; public VendorStudentTestPK getVendorStudentTestPK() { return vendorStudentTestPK; } public void setVendorStudentTestPK(VendorStudentTestPK vendorStudentTestPK) { this.vendorStudentTestPK = vendorStudentTestPK; } public Date getAssignedDate() { return assignedDate; } public void setAssignedDate(Date assignedDate) { this.assignedDate = assignedDate; } public Date getPurchasedDate() { return purchasedDate; } public void setPurchasedDate(Date purchasedDate) { this.purchasedDate = purchasedDate; } public Date getWrittenDate() { return writtenDate; } public void setWrittenDate(Date writtenDate) { this.writtenDate = writtenDate; } public double getResult() { return result; } public void setResult(double result) { this.result = result; }}VendorStudentTestPK.javapublic class VendorStudentTestPK { private Vendor vendor; private Student student; private Test test; public VendorStudentTestPK() { super(); // TODO Auto-generated constructor stub } public VendorStudentTestPK(Vendor vendor, Student student, Test test) { super(); this.vendor = vendor; this.student = student; this.test = test; } public Vendor getVendor() { return vendor; } public void setVendor(Vendor vendor) { this.vendor = vendor; } public Student getStudent() { return student; } public void setStudent(Student student) { this.student = student; } public Test getTest() { return test; } public void setTest(Test test) { this.test = test; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((student == null) ? 0 : student.hashCode()); result = prime * result + ((test == null) ? 0 : test.hashCode()); result = prime * result + ((vendor == null) ? 0 : vendor.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof VendorStudentTestPK)) return false; VendorStudentTestPK other = (VendorStudentTestPK) obj; if (student == null) { if (other.student != null) return false; } else if (!student.equals(other.student)) return false; if (test == null) { if (other.test != null) return false; } else if (!test.equals(other.test)) return false; if (vendor == null) { if (other.vendor != null) return false; } else if (!vendor.equals(other.vendor)) return false; return true; }}Hibernate mapping files as follows:vendor.hbm.xml<class name=Vendor table=vendor> <id name=vendorId type=long column=vendor_id> <generator class=increment/> </id> <property name=vendorName column=vendor_name type=string/> <property name=vendorPassword column=vendor_password type=string/> <set name=tests table=vendor_student_test inverse=true lazy=true fetch=select> <key> <column name=vendor_id not-null=true /> </key> <one-to-many class=VendorStudentTest /> </set> </class>vendor_student_test.hbm.xml<class name=Vendor table=vendor> <composite-id name=vendorStudentTestPK class=com.onlineexam.model.VendorStudentTestPK> <key-property name=vendorId column=vendor_id type=java.lang.Long /> <key-property name=studentId column=student_id type=java.lang.Long /> <key-property name=testId column=test_id type=java.lang.Long /> </composite-id> <many-to-one name=vendor class=Vendor insert=false update=false/> <many-to-one name=student class=Student insert=false update=false/> <many-to-one name=test class=Test insert=false update=false/> </class>student.hbm.xml<class name=Student table=student> <id name=studenId type=long column=student_id> <generator class=increment/> </id> <property name=studentName column=student_name type=string/> <property name=studentPassword column=student_password type=string/> <set name=tests table=vendor_student_test inverse=true lazy=true fetch=select> <key> <column name=student_id not-null=true /> </key> <one-to-many class=VendorStudentTest /> </set> </class>test.hbm.xml//this is mapped to other table I am new to hibernate. Is this correct mapping? | Many-to-many hibernate mapping if link table is having extra columns mappings | java;beginner;hibernate | null |
_cogsci.10065 | It has a name. I thought it was called 'collective' memory. .. But I cant find any articles or information about it.. So I guess it has a different name. There were a few cases where children were successful in recalling the memories of their past ancestors.How is that type of memory called? and are there articles about it?UPDATEFor the skeptics, watch the few first minutes of this doc..(or all of it)https://www.youtube.com/watch?v=uBkJLTTea34I did learn in my first psychology lessons about that memory. I cant remember wellthe case study that I studied.. but it involved a non-speaking German woman who after being hypnotized was able to talk German and recall her past life. | How is the type of memory that is passed through generations called? | memory;terminology | null |
_codereview.102080 | My Racetrack is just that. A Racetrack. You can't race it (yet) because I had trouble with collision detection, but I wanted to share it anyway.It creates a base polygon by using numpy and shapely. matplotlib (together with descartes) does the plotting and cPickle is used to write states to file so the exact same track can be plotted later.This is my first Python script using argparse instead of sys for argument handling. I'm especially interested in whether the way I implemented it is up to par.The way it's structured is probably not the best either and as always I'm not too fond of my naming. I stuck to -r and -w for reading and writing because it seemed intuitive, but deeper in the code load_state and save_state are used. I'm not sure this is acceptable and which of both I should stick with (if any of those at all).Under the argument parsing I have a couple of BOLD_SNAKE_CASE variables which are pseudo constants. There's probably a better way to do this. Some of those can be freely changed by the user, others shouldn't. I think it's self explanatory enough, but feel free to comment.As said, it was supposed to be part of an actual Racetrack-game. So extendability is important. I like extra features, but those are a pain in the behind to implement if the code isn't modular.import numpy as npimport matplotlib.pyplot as pltimport shapely.geometry as sgfrom argparse import ArgumentParserfrom descartes.patch import PolygonPatchfrom cPickle import load, dump# Argument handlingparser = ArgumentParser(description='Racetrack')parser.add_argument( 'InnerAmplitude', type=float, help='For example 0.1' )parser.add_argument( 'OuterAmplitude', type=float, help='For example 0.2, should be higher than InnerAmplitude' )parser.add_argument( -v, --verbose, action=store_true, help=increase output verbosity )mutex = parser.add_mutually_exclusive_group()mutex.add_argument( -r, --read, action=store_true, help=read state from file )mutex.add_argument( -w, --write, action=store_true, help=write state from file )args = parser.parse_args()# Define size of inner and outer bounds, between those is the RacetrackINNER_AMPLITUDE = args.InnerAmplitudeOUTER_AMPLITUDE = args.OuterAmplitudeDIAMETER = OUTER_AMPLITUDE - INNER_AMPLITUDESIZE = 1.5OUTER_WIDTH = 2MINIMUM_POINTS = 5MAXIMUM_POINTS = 15LOAD_FILE = state_fileSAVE_FILE = LOAD_FILEdef load_state(): with open(LOAD_FILE, r) as file: np.random.set_state(load(file))def save_state(): with open(SAVE_FILE, w) as file: dump(np.random.get_state(), file)# Possibility to fix seedif args.verbose: print (np.random.get_state())if args.read: load_state()elif args.write: save_state()# A function to produce a pseudo-random polygondef random_polygon(): nr_points = np.random.randint(MINIMUM_POINTS, MAXIMUM_POINTS) angle = np.sort(np.random.rand(nr_points) * 2 * np.pi) dist = 0.3 * np.random.rand(nr_points) + 0.5 return np.vstack((np.cos(angle)*dist, np.sin(angle)*dist)).T# Base polygonpoly = random_polygon()# Create a shapely ring object from base polygoninner_ring = sg.LinearRing(poly)outer_ring_inside = inner_ring.parallel_offset(DIAMETER, 'right', join_style=2, mitre_limit=10.)outer_ring_outside = inner_ring.parallel_offset(OUTER_WIDTH * DIAMETER, 'right', join_style=2, mitre_limit=10.)# Revert the third ring. This is necessary to use it to produce a holeouter_ring_outside.coords = list(outer_ring_outside.coords)[::-1]# Inner and outer polygoninner_poly = sg.Polygon(inner_ring)outer_poly = sg.Polygon(outer_ring_inside, [outer_ring_outside])# Create the figurefig, ax = plt.subplots(1)# Convert inner and outer polygon to matplotlib patches and add them to the axesax.add_patch(PolygonPatch(inner_poly, facecolor=(0, 1, 0, 0.4), edgecolor=(0, 1, 0, 1), linewidth=3))ax.add_patch(PolygonPatch(outer_poly, facecolor=(1, 0, 0, 0.4), edgecolor=(1, 0, 0, 1), linewidth=3))# Finalizationax.set_aspect(1)plt.title(Racetrack)plt.axis([-SIZE, SIZE, -SIZE, SIZE])plt.grid()plt.show()Example usage:python racetrack.py -w 0.1 0.25Example output:Not all tracks are playable, since there is nothing checking whether the angles are too sharp. This isn't considered a problem at the moment. | Racetrack plotter | python;python 2.7;numpy;community challenge;matplotlib | This is my first Python script using argparse instead of sys for argument handling. I'm especially interested in whether the way I implemented it is up to par.You nailed it :-)Under the argument parsing I have a couple of BOLD_SNAKE_CASE variables which are pseudo constants. There's probably a better way to do this.That's the common practice in Python, and it's fine like that.Except for these:INNER_AMPLITUDE = args.InnerAmplitudeOUTER_AMPLITUDE = args.OuterAmplitudeDIAMETER = OUTER_AMPLITUDE - INNER_AMPLITUDEAs these are values derived from the command line arguments.The parsing logic would be better in a main() function,which will determine the value of diameter,and pass it to a plot(diameter) function that will take care of the plotting logic.The biggest issue I see is with the layout:ImportsArgument parserConstantsSome functionsArgument handlingAnother functionThe main plotting logicI suggest to reorganize like this:ImportsConstantsHelper functionsdef plot(): The main plotting logicdef main():Argument parserArgument handlingif __name__ == '__main__': guard that simply calls main()After this change, I think it will look a lot better and clearer. |
_webapps.46943 | I have written comments in 2010 on photos that are in a Facebook album which belongs to a group. Then, in 2011 I left the group. Now I want to delete/remove all my comments and likes there. How can I do this? The group is an open group. | How to remove comments/likes from a group that you left | facebook groups | null |
_codereview.122635 | Not sure how to make the title smaller. I was reading the question A truly amazing way of making the number 2016 and some of the answers referred to programatically determining the answer set. What I am doing is related to that in concept. Given a range of number 1 to X determine all possible mathematical expressions that can be used with those numbers and group the results together to see which whole numbers prevail.function ConvertTo-Base{ [CmdletBinding()] param ( [parameter(ValueFromPipeline=$true,Mandatory=$True, HelpMessage=Base10 Integer number to convert to another base)] [int]$Number=1000, [parameter(Mandatory=$True)] [ValidateRange(2,20)] [int]$Base ) [char[]]$alphanumerics = 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ do { # Determine the remainder $Remainder = ($Number % $Base) # Get the associated character and add it to the beginning of the string. $newBaseValue = $($alphanumerics[$Remainder])$newBaseValue # Adjust the number to remove the calculated portion $Number = ($Number - $Remainder) / $Base # Loop until we have processed the whole number } while ($Number -gt 0) return $newBaseValue}# Variables$maxRange = 3 #13 would make for the largest values 13!. Cap the script as 13$lowCountThreshold = 1 # Only show group results where the match exists more than five times. # Mathematical Operators [char[]]$operators = +-*/# Define the number range for calculations. 13 would make for the largest values 13!. Cap the script as 13$range = 1..$maxRange# Build the format string that will be used for invoking. Will look like 1{0}2{1}3. Acting as place holders for mathematic operators$formatString = -join (1..($range.count - 1) | ForEach-Object{$_{$([int]$_ - 1)}}) + $range[-1]# Determine the number of possible permutations of those operators inbetween the number set. $permutations = [System.Math]::Pow($operators.Count,$range.count - 1)# Cycle each permutation0..($permutations - 1) | ForEach-Object{ # Convert the number to a base equal to the element count in operators. Use those values to represent the index of the operators array. $mathString = $formatString -f @([string[]][char[]]((ConvertTo-Base -Number $_ -Base $operators.Count).PadLeft($range.count - 1,0)) | ForEach-Object{$operators[[int]$_]}) # Build an object that contains the result and the mathematical expression [pscustomobject]@{ Expression = $mathString Value = Invoke-Expression $mathString } # Since this take a while try and give the user some semblance of progress. Write-Progress -Activity Performing mathematical calculations -Status Please wait. -PercentComplete ($_ / $permutations * 100) -CurrentOperation $([math]::Round($_ / $permutations * 100))% Completed. # Filter for whole number and only give group results} | Where-Object{$_.Value -is [int32]} | Group-Object Value | Where-Object{$_.Count -ge $lowCountThreshold} | Sort-Object Count -DescendingSo if you were to run this and change the $maxValue to something smaller like 3 and change the you would Count Name Group ----- ---- ----- 2 6 {@{Expression=1+2+3; Value=6}, @{Expression=1*2*3; Value=6}} 1 0 {@{Expression=1+2-3; Value=0}} 1 7 {@{Expression=1+2*3; Value=7}} 1 2 {@{Expression=1-2+3; Value=2}} 1 -4 {@{Expression=1-2-3; Value=-4}} 1 -5 {@{Expression=1-2*3; Value=-5}} 1 5 {@{Expression=1*2+3; Value=5}} 1 -1 {@{Expression=1*2-3; Value=-1}} So there are two operations that would get 6. 1+2+3 and 1*2*3. Who would have thought! If you are testing this be careful of using larger numbers here. Running something like a 9 would take about 7 minutes give or take since it would have 65536 permutations to figure out and then group. The function helps me convert each permutation number into its mathematical operator sequence. I take a number and convert it into base4. Then take that and use each number to pull an element out of the operator array. Then use the format operator to populate the string and use invoke expression to get the result. | Grouping all mathematical results using a number sequence with basic math operators | math expression eval;powershell | null |
_unix.15894 | Is it possible to run mplayer in fullscreen in xmonad?When I use the -fullscreen switch or f command it does nothing. | Mplayer in fullscreen in xmonad | mplayer;xmonad | You can put fstype=none in your ~/.mplayer/config.For more discussion about this see this issue in the xmonad issue tracker. |
_unix.330640 | I use shell scripts to setup different types of VMs. Often these scripts include multiline variables that need to be inserted into config files at certain positions using sed.If I create them like this, everything is fine:VAR=Config Line1\nConfig Line2\nConfig Line 3sed -i /MatchingPattern/ a $VAR somefileThis doesn't make the script very readable though, especially since the text blocks can be quite long.If I write them like so:VAR=Config Line1Config Line2Config Line 3sed -i /MatchingPattern/ a $VAR somefileI get an error when running the script: sed: -e expression #1, char 31: unknown command:C'`Is there a way to use sed with variables declared like that? | Using sed in shell script with multiline variables | shell script;sed;variable | null |
_webmaster.28504 | So I'm working on a website (Beauty Salon website for my aunt)but I want to know if I can make my home computer a server. Is this a good idea or not? What are the requirements and will my computer have to be on all the time. | Can I make my home computer a server? | server | For a small business in this case, this is extreemly practical. I don't think the site be doing any of the following:1.Accepting payements2.Being viewed by more than 10 people in a day3.having lots and lots of data being updated, maintained etc.You can get a crappy old computer and install LAMP on it, leave it connected on and forget about it.This way you will have full control of everything while you are still developing etc. You can move the files etc. to a webhost later if it is needed. You will also learn more about website maintenance issues by trying it yourself.Just keep a back up copy of files / databases needed to make the site, but you have to do the same even if you were hosting somewhere else.You should ask about the requirements and how to do it in a separate question. But the basic requirements are not much. If you are doing this to learn about web development then you must try it, you will learn much more. |
_cs.43225 | I am trying to compare asymptotic runtime bounds of a few algorithms presented in this research paper, A quasi-polynomial algorithm for discretelogarithm in finite fields of small characteristic. The functions are, $L(\alpha) = \exp(O(\log(n)^{a}(\log\log(n))^{1-\alpha}))$, which I'd like to plot for $\alpha = 1/3, 1/4+O(1)$, and $1/4 + O(n)$,and $O(n^{\log n})$ Where n is the bit-size of the input. ... Such a complexity is smaller than any $L(\epsilon)$ for any $\epsilon > 0$ I would like to plot each of these functions together to compare their growth. The problem is that the second function grows much faster than the first, which implies I am misinterpreting something.So what is the correct way to interpret and compare these functions? | How to interpret these asymptotic runtime bounds for discrete logarithm algorithms? | asymptotics | The confusion is that in the expression for $L(\alpha)$, $n$ is size of the field, whereas in $n^{O(\log n)}$, $n$ is the size of the input. The correct comparison is between $L(\alpha) = \exp O((\log n)^\alpha (\log\log n)^{1-\alpha})$ and $(\log n)^{O(\log\log n)} = \exp O((\log\log n)^2)$, which is indeed much smaller.Note that your suggestion to plot $L(\alpha)$ for $\alpha = 1/4 + O(1)$ and $\alpha = 1/4 + O(n)$ doesn't make much sense; you should think of $\alpha$ as a constant. It could make sense to consider $\alpha = 1/4 + o(1)$ (or $\alpha = 1/4 + \epsilon$, where $\epsilon$ is understood to be small), though it's not clear how exactly you'd plot it. Indeed, there is no reason to plot, and a plot wouldn't make too much sense without knowing the hidden big O constant. In practice you just do experiments. |
_unix.85145 | I have a root folder with a text file in it called pairs.txt.Within that root folder are other folders with text files called pairs.txt in them.Is there a simple way to remove them using rm?I know that there I could use find . -name 'pairs.txt' -exec rm {} \; but I would like to know of other ways, perhaps using * or some other wildcard?I tried using rm -rf pairs.txt but it seems to only remove the pairs.txt in the current directory. | Removing specific files recursively using rm or something simple? | bash;rm;recursive | With bash 4+:shopt -s globstar dotglobrm -- **/pairs.txtThe globstar option makes ** match any number of directory levels. The dotglob option makes it include directories whose name begins with . (dot files).With ksh93, use set -o globstar instead of shopt -s globstar. To get the effect of dotglob, use FIGNORE=.With zsh, use the second line directly. To include dot files, run setopt glob_dots first or make the second line rm -- **/pairs.txt(D).Note that bash's ** follows symbolic links to directories. Ksh's and zsh's don't. |
_codereview.46214 | I usually take my school code as a playground to mess around with things. I was given a bunch of premade hash functions and had to test their output and find when they reach a specific lower range. Since the functions all have the same structure, I made a check function that uses a function pointer parameter(I think this is the most efficient way to deal with this problem?). Which I'm iterating through the potential keys to feed to all of the functions it I wanted it to stop at the first one of each, but couldn't think of a way to do so without using 11 individual flags or for loops. I've never messed with bitmasks (I specifically only remember the gist of them because there was a couple commands in quake3 that used them!), but I did that instead and it turned out to not be as pretty/elegant as I thought it would in practice.in short:How would you approach the assignment Using the given 11 hash functions, find each of their first 'low' output?void findLowHash();bool foundLow(unsigned int (*hash)(const std::string &key), std::string key);void findLowHash() { string key; key.push_back(0); int mask = 2047; for (int i = 0; i < 100000; ++i) { incrStr(key); carryStr(key); if (mask == 0) break; if (mask >> 0 & 1) { if (foundLow(RSHash, key)) { mask -= 1; cout << RSHash << << mask << endl; } } if (mask >> 1 & 1) { //cout<<JSHash(key)<< <<key<<endl; if (foundLow(JSHash, key)) { mask -= 2; cout << JSHash << << mask << endl; } } if (mask >> 2 & 1) { if (foundLow(PJWHash, key)) { mask -= 4; cout << PJWHash << << mask << endl; } } if (mask >> 3 & 1) { if (foundLow(ELFHash, key)) { mask -= 8; cout << ELFHash << << mask << endl; } } if (mask >> 4 & 1) { if (foundLow(BKDRHash, key)) { mask -= 16; cout << BKDRHash << << mask << endl; } } if (mask >> 5 & 1) { if (foundLow(SDBMHash, key)) { mask -= 32; cout << SDBMHash << << mask << endl; } } if (mask >> 6 & 1) { if (foundLow(DJBHash, key)) { mask -= 64; cout << DJBHash << << mask << endl; } } if (mask >> 7 & 1) { if (foundLow(DEKHash, key)) { mask -= 128; cout << DEKHash << << mask << endl; } } if (mask >> 8 & 1) { if (foundLow(FNVHash, key)) { mask -= 256; cout << FNVHash << << mask << endl; } } if (mask >> 9 & 1) { if (foundLow(BPHash, key)) { mask -= 512; cout << BPHash << << mask << endl; } } if (mask >> 10 & 1) { if (foundLow(APHash, key)) { mask -= 1024; cout << APHash << << mask << endl; } } }}bool foundLow(unsigned int (*hash)(const std::string &key), std::string key) { if ((*hash)(key) < 10000) { std::cout << key: << key << Output: << ((*hash)(key)) << ; return true; } return false;} | Eliminating repetitiveness in code to test hash functions | c++;bitwise;hashcode | Your code does seem open to some improvement. Right now, you're not really getting much good out of using a pointer to a function. You could just about as well invoke each hash function directly in findLowHash as call it via a pointer in foundLow.In this case, we have a number of functions that all have the same signature, so we can create an array of the pointers to functions. Of course, array should also set off alarm bells--you should almost always prefer std::array or std::vector. In this case, I'll use st::vector, but if you're using a compiler new enough to include it, std::array would be an excellent choice as well.typedef unsigned int (*hash)(std::string const &key);std::vector<hash> hashes{ RSHash, JSHash, PJWHash, ELFHash, BKDRHash, SDBMHash, DJBHash, DEKHash, FNVHash, BPHash, APHash};Depending on the age of compiler you're using, it might not support the braced init-list like I've used above. At that point, it's open to argument that (under the circumstances) it would be easier to use an actual array instead. In any case, once you have your pointers to functions in something you can index like array, you can use a loop to walk through the array of functions, and use each function in turn:for (int h=0; h<hashes.size(); h++) for (int i=0; i<100000; i++) { incrStr(key); carryStr(key); if (hashes[h](key) < 10000) { std::cout << // ... break; // breaks inner loop, so goes to testing next hash function } }Again, if you have a new enough compiler (C++11) available, you can make the outer loop a little prettier using a range-based for loop:for (auto &&hash : hashes) // ... if (hash(key) < 10000) // ...Once you've done that, there are a few more fairly obvious points, such as replacing the magic numbers like 100000 and 10000 with defined constants with more meaningful names. |
_unix.381213 | I installed xrdp on xfce4 using Kali Linux Rolling distribution. I'm able to successfully connect to rdp service via Microsoft Remote Desktop from my Mac Pro.I am unsure, how would I go about fixing blackscreen after I connect. This seems to temporarily resolve after i stop the xrdp service using service xrdp stop & then restarting it. However, after my xfce4 session goes back to login screen due to obvious sleep mode or 'lock-screen', it goes black again.I tried:customizing different scalingusing various screen resolutionsconfigured .Xclients to startxfce4configured .xsession to xfce4-sessionTo no avail, I could get this working.What would be a permanent solution likely to be approached? | How do I fix blackscreen after connecting to xrdp on xfce4 (Kali Linux Rolling)? | kali linux;xfce;xfce4 terminal;xrdp;rdp | null |
_codereview.154715 | How can I make the following checksum algorithm more pythonic and readable? items = {1:'one', 2:'two', 3:'three'}text = foo # This variable may change on runtime. Added to allow the executionnumber = 1 # This variable may change on runtime. Added to allow the executionstring = text + items[number] + + trailingif items[number] == two: string=textstring = [ord(x) for x in string]iterator = zip(string[1:], string)checksum = string[0]for counter, (x, y) in enumerate(iterator): if counter % 2: checksum += x checksum += 2 * y else: checksum += x * ychecksum %= 0x10000print(Checksum:, checksum)The thing called salt by everyone here is fixed and won't change ever. Also, the code is into a bigger function.This code as-is must return this:Checksum: 9167 | Custom checksum algorithm in Python | python;performance;python 3.x | First of all, I would apply the Extract Method refactoring method and put the logic behind generating a checksum into a get_checksum() function.Also, I would avoid hardcoding the trailing salt and the 0x10000 normalizer and put them into the default keyword argument value and to a constant respectively.You can use sum() instead of having loop with if and else, which increase the overall nestedness. But, it might become less explicit and potentially a bit more difficult to understand.Comments and docstrings would definitely be needed to describe the logic behind the checksum calculations.Variable naming can be improved - str_a, str_b and string are not the best choices (even though the part1 and part2 in the code below are not either - think about what these strings represent - may be you'll come up with better variable names). Also, note that you are reusing the string variable to keep the ords of each character, which, strictly speaking, is not good - the variable name does not correspond to what it is used for. At the end you would have something like:DEFAULT_SALT = trailingNORMALIZER = 0x10000def get_checksum(part1, part2, salt=DEFAULT_SALT): Returns a checksum of two strings. combined_string = part1 + part2 + + salt if part2 != *** else part1 ords = [ord(x) for x in combined_string] checksum = ords[0] # initial value # TODO: document the logic behind the checksum calculations iterator = zip(ords[1:], ords) checksum += sum(x + 2 * y if counter % 2 else x * y for counter, (x, y) in enumerate(iterator)) checksum %= NORMALIZER return checksumWe can see that the test you've mentioned in the question passes:$ ipython3 -i test.py In [1]: get_checksum(foo, one)Out[1]: 9167 |
_unix.30855 | I have a number of console fonts installed in /lib/kbd/consolefonts/ installed.How do I list them (obviously all I can do, is just look at the filenames, but not at a list at available fonts).How can I change the console fonts?How do I make a user manipulable directory for those fonts, should I use /usr/local/lib/consolefonts/?Now, my kernel accepts the SYSFONT parameter: SYSFONT=latarcyrheb-sun16. I'd like to have a list which fonts my kernel supports and how I can select them (as in, how do I list the kernel compiled fonts, or something). | How to list console and kernel fonts? | console;fonts;linux kernel | null |
_unix.167452 | On Linux, I can easily extract the height / width / ascent / descent dimensions of Xorg fonts via xlsfonts, e.g.$ xlsfonts -ll -fn 9x15 | egrep 'bounds|max' bounds: width left right asc desc attr keysym max 9 4 9 12 3 0x0000How can I extract the same information from a TrueType font I have installed? | extract bounding box dimensions for TrueType font | command line;x11;fonts;ttf | null |
_webapps.14236 | Twitter supports saving a specific search. However, it just seems to be the basic string search as opposed their advanced search on search.twitter.com. The advanced search allows you to select a language you would like the results in. How do I get the advanced search to be saved? | How to have a saved search in Twitter only return english results? | twitter | You can simply add lang:en to the search query. e.g.cats lang:en |
_unix.185572 | I have edited bad an important file of solaris11,i want to recover from pkg repository.How to do that?Suppose i have delete /usr/bin/vim,how to recover only this file from repository?Thanks | Solaris11: recover file from repository | solaris | You can use this documentation.Pkg revert is the solutionFor examplepkg revert /usr/bin/vi |
_webapps.3155 | I want to have feeds for people that I follow on Twitter right in my Google Reader interface, but none of the ways that I've tried to subscribe seem to work. | Is there a way to follow the posts of individual Twitter users in Google Reader? | twitter;google reader | null |
_unix.356406 | I am using Kali linux installed on USB drive. But Accidetntly I remove network-manager and now I wants to re-install it.Can any one help me how can re-install it. I have installation disk.Network icon is also missing from menu. | Nwteork manager reinstallation | kali linux | null |
_cstheory.1067 | I have been working on this thread Grid $k$-coloring without monochromatic rectangles, and I am aware that the four color theorem implies that all planar graphs are four colorable. The question is whether this is a necessary condition as well, i.e. whether having a proof that a graph is not planar implies it is not four colorable ? | Is it possible to have a 4-coloring for a non-planar graph ? | graph theory;graph colouring | Obviously not. A graph is bipartite if and only if it is 2-colorable, but not every bipartite graph is planar ($K_{3,3}$ comes to mind). |
_webapps.29247 | When a Netflix show is paused, eventually the synopsis of the current episode will show on-screen. Also, when you roll over the next icon ( | ), the synopsis of the next episode will show on-screen.Is it possible to disable either or both of these synopses?To be more specific, I am watching Breaking Bad for the first time. However, whenever I need to pause or I accidentally roll over the Next Episode button, I end up learning things about the current or upcoming episode that I didn't know, yet. While the spoilers are limited, they are still spoilers. Is there any way to prevent these occurrences? | Can I hide the synopsis of the current or upcoming episodes of a series? | netflix;silverlight | Since it is now possible for many users to watch Netflix via an HTML5 player instead of Silverlight, new solutions are now possible.For example, the Flix Plus by Lifehacker extension (http://lifehacker.com/flix-plus-customizes-netflix-to-your-hearts-desire-1640968001) which I wrote will hide some text/images and blur out others and only show them while you mouse over them. |
_webapps.42398 | I want the email to be shown when chatting with friends in Gmail or Google Talk.I feel it is more secure to see their email address, as users can change their names and even have the same name as others.So I need the email address to be shown instead of the name when chatting with friends in Gmail.Is this possible? And if yes, how can I do it? | Changing Gmail's settings to displays a users email rather than their name | gmail;google talk | null |
_scicomp.8423 | I trying to find a computing algorithm for the Significant wave height $H_{1/3}$, or $H_\text{s}$ or $H_\text{sig}$ in the time domain.This is defined as the average height of the one-third part of the measured waveswhich are $N$ in numberhaving the largest wave heights:$$H_{1/3} = \frac{1}{\frac13 N} \sum_{m=1}^{\frac13 N} H_m$$For an example set consider $\{100,300,400,400, ..\}$ of height values $H_m$. | Significant wave height Algorithm | algorithms | Significant wave height, $H_{1/3}$, defined as the average height of the highest one-third of all waves, is historical. In the early days, the wave state was observed visually, which resulted in this definition of $H_{1/3}$. This quantity is not necessarily equal to the contemporary notion of significant wave height, $H_{s}$, which is defined as:$$H_{s} = 4 \sqrt{m_0},$$where $m_{0}$ is the zero-order moment of the wave variance spectrum:$$m_0 = \int{F(f)}\ df = <\!\eta^2\!\!>.$$$\eta$ is the surface elevation, and $<\!\eta^2\!\!>$ is the time average of the surface elevation variance.Though $H_{s} \ne H_{1/3}$, Phillips (1977) shows that $H_{s} \approx H_{1/3}$ for a narrow wave variance spectrum $F(f)$. See Dynamics of The Upper Ocean by Phillips, 1977, Cambridge University Press.If you have time series of $\eta$, you can then calculate $H_{s}$ from $m_0$ in a straightforward fashion. Keep in mind that $H_{s}$ as an integrated quantity only makes sense for linear (small slope) waves that are quasi-uniform in space and time, i.e. $F(f)$ and $H_s$ are changing over a significantly longer time scale than that of $\eta$. |
_cs.12139 | I was wondering when languages which contained the same number of instances of two substrings would be regular. I know that the language containing equal number of 1s and 0s is not regular, but is a language such as $L$, where $L$ = $\{ w \mid$ number of instances of the substring 001 equals the number of instances of the substring 100 $\}$ regular? Note that the string 00100 would be accepted.My intuition tells me it isn't, but I am unable to prove that; I can't transform it into a form which could be pumped via the pumping lemma, so how can I prove that? On the other hand, I have tried building a DFA or an NFA or a regular expression and failed on those fronts also, so how should I proceed? I would like to understand this in general, not just for the proposed language. | Is the language of words containing equal number of 001 and 100 regular? | formal languages;regular languages;pumping lemma | An answer extracted from the question.As pointed out by Hendrik Jan, there should be an additional 0 self-loop at q5. |
_webmaster.21221 | I'm trying to get some ajax content on my main page indexed by google. I've implemented the #! url structure for that content and the corresponding piece on the server which renders what users see when passed the _escaped_fragment_ version of the urls. Ie, I followed the instructions here http://code.google.com/web/ajaxcrawling/docs/getting-started.htmlI submitted the new site.xml to google 2 days ago through their webmaster tools. It's showing up as submitted URLs: 10, 1 URLs in index. So I'm assuming that something is wrong with my set up as the #! urls don't seem to be indexed.This is a snippet of my site.xml<url> <loc>http://www.mysite.com/</loc></url><url> <loc>http://www.mysite.com/#!/Bristol</loc></url><url> <loc>http://www.mysite.com/#!/Manchester</loc></url>I don't want to just ask What's wrong with this!? so my best guess is I shouldn't be using the same url with and without the #! perhaps? or I need to put<meta name=fragment content=!> in the page returned for those URLs? I didn't really follow what was being said on that bit of the instructions. | Site.xml with #!, still ok to have bare URL as home page? | google search console;sitemap;ajax;xml sitemap | That Sitemap file is fine. You don't need to specify the AJAX-crawling version of the URL there, but it generally will take a bit of time for these URLs to get crawled and indexed. A Sitemap file does not guarantee indexing, so in addition to just the Sitemap file, I'd also recommend doing the usual things that make sense when building & promoting a website, such as making sure that the pages are linked internally, so that the content can be crawled normally. |
_codereview.64832 | I'm 5 weeks into my first C++ class. I'm curious about how this code could be improved, more streamlined or simply things that I could/should have done better. The project was:Read from a .txt file that has different words on separate lines. Determine how many vowels each word has, and print each word AND vowel count to the console. You must write and use a function outside of main(). Here's the code I wrote: #include <iostream>#include <string>#include <fstream>using namespace std;//prototypesvoid readFile();void printWords(string);int main(){ readFile(); return 0;}//end mainvoid readFile(){ ifstream inFile; string words; inFile.open(words.txt); while(!inFile.eof()) { inFile>>words; printWords(words); }//end while loop inFile.close();}//end readFile functionvoid printWords(string str){ char a = 'a', e = 'e', z = 'i', o ='o', u ='u'; int num_A = 0, num_E = 0, num_I = 0, num_O = 0, num_U = 0; cout<< str <<endl; for(int i = 0; i < str.length(); ++i) { if(str.at(i) == a) { num_A++; } if(str.at(i) == e) { num_E++; } if(str.at(i) == z) { num_I++; } if(str.at(i) == o) { num_O++; } if(str.at(i) == u) { num_U++; } }//end for loop cout<< a: << num_A <<endl; cout<< e: << num_E <<endl; cout<< i: << num_I <<endl; cout<< o: << num_O <<endl; cout<< u: << num_U << \n <<endl;}//end printWord functionI feel like there should be a smoother function to extract, count and return the vowels. Then a function to print. Also, I tried to use a switch statement because there were so many if statements, but I couldn't get it to work. | Determining the number of vowels in each word from a file | c++;beginner;strings;file | null |
_softwareengineering.327542 | I want to do some initialization in child class constructor and pass result to super().But Java doesn't allow any processing in child class constructor before super() call.Whats a good way to solve this problem? | Processing and sending processed data to super from child class constructor | java;design patterns;object oriented design;inheritance;template method | The bad news is that you can't.The good news is that you can.How you cannot:B extends AB is an Aa B instance only can be built upon an existing A instanceYou cannot instantiate B, let alone change it's state, before instantiating AAlso remember than, after calling super(), any change you make to the state of the superclass is done to the subclass, unless you are hiding members, i.e., declaring a member or field in the subclass with the same name as one of the superclass when the superclass member is visible to the subclass.How you can:To solve that situation, don't use inheritance, use composition. But take in mind that both A and B shouldn't depend on each other. Both should depend on an abstraction (for example an interface) that both (or maybe just A) implement.Strictly speaking this is not composition but aggregation but, in a loose way of speaking, we are using composition instead of inheritance.==> I.java <==public interface I { public void setChild(I i); public void setParent(I i); public void setX(String s); public void setY(int n); public void setZ(boolean b);}==> A.java <==/* This class is abstract only for Eclipse to allow me to leave out all the method stubs for the sake of conciseness of the example (I like my examples to compile) */public abstract class A implements I { private I child; @Override public void setChild(I i) { this.child= i; this.child.setParent(this); }}==> B.java <==/* This class is abstract only for Eclipse to allow me to leave out all the method stubs for the sake of conciseness of the example (I like my examples to compile) */public abstract class B implements I { private I parent; @Override public void setParent(I i) { this.parent = i; // now modify the state of the parent this.parent.setX(Answer to the Ultimate Question of Life, The Universe, and Everything); this.parent.setY(42); this.parent.setZ(true); }} |
_reverseengineering.3704 | I use ProcessHacker version 2.33 to inspect the functions which are exported by DLLs in running processes. In the screen-shot below you can see a few exported functions from a C++ application, along with their Ordinal number and virtual address (VA):This is a pretty cool feature of ProcessHacker, which I was not able to find in ProcessExplorer. However, regarding the entries you can see in this screen-shot, I was not able to find what do the ? (question marks) and the number, which prefixes the names of the functions, mean. Also, I'm not sure what the single and double @ (at) symbols in the name, followed by a group of capital letters or number, mean.Question 1: What do the symbols (?, @), number-prefix and capital letter suffixes represent? How can one interpret them?Question 2: What does the Ordinal column mean?Question 3: Does the VA column show the offset of the procedure entry point, with respect to the base address of the .text segment of the DLL? If not, what does it represent?Question 4: How can one compute the absolute address of any function from the Exports tab? | How to interpret entries from Exports tab in ProcessHacker | dll;libraries;processhacker | Those are C++ name decorations. Name decoration usually refers to C++ naming conventions, but can apply to a number of C cases as well. By default, C++ uses the function name, parameters, and return type to create a linker name for the function. See Name Decoration on MSDN for more info.Question 2: Ordinals are just another way of making exports. You either export a function by name or by ordinal. It is unique in that binary only. You get functions by ordinals by using GetProcAddress() just the same as you would with a name. I could recommend Windows via C/C++ book for many more details about those mechanisms. |
_unix.369428 | Is it possible to change the $0 argument of a shell script (bash script) explicitly while running the script? Consider the following script: readonly SCRIPT_HELP=$(cat <<EOF Usage: $(basename $0) [-h]EOF ) echo ${SCRIPT_HELP}Is it possible to pass something else as an argument 0 to this bash script so the evaluation $(basename... would be executed with some user supplied code (potentially harmful)? And generally, if it's possible to exploit the fact that the argument 0 is not sanitized properly in a particular shell script? | Bash script arg0 vulnerability? | shell script;scripting;security | It is trivially possible to decide what $0 should be. Simply create a link:$ cat foo.sh#! /bin/bashreadonly SCRIPT_HELP=$(cat <<EOFUsage: $(basename $0) [-h]EOF)echo ${SCRIPT_HELP}$ ./foo.shUsage: foo.sh [-h]EOF$ ln -s foo.sh bar.sh$ ./bar.shUsage: bar.sh [-h]EOFIn this particular case, no, I don't imagine it will be possible to use that to any great advantage. $0 and SCRIPT_HELP are quoted when used (within nested command substitutions and heredocs, but quoted nonetheless), and they're not being evaled.$ ln -s ./foo.sh '; echo rm -rf ~; echo'$ ./\\;\ echo\ rm\ -rf\ \~\;\ echo\Usage: ; echo rm -rf ~; echo [-h]EOF |
_hardwarecs.1105 | The title pretty much says it all. I'm assembling a budget gaming PC and decided for an AMD Athlon X4 860K processor and now I need to chose a motherboard for it.My total budget for the PC is 500-600 ($550-660).I'll be using my PC to play games such as the Fallout series, the Elder scrolls series, League of Legends, Crusader Kings 2 and such. I'm using Fallout 4 as a benchmark for performance. Ideally I'd like the computer to also be able to eventually run Elder Scrolls 6, but it'll probably take some 3-6 years before they make that one, which makes system requirements difficult to predict.In case it's somehow relevant, I'm thinking about using the opportunity to switch to Linux and Wine instead of spending money on another edition of Windows.I'd like to start out with 8 or 16GB RAM and have the option to upgrade to 32GB in the future.Integrated graphics card would be nice to have as backup if my GPU fails. This is mainly a concern because I might reuse the 7 year old GeForce 9600 GT from my previous computer to save costs now and get a new graphics card as the first major upgrade.I'm aware the old GPU will be unable to run Fallout 4, but I'm not planning to play the game at release. I intend to get it during a Steam sale by which time I'll have also upgraded to a modern GPU.I'll probably get all the components from here. It's a Slovenian website so there might be a bit of a language barrier for most of you. I tried running it through Google translate, but that broke the configurator tool. Essentially the tool works by selecting components from the dropdown menu, starting with a processor, then motherboard, then everything else. Matina ploa is motherboard. The components themselves have standard international names.The website lists the following motherboards as available (from least to most expensive):ASRock FM2A88X Extreme4+, AMD A88 Mainboard - FM2+ASRock FM2A78M-HD+, DDR3, SATA3, HDMI, USB3, FM2/FM2+ mATXGIGABYTE GA-F2A78M-D3H S-FM2+ mATX Gigabyte F2A88XM-D3H, AMD A88X Mainboard - FM2+GIGABYTE GA-F2A88XM-D3H, DDR3, SATA3, USB3, HDMI FM2+ mATXGIGABYTE GA-F2A88XM-D3H 3.0 FM2+ mATXGigabyte F2A88X-D3H, AMD A88X Mainboard - FM2+ASRock FM2A88X Extreme4+, AMD A88 Mainboard - FM2+ASRock FM2A78M-ITX+, AMD A78 Mainboard - FM2+GIGABYTE G1.SNIPER A88X, DDR3, SATA3, USB3, HDMI FM2+ ATXThe description of numbers 1 and 6 says that the motherboard is intended for AMD processors that have an integrated GPU, which the Athlon X4 860K has not. I'm guessing that means I should probably pick one of the other eight, but I'm pretty clueless when it comes to hardware and have no idea which one.So finally, my question is which of the listed motherboards would be best for my needs? Or would you suggest a model not on the list? | Choosing motherboard for a budget gaming PC using AMD Athlon X4 860K processor | gaming;pc;motherboard | I recommend the Gigabyte F2A88XM-D3H, which is an A88X motherboard, which should offer most of the modern features, with 4 RAM slots, which means an upgrade path to 32 GB of DDR3, and 4+2 phases which makes for decent overclocking headroom. The more expensive Gigabyte G1.SNIPER or Asrock Extreme6 bring only limited benefit, except more bells and whistles.I must admit the budget isn't nearly as restrictive as I initially thought, since you intend to reuse your GPU, which is the most expensive part of a gaming system, and you would likely have money to spare for extras like a Windows licence or a SSD. You don't quite have enough for an i5 though, which is the next step up on the intel side, and I hesitate to recommend the AM3+ platform, so if you have any leftover budget, I suggest you save it up for your GPU, or get a better cooler.The motherboard supports the Athlon 860K, though if it ships with a old revision of the BIOS , you may have to send it back to get it flashed with a F6 or later. Be sure to communicate with the store to see if they'll do it for you.Motherboards these days don't generally come with integrated graphics. If you want one, you'll have to spend 20-40 pounds extra for an APU. Those will perform worse because of the shared TDP, but with DX12, they may be able to help out a bit. |
_webapps.105362 | For some random reason, perhaps in another bid to gain user engagement, Gchat in Gmail is being suddenly replaced with Google Hangouts. It says that if I like it looking the way it is now, I'm encouraged to choose the dense roster setting.Where is this setting? It doesn't seem to be anywhere in Gmail settings. | How do I activate dense roster on Google Hangouts? | gmail;google hangouts | You don't have to visit https://hangouts.google.com.Use dense roster is easily found within Gmail (left panel) by just clicking the little down arrow by your Icon/username in the chat/hangout area. You don't even need to navigate Settings. |
_ai.3828 | I have a question regarding Answer Set Programming on how to make an existing fact invalid, when there is already (also) a default statement present in the Knowledge Base.For example, there are two persons seby and andy, one of them is able to drive at once. The scenario can be that seby can drive as seen in Line 3 but let's say, after his license is cancelled he cannot drive anymore, hence we now have Lines 4 to 7 and meanwhile andy learnt driving, as seen in Line 7. Line 6 shows only one person can drive at a time, besides showing seby and andy are not the same. 1 person(seby).2 person(andy).3 drives(seby).4 drives(seby) :- person(seby), not ab(d(drives(seby))), not -drives(seby).5 ab(d(drives(seby))).6 -drives(P) :- drives(P0), person(P), P0 != P.7 drives(andy).In the above program, Lines 3 and 4 contradict with each other, and the Clingo solver (which I use) obviously outputs UNSATISFIABLE. Having said all these, deleting Line 3 and getting the problem solved is not what I'm epecting. The intention behind asking this question is to know whether it is possible now to make Line 3 somehow invalid to let Line 4 do its duty.However, Line 4 can also be written as:4 drives(P) :- person(P), not ab(d(drives(P))), not -drives(P).Thanks a lot in advance. | Answer Set Programming - Make a Fact INVALID | knowledge representation;logic;declarative programming | null |
_unix.272187 | We have many instances where we mount JFS2 filesystems underneath other JFS2 filesystems (eg. /fs1, /fs1/fs2, etc...) but we've never done it with NFS. Is there anything to be aware of when doing this? It appears to work just fine, I'm just worried about any gotchas while doing this. Thanks! | Any concerns with mounting a JFS2 filesystem under an NFS mount? | filesystems;nfs;aix | null |
_unix.29317 | I have two network interfaces (one wired & one wireless). I have two internet accounts too (each 256 kBps; one from a modem that I use as wired connection & the other from a wireless network). Is it possible to connect to both networks and merge them and get twice the speed (512 kBps)?How?I'm using Ubuntu 10.04 (Lucid Lynx). Thanks | Merging two internet connections from two network interfaces in order to obtain double speed | linux;ubuntu;networking;internet;merge | null |
_cs.5040 | Could anybody please explain what the difference between bounding and pruning in branch and bound algorithms is?I'd also appreciate references (preferably books), where this distinction is made clear. | What is the difference between bounding and pruning in branch-and-bound algorithms? | algorithms;terminology;branch and bound | null |
_unix.310774 | I need to execute a cronjob to run once for 7 days alone. I have tried like this: 0 0 * * 0-6 myscript.shIt gets run for once a day and running every day of the week since I gave as 0-6.But I need to run a job for one week alone not followed by multiple days. I do not want to mention the date of the month, since I need it to run at various times.(or)Using special command time in cron, I use @daily option aloneHow can I set the job to run for 7 days alone? | Cron job for 7 days alone not followed by multiple weeks | shell script;command line;cron;scheduling;jobs | null |
_softwareengineering.288775 | I'm currently reading some literature about software development process models. Everywhere I look, I only read the problems with the Waterfall model and how the iterative and incremental development approach solves these problems. But, I cannot find any information about when you should avoid this approach.So, for what kind of projects should you better avoid iterative and incremental development? | When should you avoid iterative and incremental development? | development process;development methodologies;waterfall;iterative development | null |
_webapps.73218 | I know the keyboard shortcuts for cut, copy and paste, and I use them frequently. But there are times when using the mouse is much more convenient. Especially if I want to copy a whole row, I prefer to not select it with the left button and then copy with the keyboard, but select it with the right mouse button and directly choose copy from the context menu. In other cases, I'm not sure the focus is on the window in which the current selection is, so I right click on the selection to make sure I'll copy what I want. But Google sheets is determined to admonish me to use the keyboard shortcuts every single time, breaking my flow with a modal dialog. I can understand why they think they are doing novice users a favor by teaching them this, but when I know what I'm doing, it becomes very annoying. At least Clippy didn't use modal dialogs. Is there a setting hidden somewhere to just tell them Please stop showing me this advice? | Is there a way to stop Google sheets from telling me to use Ctrl C? | google spreadsheets;usability | null |
_unix.140550 | Is there a way to write a for loop with a URL and change the URL each time? I want to append &skip=XX with different numbers to skip, is there a way to write it so that the variable is in the URL? | cURL for loop variable | curl | null |
_unix.218562 | I just tried to extract EDID file data with read-edid util; The thing is the output shows : $sudo get-edid | decode-edid...Manufacturer: AUO Model 20ec Serial Number 0Made week 0 of 2013EDID version: 1.4Digital display6 bits per primary color channelDigital interface is not definedMaximum image size: 34 cm x 19 cmGamma: 2.20Supported color formats: RGB 4:4:4First detailed timing is preferred timingEstablished timings supported:Standard timings supported:Detailed mode: Clock 77.000 MHz, 344 mm x 193 mm 1366 1382 1398 1628 hborder 0 768 771 785 788 vborder 0 -hsync -vsyncManufacturer-specified data, tag 15ASCII string: AUOASCII string: ***...I checked the xrandr and it outputs : $xrandr Screen 0: minimum 320 x 200, current 1366 x 768, maximum 8192 x 8192 eDP1 connected 1366x768+0+0 (normal left inverted right x axis y axis) 344mm x 193mm 1366x768 60.02*+ 1024x768 60.00 800x600 60.32 56.25 640x480 59.94 ...And it shows I have 60.02 refresh rate or similar which is not correct?...As a test, according to the EDID I created /etc/X11/xorg.conf.d/90-monitor.conf file with content as : Section Monitor Identifier <default monitor> DisplaySize 344 193EndSection...as you can see, the xrandr outputs as enabled the 344x193 display size but still I am not sure is the 344x193 are correct values? Should it be 344x193 or 340x190 according to Maximum image size: 34 cm x 19 cm values?Moreover, the EDID shows my notebook has 77.000MHz refresh rate (supposed to be) but the xrandr outputs (see above) I have 60.000MHz, as I can get it; So that makes me confused which values really should be used for xorg? And should I have (in linux .config) PWM as y or m if I need un-standard refresh rate be running?So my question is... how to use proper DPI and refresh values from EDID to set them into /etc/X11/xorg.conf.d/90-monitor.conf file and have them valid?p.s.kernel 3.16.7os Linux Arch x64video card : Intel HD Graphics (Sandy Bridge - Bay Trail) | EDID - help to detect proper DPI and refresh rate values | linux;x11;xorg;kernel modules;edid | 77MHz is the pixel clock, not the vertical refresh rate. The vertical refresh rate is measured in Hz, not MHz.Take a look at the mode: Clock 77.000 MHz, 344 mm x 193 mm 1366 1382 1398 1628 hborder 0 768 771 785 788 vborder 01366 is the number of active pixels per line, and 768 is the number of active lines. These are pixels you see. There are also blanking pixels and lines and border pixels and lines that are inserted to even out the clock.See the one metric that says 1628x788? This is the one that includes all active, blanking, and border pixels. If you divide 77MHz (or 77,000,000Hz) by (1628 * 788), you'll see that you get roughly 60.02 Hz. |
_unix.384584 | I'm a newly minted CS major and I have been wondering what the benefits of using grep versus spotlight on mac. I ran a command to search for a specific file because I lost track of which directory it is in, which took a while, but when I did it in spotlight the result was instantaneous. I enjoy using the command line and it makes my life much simpler than the UI directory view on mac, so I would like to learn how to use it to its full potential. | Grep versus spotlight on mac | command line;grep;terminal;osx | Quick comparisonsIterativegrep is usually to search file contents for matching patterns. Think searching file contents. grep will have to manually walk the file system from a given starting point.I am curious how you were using grep.find is the standard *nix command to search your file system for a file. Check out the man page, it has lots of ways to use it. But basically, it walks your file system from a given starting point and looks for matches.Indexedspotlight is an OSX utility that searches an indexed list of files. spotlight relies on an index and thus is capable of very fast lookups as it is not manually iterating over the file system. Usually a worker thread does that to build the index.The tradeoff with spotlight is that if the file has not been indexed, then spotlight will not find it, even if it exists. However, if the directory has been indexed, then spotlight has good performance.OthersIf you are needing to search for file contents and are using version control, say on a development project, ag silver_searcher is a much faster alternative to grep. It works within version control scenarios and respects your list of ignored file types to find files containing a pattern |
_cs.52306 | Does the conviction L-uniform NC1 != NP is incredibly hard to prove! express the core of P != NP is incredibly hard to prove! in a similar spirit as the conviction The polynomial hierarchy doesn't collapse! expresses the core of P is not equal to NP! ? Let me try to elaborate:The P vs NP problem implicitly invokes a number of related but distinct challenges and convictions. Focusing on the convictions, we have that NP != coNP is believed with nearly the same conviction as P != NP, and is part of the conviction that the polynomial hierarchy doesn't collapse. (Because the polynomial hierarchy is less familiar than NP, this conviction is weaker, but still strong enough to be used as a reasonable assumption in a proof.)Similarly, L != NP is incredibly hard to prove is believed with nearly the same conviction as P != NP is incredibly hard to prove. Now there may be weaker statements which we don't know how to prove either, like $U_{E^*}$-uniform TC0 != PH, but they don't necessarily feel natural enough to be part of real convictions. So my question is whether L-uniform NC1 != NP is incredibly hard to prove would qualify as a natural (and sufficiently strong) conviction. (I'm pretty certain that NC1 is appropriate here, but I'm less certain about L-uniform and NP. Maybe something like non-uniform NC1 != PH/poly is incredibly hard to prove would be much more natural and somehow imply all the other related natural convictions.) | Stronger versions of P != NP which better express actual convictions | complexity theory;np complete;p vs np | null |
_webmaster.61169 | I have a friend (let's say his name is Fred) who traded some services in exchange for someone (let's say his name is Sam) to build him a website for his business. Rather than registering the domain name himself, Fred let Sam register the domain name and hosting space through SquareSpace. Now Sam is coming back to Fred saying the trade wasn't a fair one and is holding the domain name ransom.I'm assuming in this case Sam is the owner of the domain name, and not Fred. Is this a correct assumption? If so, is there any way Fred can get the domain name from Sam, short of waiting until it expires (Sam only registered it for a year) and hoping Sam doesn't register it again? | Who Owns a Domain Name? | domains;ownership | The Registrant of the domain name, that is the party and contact information that the domain registration record corresponds to, is the controlling party. If Sam used his own personal or business name along with his corresponding contact information during the domain registration, it's under his control. If Sam used Fred's name and contact information, then Fred would be the Registrant and controlling party.To verify who the domain registration information corresponds to, do a WHOIS lookup on the domain name.The only recourse for obtaining a domain name registered to another party is filing a Uniform Domain-Name Dispute-Resolution Policy (UDRP) based on an existing trademark and other criteria, such as registering the domain name in bad faith. This is not a an easy or inexpensiveness process however, so Fred might want to consider registering another domain name, which given the plethora of new gTLD's, should not be so constraining to do. |
_unix.380005 | Goal: Have crontab running at start up logging output from arp command in a txt file.> Chrontab:> > # daemon's notion of time and timezones.> #> # Output of the crontab jobs (including errors) is sent through> # email to the user the crontab file belongs to (unless redirected).> #> # For example, you can run a backup of all your user accounts> # at 5 a.m every week with:> # 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/> #> # For more information see the manual pages of crontab(5) and cron(8)> #> # m h dom mon dow command* * * * * arp -n > results.txtUnfortunately, instead of writing the output of arp -n it overwrites results.txt with a blank file. The weird thing is if I use arp-n > results.txt in the terminal I get:GNU nano 2.2.6 File: results.txt Address HWtype HWaddress Flags Mask Iface192.168.42.19 (incomplete) wlan0192.168.42.14 ether (incomplete) C wlan0192.168.42.13 (incomplete) wlan0192.168.42.18 (incomplete) wlan0192.168.1.1 ether (incomplete) C eth0192.168.1.25 ether (incomplete) C eth0192.168.42.12 ether (incomplete) C wlan0192.168.1.240 ether (incomplete) C eth0192.168.42.11 (incomplete) wlan0192.168.42.16 M A wlan0Does anyone know how to fix this so I can get it running and updating the file using crontab? | Save arp output in terminal to text file every minute using crontab | cron | The problem seems to be that probably crontab does not know the PATH where the arp command lives.I would use:* * * * * /usr/sbin/arp -n >> results.txtHowever, I would use arpwatch to monitor ARP changes. It work as a daemon, and as it registers the MAC changes in a file over time, together with the epoch time of the change. It also is able to send messages to syslog and emails.From man arpwatchArpwatch keeps track for ethernet/ip address pairings. It syslogs activity and reports certain changes via email. Arpwatch uses pcap(3) to listen for arp packets on a local ethernet interface.Report MessagesHere's a quick list of the report messages generated by arpwatch(1) (and arpsnmp(1)):new activity This ethernet/ip address pair has been used for the first time six months or more.new station The ethernet address has not been seen before.flip flop The ethernet address has changed from the most recently seen address to the second most recently seen address. (If either the old or new ethernet address is a DECnet address and it is less than 24 hours, the email version of the report is suppressed.)changed ethernet address The host switched to a new ethernet address.Syslog MessagesHere are some of the syslog messages; note that messages that are reported are also sysloged.ethernet broadcast The mac ethernet address of the host is a broadcast address.ip broadcast The ip address of the host is a broadcast address.bogon The source ip address is not local to the local subnet.ethernet broadcast The source mac or arp ethernet address was all ones or all zeros.ethernet mismatch The source mac ethernet address didn't match the address inside the arp packet.reused old ethernet address The ethernet address has changed from the most recently seen address to the third (or greater) least recently seen address. (This is similar to a flip flop.)suppressed DECnet flip flop A flip flop report was suppressed because one of the two addresses was a DECnet address.Files/var/lib/arpwatch - default directoryarp.dat - ethernet/ip address databaseethercodes.dat - vendor ethernet block list |
_cs.52719 | This picture is from Computer System Architecture 3rd Edition by Morris Mano. Is it possible to interchange the data of any two registers in a single clock pulse? I know that the data of DR (data register) and AC (accumulator register) can be interchanged in a single clock pulse. But other than this I don't understand how data replacement between two registers can be accomplished. Thank you. | Data interchange in two registers | computer architecture;cpu | null |
_unix.9819 | E.g. I'm seeing this in /var/log/messages:Mar 01 23:12:34 hostname shutdown: shutting down for system haltIs there a way to find out what caused the shutdown? E.g. was it run from console, or someone hit power button, etc.? | How to find out from the logs what caused system shutdown? | logs;shutdown | Only root privileged programs can gracefully shutdown a system. So when a system shuts down in a normal way, it is either a user with root privileges or an acpi script. In both cases you can find out by checking the logs. An acpi shutdown can be caused by power button press, overheating or low battery (laptop). I forgot the third reason, UPS software when power supply fails, which will send an alert anyway.Recently I had a system that started repeatedly to power off ungracefully, turned out that it was overheating and the mobo was configured to just power off early. The system didn't have a chance to save logs, but fortunately monitoring the system's temperature showed it was starting to increase just before powering off.So if it is a normal shutdown it will be logged, if it is an intrusion... good luck, and if it is a cold shutdown your best chance to know is to control and monitor its environment. |
_cs.37129 | $\newcommand{\bs}{\mathrm{bs}}$What is the largest gap known between block sensitivity ($\bs(f)$) of a boolean function ($f$) and degree of a polynomial ($\deg(f)$) that represents/approximates it?We know of lower bound $$\bs(f)\leq c\deg^2(f)$$ for some $c>0$. Is there a Boolean function that achieves this separation? | Block sensitivity and degree | complexity theory | null |
_unix.108257 | How do I stop emacs from colouring the text of the file I am editing? I want everything just in plain white. I know that I can load themes, but it's not obvious which theme does what. Can I just disable all the colouring so that when I start emacs up, all the text is always white? | How do I stop emacs from colouring the text of the file I am editing? | emacs;syntax highlighting | Colours are provided by the font-lock minor mode.To disable colouring in your current buffer, toggle font-lock-mode off with this command:M-x font-lock-modeTo disable font-lock-mode permanently, add to your init file (~/.emacs):(global-font-lock-mode 0)More info is available under Font-Lock in the Gnu Emacs Manual |
_unix.334128 | I have a need to monitor a directory tree for any file changes. On changes I'd like to trigger a backup script (essentially a git commit, but including a database dump). As I expect there will likely be more changes within a relatively short timeframe I'd like to wait for n seconds before executing the backup script to reduce the number of commits.To sum up my requirements:monitor a directory recursively for file changesgrace period of n seconds for further changes before execution of backupany changes occurring during backup run must not be lostUsing javascript I would do something like the following on any file change:if (timeout) { clearTimeout(timeout);}timeout = setTimeout(callback, 60000);I am not clear how to replicate such behavior using a bash script. My current approach is as follows:watch.sh:#!/bin/bashinotifywait \ --recursive \ --monitor \ --event attrib,modify,move,create,delete \ --format %e \ /usr/src/app/html/themes/ |while read events; do flock -n /var/run/backup-watch.lockfile -c /usr/src/scripts/watch-backup.shdonewatch-backup.sh:#!/bin/bash# wait for more changes to happensleep 60# run script/usr/src/scripts/commit-changes.shThis has the waiting component but will ignore any changes happening while the commit-changes.sh script is running.Alternatives:I considered using a node js script, but the node fs watch command does not allow recursive directory watching, so this is not an option.Cron could be an alternative but I'd prefer to watch for changes instead of running on a schedule. The backup script will generate a new commit each time due to the db-dump being part of it. While I could make the backup more complicated by checking if there are any other changes but the db-dump I'd like to keep it simple there. | Bash script to watch for file system changes, with delay before executing a backup script | shell script;backup | null |
_codereview.23583 | Does the following code look okay? Want to see if anyone can spot any mistakes I may have made. This will be pulling from a pre-formatted Excel document - I have already specified all needed Cell locations.Things I want clarified:How many times can you invoke SetInfo and did I use it more than needed? I was under the impression that a SetInfo would be needed before a SetPassword can be used, but I could be very wrong.Does this line look okay? Was I correct to separate multiple cells using a comma in order to put all the info together? I know it worked with an Echo command:Set objUser = objOU.Create _(User, cn= & objExcel.Cells(intRow, 3).Value, objExcel.Cells(intRow, 2).Value, objExcel.Cells(intRow, 19).Value)Is this the correct code for setting a password to never expire?objUser.Put userAccountControl, intUAC XOR _ADS_UF_DONT_EXPIRE_PASSWDFull code below, I'd appreciate any feedback on anything else that is found.Set objExcel = CreateObject(Excel.Application)Set objWorkbook = objExcel.Workbooks.Open _ (C:\Book1.xls)intRow = 2Do Until objExcel.Cells(intRow,1).Value = Set objOU = GetObject _ (ou= & objExcel.Cells(intRow, 13).Value & _ , dc=satdc, dc=com) Set objUser = objOU.Create _ (User, cn= & objExcel.Cells(intRow, 3).Value, objExcel.Cells(intRow, 2).Value, objExcel.Cells(intRow, 19).Value) objUser.sAMAccountName = objExcel.Cells(intRow, 19).Value & .sat objUser.GivenName = objExcel.Cells(intRow, 3).Value objUser.SN = objExcel.Cells(intRow, 2).Value objUser.SetInfo objUser.AccountDisabled = False objUser.AccountExpirationDate = Date + 365 objUser.SetPassword objExcel.Cells(intRow, 9).Value objUser.SetInfo objUser.Put userAccountControl, intUAC XOR _ ADS_UF_DONT_EXPIRE_PASSWD objUser.HomeDirectory = \\satdc & \ & Users & \ & _ objUser.Get(sAMAccountName) objUser.homeDrive = U: objUser.SetInfo intRow = intRow + 1LoopobjExcel.Quit | VBScript for AD account creation | vbscript | null |
_unix.12848 | In terminator, the keyboard shortcut Ctrl+Shift+F opens up a small bar at the bottom of the window to let the user search a text string within the terminal scrollback.Are there any keyboard shortcuts for moving to the next or previous matched item in this search? The most complete documentation I found for Terminator is included in the Ubuntu documentation, but it doesn't cover this topic in detail. | Terminator: Shortcuts for Prev and Next? | keyboard shortcuts;search;terminal emulator | This may not be what you expect, nor was if for me, but it works (no mouse required)... (btw: I've just started using Terminator, and so far I like it).. A way to do it is to simply do this: If your active cursor is already in the Find box, just keep pressing Enter for Next.... and for Prev, press Tab to make the Prev button active an then just keep pressing Enter... the Prev button stays active, so it locates backwards each time you press enter.. If your current active cursor in in the window body, just press Ctrl+Shift+F again, to get you back into the Find box, then just press Enter (next), or Tab, then Enter (prev).. Also, you can switch between buttons, to reverse the search direction, via the Left and Right cursor(arrow) keys (I find that easier than Shift-Tab) ... |
_codereview.134504 | I'm just wondering if you would consider this to be safe from SQL injection.A peculiarity of my program is I need to dynamically access table names depending on my scenario.This is not for publishing online, but I wish to know if this approach is any good.I'm using Python3 and SQLite3. My database object contains the table name, and is not controlled by any user. It comes from another class in a config.cfg file.def save_record(state_int, database): query = '''INSERT INTO %s (state_int, turn_left, turn_right, move_forward) VALUES (?,?,?,?)''' %(database.records_table_name) database.cursor.execute(query, (state_int, 0, 0, 0)) database.robot_memory.commit()save_record(10012, database) | Inserting robot moves into an SQLite3 database | python;python 3.x;sqlite;sql injection | Just a philosophical answer here.I think you're asking the wrong question. You shouldn't ask yourself is my SQL code safe or vulnerable? This is too hard to answer in any individual case, and coming up with the right answer could depend on a lot of contextual things such as the system configuration, the whole program structure, etc.You don't want to have to consider all these things when writing code. People have already considered them a lot, and based on their experience they have come up with best practices.Instead you should ask the question,Does my code follow the standard best practices for preventing SQL injection?As alluded to in another answer, using string interpolation to build queries is against best practices. So, while it doesn't seem like this creates a vulnerability in your code, we can't rule out that there is some edge case based on the rest of your program structure that would allow an attacker to put something into this string interpolation.Unless you have a very good reason for doing so, follow the best practices, even if you don't need to. Then you can sleep well and ignore pathological edge cases. |
_webapps.23508 | Is it possible to create a board as a template? It would be nice to create the board with a pre-defined set of lists and cards for a standard set of tasks. | Create Template Board and Cards on Trello | trello;templates | null |
_softwareengineering.314524 | Disclaimer: This is my first time: using node, creating a REST API, and trying out MVC server side. (so, just statistically speaking, I'm probably doing something wrong \_()_/)I'm working on creating a video sharing platform for use at my university. It's going to be a single page application with client side routing. I plan on making ajax requests to a REST API for the CRUD functionality. The basic structure I have going so far is that my controllers are receiving the routing requests and calling the model functions to interact with the DB. For example:controllers/courses.js:var express = require('express');var router = express.Router();var models = {};models.courses = require('../models/courses.js');router.get('/api/courses', models.courses.get_all);router.get('/api/courses/:id', models.courses.get);router.post('/api/courses', models.courses.create);router.put('/api/courses/:id', models.courses.update);router.delete('/api/courses/:id', models.courses.delete);models/courses.js:var db = require('../config/db_config.js');exports.get_all = function (req, res, next) { db.any('select * from course') .then(function (data) { res.status(200).json({ status: 'success', data: data, message: 'Retrieved all courses' }); }) .catch(function (err) { return next(err); });};exports.get = function (req, res, next) { db.one('select * from course where id = $1', req.params.id) .then(function (data) { res.status(200).json({ status: 'success', data: data, message: 'Retrieved a course' }); }) .catch(function (err) { console.log(err); return next(err); });};Is this more or less the right way to do it? Do you forsee me running into issues down the road?My gut says that the model code should be passing the query results back to the controller, rather than directly back to the client. Is this correct? If so, how would I go about that? Tell me what you would do differently. | Should models be returning data directly to the client, or to the controller instead? | javascript;mvc;rest;node.js;separation of concerns | Here is how MVC is intended to work...The controller receives the request from the client, performs any business rules logic to determine and implement the changes to the model that are required. The final part is that it selects the appropriate model and view to return to the client. The View defines the presentation of the model to the client.I have a second observation to make. If you implement a REST api to deliver a CRUD service you need to be in complete control of all clients that can connect to the REST API. If, as it seems from your question, that the clients are javascript code running in the web browser, then you cannot be in control of all clients, as someone could write their own client to access your CRUD API, and manipulate the back end objects as they see fit.Hopefully, you mean that you are implementing a REST API that includes the business rules authenticating and validating requests as well as performing object updates. |
_codereview.123292 | Executive summaryThe twist is that the consumers do not consume, they just read. The producer makes items continuously in one of two alternating slots. Readers read from the other slot. When producer comes up with a new item it waits until readers are done with their read slot (that would become the new write slot). The slots effectively alternate between write slot and read slot.The long storyBackground: solving a practical problem - watching my son overnight using an infrared Raspberry Pi camera. Came up with a basic C++ web server. One thread takes pictures (the producer). It takes ~6 secs for a picture! As explained above, the pictures are kept in memory in 2 picture slots - one in which the current picture is taken and the other one from which one can only read. The readers are web browsers (> 50 msecs to serve a picture).The code below works (as much as tested) but doesn't look pretty. Locks are abused and notify() is called way too many times. Is there for sure no deadlock/race condition?I looked at myself reasoning about the problem and saw myself adding a mutex/condition variable to solve this or that... notify() called too often? Well, adding 'if (no readers)' is tempting but things can change underneath... so protect that with a mutex... patching...I'd like an approach that's crystal clear.Feel free to scrap the code and come up with a different approach. This wheel should have been already invented somewhere. Use semaphores if that makes things clearer. Should I ask for more than 2 slots (as latency becomes an issue on slow links/readers) :)? Maybe later.The idea is that callbacks are called with an index (slot) argument. For the duration of producer callback there should be a guarantee that no readers are using that index, etc. main() is just the test harness.#include <mutex>#include <condition_variable>#include <atomic>#include <iostream>#include <thread>#include <unistd.h>std::mutex global_mutex;std::condition_variable cv[2];std::mutex slot_mutex[2];std::atomic_int reader_count[2]; // Number of readersint read_slot{ 0 };int write_slot{ 1 };// When callback is called below only the producer uses the slot indexvoid produce(std::function<void(int index)>& callback){ { // 'Swap' the read/write slots std::lock_guard<std::mutex> guard(global_mutex); read_slot = write_slot; write_slot = (write_slot + 1) % 2; } // Wait until no readers in the write slot std::unique_lock<std::mutex> lock(slot_mutex[write_slot]); cv[write_slot].wait(lock, []{ return reader_count[write_slot] == 0;} ); callback(write_slot); // USE EXCLUSIVELY write_slot}// >1 reader (and no producer) can call callback belowvoid read(std::function<void(int index)>& callback){ // Busy wait to get the read slot int read_slot_copy; while (1) { { std::lock_guard<std::mutex> guard(global_mutex); read_slot_copy = read_slot; } std::unique_lock<std::mutex> lock(slot_mutex[read_slot_copy], std::defer_lock); bool slot_acquired = lock.try_lock(); if (slot_acquired) { ++reader_count[read_slot_copy]; break; } else { std::this_thread::yield(); } } callback(read_slot_copy); // SHARE read_slot_copy WITH OTHER CONSUMERS --reader_count[read_slot_copy]; cv[read_slot_copy].notify_one(); // Should really notify only when read_slot_copy = 0...}int main(){ // 6 secs to take a picture std::function<void(int)> producerFct = [](int index) { /* use index */; sleep(6); }; // Producer std::thread producerThread([&producerFct] { while (1) produce(producerFct); }); // 50 msec to send the photo std::function<void(int)> readerFct = [](int index) { /* use index */; usleep(50000); }; const int NUMBER_READERS = 10; const int NUMBER_READS_PER_READER = 1000; std::thread readers[NUMBER_READERS]; for (int i = 0; i < NUMBER_READERS; ++i) { readers[i] = std::thread([&readerFct, i] { int reads = NUMBER_READS_PER_READER; while (--reads) read(readerFct); }); } for (int i = 0; i < NUMBER_READERS; ++i) { readers[i].join(); } exit(0); // On purpose quick exit} | Producer-consumer with a twist (consumer is a reader) in C++ | c++;c++11;multithreading;producer consumer | null |
_unix.159904 | I have setup a NIS Master Server and client. On the server, I created a test account. This account can login without issue to the NIS client, but when I attempt to login to the NIS Master Server with this client, I get this error...Could not update ICEauthority file /home/nisusers/.ICEauthorityI am able to open the text command line using ctrl+alt+f1 and login to the account. However, I have no home directory for the account and therefor no .ICEauthority file. | NIS Accounts Can't Login to NIS Server, work on NIS Clients - ICEauthority | debian;nis | null |
_unix.295671 | Both my systems show the very same permissions on the file.-rw-r--r--I have a script running in R that uses a basic R function download.file('http://www.sample-videos.com/csv/Sample-Spreadsheet-100-rows.csv', '/home/rstudio/xyz9', mode = a, quiet = FALSE)mode=a means append mode. I run the scrit on local system through Rstudio(IDE for R). It appends the files on my ubuntu system which is the local system. I run this script on server which is a centos through RStudio only and instead of appending data to the file, it completely overwrites the file.Is that a problem on system level or script level? permissions look just fine to me .When I run it on the server, I get the following on console:--2016-07-13 19:28:23-- http://www.sample-videos.com/csv/Sample-Spreadsheet-100-rows.csvResolving www.sample-videos.com... 52.74.31.185Connecting to www.sample-videos.com|52.74.31.185|:80... connected.HTTP request sent, awaiting response... 200 OKLength: unspecified [text/csv]Saving to: /home/rstudio/xyz9 0K .......... 267M=0s2016-07-13 19:28:24 (267 MB/s) - /home/rstudio/xyz9 saved [10998]When I run it on ubuntu, I get:trying URL 'http://www.sample-videos.com/csv/Sample-Spreadsheet-100-rows.csv'downloaded 10 KBWhat could be wrong here? I do really want the append mode to work on centos machine. Since I am running exactly the same script, I believe this has something to do with file permissions?Edit:As I see, Modified date is a little messed up on the centos machine. It's a server and hosted remotely. I see weird time stamp for split of a second when the file is updated. At 7:43, It shows modified date be :5:56 p.m (same date).When I run the download.file function, file size for a moment becomes 0 Kb.Modified date changed to correct time for a moment.After update, modified date changed to 6:40 p.m Time has been correctly set on the centos system.What seems not to work here? | append mode in Centos and Ubuntu | ubuntu;centos;r | There shouldn't be problem with permissions. You can write and read data, that's all, but program has to decide how to work with data inside a file. It looks like R, not system, problem to me.Anyway, outputs from server and local host are different. The one from server looks same like from wget. Check download.file.method which have to be set to internal (according to docs) - only this method support appending to file. |
_unix.269790 | I'm just wondering: why does less store its configuration in a binary file .less, which you have to generate with lesskey from the text-file .lesskey?What could be the benefits of this behavior? Speed? But parsing a tiny human-readable configuration file can't take that long. | Why does less store its configuration in a binary file? | configuration;less | The source code for lesskey says: * Copyright (C) 1984-2015 Mark Nudelmanwhich gives a hint that performance might have been a factor in deciding to use a compiled configuration file. Machines were a little smaller and slower 32 years ago. |
Subsets and Splits