id
stringlengths
5
27
question
stringlengths
19
69.9k
title
stringlengths
1
150
tags
stringlengths
1
118
accepted_answer
stringlengths
4
29.9k
_webmaster.12777
I'm hosting my website on Google App Engine and my domain name on GoDaddy.Google App Engine does not allow you to have naked URLs. So it doesn't allow you to have example.com but does allow you to have www.example.com.I can easily enable forwarding in GoDaddy to forward exmample.com to www.example.com however it does not keep the relative URL path.For example I would like for example.com/images/3.jpg to be forwarded to www.example.com/images/3.jpg and not just www.example.com.
GoDaddy URL forwarding while keeping relative path
domains;301 redirect;godaddy;no www;google app engine
null
_cogsci.9976
It is the major problem of all cognitive sciences to deal with subjectivity. On the other hand, in order to figure out what is cognition or psychology, one must ultimately deal with this problem. As a starter, I wonder if there is any study about identicalness of perceptions among subjects. Are the perceptions of two different subjects on an object identical? In other words, can the perceptions of two subjects about a tomato differ from each other? One may experience the redness of tomato as what the other call blue.
Is there a way to compare the subjective experiences of two different subjects upon an object?
cognitive psychology;perception
null
_webmaster.55861
I have a Google Analytics account. For a given time period, the abandonment rate on a single goal is 73.15% on the Goal Overview page.If I switch pages to the Funnel Visualization for the exact same goal and time period, I have a 25.98% funnel conversion rate.Surely, if 25.98% of funnel attempts resulted in a goal completion, then the remainder (74.02%) must have been abandonments?100 - 25.98 = 74.0274.02 != 73.15Why are the two numbers different?
Why does abandoment rate not equal the inverse of funnel conversion rate?
google analytics
null
_unix.255693
I use feh to view images on my hard drive. However, if I hit [delete] the images are removed from the current slideshow, but not from the disk. What is the right way of removing images from the drive straight from feh?
How do I delete images from disk using feh?
feh
From man fehCTRL+delete [delete]Remove current file from filelist and delete itCTRL+delete will do the job
_softwareengineering.143722
CoffeeScript is a language with a very clean Ruby-like syntax that transcompiles to JavaScript. Does the same thing exists with C? Then writing more readable and as fast as original C programs would be possible. If it doesn't exist, do you think that it would be a good idea?
Is there a language that transcompiles to C with a better syntax?
c;syntax;compiler
CoffeeScript compiles to JavaScript for a very simple reason, JavaScript is the de facto client side language and it would be unreasonable to expect browser vendors to natively support CoffeeScript, when all it offers is an alternative syntax.In a very similar manner, the main point of high level language to C translators is immediate portability, as there's a C compiler for almost every platform and an abundance of C libraries. Vala, for example, was designed to:be a compiler for the GObject, build native executables (through the machine's C compiler), automate reference counting, and still be accessible to GNOME C programmersGNOME is a traditionally C oriented project and GObject specifically is written in C, Vala wouldn't probably find much love amongst GNOME developers if it compiled to machine code, regardless of it's friendlier nature (and syntax). Not everyone seemed to like the syntax, to the point that another language, Genie, was build to improve upon it. For a C++ example, Facebook developed HipHop, a PHP to C++ translator. They were trying to solve a very specific issue, CPU usage, without having to replace all their PHP code and re-train their engineers (or worst, replace them). This is a far more specific example, as Facebook scalability issues are, well, unique, and again having access to the intermediate C++ code can be useful, as PHP extensions are written in C and C++. So a translator from a high level language to another is a good idea mostly when you access to the intermediate code is required. For CoffeeScript, the JavaScript code is necessary because of its wide browser adoption, and for Vala, Genie and HipHop because of the existing codebase. Obviously having access to the intermediate code means that you can further optimize it if need be. But generally speaking, it wouldn't be such a good idea to build a language that translates to C, or any other language, if you didn't have any use of the resulting code. There are so many languages out there, if you can't cope with C, just pick an other. Coincidentally the first C++ compiler written by Bjarne Stroustrup, CFront, was a C with Classes to C translator, but that was mainly because as a new language, it was impossible to bootstrap C with Classes.
_codereview.147419
I'm looking for an effective way to parse html content in node.JS.The objective is to extract data from inside the html, not handle objects.It is a server-side thing.I tried using jsdom and I found two major issues:Massive memory usage (probably some memory leak)Won't parse properly if the code is a malformed html.So I'm considering using regex to seek inside html streams.In the code bellow I slim down the html stream removing extras spaces and new lines so the regex will cost less to match:html = html.replace(/\r?\n|\s{2,}/g,' ');console.log(html.match(/<my regex>/));I also thought of putting it on a function that would narrowing down even more by getting only the part of the html that matters like:<html> <!-- a lot of irrelevant code --><table id=fooTable> </table><!-- a lot of irrelevant code --></html> This would narrow down the code to cost even less to apply the regex match:var i = html.indexOf('fooTable');var chunck = html.substring(i); Please have your say.Would regex be an elegant/effective way to parse large html content? Is it cpu expensive to run a regex on a very large string?
Parsing HTML in Node.js with regex
javascript;node.js
null
_reverseengineering.6668
Looking for a way to determine whether the loaded binary in IDA is either little or big endian (example do i have a MIPSLE or MIPSBE binary open). I want to avoid just running file on the executable, as I may just not have a copy of the executable.
Determine endianness of file opened in IDA
ida
Found the solution. It is slightly hidden but it is: idaapi.cvar.inf.mfThis returns true on Big and false on Little endian. idaapi.py uses it:def as_unicode(s): Convenience function to convert a string into appropriate unicode format # use UTF16 big/little endian, depending on the environment? return unicode(s).encode(UTF-16 + (BE if _idaapi.cvar.inf.mf else LE))
_codereview.136195
For example if I start with the number 146. I first reverse it, so it becomes 641. Then I add this to the original number to make 787 which is a palindrome. I would repeat the process if the answer is not a palindrome.I made this program show how long it ran for when it finishes or is interrupted and also to write the output to a file called output.txt.from sys import exitfrom signal import SIGINT, signalfrom timeit import default_timerdef n(x): counter = 0 b = 0 start = default_timer() def t(*args): end = default_timer() total = end - start print (total) with open('output.txt','w') as f: f.write('{}\n{}\n{}'.format(b, counter, total)) exit(0) signal(SIGINT,t) while True: b += int(str(x)[::-1]) if b == int(str(b)[::-1]): end = default_timer() print (b, counter) t() break else: counter += 1 print (b,counter) x = b
Palindrome-inize a number
python;strings;python 3.x;palindrome
A few notes:A more pythonic way to determine if a given value is a palindrome:str(n) == str(n)[::-1]You do something similar in your code, but are converting from a string back to an int. This is more readable to me. However, this can slow down the code if we do this sort of casting a lot, so it would be better to abstract this functionality to a loop to reduce the number of casts and further increase readablity:def is_palindrome(num): string = str(num) return string == string[::-1]Use the palindrome test as a check with the while loopIn the while loop, use the logic you already have to add on a reversed int:n += int(str(n)[::-1])I would make it easier to input a number for the code to use, I did this with argparse.def get_args(): parser = argparse.ArgumentParser(description= 'Generate palindrome from number when added to its reverse') parser.add_argument('num', type=int, help='number for palindrome generator') return parser.parse_args()Right now you are writing just a snippet of data to a file, but it is being overwritten every time. I'd recommend just outputting to stdout with this current method, or changing it so you append to a file instead of overwrite it. I've gone with the former recommendation in my final code.For profiling and timing code, it's recommended you use a Python profiler instead of writing code yourself.Final Codeimport argparsedef get_args(): parser = argparse.ArgumentParser(description= 'Generate palindrome from number when added to its reverse') parser.add_argument('num', type=int, help='number for palindrome generator') return parser.parse_args()def is_palindrome(num): string = str(num) return string == string[::-1]def main(): args = get_args() while not is_palindrome(args.num): args.num += int(str(args.num)[::-1]) return args.numif __name__ == __main__: print(main())Test run:$ python test.py 146787
_cs.10257
If $L$ is a binary language (that is, $L \subseteq \Sigma = \{0,1\}^$) and $\overline{L}$ is the complement of $L$:How can I show that if $L \in \mathsf P$, then $\overline{L} \in \mathsf P$ as well?
How to show that the complement of a language in $\mathsf P$ is also in $\mathsf P$?
complexity theory;formal languages;time complexity;complexity classes
Suppose you have an algorithm that decides membership in $L$ in polynomial time (by assumption since it's in $P$). You can easily write an algorithm that uses the previous one for deciding membership in $\bar L$ and prove that it takes polynomial time.
_codereview.88636
I wrote a basic Minesweeper game for practice. It consist 3 classes:Main - only as launcherCell - controling behavior of single cellBoard - coordinating behavior of cells. The hardest part for me, was a determining the value of single cells (how many mines is around it), and firing a chain reaction, if some cell was empty(value = 0) - it check closest cells, if they have value, it just reveal it, if they are empty it repeats process on them. So I wonder if my solution is reasonable (it works, but it look scary), and I would be great, if someone would review it. These are two methods in Board Class: setCellValues() and scanForEmptyCells(). However I will be gratefull for any commants and advices, also concenring OOP, code structure and style.I post basic working GUI version, if someone would like to run it.Main Class:public class Main { public static void main(String[] args){ Board board = new Board(); board.setBoard(); }}Board Class:import javax.swing.*;import java.awt.*;import java.util.ArrayList;public class Board { private Cell[][] cells; private int cellID = 0; private int side = 8; private int limit = side-2; public void setBoard(){ JFrame frame = new JFrame(); frame.add(addCells()); plantMines(); setCellValues(); frame.pack(); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setVisible(true); } public JPanel addCells(){ JPanel panel = new JPanel(new GridLayout(side,side)); cells = new Cell[side][side]; for(int i = 0; i< side; i++){ for(int j = 0; j<side; j++){ cells[i][j] = new Cell(this); cells[i][j].setId(getID()); panel.add(cells[i][j].getButton()); } } return panel; } public void plantMines(){ ArrayList<Integer> loc = generateMinesLocation(10); for(int i : loc){ getCell(i).setValue(-1); } } /*Choose rendom places for mines*/ public ArrayList<Integer> generateMinesLocation(int q){ ArrayList<Integer> loc = new ArrayList<Integer>(); int random; for(int i = 0; i<q;){ random = (int)(Math.random()* (side*side)); if(!loc.contains(random)){ loc.add(random); i++; } } return loc; } // MOST IMPORTANT PART///////////////////////////////////////////////////// /*This method count number of mines around particular cell and set its value*/ public void setCellValues(){ for(int i = 0; i<side; i++){ for(int j = 0; j<side; j++){ if(cells[i][j].getValue() != -1){ if(j>=1 && cells[i][j-1].getValue() == -1) cells[i][j].incrementValue(); if(j<= limit && cells[i][j+1].getValue() == -1) cells[i][j].incrementValue(); if(i>=1 && cells[i-1][j].getValue() == -1) cells[i][j].incrementValue(); if(i<= limit && cells[i+1][j].getValue() == -1) cells[i][j].incrementValue(); if(i>=1 && j>= 1 && cells[i-1][j-1].getValue() == -1) cells[i][j].incrementValue(); if(i<= limit && j<= limit && cells[i+1][j+1].getValue() == -1) cells[i][j].incrementValue(); if(i>=1 && j<= limit && cells[i-1][j+1].getValue() == -1) cells[i][j].incrementValue(); if(i<= limit && j>= 1 && cells[i+1][j-1].getValue() == -1) cells[i][j].incrementValue(); } } } } /*This method starts chain reaction. When user click on particular cell, if cell is empty (value = 0) this method look for other empty cells next to activated one. If finds one, it call checkCell and in effect, start next scan on its closest area. */ public void scanForEmptyCells(){ for(int i = 0; i<side; i++){ for(int j = 0; j<side; j++){ if(!cells[i][j].isNotChecked()){ if(j>=1 && cells[i][j-1].isEmpty()) cells[i][j-1].checkCell(); if(j<= limit && cells[i][j+1].isEmpty()) cells[i][j+1].checkCell(); if(i>=1 && cells[i-1][j].isEmpty()) cells[i-1][j].checkCell(); if(i<= limit && cells[i+1][j].isEmpty()) cells[i+1][j].checkCell(); if(i>=1 && j>= 1 && cells[i-1][j-1].isEmpty()) cells[i-1][j-1].checkCell(); if(i<= limit && j<= limit && cells[i+1][j+1].isEmpty()) cells[i+1][j+1].checkCell(); if(i>=1 && j<= limit && cells[i-1][j+1].isEmpty()) cells[i-1][j+1].checkCell(); if(i<= limit && j>= 1 && cells[i+1][j-1].isEmpty()) cells[i+1][j-1].checkCell(); } } } } ////////////////////////////////////////////////////////////////////////////////// public int getID(){ int id = cellID; cellID++; return id; } public Cell getCell(int id){ for(Cell[] a : cells){ for(Cell b : a){ if(b.getId() == id) return b; } } return null; } public void fail(){ for(Cell[] a : cells){ for(Cell b : a){ b.reveal(); } } }}Cell Clas:import javax.swing.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;public class Cell implements ActionListener{ private JButton button; private Board board; private int value; private int id; private boolean notChecked; public Cell(Board board){ button = new JButton(); button.addActionListener(this); button.setPreferredSize(new Dimension(20,20)); button.setMargin(new Insets(0,0,0,0)); this.board = board; notChecked = true; } public JButton getButton() { return button; } public int getValue() { return value; } public int getId() { return id; } public void setId(int id) { this.id = id; } public void setValue(int value) { this.value = value; } public void displayValue(){ if(value==-1){ button.setText(\u2600); button.setBackground(Color.RED); }else if(value!=0){ button.setText(String.valueOf(value)); } } public void checkCell(){ button.setEnabled(false); displayValue(); notChecked = false; if(value == 0) board.scanForEmptyCells(); if(value == -1) board.fail(); } public void incrementValue(){ value++; } public boolean isNotChecked(){ return notChecked; } public boolean isEmpty(){ return isNotChecked() && value==0; } public void reveal(){ displayValue(); button.setEnabled(false); } @Override public void actionPerformed(ActionEvent e) { checkCell(); }}
Beginner Minesweeper game
java;beginner;game;swing;minesweeper
Some simple pointers to get things started...Magic numbersYou have hard-coded your side, limit (how is it used, and why does it default to side - 2?), the number of mines, the dimensions of your buttons and the meaning of a Cell's value to -1 when it is a mine... these should either be extracted out as constants, or documented clearly to show how they are being used.GUI and usability (UX)Lumping four UX-related suggestions together:Your game is missing the fun of minesweeper: a timer and the ability to flag mines!Also, it will be nice if you had at least a reset button, if not a button to change the number of mines. :)Oh yeah, your expansion logic doesn't seem to expand to also include the numbered cells... It only expands the empty ones, leaving the user to have to manually click on the surrounding numbered cells. This diminishes the playing quality somewhat.Following from the earlier section, your Dimensions(20, 20) can be a bit small for high-DPI displays, it will be nice if you either went with higher values, or look for non-pixel-based scaling alternatives... Here's a related StackOverflow link I found that may be of interest: Side-note: The older Minesweeper for Windows avoids triggering a mine on the first click, it'll be... nice(?) if you can replicate that too. ;)Other minor code stuffVariable declarations should be done with the interface, i.e. List<Integer> loc = ... instead of ArrayList<Integer> loc = ...Board.getID() can just be return cellID++, since that is a post-increment operator. That means (roughly) after the variable is called, the value before the increment is returned to the caller, but the value after the increment is written to the variable for the next usage. It is not that hard to understand as long as you realize the difference between pre- and post-increment operators.This could be just my personal preference, but I'm not fond of the idea of a somewhat complicated ActionListener implementation that knows a Board and also generates JButtons... I have a feeling you might be able to have a generic listener that acts on a pair of (x,y) button coordinates.And that nest of if statements... looks ripe for refactoring, but maybe I'll take a more in-depth look the next time. Code Review: Part Deux (fortified with a bit of Java 8 magic features)Starting your boardIf you can rename setBoard() as getBoard() and change its return type as a JFrame, the following approach is what I believe the more conventional form of starting a Swing application:public static void main(String[] args) { SwingUtilities.invokeLater(() -> new Board().getBoard());}Separating the creation of GUI elements and CellsaddCells() is doing both the creating of GUI elements and the initialization of your side * side Cell-array. It will be better if (the renamed) getBoard(), which calls addCells(), is only concerned with creating the GUI layer, and that instantiating your Board class actually initializes the Cells and the mines for us. This means that any Board instances are properly initialized and ready to be played, which is arguably more 'object'-like. Applying these points will result in the following code:public Board() { cells = new Cell[SIDE][SIDE]; IntStream.range(0, SIDE).forEach(i -> { IntStream.range(0, SIDE).forEach(j -> cells[i][j] = new Cell(this)); }); init();}private void init() { plantMines(); setCellValues();}I have taken the liberty of turning side into a static final SIDE field.Will explain init() later...Iterating through the cells arrayBased on my current understanding, a simpler way of iterating through our 2D array is to create a helper method that accepts a Consumer<Cell> operation in Java 8.private void forEach(Consumer<Cell> consumer) { Stream.of(cells).forEach(row -> Stream.of(row).forEach(consumer));}This allows us to further simplify most of our code afterwards. The first method to be simplified is our addCells() method, provided the separation of concerns described in the earlier section is done.private JPanel addCells() { JPanel panel = new JPanel(new GridLayout(SIDE, SIDE)); forEach(cell -> panel.add(cell.getButton())); return panel;}Cell implementation and couplingAs mentioned in my original answer, I am not fond of Cell implementing the ActionListener interface, and I could be biased. My take on this is to give each JButton generated by the Cell a listener that calls its checkCell() method instead.Cell(Board board) { this.board = board; button = new JButton(); button.addActionListener(listener -> { this.checkCell(); }); ...}As pointed out by @Simon, it'll be better have methods that directly represents the exact actions we want on a Cell, i.e. to setMine(), or check isMine(), or the more straightforward isChecked() as opposed to isNotChecked(). Here they are...int setMine() { if (!isMine()) { setValue(-1); return 1; } return 0;}void checkCell() { reveal(null); if (isMine() || board.isDone()) { board.reveal(isMine() ? Color.RED : Color.GREEN); } else if (value == 0) { board.scanForEmptyCells(); }}boolean isChecked() { return checked;}boolean isEmpty() { return !isChecked() && value == 0;}boolean isMine() { return value == -1;}The other observation I had is that your Cell class seems to be quite coupled with the Board class, and this is evident from the number of non-private methods in them. A quick test shows:All methods in Cell are accessed by Board exceptsetValue(int)displayValue(Color)The following methods in Board are accessed by CellscanForEmptyCells()reveal(Color)isDone()These suggests that there is a bit of 'to-and-fro-ing' between Board and Cell methods, which can be improved upon.Game over?A slight enhancement shown above is the usage of Color to choose how we want to shade the background of a revealed cell. This is useful in the end-game scenario, where we assist the user in showing that all the cells left unchecked (since we don't have the ability to flag) are indeed all the mines. In Board:void reveal(Color color) { forEach(cell -> cell.reveal(color));}boolean isDone() { int[] result = new int[1]; forEach(cell -> { if (cell.isEmpty()) { result[0]++; }}); return result[0] == MINES;}The int[] result is just to get past the limitation that our operation can only be done on a mutable container.In Cell:void reveal(Color color) { displayValue(color); checked = true; button.setEnabled(!checked);}private void displayValue(Color color) { if (isMine()) { button.setText(\u2600); button.setBackground(color); } else if (value != 0) { button.setText(String.valueOf(value)); }}Planting minesAgain, @Simon has some good pointers about your generateMinesLocation() method, but I think it can be further improved... by removing it entirely. Why?It is the only place where a cell ID is used.You don't really need a cell ID as long as you can provide your x, y or row, column coordinates.Nothing beats a straightforward reference in a 2D array.Therefore, all you need is your plantMines():private void plantMines() { Random random = new Random(); int counter = 0; while (counter != MINES) { counter += cells[random.nextInt(SIDE)][random.nextInt(SIDE)].setMine(); }}Cell.setMine() returns 1 if the mine is set, else 0. We can then make use of the return value to increment the total number of mines we have until the desired number of MINES (extracted out as a static final field).Banishing the if nestNow onto the exciting part... What's a reasonable way of generating a 3x3 matrix centered around x, y? We'll need the valid preceding and succeeding values, i.e. x-1 ... x+1 and y-1 ... y+1, and then every permutation of them except x,y itself:A method to get valid preceding and succeeding values:private IntStream sidesOf(int value) { return IntStream.rangeClosed(value - 1, value + 1).filter( x -> x >= 0 && x < SIDE);}Permute horizontally and vertically, and then exclude x,y:private Set<Cell> getSurroundingCells(int x, int y) { Set<Cell> result = new HashSet<>(); sidesOf(x).forEach(a -> { sidesOf(y).forEach(b -> result.add(cells[a][b])); }); result.remove(cells[x][y]); return result;}The nest of if statements is essentially describing:If the current cell (1 of 8) matches a specific criteriaPerform an operation either on that cell, or the cell at x,yAs such, with our getSurroundingCells() method, we can implement that as a pair of filter-and-forEach steps:getSurroundingCells(x, y).stream().filter(predicate).forEach(consumer);Final post-code-refactoring for the two main methods:/** * This method count number of mines around particular cell and set its value */private void setCellValues() { IntStream.range(0, SIDE).forEach(x -> { IntStream.range(0, SIDE).forEach(y -> { if (!cells[x][y].isMine()) { getSurroundingCells(x, y).stream().filter(Cell::isMine) .forEach(z -> cells[x][y].incrementValue()); } }); });}/** * This method starts chain reaction. When user click on particular cell, if cell is * empty (value = 0) this method look for other empty cells next to activated one. * If finds one, it call checkCell and in effect, start next scan on its closest * area. */void scanForEmptyCells() { IntStream.range(0, SIDE).forEach(x -> { IntStream.range(0, SIDE).forEach(y -> { if (cells[x][y].isChecked()) { getSurroundingCells(x, y).stream().filter(Cell::isEmpty) .forEach(Cell::checkCell); } }); });}Bonus! Resetting a BoardMinesweeper addicts* playing your application may revel in the clutter-free interface and possibly even the simplicity of non-flagging and having to maintain a mental map of the mines, but they'll probably be dismayed that starting a new game involves restarting the application... How hard will it be to implement a reset feature?In Board:private JFrame getBoard() { JFrame frame = new JFrame(); frame.getContentPane().setLayout(new BorderLayout()); frame.add(addCells(), BorderLayout.NORTH); frame.add(addControlPanel(), BorderLayout.SOUTH); ...}private JPanel addControlPanel() { JPanel panel = new JPanel(); JButton reset = new JButton(Reset); reset.addActionListener(listener -> reset()); panel.add(reset); return panel;}void reset() { forEach(cell -> cell.reset()); init();}Just in case you forgot, init() does the plantMines() and setCellValues() for us.In Cell:void reset() { setValue(0); button.setText(); button.setBackground(null); checked = false; button.setEnabled(!checked);}* - I will neither confirm nor deny if this includes myself.Have fun!
_datascience.2298
I've built a toy Random Forest model in R (using the German Credit dataset from the caret package), exported it in PMML 4.0 and deployed onto Hadoop, using the Cascading Pattern library.I've run into an issue where Cascading Pattern scores the same data differently (in a binary classification problem) than the same model in R. Out of 200 observations, 2 are scored differently.Why is this? Could it be due to a difference in the implementation of Random Forests?
Differences in scoring from PMML model on different platforms
machine learning;r;apache hadoop;random forest;predictive modeling
The difference was, it appears, due to the different implementation of Random Forests in R and Cascading Pattern (as well as openscoring which I tried later) with respect to ties in the tree voting - i.e. when an even number of trees are built (say, 500) and exactly half classify an application as Good, and the other half as Bad, the handling of those situations differs. Solved it by growing and odd (501) number of trees.
_codereview.165853
I have posted this question 2 days ago and got amazing feedback on it.Hands back to the keyboard, I believe I took the suggestions into account and improved the classes drastically. In this question, would love further criticism and suggestions in regard to my code logic and coding style.The TokenFactory and TokenParser:using System;using System.Collections.Generic;using System.Linq;using System.Text.RegularExpressions;namespace ShirLanguageCompiler{ public class TokenParser { private Regex Pattern; private SyntaxKind Type; public bool CanParse(TokenFactory factory) => Pattern.IsMatch(factory.UpcomingCode); public Token Parse(TokenFactory factory) { Match match = Pattern.Match(factory.UpcomingCode); return new Token(factory.Position, match.Length, factory.Location, Type, match.Value); } public TokenParser(Regex pattern, SyntaxKind type) { this.Pattern = pattern; this.Type = type; } } public class TokenFactory { private int Length { get; } private string Code { get; set; } public int Position { get; set; } public (int Line, int Column) Location; public string UpcomingCode => this.Code.Substring(Position); TokenParser[] Parsers = { new TokenParser(new Regex(@^(?:\\|[^])*, RegexOptions.Compiled),SyntaxKind.LiteralStringToken ), new TokenParser(new Regex(@^'(?:\\'|[^'])+', RegexOptions.Compiled),SyntaxKind.LiteralCharToken ), new TokenParser(new Regex(@^d\d+, RegexOptions.Compiled),SyntaxKind.LiteralNumberToken ), new TokenParser(new Regex(@^false, RegexOptions.Compiled),SyntaxKind.LiteralFalseKeyword ), new TokenParser(new Regex(@^true, RegexOptions.Compiled),SyntaxKind.LiteralTrueKeyword ), new TokenParser(new Regex(@^:, RegexOptions.Compiled),SyntaxKind.ColonToken ), new TokenParser(new Regex(@^;, RegexOptions.Compiled),SyntaxKind.SemiColonToken ), new TokenParser(new Regex(@^\s, RegexOptions.Compiled),SyntaxKind.WhitespaceToken ), new TokenParser(new Regex(@^[\r\n]+, RegexOptions.Compiled),SyntaxKind.EOLToken ), new TokenParser(new Regex(@^,, RegexOptions.Compiled),SyntaxKind.CommaToken ), new TokenParser(new Regex(@^->, RegexOptions.Compiled),SyntaxKind.AccessorToken ), new TokenParser(new Regex(@^=>, RegexOptions.Compiled),SyntaxKind.AssignmentToken ), new TokenParser(new Regex(@^\(, RegexOptions.Compiled),SyntaxKind.OpenParenthesisToken ), new TokenParser(new Regex(@^\), RegexOptions.Compiled),SyntaxKind.CloseParenthesisToken ), new TokenParser(new Regex(@^\{, RegexOptions.Compiled),SyntaxKind.OpenCurlyBracketToken ), new TokenParser(new Regex(@^\)}, RegexOptions.Compiled),SyntaxKind.CloseCurlyBracketToken ), new TokenParser(new Regex(@^\[, RegexOptions.Compiled),SyntaxKind.OpenSquareBracketToken ), new TokenParser(new Regex(@^\], RegexOptions.Compiled),SyntaxKind.CloseSquareBracketToken ), new TokenParser(new Regex(@^\?, RegexOptions.Compiled),SyntaxKind.QuestionMarkToken ), new TokenParser(new Regex(@^\+, RegexOptions.Compiled),SyntaxKind.PlusOperationToken ), new TokenParser(new Regex(@^\-, RegexOptions.Compiled),SyntaxKind.MinusOperationToken ), new TokenParser(new Regex(@^\*}, RegexOptions.Compiled),SyntaxKind.MultiplyOperationToken ), new TokenParser(new Regex(@^\*\*, RegexOptions.Compiled),SyntaxKind.PowerOperationToken ), new TokenParser(new Regex(@^\/, RegexOptions.Compiled),SyntaxKind.DivideOperationToken ), new TokenParser(new Regex(@^\/\/, RegexOptions.Compiled),SyntaxKind.RootOperationToken ), new TokenParser(new Regex(@^==, RegexOptions.Compiled),SyntaxKind.EqualToken ), new TokenParser(new Regex(@^!=, RegexOptions.Compiled),SyntaxKind.InEqualToken ), new TokenParser(new Regex(@^letter, RegexOptions.Compiled),SyntaxKind.LetterKeyword ), new TokenParser(new Regex(@^number, RegexOptions.Compiled),SyntaxKind.NumberKeyword ), new TokenParser(new Regex(@^boolean, RegexOptions.Compiled),SyntaxKind.BooleanKeyword ), new TokenParser(new Regex(@^str, RegexOptions.Compiled),SyntaxKind.StringKeyword ), new TokenParser(new Regex(@^bind, RegexOptions.Compiled),SyntaxKind.BindKeyword ), new TokenParser(new Regex(@^return, RegexOptions.Compiled),SyntaxKind.ReturnKeyword ), new TokenParser(new Regex(@^ref, RegexOptions.Compiled),SyntaxKind.RefKeyword ), new TokenParser(new Regex(@^val, RegexOptions.Compiled),SyntaxKind.ValKeyword ), new TokenParser(new Regex(@^\D\w+\(\), RegexOptions.Compiled),SyntaxKind.FunctionNameToken ), new TokenParser(new Regex(@^\D\w+, RegexOptions.Compiled),SyntaxKind.VariableNameToken ) }; public TokenFactory(string code) { this.Code = code; this.Length = code.Length; this.Position = 0; this.Location = (0, 0); } public IEnumerable<Token> GetTokenStream() { while(this.Position < this.Length) { TokenParser Parser = Parsers.First(n => n.CanParse(this)); Token Parsed = Parser.Parse(this); if (Parsed.Type == SyntaxKind.EOLToken) this.Location = (this.Location.Line++,0); else this.Location.Column += Parsed.Length; this.Position += Parsed.Length; #if DEBUG Console.Write(Parsed); #endif yield return Parsed; } } }}And here the Token class:using System.Diagnostics;using System.Text.RegularExpressions;namespace ShirLanguageCompiler{ public enum SyntaxKind { PlusOperationToken, MinusOperationToken, DivideOperationToken, MultiplyOperationToken, PowerOperationToken, RootOperationToken, EqualToken, InEqualToken, VariableNameToken, FunctionNameToken, NumberKeyword, BooleanKeyword, LetterKeyword, StringKeyword, BindKeyword, ReturnKeyword, RefKeyword, ValKeyword, LiteralTrueKeyword, LiteralFalseKeyword, LiteralNumberToken, LiteralCharToken, LiteralStringToken, EOLToken, QuoteToken, ColonToken, SemiColonToken, CommaToken, QuestionMarkToken, WhitespaceToken, AssignmentToken, AccessorToken, OpenParenthesisToken, CloseParenthesisToken, OpenCurlyBracketToken, CloseCurlyBracketToken, OpenSquareBracketToken, CloseSquareBracketToken } public interface IContainsLocation { (int Line, int Column) Location { get; set; } string LocationString { get; } } [DebuggerDisplay(Value = {EscapedString} Start = {Start}, Length = {Length}, Location = {LocationString})] public class Token: IContainsLocation { public int Start, Length; public (int Line, int Column) Location { get; set; } public SyntaxKind Type { get; private set; } public string InnerValue { get; private set; } public string LocationString { get { return $(Line:{this.Location.Line},Collumn:{this.Location.Column}); } } public string EscapedString { get { return Regex.Escape(InnerValue); } } public Token(int start, int length, (int Line, int Column) Location, SyntaxKind type, string innervalue) { this.Start = start; this.Length = length; this.Type = type; this.InnerValue = innervalue; this.Location = Location; } public override string ToString() => this.InnerValue; }}
Compiler Tokenizer implementation in C# - follow-up
c#;parsing;compiler;lexical analysis
I would start by replacing the tuple (int Line, int Column) location with an immutable struct named SourceLocation. Here are some of the reasons why I would do this.The concept already exists in several places. TokenFactory, Token, and IContainsLocation know about this tuple. Adding a FileName field to the tuple would require changes to all three types. TokenParser and Token should not be modifying the contents of this tuple.TokenFactory modifies its Location field but it is easy to change the interface so that it doesn't need to.Replacepublic (int Line, int Column) Location;withpublic int Line {get; private set;}public int Column {get; private set;}Why Properties Matter gives a detailed explanation of why you should avoid using public fields.Mutable tuples are a relatively new idea and there isn't a consensus on whether they are appropriate to use in APIs. I use them only in types that are internal or private. Here is how I would write SourceLocation. I used ReSharper to generate the overrides and the IEquatable implementation. public struct SourceLocation : IEquatable<SourceLocation> { public int Line { get; } public int Column { get; } public SourceLocation(int line, int column) { Line = line; Column = column; } public bool Equals(SourceLocation other) { return Line == other.Line && Column == other.Column; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is SourceLocation && Equals((SourceLocation) obj); } public override int GetHashCode() { unchecked { return (Line * 397) ^ Column; } } public void Deconstruct(out int line, out int column) { line = Line; column = Column; } }TokenParser Pattern and Type should both be marked readonly.Your code currently evaluates each regular expression twice.Consider changing the interface to something like this:public bool TryParse(TokenFactory factory, out Token token)TokenParser knows more about TokenFactory than it needs to.If you change the signature of TryParse to the following then you can test it independently of TokenFactory.public bool TryParse(int position, string input, SourceLocation location, out Token token)This would make it easier to write unit tests for the different SyntaxKinds and run them on every build.Token This class seems like it could be made immutable without any loss in functionality. You can make Token immutable by replacing the public fields with get-only properties, removing all other property setters, and sealing the class. Immutability eliminates the need to reason about what state an object is in. The article Functional C#: Immutability discusses this topic in detail.
_codereview.60586
I am usingNode.jsExpress.jsnode-mysql.jsasync.jsI am making multiple asynchronous queries to my DB, but every query relies on the previous one's results, so I decided to use the waterfall method. Right now, my code looks like this (I simplified it with only 2 queries, but there are more):async.waterfall([ function(cb){ db.query(insertQuery,values,cb); }, function(results,_,cb){ var lastInsertId = results.insertId; db.query(anotherInsertQuery,otherValues.concat(lastInsertId),cb); }],callback);But I found my code a bit messy, especially the function(cb) { ... } wraps. Is there a way to get rid of those annoying function(cb){...} ?
Shorten my asynchronous DB queries, using async.js module
javascript;node.js;asynchronous;async.js
null
_codereview.146440
I'm in the process of improving my coding style and performance hence I decided to delve into bit manipulation on Hackerrank. I thought the question was straight forward but on large input, my solution's performance declines. How do I improve it? Any smart tricks to solve the below question is welcome as well.Below is the questionGiven an integer, \$n\$ , find each \$x\$ such that:\$0 \leq x \leq n \$\$ n + x = n \oplus x \$where \$\oplus\$ denotes the bitwise XOR operator. Then print an integer denoting the total number of \$x\$ 's satisfying the criteria above.Input FormatA single integer, \$n\$ .Constraints\$0 \leq n \leq 10 ^ {15}\$ Subtasks\$0 \leq n \leq 100\$ for \$60\%\$ of the maximum scoreOutput FormatPrint the total number of integer \$x\$ 's satisfying both of the conditions specified above.Sample Input 05Sample Output 02Explanation 0For \$n = 5\$ , the \$x\$ values \$0\$ and \$2\$ satisfy the conditions:Thus, we print \$2\$ as our answer.Here is my codeusing System;using System.Collections.Generic;using System.IO;using System.Linq;class Solution { static int SumVsXoR(long number) { int count =0; long j = 0; while (j <= number) { if(j + number == (j^number)){ count++; } j++; } return count; } static void Main(String[] args) { long n = Convert.ToInt64(Console.ReadLine()); Console.WriteLine(SumVsXoR(n)); }}
Hackerrank Sum vs XoR
c#;programming challenge;time limit exceeded;bitwise
null
_codereview.25620
As the question states: have I missed some obvious security vulnerabilities in this code? Particularly interested in XSS...I'm trying to create something more robust that strip_tags, but simpler than HTML Purifier which just feels like overkill.class StripTags { private $tags; private $dom; function __construct($html, $tags = null) { // Setup tags $this->setTags($tags); //Initialise document using provided HTML $doc = new DOMDocument(); @$doc->loadHTML($html); //suppress invalid HTML warnings $doc_elem = $doc->documentElement; $this->traverseAndRemove($doc_elem); // Store DOM for processing in __toString() $this->dom = $doc; } public function __toString() { // Remove unwanted DOCTYPE etc $str = $this->dom->saveHTML(); $str = str_replace('<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.0 Transitional//EN http://www.w3.org/TR/REC-html40/loose.dtd>', , $str); $str = preg_replace(/^<html><body>/, , trim($str)); $str = preg_replace(/<\/body><\/html>$/, , trim($str)); return $str; } private function setTags($t) { if (empty($t) or !is_array($t)) { $this->tags = array(html, body, p, span, div, img, b, i, em, strong, h1, h2, h3, h4, a, pre); } else { $this->tags = $t; } if (!in_array(html,$this->tags)) { $this->tags[] = html; } if (!in_array(body,$this->tags)) { $this->tags[] = body; } } private function traverseAndRemove(&$elem) { // Check node type, attributes and child nodes // Reset child/attribute loops if one is removed if ($elem->nodeType === XML_ELEMENT_NODE) { $tagName = $elem->tagName; if (!in_array($tagName, $this->tags)) { // Remove any elements in the tags array and stop processing it $elem->parentNode->removeChild($elem); return; } // Check attributes for Javascript events and src/hrefs with javascript too... if ($elem->hasAttributes()) { $attrs = $elem->attributes; for ($i=0,$max=$attrs->length; $i<$max; $i++) { $name = $attrs->item($i)->name; if (in_array($name, array(onload, onclick,onmouseover,onmousemove,onmousehover,onmousedown,onmouseup, onunload))) { $elem->removeAttribute($name); $max--; $i--; } if (in_array($name,array(src, href)) and preg_match(/^javascript:/i, $attrs->item($i)->value)) { $elem->removeAttribute($name); $max--; $i--; } } } } // Check all child nodes too if ($elem->hasChildNodes()) { $children = $elem->childNodes; for ($i=0, $max=$children->length; $i<$max; $i++) { $this->traverseAndRemove($children->item($i)); if ($children->length < $max) { $i -= ($max - $children->length); $max = $children->length; } } } }}
Have I missed some obvious XSS vulnerabilities?
php;html;parsing
null
_unix.105564
I am connecting to an embedded Linux board using screen over a serial link and trying to change the terminal type, as the default vt100 is pretty restrictive in terms of colours and scrolling etc.The screen manual suggests the configuration option termcapinfo but using that doesn't fix the issue.On the host machine, TERM is set to xterm-256color and when I connect to the target, using the termcapinfo setting in my .screenrc, TERM is still set to vt100.I am thinking maybe I should set something on the target machine?
Change terminal type for screen over a serial connection
terminal;gnu screen;gnome terminal;xterm
It's the remote machine that sets $TERM to vt100, because it cannot know what terminal emulator your connecting with. vt100 is a safe value as the majority of modern terminals and terminal emulators (including screen) are compatible.To tell the applications over there what your terminal actually is, you have to set $TERM explicitely:TERM=screenYou can do:find $(infocmp -D) -printf '%f\n' | sort -u | grep screento see if there are more appropriate entries like screen-256color.
_codereview.172345
I have SELECT with UNION and LIKE in my project and I have this code:SELECT TOP 10 pcchrgcodFROM ( SELECT TOP 10 acctno AS pcchrgcod FROM hdocordWHERE acctno LIKE '2007-000%' GROUP BY acctnoUNIONSELECT TOP 10 acctno AS pcchrgcod FROM hpatchrgWHERE acctno LIKE '2007-000%' GROUP BY acctno UNIONSELECT TOP 10 acctno AS pcchrgcod FROM hrqdWHERE acctno LIKE '2007-000%' GROUP BY acctnoUNIONSELECT TOP 10 acctno AS pcchrgcod FROM hrxoWHERE acctno LIKE '2007-000%' GROUP BY acctno )sub GROUP BY pcchrgcodWhen I run this code in MSSQL IDE I get:The query result is too slow.So when I try in a browser I get:Fatal error: Maximum execution time of 30 seconds exceeded in Is there another way to improve the SELECT query to make it return the result faster in a web browser?
Fasten select JOINs and SELECT UNION to get results faster
sql;sql server
null
_unix.108281
First and foremost I want to know how long my laptop (unix, apple, OSX 10.9 mavericks) has been 'awake' (i.e. how long its been open, or since it last 'slept'). I' also be interested in how long since the last restart, and time since the last shutdown (if those two things can be differentiated). I've tried the who and w commands, which seem to show me time for the whole system, and for individual processes (terminals?) since the system last restarted.Is there a way to tell how long the system has been awake, explicitly?Does the reported process times include sleep-time (i.e. when my laptop is closed)?Is there a way to distinguish between restart and shutdown?
How long system has been awake / running / since restart
time;laptop
Use uptime command. Yes, it includes sleep time, if you don't want to include it see:How to find the uptime since last wake from standby?. There is no way to distinguish between restart and shutdown, without parsing logs.
_webapps.15415
The Twitter app is showing in my Facebook profile, so I think it's installed, but when I go here: http://apps.facebook.com/twitter/ -- I just get a blank page.According to help videos I've watched, when I go there, there should be the ability to specify which of my Facebook pages my tweets should be published on.I'd like to make my tweets appear on my page -- not my personal page -- my business page. Why is the http://apps.facebook.com/twitter/ page blank? How do I get this app to function?
Blank page at http://apps.facebook.com/twitter/
facebook;twitter
You have to delete/uninstall the application, remove the permissions and try again. I wish I could tell you the exact problem with the application but I have not figured it out. Facebook and Twitter do not share information well so there are bugs that have not been fixed over the past few months.
_cogsci.13386
If I give a task in which there are only two response-options, and I want to categorise the participant according to their responses, what is the 'cutoff' or required proportion of one type of response?E.g.50-50 would be chance level performance: 50% Type A responses; 50% Type B responses.100-0 would be a perfect Type A performance: 100% Type A responses.Presumably a significant number of Type A responses (say, probably around 65%) would qualify as 'Type A' as opposed to 'chance performance'. But how should I decide on what that number is - what is a justifiable criterion and how do I justify using it?
In a forced-choice task, what proportion of responses is above chance level?
statistics
null
_scicomp.444
For example, I would like to numerically compute the $L^2$-norm of $\displaystyle u = \frac{1}{(x^2+y^2+z^2)^{1/3}}$ in some domain that includes zero, I tried Gauss quadrature and it fails, it is kinda far from the real $L^2$-norm on the unit ball using spherical coordinates to integrate, is there any good way to do this? This problem is often seen in the finite element computing toy problems for domains with re-entrant corners. Thanks.
What numerical quadrature to choose to integrate a function with singularities?
numerics;finite element;quadrature
You should be able to get accurate results with mpmath, a Python module for arbitrary-precision floating-point computations. There are examples of integration with singularities in the documentation. You'll want to explicitly tell it to break up the interval:from mpmath import *f = lambda x,y,z: 1./(x**2+y**2+z**2)**1./3quad(f,[-1,0,1],[-1,0,1],[-1,0,1])You may need to increase the precision (e.g. mp.dps=30) and it will likely be slow, but should be quite accurate.You could also try nesting calls to MATLAB's quadgk(), which uses adaptive Gauss-Kronrod quadrature in 1D.
_unix.87223
I have the following line in my /etc/rsyslog.conf:programname, contains, suhosin /var/log/suhosin.logwhich logs all php security related incidents to /var/log/suhosin.log. That is nice, but I would like rsyslog to execute my script action.sh instead of logging to file. How could I do that?
rsyslog: execute script on matching log event
rsyslog
You are looking for omprog.module(load=omprog)action(type=omprog binary=/pathto/omprog.py --parm1=\value 1\ --parm2=\value2\ template=RSYSLOG_TraditionalFileFormat)See the docs for more details:http://www.rsyslog.com/doc/v8-stable/configuration/modules/omprog.html
_unix.337647
I am using Debian Testing/Stretch with Xfce. I just bought this wired keyboard. I would like the num lock to be turned on by default, but I do not want to have the led indicator light on. This could be accomplished by disabling the num lock indicator altogether, reversing the state (showing the indicator light when the num lock is off), or all of the num-lock-off keys could be remapped to type numbers instead (with this I can type numbers when the indicator is on or off). setleds -L -num works but only in a tty session. Thanks
Disable num lock indicator LED or reverse keypad so when num lock is on, indicator light is off
x11;keyboard;keyboard layout
null
_codereview.75848
I'm applying fallbacks to rem values only if required (you know, the whole progressive enhancement train), without conditional comments (because it's not just an IE issue) and without additional lines of CSS for fallbacks all over the place. I'm just checking for the edge cases (userAgent) and adding a stylesheet into the head only when these come into play. This stylesheet has overrides to apply px values where needed.I'm aware modernizr.js does a great job of detection and I would only need to use .no-cssremunit (I've used it before) but I'm not using modernizr anywhere else and think it unnecessary to load a new library for only this, if I'm wrong, please correct me.rem support issues in questionSamsung Note 2 (Android 4.3) doesn't support remlte IE8 doesn't support rem valuesOpera Mini doesn't support rem valuesSource, the other issues with rem's do not apply here.I wrote this and it seems to be working well in IE <9 and Opera Mini (I'm unable to really test with a Note 2 with Android 4.3 at this time, will soon). BUT not being a JavaScript/jQuery developer I wanted to have another set of eyes on this to see if it is a good approach. Am I missing anything that could throw a wrench into it?/* detect opera mini */var isOperaMini = (navigator.userAgent.indexOf(Opera Mini) > -1);/* userAgent detect (Samsung Note 2 -- Android 4.3) */var isNoteTwo = (navigator.userAgent.match(Mozilla/5.0 (Linux; U; Android 4.3; de-de; SAMSUNG GT-N7105/N7105XXUENA1 Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30));/* <ie8 -- addEventListener not supported by IE8 or later */var isltIE9 = (!document.addEventListener);/* if either variable matches, import stylesheet */if (isOperaMini || isNoteTwo || isltIE9) { var css = document.createElement(link); css.rel = stylesheet; css.href = css/rem-fallback.css;}
Load stylesheet for rem value fallback to px
javascript;portability
I have tested the following code in IE8 and Safari and it works, although I cannot test on the Galaxy Note or Opera Mini. The following javascript allows you to test rem support. Since IE9 or lower throws an error when you try to set as rem, I used a try{}catch(){} - newer browsers should remove the value as soon as its set when they don't support setting the value as such. I don't know if this solves all your problems (if the Galaxy allows you to set rem but doesn't apply it, then this won't work). I have used pure javascript, so you don't need support for anything else (like jQuery).function supports(attribute, test){ var supports = false; try { var div = document.createElement(div); div.style[attribute] = test; if(div.style[attribute] === test){ supports = true; } } catch(e){} return supports;}You could then test for rem support as such:if(supports(fontSize, 1rem)){ /* Rem supported, don't add your stylesheet */} else { /* No rem support, add another stylesheet to make up for it */}This is a purer and simpler, and more reusable, version of your code. Sniffing user agents is generally a bad idea as they inevitably lead to confusion, and a user agent string in the future might match what you are testing for and therefore have an unexpected outcome. It is also best practise to allow for more universal solutions. You could, for example, use this same function to see if you can set background-imageto 1rem and it would return false.UpdateI have just done some testing with browser stack (which, granted, is an emulator) and the Galaxy Note 2 does support rem. And not because my function says it, I made a page with this code:<!DOCTYPE html><html style=font-size: 12px;><head></head><body> <div style=font-size: 5em;>5EM <div style=font-size: 2em; font-size: 2rem;>2(*5)EM/2REM</div> </div></body></html>and the nested 2(*5)EM/2REMis smaller than the 5EM, which indicates its getting the base value from the html tag and not from the parent, indicating rem support.
_cogsci.9120
Why do we sympathize in general when we see something or someone dying even if we personally don't know it/them?Is there any species other than humans which sympathize with the death of its own species?Is there any species other than humans which sympathize with the death of other species?
Psychology of Sympathizing with Death
animal cognition;health psychology
null
_webmaster.44776
I have two domains, one for UK and another for Australia. I want keep same design and content on both websites the same and I want to promote them country wise. My question is: can I keep same content on both? Is there a technique or tag for this?
Website promotion by country
seo
null
_unix.11530
I'm having some trouble in exporting the PATH I've modified inside the Makefile into the current Terminal. I'm trying to add to the PATH, the bin folder inside wherever the Makefile directory is.Here's the relevant strip of the makefile:PATH := $(shell pwd)/bin:$(PATH)install: mkdir -p ./bin export PATH echo $(PATH)The echo prints it correctly but if I redo the echo in the terminal, the PATH remains the same.
Adding directory to PATH through Makefile
environment variables;path;make
null
_codereview.5196
The following is a function that I wrote to display page numbers as they appear in books.If you enter the list [1,2,3,6,7,10], for example, it would return:1-3,6-7,10This seemed like a nice example of how the dictionary data type can be used in Python.Is there is an even more code-efficient way to do this?def formatpagelist (numberlist): tempdic={} returnstring='' for number in numberlist: if number-1 in tempdic.keys(): tempdic[number-1]=number elif number-1 in tempdic.values(): for key in tempdic.keys(): if number-1==tempdic[key]: foundkey=key tempdic[foundkey]=number else: tempdic[number]=0 keylist=list(tempdic.keys()) keylist.sort() for key in keylist: if tempdic[key]>0: returnstring+=(str(key)+'-'+str(tempdic[key])+',') else: returnstring+=str(key)+',' return returnstring
Grouping consecutive numbers into ranges in Python 3.2
python;clustering;interval
null
_codereview.155612
I've been trying to write nice snippet of code to simulate pi estimation by randomly throwing darts on a dartboard. While running the following code on high but reasonable numbers my mac doesn't plot. When looking at it I don't find the source of such a high complexity.I checked similar questions like this but haven't been able to find straightforward answer.My guess is that the line plotting real pi is computationally intense - but that's just a hunch.I'd also appreciate any comment regarding style / efficiency.import numpy as npimport randomimport mathfrom matplotlib import pyplot as pltdef estimatePi(r,w,h,N): center = (w/2.0,h/2.0) in_circle = 0 for i in range(N): x = random.uniform(0.0,w) y = random.uniform(0.0,h) distance = math.sqrt((x-center[0])**2+(y-center[1])**2) if distance <= r: in_circle += 1 outOfCircle=N-in_circle ratio = float(in_circle)/N #ratio = ((r**2)*pi)/(w*h) // *(w*h) #ratio*(w*h) = ((r**2)*pi) // : r**2 pi = ratio*(w*h)/(r**2) return pi#run, aggregate results:PiEstimation=[]num_darts=[]loopcount = 1000001i=10000while i <loopcount: result=estimatePi(3,10,10,i) num_darts.append(i) PiEstimation.append(result) i += 15000# plot:plt.title('Estimating the Value of Pi - Dartboard Simulation')plt.plot([0,100000000], [3.14,3.14], 'k-',color=red, linewidth=2.0)plt.ylabel('Pi Estimation')plt.xlabel('Number of Darts')plt.errorbar(num_darts,PiEstimation, yerr=.0001,ecolor='magenta')plt.show('hold')
Estimating Pi with random darts on dartboard - high complexity issues
python;python 2.7;time limit exceeded;numerical methods;matplotlib
PerformanceThe biggest simple performance improvement would be to use xrange() instead of range() for the loop counter in estimatePi(). Note that i is unused; it is customary to use _ as the name of a throwaway variable.I don't see much point in the r, w, and h parameters. If you make the dartboard a unit circle centered at the origin, then you could do away with the math.sqrt().outOfCircle is never used. Its naming is also inconsistent with in_circle.Plot qualityFor a program that aims to visualize the accuracy of the technique to estimate , you're being awfully sloppy by plotting a horizontal line at y = 3.14 rather than at math.pi. The easier way to plot a horizontal line is to use axhline().It makes no sense to use an errorbar plot here, with an arbitrarily chosen yerr=.0001, since you have just one sample at each x.LoopingNeither loop is as expressive as it could be.In estimatePi(), you can calculate in_circle using sum() with a generator expression. (When coerced into an integer, True is treated as 1, and False as 0.)To make the lists num_darts and PiEstimation, you can use range() and a list comprehension, respectively.Suggested solutionTake care to follow PEP 8 naming conventions.from math import pifrom random import uniformimport matplotlib.pyplot as pltdef estimate_pi(n): in_circle = sum( uniform(-1, 1)**2 + uniform(-1, 1)**2 <= 1 for _ in xrange(n) ) return 4.0 * in_circle / ndarts = range(10000, 1000001, 15000)pi_estimations = [estimate_pi(n) for n in darts]plt.title('Estimating the Value of Pi - Dartboard Simulation')plt.ylabel('Pi Estimation')plt.xlabel('Number of Darts')plt.axhline(y=pi, color=red, linewidth=2.0)plt.plot(darts, pi_estimations, marker='o')plt.show('hold')This runs in under a minute on my machine.
_unix.185650
I stuck on installation in centos with some soft on error. How I can exit of installation proccess or reboot server?
How to reboot centos with hotkeys?
centos
null
_softwareengineering.332025
I have a file editor. It reads from a file, creates an object with the read data and can then write that data into a same (or another) file.Every time user opens a file a new tab is created and a private instance of the object is assigned to it, containing it in the tab. The object itself is complex and is composited of other objects. Each custom type has a Write() and Read() methods that extract and save data from and into the file. Something like this:TopObject a0 int a int b string c CustomObjectMid d int e bool f List<CustomObjectMid2> g CustomObjectMid3 h CustomObjectBottom i long j ulong k Dictionary<string, int> l byte mThe real object is much bigger and has more depth (levels) to it.TopObject, CustomObjectMid, CustomObjectMid2, CustomObjectMid3 and CustomObjectBottom all have a Write() and Read() methods that populate all standard types with data from file. They don't contain any other methods. They don't even have constructors (other than the default).The sole purpose of this object is to hold information. It's essentially a structure. This is actually written as a DLL which purpose it to enable users to make sense of that particular file format (read from it and write to it). So the actual code is not in my program, but is a part of a library. As such, I'd like to keep the library relatively neutral - I don't want to implement code that is specific to the editor into the library.The way this object is implemented is that everything is public and I can access anything in a0.h.i.j manner. I tend to pass relevant parts of the objects to pieces of program that use it, so I don't have to reference to everything from the top (a0).Other parts of the program display the data to the user and translate the changes user makes into the object. They also perform the necessary checks to keep the integrity of data (prevent passing of chars for ints, etc)My question is is this good design? I decided not to use getters and setters. It would just bloat the code for no reason (at least I can't see one).All that being said, for some reason this smells like a bad code to me (not sure why), but I don't really see any other way of implementing it without doing an overkill, given it's role in the program.EDIT: Here is the full code of the root class. All the other classes have the same structure:namespace SaveManipulator.GameData{[Serializable]public class CustomFile{ //version = 7 public Value<uint> saveFileVersion; //ecd public ECD ecd; //food public Food food; //drink public Drink drink; //inventory public Stack[] inventory; //selectedSlot public Value<int> selectedSlot; //bag public Stack[] bag; //craftedList public HashSet<string> craftedList; //spawnPoints public List<Vector3Di> spawnPoints; //SpawnKey public Value<long> SpawnKey; //notSaved = true public Value<bool> randomBoolean; //notSaved = 0 public Value<short> randomShort; //bLoaded public Value<bool> bLoaded; //lastPosition public Vector3Di lastPosition; //id public Value<int> id; //droppedPosition public Vector3Di droppedPosition; //kills public Value<int> kills; //fKills public Value<int> fKills; //deaths public Value<int> deaths; //score public Value<int> score; //equipment public Equipment equipment; //unlockedList public List<string> unlockedList; //notSaved = 1 public Value<ushort> randomUShort; //marker public Vector3Di marker; //favorites public Equipment favorites; //experience public Value<uint> experience; //level public Value<int> level; //bCrouched public Value<bool> bCrouched; //cdata public Cdata cdata; //favoriteList public List<string> favoriteList; //J public Skills skills; //totalItems public Value<uint> totalItems; //distance public Value<float> distance; //life public Value<float> life; //waypoints public Waypoints waypoints; //skillPoints public Value<int> skillPoints; //quests public Quests quests; //deathTime public Value<int> deathTime; //currentL public Value<float> currentL; //bDead public Value<bool> bDead; public CustomFile Clone() { Stream stream = new FileStream(CustomFile , FileMode.Create, FileAccess.Write, FileShare.None); IFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, this); stream.Close(); stream = new FileStream(CustomFile, FileMode.Open, FileAccess.Read, FileShare.None); PlayerDataFile clone = (PlayerDataFile)formatter.Deserialize(stream); stream.Close(); File.Delete(CustomFile); return clone; } public void Read(string path) { BinaryReader reader = new BinaryReader(new FileStream(path, FileMode.Open)); if (reader.ReadChar() == 'd' && reader.ReadChar() == 't' && reader.ReadChar() == 's' && reader.ReadChar() == '\0') { saveFileVersion = new Value<uint>((uint)reader.ReadByte()); ecd = new ECD(); ecd.Read(reader); food = new Food(); food.Read(reader); drink = new Drink(); drink.Read(reader); inventory = Stack.Read(reader); selectedSlot = new Value<int>((int)reader.ReadByte()); bag = Stack.Read(reader); //num int craftedListLength = (int)reader.ReadUInt16(); craftedList = new HashSet<string>(); for (int i = 0; i < craftedListLength; i++) { craftedList.Add(reader.ReadString()); } //b byte spawnPointsCount = reader.ReadByte(); spawnPoints = new List<Vector3Di>(); for (int j = 0; j < (int)spawnPointsCount; j++) { Vector3Di spawnPoint = new Vector3Di(); spawnPoint.x = new Value<int>(reader.ReadInt32()); spawnPoint.y = new Value<int>(reader.ReadInt32()); spawnPoint.z = new Value<int>(reader.ReadInt32()); spawnPoints.Add(spawnPoint); } spawnKey = new Value<long>(reader.ReadInt64()); randomBoolean = new Value<bool>(reader.ReadBoolean()); randomShort = new Value<short>(reader.ReadInt16()); bLoaded = new Value<bool>(reader.ReadBoolean()); lastPosition = new Vector3Di(); lastPosition.x = new Value<int>(reader.ReadInt32()); lastPosition.y = new Value<int>(reader.ReadInt32()); lastPosition.z = new Value<int>(reader.ReadInt32()); lastPosition.heading = new Value<float>(reader.ReadSingle()); id = new Value<int>(reader.ReadInt32()); droppedPosition = new Vector3Di(); droppedPosition.x = new Value<int>(reader.ReadInt32()); droppedPosition.y = new Value<int>(reader.ReadInt32()); droppedPosition.z = new Value<int>(reader.ReadInt32()); kills = new Value<int>(reader.ReadInt32()); fKills = new Value<int>(reader.ReadInt32()); deaths = new Value<int>(reader.ReadInt32()); score = new Value<int>(reader.ReadInt32()); equipment = Equipment.Read(reader); //num int count = (int)reader.ReadUInt16(); unlockedList = new List<string>(); for (int k = 0; k < count ; k++) { unlockedList .Add(reader.ReadString()); } randomUShort = new Value<ushort>(reader.ReadUInt16()); marker = new Vector3Di(); marker.x = new Value<int>(reader.ReadInt32()); marker.y = new Value<int>(reader.ReadInt32()); marker.z = new Value<int>(reader.ReadInt32()); favorites = Equipment.Read(reader); experience = new Value<uint>(reader.ReadUInt32()); level = new Value<int>(reader.ReadInt32()); bCrouched = new Value<bool>(reader.ReadBoolean()); cdata = new Cdata(); cdata.Read(reader); //num int favoriteListSize = (int)reader.ReadUInt16(); favoriteList = new List<string>(); for (int l = 0; l < favoriteListSize; l++) { favoriteList.Add(reader.ReadString()); } //num2 int size = (int)reader.ReadUInt32(); skills = new Skills(); skills.Read(reader); totalItems = new Value<uint>(reader.ReadUInt32()); distance = new Value<float>(reader.ReadSingle()); life = new Value<float>(reader.ReadSingle()); waypoints = new Waypoints(); waypoints.Read(reader); skillPoints = new Value<int>(reader.ReadInt32()); quests = new Quests(); quests.Read(reader); deathTime = new Value<int>(reader.ReadInt32()); currentL = new Value<float>(reader.ReadSingle()); bDead = new Value<bool>(reader.ReadBoolean()); //irelevant bytes reader.ReadByte(); reader.ReadBoolean(); reader.Close(); } else { throw new IOException(Save file corrupted!); } } public void Write(string path) { BinaryWriter writer = new BinaryWriter(new FileStream(path, FileMode.Create)); writer.Write('d'); writer.Write('t'); writer.Write('s'); writer.Write((byte)0); writer.Write((byte)saveFileVersion.Get()); ecd.Write(writer); food.Write(writer); drink.Write(writer); Stack.WriteItemStack(writer, inventory); writer.Write((byte)selectedSlot.Get()); Stack.WriteItemStack(writer, bag); writer.Write((ushort)craftedList.Count); HashSet<string>.Enumerator enumerator = craftedList.GetEnumerator(); while (enumerator.MoveNext()) { writer.Write(enumerator.Current); } writer.Write((byte)spawnPoints.Count); for (int i = 0; i < spawnPoints.Count; i++) { writer.Write(spawnPoints[i].x.Get()); writer.Write(spawnPoints[i].y.Get()); writer.Write(spawnPoints[i].z.Get()); } writer.Write(selectedSpawnKey.Get()); writer.Write(randomBoolean.Get()); writer.Write(randomShort.Get()); writer.Write(bLoaded.Get()); writer.Write((int)lastPosition.x.Get()); writer.Write((int)lastPosition.y.Get()); writer.Write((int)lastPosition.z.Get()); writer.Write(lastPosition.heading.Get()); writer.Write(id.Get()); writer.Write(droppedPosition.x.Get()); writer.Write(droppedPosition.y.Get()); writer.Write(droppedPosition.z.Get()); writer.Write(kills.Get()); writer.Write(zKills.Get()); writer.Write(deaths.Get()); writer.Write(score.Get()); equipment.Write(writer); writer.Write((ushort)unlockedList.Count); List<string>.Enumerator enumerator2 = unlockedList.GetEnumerator(); while (enumerator2.MoveNext()) { writer.Write(enumerator2.Current); } writer.Write(randomUShort.Get()); writer.Write(marker.x.Get()); writer.Write(marker.y.Get()); writer.Write(marker.z.Get()); favorites.Write(writer); writer.Write(experience.Get()); writer.Write(level.Get()); writer.Write(bCrouched.Get()); cdata.Write(writer); writer.Write((ushort)favoriteList.Count); List<string>.Enumerator enumerator3 = favoriteList.GetEnumerator(); while (enumerator3.MoveNext()) { writer.Write(enumerator3.Current); } skills.Write(writer); writer.Write(totalItems.Get()); writer.Write(distance.Get()); writer.Write(life.Get()); waypoints.Write(writer); writer.Write(skillPoints.Get()); quests.Write(writer); writer.Write(deathTime.Get()); writer.Write(currentL.Get()); writer.Write(bDead.Get()); writer.Write((byte)88); writer.Write(true); writer.Close(); } public CustomFile(string path) { Read(path); }}}Since the code is mostly copied from the source of the game, I obfuscated it a little bit, that's why some names may look vague. Also Value<Type> is a wrapper class used to pass around value types while keeping their reference without explicitly having to think about it. That way the user can change bits of the file easier. I don't really see how I could partially save the file. Save files are usually from 4kB to (my estimate) 10kB. They aren't that big.
Design of a storage object - object used soley to store data
design;object oriented;object oriented design
null
_codereview.86673
Where I work, we have 3 forms for leavers: HR, IT and rota. Lots of questions are duplicated across all 3 forms. So I thought, why not fill ONE form out, remove all duplicate questions, and simply split out the answers into formats that match original forms? I combined the form questions, then wrote a script to get the correct data I wanted, in the layout I wanted. All is working, but as I'm not great at JavaScript, I'd really appreciate any feedback on what I've done and if there are any improvements to be made.I've annotated my code as best as I can.function splitForm() {// Part 1 of the code. Set the variables and read load data.// Control variables. Can be changed by user.var done = 22; // In the source sheet, what column number is Done. If A = 1, B = 2var when = 23; // In the source sheet, what column number is Date Moved. If A = 1, B = 2// Sheet name variables. Can be changed if sheet names change.var source = Form responses; //Name of the sheet with form responsesvar hrSheet = HR; // Name of the sheet for HR responsesvar itSheet = IT; // Name of the sheet for IT responsesvar wfmSheet = WFM; // Name of the sheet for WFM responses// Temporary array variables. As the script splits data, this is where we'll store the data.var hrArray = [];var itArray = [];var wfmArray = []; // Gets the data from the source sheet and loops through it a row at a time, starting at row 2. Row 1 has headers and can be ignored.var ss = SpreadsheetApp.getActiveSpreadsheet();var sheet = ss.getSheetByName(source);var values = sheet.getDataRange().getValues();// Part 2 of the code. Read and split the data into formats ready for the 3 different sheets.for (i=1;i<values.length;i++){// The if statement is a duplicate check. It checks if the Done column is empty. If it is, it then gets data.if(values[i][done-1] == ){// The var name gets the employees full name from the split first and second name.var name = values[i][2]+ + values[i][3];// Below we replace the email domain with nothing. Then replace the full stop with a space.// This is to give us the Name of the person submitted form value.// Email addresses are always in [email protected] formatvar submit1 = values[i][1].replace(@email-domain.co.uk,);var submit2 = submit1.replace(., );// Pushes unsubmitted data to the HR data Array. This also trims the data so it fits the HR sheet layout.hrArray.push(values[i].slice(0,13));// Sorts the layout of the IT data so it matches destination sheet, then pushes it to an array// I've created an array called itLayout, so the final array's data, matches the destinations.var itLayout = [ values[i][0],values[i][1],name, values[i][7], values[i][10],values[i][13],values[i][14],values[i][15]];itArray.push(itLayout);// Only if Values[i][20] has No will this push data into an array, anything eles we are not interested in.// Sorts the layout of the wfm data, so it matches the destination sheet, then pushes the data to an array.// I've created an array called wfmLayout, so the final array's data, matches the destinations.if(values[i][20] == No){var wfmLayout = [values[i][0],values[i][1],submit2,name,,,,values[i][17],values[i][10],values[i][18],values[i][19],values[i][16]];wfmArray.push(wfmLayout);}// This row of data has been pushed to the various Arrays, time to mark the items as done on the source sheet before it checks the next line of datavar date = new Date();sheet.getRange(i+1, done).setValue(Hell yeah);sheet.getRange(i+1, when).setValue(date);}}// Part 3 of the code which writes the data into the appropriate sheets.// Checks how many rows are needed per sheet and stores for latervar hrLength = hrArray.length;var itLength = itArray.length;var wfmLength = wfmArray.length;// This checks first if there is data to write, then sees if there are enough rows. Finally the data is written to the sheet if (hrLength != 0){ var hrTarget = ss.getSheetByName(hrSheet); var lastRow = hrTarget.getLastRow(); var requiredRows = lastRow + hrLength - hrTarget.getMaxRows(); if (requiredRows > 0) hrTarget.insertRowsAfter(lastRow, requiredRows); hrTarget.getRange(lastRow + 1, 1, hrLength, hrArray[0].length).setValues(hrArray); }// This checks first if there is data to write, then sees if there are enough rows. Finally the data is written to the sheet if (itLength != 0){ var itTarget = ss.getSheetByName(itSheet); var lastRow1 = itTarget.getLastRow(); var requiredRows1 = lastRow1 + itLength - itTarget.getMaxRows(); if (requiredRows1 > 0) itTarget.insertRowsAfter(lastRow1, requiredRows1); itTarget.getRange(lastRow1 + 1, 1, itLength, itArray[0].length).setValues(itArray); }// This checks first if there is data to write, then sees if there are enough rows. Finally the data is written to the sheet if (wfmLength != 0){ var wfmTarget = ss.getSheetByName(wfmSheet); var lastRow2 = wfmTarget.getLastRow(); var requiredRows2 = lastRow2 + wfmLength - wfmTarget.getMaxRows(); if (requiredRows2 > 0) wfmTarget.insertRowsAfter(lastRow2, requiredRows2); wfmTarget.getRange(lastRow2 + 1, 1, wfmLength, wfmArray[0].length).setValues(wfmArray); }}
Combining 3 forms into 1, then writting data to 3 different sheets, with different layouts
google apps script;google sheets
Line-by-line reviewfunction splitForm() {Start every function with a comment explaining what it does, no matter how obvious you think the title is. For example, maybe this function isn't really about scoring the form of splits in a gymnastics routine...I like using jsdoc format in GAS code. It's supported for custom functions, appears in Google's documents, is used for automatic documentation of GAS libraries. Embrace it, get fluent in it... and don't be afraid to use tags that aren't supported by GAS.For example:/** * Split form responses in a spreadsheet and deliver the relevant * parts to each of three role-specific sheets. * * @param {type} name Description of parameter * * @returns {type} Description of returns * @throws Description of any thrown errors */function splitForm() { ...// Part 1 of the code. Set the variables and read load data.// Control variables. Can be changed by user.var done = 22; // In the source sheet, what column number is Done. If A = 1, B = 2var when = 23; // In the source sheet, what column number is Date Moved. If A = 1, B = 2Rather than embed these column numbers as constants in code, you could calculate them using the column headers. You'd have to do that after you've read the sheet's values.Doing this makes it easier to distribute your script to less-technical users, as it frees them to change the spreadsheet layout without needing to make matching changes in the script.Something like:var values = sheet.getDataRange().getValues();// Locate control columns - throw error if missingvar headers = values[0];var done = headers.indexOf(Done) + 1;var when = headers.indexOf(Date Moved) + 1;if (done == 0 || when == 0) { throw new Error( 'Must have columns labelled Done and Date Moved.' );}Decide whether you need 0-based indexes for use in Javascript arrays, or 1-based indexes for use in Spreadsheet Service methods. This example is for the latter, but I think you really need the former.// Sheet name variables. Can be changed if sheet names change.var source = Form responses; //Name of the sheet with form responsesvar hrSheet = HR; // Name of the sheet for HR responsesvar itSheet = IT; // Name of the sheet for IT responsesvar wfmSheet = WFM; // Name of the sheet for WFM responsesSimilarly, these values present a problem for maintaining & sharing your script. Investigate options that pull the constants out of your code, making them into auto-discovery or configuration data. // Temporary array variables. As the script splits data, this is where we'll store the data. var hrArray = []; var itArray = []; var wfmArray = [];I prefer to keep these sorts of declarations as close to the first use of the variable as possible. It makes no functional difference, but increases readability & understand-ability of code. (IMHO) // Gets the data from the source sheet and loops through it a row at a time, starting at row 2. Row 1 has headers and can be ignored. var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheetByName(source); var values = sheet.getDataRange().getValues();Ok, although the comment doesn't match the code it's sitting with. // Part 2 of the code. Read and split the data into formats ready for the 3 different sheets. for (i = 1; i < values.length; i++) { // The if statement is a duplicate check. It checks if the Done column is empty. If it is, it then gets data. if (values[i][done - 1] == ) {Here you're converting between 0- and 1- based indexes, see previous comment. Eliminating +/- 1 will help avoid these simple, yet hard-to-find bugs. // The var name gets the employees full name from the split first and second name. var name = values[i][2] + + values[i][3];More magic column numbers! If you decide not to auto-discover these, that's fine, but at least use meaningful name, like values[i][colFirstName]. // Below we replace the email domain with nothing. Then replace the full stop with a space. // This is to give us the Name of the person submitted form value. // Email addresses are always in [email protected] format var submit1 = values[i][3].replace(@email-domain.co.uk, ); var submit2 = submit1.replace(., );Once again, you're relying on a constant that limits portability, a string this time. See How can I extract the user name from an email address using javascript? // Pushes unsubmitted data to the HR data Array. This also trims the data so it fits the HR sheet layout. hrArray.push(values[i].slice(0, 13)); // Sorts the layout of the IT data so it matches destination sheet, then pushes it to an array // I've created an array called itLayout, so the final array's data, matches the destinations. var itLayout = [values[i][0], values[i][4], name, values[i][7], values[i][10], values[i][13], values[i][14], values[i][15]]; itArray.push(itLayout); // Only if Values[i][20] has No will this push data into an array, anything eles we are not interested in. // Sorts the layout of the wfm data, so it matches the destination sheet, then pushes the data to an array. // I've created an array called wfmLayout, so the final array's data, matches the destinations. if (values[i][20] == No) { var wfmLayout = [values[i][0], values[i][5], submit2, name, , , , values[i][17], values[i][10], values[i][18], values[i][19], values[i][16]]; wfmArray.push(wfmLayout); }This whole block is full of magic numbers, so at a minimum that needs to be addressed.This repeats a cell-by-cell copy three times, with slight differences. When you see repeated logic, you should ask yourself if there is some way to refactor it to just ONE piece of code (often in a separate function) by focusing on the requirements that are common across all. // This row of data has been pushed to the various Arrays, time to mark the items as done on the source sheet before it checks the next line of data var date = new Date(); sheet.getRange(i + 1, done).setValue(Hell yeah); sheet.getRange(i + 1, when).setValue(date); } }Question: What happens if your script gets interrupted right now? You'll have marked rows as done, yet not written them out to their destination sheets. How do you recover from that?Efficiency would be improved if you held off marking individual rows at this time, as well. That implies a solution that marks rows as done all at once, AFTER all destination updates are done.Would be helpful to explain the i + 1 in this case, e.g. in code with row = i+1; // 1-based row numbering. // Part 3 of the code which writes the data into the appropriate sheets. // Checks how many rows are needed per sheet and stores for later var hrLength = hrArray.length; var itLength = itArray.length; var wfmLength = wfmArray.length; // This checks first if there is data to write, then sees if there are enough rows. Finally the data is written to the sheet if (hrLength != 0) { var hrTarget = ss.getSheetByName(hrSheet); var lastRow = hrTarget.getLastRow(); var requiredRows = lastRow + hrLength - hrTarget.getMaxRows(); if (requiredRows > 0) hrTarget.insertRowsAfter(lastRow, requiredRows); hrTarget.getRange(lastRow + 1, 1, hrLength, hrArray[0].length).setValues(hrArray); } // This checks first if there is data to write, then sees if there are enough rows. Finally the data is written to the sheet if (itLength != 0) { var itTarget = ss.getSheetByName(itSheet); var lastRow1 = itTarget.getLastRow(); var requiredRows1 = lastRow1 + itLength - itTarget.getMaxRows(); if (requiredRows1 > 0) itTarget.insertRowsAfter(lastRow1, requiredRows1); itTarget.getRange(lastRow1 + 1, 1, itLength, itArray[0].length).setValues(itArray); } // This checks first if there is data to write, then sees if there are enough rows. Finally the data is written to the sheet if (wfmLength != 0) { var wfmTarget = ss.getSheetByName(wfmSheet); var lastRow2 = wfmTarget.getLastRow(); var requiredRows2 = lastRow2 + wfmLength - wfmTarget.getMaxRows(); if (requiredRows2 > 0) wfmTarget.insertRowsAfter(lastRow2, requiredRows2); wfmTarget.getRange(lastRow2 + 1, 1, wfmLength, wfmArray[0].length).setValues(wfmArray); }These three nearly-identical pieces would be easily refactored into a parameterized function.Are you sure you need to worry about adding rows to the sheets? Isn't that taken care of automatically by setValues()?General commentsConsistently well-formatted code is easier to read & maintain. Make sure you've enabled Indenting on the GAS editor. Run your existing code through a pretty-printer to tame it. For example, JSBeautifier with the settings below will produce the same results as the editor:Select all - copy - paste - beautify - copy - paste back - WHAM!Generally speaking, smaller pieces of code are easier to understand and maintain than larger ones. Your single, large function could be separated into a few smaller ones, especially where there is an opportunity to support all three target sheets with one block of code.This looks like it's a function that you intend to execute manually, possibly through a custom menu. Have you considered instead using a form submission trigger function to process forms as they arrive? It would require significantly simpler code, as all the row-looping would be eliminated. You could still support a manual function by simulating form submissions using the technique from How can I test a trigger function in GAS?
_webapps.81137
Is there a way I can change the subject line (example, instead of Re:, I could put In Progress: or Done:) and not have Gmail split the conversation into a new email?
Changing subject line without splitting up the conversation
gmail
null
_softwareengineering.45564
Do programmers perform better when working from office or from a location of their choice? Also do they work better with fixed timings compared to flexible hours?
Programmer performance : based on location, timings
productivity;performance
This depends highly on the individual programmers involved, and the need for collaboration, teamwork and mentoring.I've seen teams fail because the programmers all worked different hours in different places, and couldn't keep on the same page or share knowledge quickly by ways such as instant whiteboard meetings in the hallway, talking over cubicle walls, pair programming, etc.I've also seen teams perform poorly because programmers who who liked to code all night were expected to come in for too many morning meetings after a long commute, and ended up too sleep deprived to get in the groove and meet schedule. If you have management flexibility, I suggest varying the routine near the beginning of a project, and find an unbiased observer to estimate if any type of routine seems to help or hinder the team on average. If the programmers are employees in a competitive market for their skill sets, you also have to include job satisfaction in any decisions.
_webapps.103600
On https://slack.com/, how do I display message timestamps in 24-hour format instead of AM/PM?
How to display 24-hour format time in Slack?
slack
From Slack support: Click your team name to open the Team Menu.Choose Preferences.Select the Messages & Media tab.Check out the Message Theme and Display Options settings.You can adjust other message-related settings under Display Options:...Show times with 24-hour clock Choose between 24-hour and 12-hour times (e.g. 16:12 or 4:12 PM).
_webmaster.98081
So I have an organization created in Github and I created a project in that organization. Now I can create the site for this project by creating the branch gh-pages and pushing the html files here. I want to point a subdomain to this github pages site. For example, I have a domain called testdomain.com and I want app.testdomain.com should point to github pages located at http://orgname.github.io/app I went through the documentation but I can't understand how to make this redirect. Any leads will be helpful.
Redirect Github project page to a subdomain
dns;cname;github
null
_webapps.54842
I recently saw this message in my Recent activity feed in Google Drive:[Name Redacted] restricted access to 3 itemsHow do i find out which items I've lost access to? My drive has a large number of documents on it, and i'd like to be able to ask for access back to items that are relevant, soon after the access was changed - and not much later, when the other person might not remember they've changed things.
Which items has my access been restricted to?
google drive
null
_unix.103885
I have an executable that starts a user-interactive shell. I would like to, upon launch of the shell, inject a few commands first, then allow the user to have their interactive session. I can do this easily using echo:echo command 1\ncommand 2\ncommand3 | ./shell_executableThis almost works. The problem is that the echo command that is feeding the process's stdin hits EOF once it's done echoing my commands. This EOF causes the shell to terminate immediately (as if you'd pressed Ctrl+D in the shell).Is there a way to inject these commands into stdin without causing an EOF afterwards?
Piping data to a process's stdin without causing EOF afterward
shell script;pipe;stdin
Found this clever answer in a similar question at stackoverflow(echo -e cmd 1\ncmd 2 && cat) | ./shell_executableThis does the trick. cat will pump in the output of echo into input stream of shell_executable and wait for more inputs until EOF.
_unix.61763
I host a wordpress site on my server which has 2GB mem, I have used some cache plugin, but when I type ps -eo %C : %p : %z : %a | sort -k5 -nr in SSH, I see the httpd memory usage is very high.15.7 : 3131 : 4732740 : /usr/local/mysql/bin/mysqld 0.5 : 3356 : 515860 : /usr/sbin/httpd 0.6 : 3363 : 509308 : /usr/sbin/httpd 0.6 : 3333 : 509308 : /usr/sbin/httpd 0.5 : 3367 : 509308 : /usr/sbin/httpd 0.5 : 3361 : 509308 : /usr/sbin/httpd 0.5 : 3358 : 509308 : /usr/sbin/httpd 0.5 : 3338 : 509308 : /usr/sbin/httpd 0.4 : 3366 : 509308 : /usr/sbin/httpd 0.3 : 3370 : 509308 : /usr/sbin/httpd 0.3 : 3359 : 509308 : /usr/sbin/httpd 0.0 : 3193 : 410980 : /usr/sbin/httpd ...The server always dead. I have set memory in php.ini like this:memory_limit = 768Mmemory = 20M
httpd memory usage very high
memory;php;apache httpd
Main reason for your server load is due to memory_limit (768M) of php.ini. As your server has only 2GB ram could not able to handle if more http request made into the server leads of multiple connection of php that consume more memory. so, i suggest you to decrease the global php.ini memory_limit to optimal that is below 200M to control the load.
_cstheory.4858
I hope you can help. I am looking for the best way to generate random bipartite graphs with localised structure within one of the node types. Such that type A visits a local group of type B with a particular probability and then within that group connectes an edge with type be also with a particular probablity based on the attribute of nodes of type B. Basically this is social network data where one group has a preference function that determines the probability of linking with another individual of a different type. However the choosey group os restricted in the node value distributions they see due to the localised groupings of the chosen type. Sorry I hope this question does not bore. All programs I have tried do not allow both this localised structure by trait values as well as probability of pairing based on trait values.Best Wishes,Colin
Structured Graph Generation
ds.algorithms;network modeling;pseudorandom generators;social sciences
null
_webmaster.37805
I'm having a look at a friends website (a fairly old PHP based one) which they've been advised needs re-structuring. The key points being:URLs should be lower case and more friendly. The root of the domain should be not be re-directed.The first point I'm happy with (and the URLs needed tidying up anyway) and have a draft plan of action, however the second is baffling me as to not only the best way to do it, but also whether it should be done.Currently http://www.example.com/ is redirected to http://www.example.com/some-link-with-keywords/ using the follow index.php in the root of the Apache2 instance.<?php$nextpage = some-link-with-keywords/;header( HTTP/1.1 301 Moved Permanently );header( Status: 301 Moved Permanently );header(Location: $nextpage);exit(0); // This is Optional but suggested, to avoid any accidental output?>As far as I'm aware, this has been the case for around three years -- and I'm sorely tempted to advise to not worry about it. It would appear taking off the 301 could:Potentially affect page ranking (as the 'homepage' would disappear - although it couldn't disappear because of the next point...)Introduce maintainance issues as existing users would still have the re-directed page in their cacheFollowing the above, introduce duplicate contentConfuse Google/other SE's as to what the homepage actually is nowI may be over-analysing this but I have a feeling it's not as simple as removing the 301 from the root, and 301'ing the previous target to the root...Any suggestions (including it's not worth it) are sincerely appreciated.
Removing 301 redirect from site root
seo;php;htaccess;mod rewrite
Redirecting the homepage is never best practice. A proper homepage with a link to the second page is a better structure and gives you two pages now for targeting to search engines for different terms. It also allows search engines to better understand what your site is about. If you wanted to redirect the second page back to the homepage that is not an issue (I'd use htaccess and a 301 redirect) however two pages of different content might suit your purposes better depending on what you are trying to do.Users who have visited the page before will be redirected as it is a server side redirect.
_cs.13542
There are a number of collections of network (or graph) data sets freely available on the web, e.g.http://snap.stanford.edu/data/index.htmlhttp://www.cc.gatech.edu/dimacs10/downloads.shtmlI am looking for dynamic network data sets, i.e. networks whose structure varies over time. They seem to be quite rare: The SNAP collection contains only a few temporal graphs.Do you known any other possible sources?
Looking for dynamic network data sets
graphs;data sets;social networks;big data
null
_webmaster.8182
I see a lot of requests for nonexistent php files on my website. They tend to have a querystring like appserv_root=http://www.example.com, using domains with evil-looking php code.I am pretty confident that this is trying to make use of some php vulnerability or other. So, I am curious:What vulnerability is this trying to make use of?How does one protect against this vulnerability?What in the site configuration would be changed if this vulnerability was successfully exploited?
What is the purpose of the appserv_root requests?
php;security
Looks like they're trying to do a remote file include attack. Looks like this is the vulnerability they are trying to exploit but I'm not 100% sure of it. I'm guessing you look safe if you're not using that application and/or have register_globals turned off (which you always should).
_codereview.43627
I want a thread safe list with a max item count, will the following implementation correctly provide this?public class ConcurrentThrottledList<T>{ private readonly List<T> items = new List<T>(); private readonly int maxItems; private object _lock = new object(); public ConcurrentThrottledList(int maxItems) { this.maxItems = maxItems; } public bool TryAdd(T item) { lock (_lock) { if (items.Count < maxItems) { items.Add(item); return true; } return false; } } public bool TryRemove(T item) { lock (_lock) { return items.Remove(item); } } public bool IsFull { get { lock (_lock) { return items.Count >= maxItems; } } } public T[] Items { get { lock(_lock) { return items.ToArray(); } } }}
ConcurrentThrottledList - Will this implementation be thread safe?
c#;thread safety
null
_unix.331885
This is the output of lsusb:Bus 003 Device 005: ID 04f2:b409 Chicony Electronics Co., Ltd Bus 003 Device 006: ID 13d3:3408 IMC Networks Bus 003 Device 003: ID 046d:c077 Logitech, Inc. M105 Optical MouseBus 003 Device 002: ID 8087:8000 Intel Corp. Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub # this is the one which I want to unbindBus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hubBus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hubI want to be able to permanently unbind the fifth device. Any solution?
Disable specific usb device
arch linux;usb
null
_codereview.19959
So, I have coded a PHP script that will make it able for the users to edit their Post, or comments on a site that runs SociaEngine 4.So, Is there anything that could get inproved/fixed on this?<?php session_start(); $Mysql_Hostname = 192.168.1.110; $Mysql_Username = *user; $Mysql_Password = ************; $Mysql_Database = Socialengine; $Sql = new mysqli($Mysql_Hostname, $Mysql_Username, $Mysql_Password, $Mysql_Database); if ($Sql->connect_error){die($Sql->connect_error);} $ID = session_id(); // Get session cookie data / id $GetSession = $Sql->query(SELECT * FROM `engine4_core_session` WHERE id = '.$ID.'); // Get the session data for the user. $Session = $GetSession->fetch_array(); // blah blah... if($Session['user_id'] == NULL) { die(You need to be logged inn to use this); } // Check if the user is logged inn $GetUser = $Sql->query(SELECT * FROM `engine4_users` WHERE `user_id` = '.$Session['user_id'].'); // Get user data $User = $GetUser->fetch_array(); // blah... echo <p>You are currenty logged inn as: .$User['displayname'].</p>; // Give a message that they are logged in if($_GET['mode'] == done) { // If they have edited, Then close the window echo '<script type=text/javascript> window.close(); </script>'; } if($_GET['mode'] == edit) { // If they want to edit a comment... $CID = $_GET['id']; // Get comment id $GetComment = $Sql->query(SELECT * FROM `engine4_activity_comments` WHERE `poster_id` = '.$Session['user_id'].' AND `comment_id` = '.$Sql->real_escape_string($CID).'); // Get the comment from Mysql with User restriction... $Comment = $GetComment->fetch_array(); // blah if($GetComment->num_rows == 0) { die(Not authorized to edit); } // If the comment wasn't theirs, Then die... echo <<<HTML <form action=Session.php?mode=done&type=comment method=post> <input type=hidden name=ID value={$Comment['comment_id']}> <textarea rows=3 cols=45 name=Comment>{$Comment['body']}</textarea> <p><input type=submit value=Edit comment></p> </form>HTML;// Render the edit form exit; // Stop processing } if($_GET['mode'] == post) { // If they want to edit a post... $CID = $_GET['id']; // Get post id $GetPost = $Sql->query(SELECT * FROM `engine4_activity_actions` WHERE `subject_id` = '.$Session['user_id'].' AND `action_id` = '.$Sql->real_escape_string($CID).'); // Same as comments, Get with post id and user id $Post = $GetPost->fetch_array(); // blah if($GetPost->num_rows == 0) { die(Not authorized to edit); } // No! Don't try to edit others post's... echo <<<HTML <form action=Session.php?mode=done&type=post method=post> <input type=hidden name=ID value={$Post['action_id']}> <textarea rows=3 cols=45 name=Comment>{$Post['body']}</textarea> <p><input type=submit value=Edit post></p> </form>HTML;// Render the post edit form exit; // and stop } if(isset($_POST['Comment'])) { // If the form has been submitted. if($_GET['type'] == comment) { // Check if it's a comment or a post $Verify = $Sql->query(SELECT * FROM `engine4_activity_comments` WHERE `poster_id` = '.$Session['user_id'].' AND `comment_id` = '.$Sql->real_escape_string($_POST['ID']).'); // Verify if it's theirs... if($Verify->num_rows == 1) { // If it's theirs, Contiune $Update = $Sql->query(UPDATE `Manehatten`.`engine4_activity_comments` SET `body` = '.$Sql->real_escape_string($_POST['Comment']).' WHERE `poster_id` = '.$Session['user_id'].' AND `comment_id` = '.$Sql->real_escape_string($_POST['ID']).'); // Update the data in mysql } } elseif($_GET['type'] == post) { // Check if it's a comment or a post $Verify = $Sql->query(SELECT * FROM `engine4_activity_actions` WHERE `subject_id` = '.$Session['user_id'].' AND `action_id` = '.$Sql->real_escape_string($_POST['ID']).'); // Verify if it's theirs... if($Verify->num_rows == 1) { // If it's theirs, Contiune $Update = $Sql->query(UPDATE `Manehatten`.`engine4_activity_actions` SET `body` = '.$Sql->real_escape_string($_POST['Comment']).' WHERE `subject_id` = '.$Session['user_id'].' AND `action_id` = '.$Sql->real_escape_string($_POST['ID']).'); // Update the data.. } } } // This script is only for test, or comment id getting /IGNORE THIS/ echo <p>Displaying Comments with Limit of 30 </p>; echo <hr>; $GetComments = $Sql->query(SELECT * FROM `engine4_activity_comments` WHERE `poster_id` = '.$Session['user_id'].' ORDER BY `engine4_activity_comments`.`creation_date` DESC LIMIT 0, 30); while($Data = $GetComments->fetch_assoc()){ echo <p>.$Data['body'].' | ID: <a href=Session.php?mode=edit&id='.$Data['comment_id'].'>'.$Data['comment_id'].</a> <- Click to edit</p>; }I have added comments for what lines do what.I am just a bit unsure if they can use this and alter their session cookie to gather a valid user cookie. The script works fine, Just that if there was something that could be improved.
SocialEngine 4: Edit Post / Comment feature [Anything that can be improved? ]
php
You might consider incorporating a config file for your SQL connection. This will allow you to reuse it should that become necessary and update it more easily. Additionally, the $Mysql_* namespace seems unnecessary.Typically variables are not capitalized. This may just be a style choice, but it looks odd and may cause issues should anyone decide to try and integrate your script into their own.die() is a very inelegant way of terminating your script. You should throw an error or render an error page, with the former eventually accomplishing the latter anyways. You especially shouldn't just dump the error onto the page for any malicious user to see. Save it to a log. The same goes for exit, except you should return early instead. Returning early is really only possible with functions, but exiting the script completely stops everything. That means that if this script were included in another and that other script still needed to do something it couldn't, making your script very hard to incorporate.Comments explaining your code should be unnecessary. If your code is self-documenting then it should be obvious. You should especially avoid comments that don't add anything to your code, such as blah..., its just clutter and makes your code less legible.You are using MySQLi, which is a prepared SQL language, but you aren't using prepared statements. I'm not much of a SQL guru here, but I thought that was the whole reason for the switch from MySQL to MySQLi/PDO.You might also consider adding whitespace to your SQL statements and long PHP statements. Neither PHP nor SQL minds extra whitespace, so making your code more legible is always a plus. The following might be a little excessive, I rewrote it using my style, but it just demonstrates how little whitespace makes a difference in operation, and how much more it adds to legibility.$GetSession = $Sql->query( SELECT * FROM `engine4_core_session` WHERE id = ' . $ID . ' );//andif( $Session[ 'user_id' ] == NULL ) { die( You need to be logged inn to use this );}Also, there is no need to escape the string sequence to incorporate the PHP variable. That's the whole reason for using double quotes. PHP automatically escapes any entities or variables it finds in double quoted strings.WHERE id = '$ID'There is no need to explicitly check for a NULL value when doing a loose == comparison. Unless you are specifically looking for NULL, in which case you should be using an absolute === comparison.if( ! $Session[ 'user_id' ] ) {Instead of echoing HTML, you should consider escaping from PHP. This will allow your IDE to do proper tag matching/highlighting, and will make your code a little easier to read.?><p>You are currently logged in as: <?php echo $User[ 'displayname' ]; ?></p><?phpWhen outputting a lot of HTML, you can consider creating an include. This cleans up some of the clutter from your PHP and separates the display from the logic.//include page<form action=Session.php?mode=done&type=comment method=post><input type=hidden name=ID value=<?php echo $Comment[ 'comment_id' ]; ?>><textarea rows=3 cols=45 name=Comment> <?php echo $Comment[ 'body' ]; ?></textarea><p><input type=submit value=Edit comment></p></form>When you find yourself comparing the same variable multiple times against different values, you might consider using a switch. Switches are slightly faster than a normal if statement and are a little cleaner.switch( $_GET[ 'mode' ] ) { case 'done' : //etc... break; case 'edit' : //etc... break; //etc...}The rest appears to be more of the same. The biggest improvement I can suggest would be to incorporate the use of functions to make this more legible and reusable. Also you appear to be violating the Don't Repeat Yourself (DRY) Principle. As the name implies, your code should not repeat itself. Some of those latter SQL statements appeared very similar, meaning you could probably create a template string and modify it as necessary. Hope this helps.
_unix.48138
I'm looking for a way to limit a processes disk io to a set speed limit. Ideally the program would work similar to this:$ limitio --pid 32423 --write-limit 1MLimiting process 32423 to 1 megabyte per second hard drive writing speed.
How to Throttle per process I/O to a max limit?
hard disk;io;process management;limit;ulimit
That is certainly not trivial task that can't be done in userspace. Fortunately, it is possible to do on Linux, using cgroup mechanizm and its blkio controller. Setting up cgroup is somehow distribution specific as it may already be mounted or even used somewhere. Here's general idea, however (assuming you have proper kernel configuration):mount -t tmpfs cgroup_root /sys/fs/cgroupmkdir -p /sys/fs/cgroup/blkiomount -t cgroup -o blkio none /sys/fs/cgroup/blkioNow that you have blkio controller set, you can use it:mkdir -p /sys/fs/cgroup/blkio/limit1M/echo X:Y 1048576 > /sys/fs/cgroup/blkio/limit1M/blkio.throttle.write_bps_device Now you have a cgroup limit1M that limits write speed on device with major/minor numbers X:Y to 1MB/s. As you can see, this limit is per device. All you have to do now is to put some process inside of that group and it should be limited:echo $PID > /sys/fs/cgroup/blkio/limit1M/tasksI don't know if/how this can be done on other operating systems.
_cs.69109
And if it is how can it be proved ?What are the closure properties of Context Free Languages ?
Is the difference of two Context Free Language also a Context Free Language?
formal languages;context free;formal grammars
null
_webmaster.85538
My webpages on my website may appear static to the user, but they're actually dynamic since data is retrieved from a database and may be changed at anytime. Additionally, users may customize some preferences and that also changes the output as well.At this present time, I have set the client side caching to nothing with the following HTTP headers:Expires: Sat, 01 Jan 2000 00:00:00 GMTPragma: no-cacheCache-control: private, no-cache, no-store, must-revalidateI also added a connection: close since the assets to the page are from a different subdomain.For some reason, I feel there could be more optimal values for cache-control and expires. I also feel I could use etag validation but I'm not 100% sure. I want to use optimal values based on the worst-user perspective. and I think the worst user may consist of hitting the refresh button 100 times a minute. I know for sure if I set the caching values too high, then when users choose customized settings (aka cookie value changes), they will have to refresh the browser or wait the number of seconds the cache is set for in order for the settings to take effect. With no caching set, the customized settings can be saved immediately. I'm just trying to strike the right balance.Should I enable caching, and if so, how long? and have other dynamic sites enabled caching for their dynamic html pages?
optimal cache setting for dynamic page
html;cache;dynamic
null
_unix.271338
I have a remote Linux server, I was trying to connect to it using TigerVNC, I can sucessfully connect to my remote server, when the server iptable is not running, but after I start running iptables, I am unable to connect to remote server using VNC Error : The connection was refused by the host computerConnecting as IP_ADDRESS::5901 Do I need to add entry in iptables to all all to connect to VNC server, or any suggestions? Thanks
VNC Client - Server, Unable to connect to remote server
linux;vnc
null
_cs.51166
Is there a way to randomly shuffle an array using only a source of random boolean values? SO to clarify, shuffle using true /false only, and not integers or decimals.For this question, I'm specifically excluding an approach whereby the booleans are just arranged into an integer and then it's used in a Fisher-Yates shuffle. I'd be repeatedly shuffling approximately 30,000 items and have a ready source of random booleans. I'd need to build up a very large integer for Fischer-Yates to avoid any form of bias in the shuffle. Can this step be avoided and true /false used directly somehow? I have the sense that some soft of bubble sort might do it, with the comparison determined randomly, but I can't quite flesh it out.I'd be interested in any algorithm than wasn't ridiculous i.e. with a stupid time complexity of something like 2^O(n). This question builds upon some of the concepts of Best random permutation employing only one random number but isn't identical.
Is there a random shuffle algorithm using only true /false?
algorithms;randomized algorithms;sampling
null
_softwareengineering.226164
Going through Modulo operation (the avenue I entered while exploring the difference between rem and mod) I came across:In mathematics the result of the modulo operation is the remainder of the Euclidean division. However, other conventions are possible. Computers and calculators have various ways of storing and representing numbers; thus their definition of the modulo operation depends on the programming language and/or the underlying hardware.Questions:Going through Euclidean division I found that remainnder of this operation is always positive (or 0). What limitation of the underlying computer hardware forces programming language designers to differ from mathematics?Every programming language has it predefined, or undefined, rule according to which the result of the modulo operation gets it's sign. What rationale is adopted while making these rules? And if the underlying hardware is the concern then shouldn't rules change according to that, independent of programming language?
What rationale is used when programming language designers decide what sign the result of modulo operation takes?
programming languages;language design;math;arithmetic;design decisions
null
_unix.379520
I have a script that is running some package updates and I want to do a reboot after they are done. The only problem is there are executions that must happen after the reboot occurs. Obviously the script will no longer be running once the system is rebooted.How can I continue what the script was doing after the reboot?Is there any setting that says nextBoot or anything like that where I could insert the contents of the rest of the script?I know about /etc/init.d but this script is only going to be running once a month at most and I don't want the whole script to be running on boot.thanks in advance!
Running a script with shutdown in the middle
scripting;aix;reboot;suse;oracle linux
null
_webmaster.67049
I found a GIF of a guy skeet shooting listed on several sites and I've posted it in my Twitter account below:https://twitter.com/leeand00/status/488894537599680515I looked up the image on Google Images and it's listed several thousand times as having no license associated with it. When I check the other license types it isn't listed there at all. Would I be posting this to my non-profits' account at our own risk? Or does the fact that there is no license listed on Google make the image free game?
Google lists this gif several thousand times as not having a license, is it safe to post on my company's Twitter account?
images;licenses
null
_unix.233899
By pre-typed, I mean the interactive console has code text waiting for the user to (edit and) run by simply pressing enter.It looks like something readline should support, but a confirmation that it doesn't is good enough. At least I will know that installing an additional automation tool (like expect) is the only way.
How can I make readline add pre-typed text on terminal startup?
shell;terminal;readline
Not sure if this helps, and is not per readline, but if python is an alternative (or some similar) one approach could be in the direction of:#!/usr/bin/env python Inject command to own command line import sys, fcntl, termiosdef main(): x tty = sys.stdin old_attr = termios.tcgetattr(tty) new_attr = termios.tcgetattr(tty) # No echo please new_attr[3] &= ~termios.ECHO termios.tcsetattr(tty, termios.TCSANOW, new_attr) cmd = ' '.join(sys.argv[1:]) for char in cmd: fcntl.ioctl(tty, termios.TIOCSTI, char) termios.tcsetattr(tty, termios.TCSANOW, old_attr)if __name__ == '__main__': main()As in: script_name command to inject
_unix.287634
I am trying to get my CentOS v7 server to run IPv6. Root works, it can ping using ping6 ipv6.google.com, and ifconfig looks great; I see the lines:eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500inet 149.202.217.90 netmask 255.255.255.0 broadcast 149.202.217.255inet6 fe80::ec4:7aff:fec4:d912 prefixlen 64 scopeid 0x20<link>inet6 2001:41d0:1000:1c5a:: prefixlen 64 scopeid 0x0<global>But as an unprivileged user, I can't ping ipv6 and I don't see the inet6 addresses in ifconfig. What is happening? Why can't my users see the same interfaces, setup in the same way as root?[edit]As requested, ip a s and ping6 -c1 ipv6.google.com output:root[root@rabbit ~]# ip a s1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 scope host lo valid_lft forever preferred_lft forever inet6 2001:41d0:1000:1c5a::/64 scope global valid_lft forever preferred_lft forever inet6 ::1/128 scope host valid_lft forever preferred_lft forever2: bond0: <BROADCAST,MULTICAST,MASTER> mtu 1500 qdisc noop state DOWN link/ether 5e:63:58:37:5d:30 brd ff:ff:ff:ff:ff:ff3: dummy0: <BROADCAST,NOARP> mtu 1500 qdisc noop state DOWN link/ether 32:ad:47:94:1f:b1 brd ff:ff:ff:ff:ff:ff4: ifb0: <BROADCAST,NOARP> mtu 1500 qdisc noop state DOWN qlen 32 link/ether 7e:52:08:a5:1a:dd brd ff:ff:ff:ff:ff:ff5: ifb1: <BROADCAST,NOARP> mtu 1500 qdisc noop state DOWN qlen 32 link/ether 3e:ba:b9:d1:09:3b brd ff:ff:ff:ff:ff:ff6: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000 link/ether 0c:c4:7a:c4:d9:12 brd ff:ff:ff:ff:ff:ff inet 149.202.217.90/24 brd 149.202.217.255 scope global eth0 valid_lft forever preferred_lft forever inet6 2001:41d0:1000:1c5a::/64 scope global valid_lft forever preferred_lft forever inet6 fe80::ec4:7aff:fec4:d912/64 scope link valid_lft forever preferred_lft forever7: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000 link/ether 0c:c4:7a:c4:d9:13 brd ff:ff:ff:ff:ff:ff8: teql0: <NOARP> mtu 1500 qdisc noop state DOWN qlen 100 link/void9: tunl0@NONE: <NOARP> mtu 1480 qdisc noop state DOWN link/ipip 0.0.0.0 brd 0.0.0.010: sit0@NONE: <NOARP> mtu 1480 qdisc noop state DOWN link/sit 0.0.0.0 brd 0.0.0.011: ip6tnl0@NONE: <NOARP> mtu 1452 qdisc noop state DOWN link/tunnel6 :: brd ::[root@rabbit ~]# ping6 -c1 ipv6.google.comPING ipv6.google.com(par03s15-in-x0e.1e100.net) 56 data bytes64 bytes from par03s15-in-x0e.1e100.net: icmp_seq=1 ttl=57 time=6.61 ms--- ipv6.google.com ping statistics ---1 packets transmitted, 1 received, 0% packet loss, time 0msrtt min/avg/max/mdev = 6.615/6.615/6.615/0.000 msuser (pryormic)[pryormic@rabbit ~]$ ip a s1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 scope host lo valid_lft forever preferred_lft forever inet6 2001:41d0:1000:1c5a::/64 scope global valid_lft forever preferred_lft forever inet6 ::1/128 scope host valid_lft forever preferred_lft forever2: bond0: <BROADCAST,MULTICAST,MASTER> mtu 1500 qdisc noop state DOWN link/ether 5e:63:58:37:5d:30 brd ff:ff:ff:ff:ff:ff3: dummy0: <BROADCAST,NOARP> mtu 1500 qdisc noop state DOWN link/ether 32:ad:47:94:1f:b1 brd ff:ff:ff:ff:ff:ff4: ifb0: <BROADCAST,NOARP> mtu 1500 qdisc noop state DOWN qlen 32 link/ether 7e:52:08:a5:1a:dd brd ff:ff:ff:ff:ff:ff5: ifb1: <BROADCAST,NOARP> mtu 1500 qdisc noop state DOWN qlen 32 link/ether 3e:ba:b9:d1:09:3b brd ff:ff:ff:ff:ff:ff6: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000 link/ether 0c:c4:7a:c4:d9:12 brd ff:ff:ff:ff:ff:ff inet 149.202.217.90/24 brd 149.202.217.255 scope global eth0 valid_lft forever preferred_lft forever inet6 2001:41d0:1000:1c5a::/64 scope global valid_lft forever preferred_lft forever inet6 fe80::ec4:7aff:fec4:d912/64 scope link valid_lft forever preferred_lft forever7: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000 link/ether 0c:c4:7a:c4:d9:13 brd ff:ff:ff:ff:ff:ff8: teql0: <NOARP> mtu 1500 qdisc noop state DOWN qlen 100 link/void9: tunl0@NONE: <NOARP> mtu 1480 qdisc noop state DOWN link/ipip 0.0.0.0 brd 0.0.0.010: sit0@NONE: <NOARP> mtu 1480 qdisc noop state DOWN link/sit 0.0.0.0 brd 0.0.0.011: ip6tnl0@NONE: <NOARP> mtu 1452 qdisc noop state DOWN link/tunnel6 :: brd ::[pryormic@rabbit ~]$ ping6 -c1 ipv6.google.comping: icmp open socket: Operation not permitted[edit2]I've added ifconfig output below:root[root@rabbit ~]# ifconfigeth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 149.202.217.90 netmask 255.255.255.0 broadcast 149.202.217.255 inet6 fe80::ec4:7aff:fec4:d912 prefixlen 64 scopeid 0x20<link> inet6 2001:41d0:1000:1c5a:: prefixlen 64 scopeid 0x0<global> ether 0c:c4:7a:c4:d9:12 txqueuelen 1000 (Ethernet) RX packets 12131475 bytes 2122218137 (1.9 GiB) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 1113935 bytes 690582284 (658.5 MiB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0eth1: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 ether 0c:c4:7a:c4:d9:13 txqueuelen 1000 (Ethernet) RX packets 0 bytes 0 (0.0 B) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 6632 bytes 1169904 (1.1 MiB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536 inet 127.0.0.1 netmask 255.0.0.0 inet6 ::1 prefixlen 128 scopeid 0x10<host> inet6 2001:41d0:1000:1c5a:: prefixlen 64 scopeid 0x0<global> loop txqueuelen 0 (Local Loopback) RX packets 332704 bytes 448694222 (427.9 MiB) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 332704 bytes 448694222 (427.9 MiB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0user (pryormic)[pryormic@rabbit ~]$ ifconfigeth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 149.202.217.90 netmask 255.255.255.0 broadcast 149.202.217.255 ether 0c:c4:7a:c4:d9:12 txqueuelen 1000 (Ethernet) RX packets 0 bytes 0 (0.0 B) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 0 bytes 0 (0.0 B) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0eth1: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 ether 0c:c4:7a:c4:d9:13 txqueuelen 1000 (Ethernet) RX packets 0 bytes 0 (0.0 B) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 0 bytes 0 (0.0 B) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536 inet 127.0.0.1 netmask 255.0.0.0 loop txqueuelen 0 (Local Loopback) RX packets 0 bytes 0 (0.0 B) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 0 bytes 0 (0.0 B) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
Unprivileged ping6 not working
centos;permissions;ip;ipv6;ifconfig
The following command should give users the capability to use ping6. As root runsetcap cap_net_raw+ep /usr/bin/ping
_softwareengineering.178603
Should the singleton be designed so that it can be created and destroyed at any time in program or should it be created so that it is available in life-time of program. Which one is best practice? What are the advantages and disadvantages of both? EDIT :- As per the link shared by Mat, the singleton should be static. But then what are the disadvantages of making it destroyable? One advantage is it memory can be saved when it is not useful.
should singleton be life-time available or should it be destroyable?
c++;object oriented;singleton
null
_softwareengineering.147480
Last week, we had a heated argument about handling nulls in our application's service layer. The question is in the .NET context, but it will be the same in Java and many other technologies.The question was: should you always check for nulls and make your code work no matter what, or let an exception bubble up when a null is received unexpectedly?On one side, checking for null where you are not expecting it (i.e. have no user interface to handle it) is, in my opinion, the same as writing a try block with empty catch. You are just hiding an error. The error might be that something has changed in the code and null is now an expected value, or there is some other error and the wrong ID is passed to the method.On the other hand, checking for nulls may be a good habit in general. Moreover, if there is a check the application may go on working, with just a small part of the functionality not having any effect. Then the customer might report a small bug like cannot delete comment instead of much more severe bug like cannot open page X.What practice do you follow and what are your arguments for or against either approach?Update:I want to add some detail about our particular case. We were retrieving some objects from the database and did some processing on them (let's say, build a collection). The developer who wrote the code did not anticipate that the object could be null so he did not include any checks, and when the page was loaded there was an error and the whole page did not load. Obviously, in this case there should have been a check. Then we got into an argument over whether every object that is processed should be checked, even if it is not expected to be missing, and whether the eventual processing should be aborted silently. The hypothetical benefit would be that the page will continue working. Think of a search results on Stack Exchange in different groups (users, comments, questions). The method could check for null and abort the processing of users (which due to a bug is null) but return the comments and questions sections. The page would continue working except that the users section will be missing (which is a bug). Should we fail early and break the whole page or continue to work and wait for someone to notice that the users section is missing?
Should one check for null if he does not expect null?
error handling;null
The question is not so much whether you should check for null or let the runtime throw an exception; it is how you should respond to such an unexpected situation.Your options, then, are:Throw a generic exception (NullReferenceException) and let it bubble up; if you don't do the null check yourself, this is what happens automatically.Throw a custom exception that describes the problem on a higher level; this can be achieved either by throwing in the null check, or by catching a NullReferenceException and throwing the more specific exception.Recover by substituting a suitable default value.There is no general rule which one is the best solution. Personally, I would say:The generic exception is best if the error condition would be a sign of a serious bug in your code, that is, the value that is null should never be allowed to get there in the first place. Such an exception may then bubble all the way up into whatever error logging you have set up, so that someone gets notified and fixes the bug.The default value solution is good if providing semi-useful output is more important than correctness, such as a web browser that accepts technically incorrect HTML and makes a best effort to render it sensibly.Otherwise, I'd go with the specific exception and handle it somewhere suitable.
_unix.363687
We are generating scripts for running java on RHEL or an Amazon Linux ami. The scripts all now contain the -d64 option. We are using OpenJdk 1.8 64-bit. The oracle faq question When you download the SDK or JRE, must you choose between the 32 and 64-bit versions? indicates that this option is only on Linux for compatibility reasons. It saysAll other platforms (Windows and Linux) contain separate 32 and 64-bit installation packages. If both packages are installed on a system, you select one or the other by adding the appropriate bin directory to your path. For consistency, the Java implementations on Linux accept the -d64 option.So it seems like -d64 is not needed for scripts running on Linux. It may be better to only add that option when running on solaris.Is it required? What would be the harm in removing it from our scripts?
Is -d64 required for java on linux?
linux;java
null
_softwareengineering.198894
I've been working on writing .NET bindings for Rollbar, an error and message reporting service, like Airbrake. My library is working nicely and is published in the NuGet gallery.So now I want to take it to the next level of usability and implement an NLog Extension for this. This entails writing one screen's-worth of code and referencing the NLog library. It's a wrapper. I may also implement one for Log4Net.At this point it's already getting blurry as to how I should organize this and manage it with source control and nuget. One thing for sure is that there will be separate nuget packages so people don't have to install dependencies they don't want.My questions are:Should I create separate git repositories for the base library and NLog extension and Log4Net extension? Seems like it would be easier to track changes have clearly separated build processes and such. It may make contributing to the project(s) easier...but I'm not sure.Should I reference my Rollbar base library as a dependency of the extension libraries, or ILMerge it? The upside to ILMerge is the user only needs one reference and DLL. The odd part is with versioning. Like how to have version numbers that make sense when only the base library changed, or only the extension changed. Also, it seems like nuget doesn't list updates to dependencies of installed packages, only to the packages itself. I'd want updates to the base library to bubble-up as an update the user should install! I suppose one way to do that would be version-bumping the extension and setting the version of the dependency library.This is my first foray into writing an open source library and publishing it and managing it. I'd love some feedback from people who have dealt with this so I can get it right!I'm using Albacore for my build process, for what it's worth.(Current code: https://github.com/mroach/RollbarSharp)
Organizing related projects and dependencies for nuget publishing
c#;.net;builds;versioning;code organization
I wouldn't mind including a useless-to-me, small DLL as part of a bigger package, but I wouldn't want to include that and NLog, so that I can use Rollbar with log4net.So, if you are going to include them in the main package, don't make the package dependent on the secondary product. Because it's not dependent. I don't need NLog to use Rollbar. But, note that this means I'll be able to install any version of NLog alongside Rollbar, which means I'm screwed if I pick one that's incompatible.There are plenty of open-source projects on nuget that link two others and have combined names, like Rollbar.NLog, which makes them turn up next to Rollbar when I'm searching but gives me the choice whether to include them or not.If you take that option, you can make version numbers independant, by setting dependency versions. For example, you say Rollbar.NLog v1.2 requires Rollbar v1.x (the dependency tag in your nuspec file, (id=Rollbar version=[1.1,1.2)) and give me permission to upgrade the two packages independently, as long as neither is upgraded to v2.x.If you have a Rollbar.NLog package then you should make it dependent on NLog. If you can be confident of NLog's versioning (eg. will always be backward compatible, unless the major version changes) then give me freedom with that too. But you don't have to. You can specify id=NLog version=[3.2.1]. Doing so makes it safe for me, but less flexible -- my NLog upgrade strategy is tied to your release strategy.
_codereview.123935
I have written a safe read function for haskell (for education!). I think this is fairly idiomatic haskell code, but I'd like to know for sure. If you see anything else that could be improved, please let me know in your answer. module ReadNum (readNum) wheremain = print $ readNum 87k7readNum :: String -> Maybe IntreadNum xs = readNum' $ reverse xsreadNum' :: String -> Maybe IntreadNum' (x:xs) = (\y z -> y + 10 * z) <$> readChr x <*> readNum' xsreadNum' [] = Just 0chrToNum :: [(Char, Int)]chrToNum = [('0', 0), ('1', 1), ('2', 2), ('3', 3), ('4', 4), ('5', 5), ('6', 6), ('7', 7), ('8', 8), ('9', 9)]readChr :: Char -> Maybe IntreadChr c = lookup c chrToNum
`read` re-implemented for Int's
strings;parsing;haskell;reinventing the wheel;integer
The change I'd make, respecting your overall design, is to refactor chrToNum as this:chrToNum :: [(Char, Int)]chrToNum = zip 0123456789 [0..]Apart from that, if we are willing to slightly alter the design, I would separate the string validation from the computation of the Int represented. The string validation can be done using mapM :: (a -> m b) -> [a] -> m [b] (this way we avoid explicitly writing the recursion).validateString :: String -> Maybe [Int]validateString = mapM readChrThen, you can define a function computing the Int represented by a list of digits (I use foldl' which requires you to add import Data.List but you can equally well use reverse + foldr as you originally did)represents :: [Int] -> Intrepresents = foldl' (\ ih z -> 10 * ih + z) 0Finally, putting it all together we get:readNum :: String -> Maybe IntreadNum = fmap represents . validateString
_webapps.4667
I live in the UK, and whenever I visit google.com I am redirected to google.co.uk, but I want to see my website's rankings on the US version (I presume the results are different). Is there a way to do this?
How can I access google.com outside the US?
google search;geolocation
Try http://www.google.com/ncrThis is only one of several ways to do this according to Google:Click the Google.com link on any other domain.Choose a Google domain manually by visiting the Language Tools page (the section with the flags).Bookmark http://www.google.com/ncr. This is an alternative web address for Google.com that always takes you to Google.com without redirecting you.
_unix.1660
What does it mean when your computer has a kernel panic?Does it equate to the windows BsoD?Also, what methods, tips, tricks are available to the user when a kernel panic strikes?
What is a kernel panic?
kernel panic
Kernel panic is the same as BSOD and is non-rescuable IIRC. However smaller failure is OOPS which denotes some error in kernel.You can use kexec which switches to new kernel on panic (you can threat it as fast reboot) - possibly getting meaningful dump of system to debug the problemYou can use panic parameter which reboots kernel after n seconds. You can instruct GRUB to switch to fallback kernel in such caseUse Magic SysRQ keys to print stack traces etc.
_codereview.165828
I'm working on an Outlook Web Addin that gets the email body. So in the Office API you could get the email body in two types: Simple Text and Html. Our requirement is to get the HTML format so this is easy, however, even if the email body is empty the HTML format still returns a value which is the HTML elements but does not have contents in it. So my solution is to check first for the Simple Text version of the email body then if there is a content get the HTLM format version. Please see the below codes:var mailItem = Office.context.mailbox.item;mailItem.body.getAsync(Office.CoercionType.Text, function (result) { if (result.status === Office.AsyncResultStatus.Succeeded) { var normalizeValue = null; if (result.value) { normalizeValue = result.value.trim(); } if (normalizeValue !== '') { mailItem.body.getAsync(Office.CoercionType.Html, function (result) { if (result.status === Office.AsyncResultStatus.Succeeded) { // the value will be initialized in input value $('#body').val(result.value.trim()); } }); } }});I would like to get the value from the 'Text' type and pass this in a variable then check the variable then run the getAsync for the html version separately instead of having the codes inside the method of body.getAsync. Or anything the code could improve?
Get value from an async function in Outlook Web Addin
javascript;jquery;email;outlook
null
_unix.159949
I have a text file, modifyhostslist.txt, which contains entries that correspond to entries found in my hosts file. Not every entry in my hosts file needs to be modified, only entries also found in modifyhostslist.txt.The entries found in modifyhostslist.txt are to be commented out in the hosts file.Sample line (entry) found in modifyhostslist.txt: 127.0.0.1 www.domain.comThe following serves as the comment out sequence: #%%#I've attempted to use sed to complete the task, but so far I've been unsuccessful. Here's my most recent stab at it: while read line; do sed -i 's/'$line'/#%%#'$line'/' /system/etc/hosts;done < modifyhostslist.txtIn addition, the #%%# comments will be removed at specific intervals thereby returning the hosts file to its original condition. I suspect simply rearranging the command which is used to insert the comments can also be used to remove the comments in the hosts file?It seems the awk command might work, but I'm unsure of how to use it as well.
Sed to Modfiy Hosts File
sed;awk;hosts
You used the command: while read line; do sed -i 's/'$line'/#%%#'$line'/' /system/etc/hosts;done < modifyhostslist.txtAs long as the lines in modifyhostslist.txt match the lines in /system/etc/hosts, that command really should work.If the lines look identical to the eye but the command still does not work, the cause might be a mismatch between the (invisible) line-endings. DOS/Windows files have two-character line-endings while Unix and Mac use one-character line-endings. If this is the problem, the solution is to remove the offending characters. Since hosts is a Unix system file, I expect that it has the correct line-endings and we thus need to remove the surplus \r characters from the modifyhostslist.txt file. This can be done as follows:while read line; do sed -i 's/'$(echo $line | tr -d '\r')'/#%%#'$line'/' /system/etc/hosts;done < modifyhostslist.txt
_webapps.42783
I haven't had any luck getting an answer from Google on this, and I couldn't find this on their tour, but the new compose and reply screens don't appear to have an area where you can set the from address if you have other hosts set up in your account.This is a problem for me, as I use Gmail for multiple e-mail addresses that all forward to the same place. For now I've set it to go back to the old compose screen, but once I'm forced to use the new one I'm not sure how (or if) it can be done.
Set from address with Gmail's new compose
gmail
Click on the dropdown on the From field, you can switch between sending from email address
_scicomp.20456
I am currently writing my dissertation on different methods for pricing barrier options. As part of this, I have implemented a finite differences method for solving one partial differential equation, and another finite differences method for solving another partial differential equation.I would like to create some plots or tables, to show which of these methods are preferable. My problem is, that I have no idea which plots to create. I do not really have much experience with this, so I don't know what will be valuable. Does anyone have any suggestions?I suppose it is worth mentioning that I have available an analytical formula for the solution.
Comparing finite differences methods
pde;finite difference;numerical analysis
null
_softwareengineering.274959
I know, title is a little confusing but the problem is, too. I am working on a company, it has several different applications and wants these applications have search functionality. We have developed a package and used Elasticsearch for a Laravel-powered application, it was time comsuming. Now, we want to add search functionality to some applications which were written with Codeigniter, Spring and ASP.NET. We have thought to set up an Elasticsearch cluster, put an application in front of it which behaves a reverse proxy and integrate all of these applications with this search middleware. This proxy application will do authorization and authentication, client(integrated application) and index management, automatic mapping and indexing taking related URLs from clients and providing a variety of search interfaces such as HTML, iframe and JSON.If we use a proxy application in front of Elasticsearch, our applications will just provide mapping and indexing URLs and implement search interface, and the proxy application will handle other issues. But if we write or use packages for all of our applications, we will have to handle all these issues in every different application and the proxy application will not be developed.Which solution should we use and why?Thanks.
Google-like search solution for an enterprise application stack using Elasticsearch
search;elasticsearch
null
_codereview.124596
I have made my first game in Python.My program can determine when there is a winner, however I am unsure what to do if the board is full and there is NO winner (a cats game).import cTurtleimport randomimport sysdef DrawTicTacToeBoard(t): #Vertical Lines of board t.pensize(3) t.up() t.goto(.5,-.5) t.down() t.goto(.5,2.5) t.up() t.goto(1.5,-.5) t.down() t.goto(1.5,2.5) #Horizontal Lines of board t.up() t.goto(-.5,.5) t.down() t.goto(2.5,.5) t.up() t.goto(-.5,1.5) t.down() t.goto(2.5,1.5)def flipPlayer(currentPlayer): if currentPlayer==0: currentPlayer=1 else: currentPlayer=0 return currentPlayerdef drawWhiteBox(t,x,y): t.up() t.goto(x-.25,y+.25) t.down() t.color(white) t.begin_fill() for i in range(4): t.forward(.8) t.right(90) t.end_fill() t.color(black)def drawMarker(t,currentPlayer,markerList,move,boardLoL): by=int(move[0:1]) bx=int(move[2:]) y=by+(.22) x=bx-(.15) drawWhiteBox(t,x,y) t.up() t.goto(x,y) boardLoL[by][bx]=markerList[currentPlayer] t.write(markerList[currentPlayer],move=False,align=left,font=(Arial,48,normal))def getValidMove(validMoveList,markerList,currentPlayer,boardLoL): move = while move not in validMoveList: move = input(Enter location to place your marker + markerList[currentPlayer] + , or EXIT to end game => ) if move==EXIT: sys.exit() if move in validMoveList: by=int(move[0]) bx=int(move[2:]) if boardLoL[by][bx]==: return move else: print(Location already occupied) move=def gameWon(b): for row in range(3): if b[row][0]==b[row][1] and b[row][1]==b[row][2] and b[row][0]!=: print(Way to go,b[row][0]) return b[row][0] for column in range(3): if b[0][column]==b[1][column] and b[1][column]==b[2][column] and b[0][column]!=: print(Way to go,b[column][0]) return b[0][column] for diag in range(2): if b[0][0]==b[1][1] and b[1][1]==b[2][2] and b[0][0]!=: print(Way to go,b[0][0]) return b[0][0] if b[2][0]==b[1][1] and b[1][1]==b[0][2] and b[2][0]!=: print(Way to go,b[2][0]) return[2][0] return def boardIsFull(boardLoL): return Falsedef main(): boardLoL=[[,,],[,,],[,,]] markerList=[O,X] validMoveList=[0,0,0,1,0,2,1,0,1,1,1,2,2,0,2,1,2,2] joe=cTurtle.Turtle() joe.setWorldCoordinates(-2,3,4,-1) joe.ht() currentPlayer=random.randint(0,1) DrawTicTacToeBoard(joe) move = while boardIsFull(boardLoL)==False and gameWon(boardLoL)== and move !=EXIT: move = getValidMove(validMoveList,markerList,currentPlayer,boardLoL) drawMarker(joe,currentPlayer,markerList,move,boardLoL) currentPlayer=flipPlayer(currentPlayer) gameWon(boardLoL) boardIsFull(boardLoL)main()
Tic Tac Toe Cats Game/End Game
python;game;tic tac toe;turtle graphics
null
_unix.180396
I'm trying to use my ThinkPad W520 with external monitors in a docking station. When I start my computer with [Discrete Graphics] set in the BIOS, systemd loads and then the computer just hangs as if it can't find any screens. I've tried reinstalling with the latest nVidia driver, but that didn't help. I also didn't see anything out of the ordinary in Xorg.0.log. How might I debug this issue?If I change the BIOS to integrated graphics mode the login prompt displays on the laptop screen as expected. But since the external monitor ports are wired through the nVidia chip, I can't use my external monitors.journalctl | grep 'bumblebeed' reveals that it cannot find my nVidia graphics card.Nov 29 21:38:34 w520 systemd[1]: bumblebeed.service failed.Nov 29 21:39:34 w520 bumblebeed[1071]: [ 75.407054] [ERROR]No integrated video card found, quitting.Nov 29 21:39:34 w520 systemd[1]: bumblebeed.service: main process exited, code=exited, status=1/FAILURENov 29 21:39:34 w520 systemd[1]: Unit bumblebeed.service entered failed state.Nov 29 21:39:34 w520 systemd[1]: bumblebeed.service failed.journalctl | grep nvidia gives:Nov 29 21:41:27 w520 kernel: nvidia 0000:01:00.0: irq 39 for MSI/MSI-XNov 29 22:47:04 w520 kernel: nvidia 0000:01:00.0: irq 39 for MSI/MSI-XDec 09 22:07:12 w520 kernel: nvidia 0000:01:00.0: irq 39 for MSI/MSI-XDec 09 22:12:44 w520 kernel: nvidia 0000:01:00.0: irq 39 for MSI/MSI-XDec 31 20:31:26 w520 sudo[19776]: wdkrnls : TTY=pts/1 ; PWD=/home/wdkrnls ; USER=root ; COMMAND=/usr/sbin/pacman -S xf86-video-modesetting nvidiaJan 16 18:01:58 w520 sudo[27554]: wdkrnls : TTY=pts/4 ; PWD=/home/wdkrnls ; USER=root ; COMMAND=/usr/sbin/pacman -Rscn nvidiaJan 16 18:02:10 w520 userdel[27699]: delete user 'nvidia-persistenced'Jan 16 18:02:10 w520 userdel[27699]: removed group 'nvidia-persistenced' owned by 'nvidia-persistenced'Jan 16 18:02:10 w520 userdel[27699]: removed shadow group 'nvidia-persistenced' owned by 'nvidia-persistenced'Jan 16 18:02:17 w520 sudo[27720]: wdkrnls : TTY=pts/4 ; PWD=/home/k ; USER=root ; COMMAND=/usr/sbin/pacman -S nvidiaJan 16 18:02:21 w520 groupadd[27758]: group added to /etc/group: name=nvidia-persistenced, GID=143Jan 16 18:02:21 w520 groupadd[27758]: group added to /etc/gshadow: name=nvidia-persistencedJan 16 18:02:21 w520 groupadd[27758]: new group: name=nvidia-persistenced, GID=143Jan 16 18:02:21 w520 useradd[27763]: new user: name=nvidia-persistenced, UID=143, GID=143, home=/, shell=/sbin/nologinJan 16 18:02:50 w520 sudo[27831]: wdkrnls : TTY=pts/4 ; PWD=/home/k ; USER=root ; COMMAND=/usr/sbin/pacman -S opencl-nvidiaJan 19 19:10:53 w520 kernel: nvidia: module license 'NVIDIA' taints kernel.Jan 19 19:10:53 w520 kernel: nvidia 0000:01:00.0: enabling device (0000 -> 0003)Jan 19 19:10:53 w520 kernel: [drm] Initialized nvidia-drm 0.0.0 20130102 for 0000:01:00.0 on minor 1Jan 19 19:10:53 w520 kernel: nvidia 0000:01:00.0: irq 41 for MSI/MSI-XJan 19 19:10:58 w520 kernel: nvidia_uvm: Loaded the UVM driver, major device number 245Jan 22 00:36:02 w520 kernel: nvidia: module license 'NVIDIA' taints kernel.The nVidia driver was working great until the beginning of december. Some of my attempt to fix it show up in the log.If I switch to Optimus mode in the BIOS and set Optimus OS detection to TRUE, then I am able to run optirun glxgears -info on my graphics card.
nvidia driver [discrete graphics] on Optimus laptop doesn't load
arch linux;nvidia;laptop;multi monitor
null
_cstheory.16364
BackgroundThe external memory, or DAM model, defines the cost of an algorithm by the number of I/Os it performs (essentially, the number of cache misses). These running times are generally given in terms of $M$, the size of memory, and $B$, the number of words that can be transferred to memory at one time. Sometimes $L$ and $Z$ are used for $B$ and $M$ respectively. For example, sorting requires a cost of $\Theta(N/B\log_{M/B} N/B)$ and naive matrix multiplication requires $\Theta(n^3/B\sqrt{M})$. This model is used to analyze cache-oblivious algorithms, which do not have knowledge of $B$ or $M$. Generally the goal is for the cache-oblivious algorithm to perform optimally in the external memory model; this is not always possible, as in the Permutation problem for example (shown in Brodal, Faderberg 2003). See this writeup by Erik Demaine for a further explanation of cache-oblivious algorithms, including discussions of sorting and matrix multiplication.We can see that changing $M$ causes a logarithmic speedup for sorting and a polynomial speedup for matrix multiplication. (This result is originally from Hong, Kung 1981 and actually predates both cache obliviousness and the formalization of the external memory model). My question is this:Is there any case where the speedup is exponential in $M$? The running time would be something like $f(N,B)/2^{O(M)}$. I am particularly interested in a cache-oblivious algorithm or data structure that fits this description but would be happy with a cache-aware algorithm/data structure or even a best-known lower bound.It is generally assumed in most models that the word size $w = \Omega(\log N)$ if $N$ is the input size and clearly $M > w$. Then a speedup of $2^M$ gives a polynomial speedup in $N$. This makes me believe that if the problem I'm looking for exists, it is not polynomial. (Otherwise we can change the cache size by a constant to obtain a constant number of I/Os, which seems unlikely).
Exponential Speedup in External Memory
ds.algorithms;ds.data structures;cache oblivious
null
_codereview.78487
I'm trying to get table header name in excel. I tried it using index, IF and MATCH. It works but I am not sure whether my formula is the best or not.This is how my sheet looks:And here is my formula to get produk name (E19:E22):=INDEX( $C$10:$H$10,0, IF(IFERROR(MATCH(D19,$C$12:$C$14,0),0),1, IF(IFERROR(MATCH(D19,$E$12:$E$14,0),0),3, IF(IFERROR(MATCH(D19,$G$12:$G$14,0),0),5,0))))
Get table header name in excel
excel
You have hard-coded the 1, 3 and 5 column index... and you don't really have a choice, given the shape of your data.The problem is that your table is not a table: it's essentially a pivot. This would be a table:If you can un-pivot your top table into an actual table like above, then you could have a much simpler, easier to read (and to maintain!) table formula - given a Table1 table name for the above table:=INDEX(Table1[Category],MATCH([@Id],Table1[Id],0))Excel likes data that's organized in rows and columns; if you have 2 levels of headings, and repeating columns under each heading, you haven't organized your data in rows and columns, and you've set yourself up for complicated lookups - as you've noticed.By laying out your data in a table, you make a database-friendly list of records that can easily be sourced from a CSV or XML file, or directly from a database table or view.Having 3 times the same [Id] and [Name] columns under a different heading, looks like you have 3 identical tables, with different values: by combining them into one (and adding a column to identify which of the 3 tables it's coming from), lookups become much, much simpler.Other than that, I would add the following:The bottom table should be turned into an actual table, so leverage table formulas. D19 would then say [@Id], which is much easier to understand.The top table should be on its own worksheet, and adding rows in that table should not force you to update the formulas in the bottom one - as it stands, you'll have to be careful about that.If you can't turn the top table into an actual table, consider using named ranges to abstract $C$12:$C$14 & friends behind a name. You'll still have to be careful when adding rows, that the new rows are included in the named range - but if the formulas in the bottom table refer to named ranges instead of addresses, you won't need to modify the formulas, just to verify the reference the named ranges point to.If 1, 3 and 5 are the only valid values, you could name them:That way you can replace the hard-coded 1, 3 and 5 by Funding, Lending and Example in your formula, giving a meaning for these numbers:=INDEX( Categories,0, IF(IFERROR(MATCH(D19,FundingIds,0),0),Funding, IF(IFERROR(MATCH(D19,LendingIds,0),0),Lending, IF(IFERROR(MATCH(D19,ExampleIds,0),0),Example,0))))But I would really push to remove the first-level heading and turn it into a column: logically, it's a piece of data - it belongs at the row level, not as a heading. Your worksheet will be much easier to extend that way.
_unix.74496
I have about twenty files symmetrically encrypted with CAST5. I have a single passphrase that is meant to work with all of the files and I wish to confirm that it does. I wrote a script to perform a check a check on each file.read passfor file in *.gpg ; do if ! gpg --batch --passphrase $pass -d $file &>/dev/null ; then echo Passphrase invalid for '$file'. fidoneMy method of checking to see if the passphrase is valid for each file requires the decryption of the entire file, which is extremely slow. Is there a quicker way to do what I am attempting to do?
Checking if a passphrase is able to decrypt symmetrically encrypted files
shell script;encryption;gpg
Unfortunately there is no way of asking gpg-agent whether a key is passphrase protected. But you need not check the files but each key once only. Thus you should first check which keys are involved. There is no need to check the same key twice (by using it to decrypt two files).I have to admit that though I consider myself a GnuPG expert I don't get this done in an elegant way thus I have just asked on the GnuPG mailing list. I will edit this answer when I have the info from there.Edit 1Took the masters a few minutes only... The solution is: --list-onlygpg --status-fd 1 --list-only --list-packets file.gpg | awk '$2 == ENC_TO {print 0x $3; }'gives you the key ID(s). Before you try to decrypt a file you check whether one of its recipient keys is in the list of keys which you have already checked.The slow operation is the asymmetric decryption. Nonetheless you should sort the files by size and start with the smallest.The above command gives you the subkey (if it was encrypted for a subkey). If you want to be really good then you don't compare the subkeys but the respective main keys. In every normal installation the main key and the subkeys have the same passphrase (with GnuPG you even have to fight to give them different passphrases).
_codereview.6806
Looking for the best way to do this. Currently in 4 different classes I have:textArea = new JTextArea(10, 55) { { setOpaque(false); } @Override protected void paintComponent(Graphics g) { for (int i = 0; i < list.size(); i++) { if(i == lineIndex) g.setColor(Color.black); g.drawRect(0, 20, 750, 20); } super.paintComponent(g); }};I've simplified down what I actually have. As you can see there is duplication. The only data that is different is what is in the list.A list is passed into each of these classesThere are some other stuff in the class which depends on the textarea and the lineIndex variable changes in the class depending on what the user does. I call the repaint() method of the textarea when I need the textarea to draw something else. The paintcomponent does a simple draw.I'm not sure of the best way for each of the classes to contain the textarea so I dont have duplication. In each of the classes I have an addList(List list) method which the textareas need to use.Hope I explained this ok.Thanks
Refactoring code duplication so the same textArea is not used in 4 different classes
java;swing
Write your own class:class MyTextArea extends JTextArea{ private final List<Foo> list; MyTextArea(int row, int col, List<Foo> list) { super(row, col); this.list = list; setOpaque(false); } @Override protected void paintComponent(Graphics g) { for (int i = 0; i < list.size(); i++) { if(i == lineIndex) g.setColor(Color.black); g.drawRect(0, 20, 750, 20); //use list... } super.paintComponent(g); }}
_codereview.139448
I created a class that is able to generate a Sudoku board.The following board generation steps are made:Create a valid board with numbers on all squares, row by rowBasically I always generate the sequence 1 to 9 and I shift the elements on the cells. The shift amount depends on the row index.Shuffle the boardNothing extraordinary to explain here. Maybe just the fact that I also set the cells index here as well.Empty the board until there is only 1 solutionWell, I am not totally sure if that is what my algorithm really does, but it seems to do a good job at least.I start by picking the group with most visible cells (at the start they are all visible). Then, if I can solve that cell using sudoku solving methods (is this cell missing in the group/coulmn/row?) I make it invisible.This ends when I am not able to find any other cell that I can hide. public class SudokuGame{ [DebuggerDisplay({Value})] private class Cell { public int X { get; set; } public int Y { get; set; } public int Value { get; set; } public bool IsVisible { get; set; } private int Group { get { return Y/3 + X/3*3; } } public bool CanSolve(SudokuGame game) { var canSolve = game.GetColumnGroup(this) .Where(c => c.X != X && c.Y != Y && c.Value == Value) .All(c => c.IsVisible); canSolve |= game.GetRowGroup(this) .Where(c => c.X != X && c.Y != Y && c.Value == Value) .All(c => c.IsVisible); canSolve |= game.GetGroup(Group) .Where(c => !c.IsVisible) .Any(c => game.GetRow(c.X).Count(s => s.IsVisible) == 1 || game.GetColumn(c.Y).Count(s => s.IsVisible) == 1 ); return canSolve; } } private Cell[][] _board = new Cell[9][]; public SudokuGame() { Contract.Assert(_board != null); for (int i = 0; i < _board.GetLength(0); ++i) { CreateRow(i); } Shuffle(); EmptyUntilUniqueSolution(); } private IEnumerable<Cell> GetColumnGroup(Cell cell) { var transpose = _board.Transpose(); for (int i = cell.Y / 3; i < cell.Y / 3 + 3; ++i) { foreach (var aux in transpose[i]) { yield return aux; } } } private IEnumerable<Cell> GetRowGroup(Cell cell) { for (int i = cell.X/3; i < cell.X/3 + 3; ++i) { foreach (var aux in _board[i]) { yield return aux; } } } private Cell[] GetColumn(int i) { return _board.Transpose()[i]; } private Cell[] GetRow(int i) { return _board[i]; } private Cell[] GetGroup(int i) { return _board.ViewAsNByM(3, 3).ToList()[i].SelectMany(c => c).ToArray(); } private void Shuffle() { for (int i = 0; i < 10; ++i) { _board = _board.ViewAsNByM(3, 9) .SelectMany(c => c.Shuffle()) .ToArray() .Transpose() .ViewAsNByM(3, 9) .SelectMany(c => c.Shuffle()) .ToArray(); } for (int i = 0; i < _board.GetLength(0); ++i) { for (int j = 0; j < _board[i].GetLength(0); ++j) { var cell = _board[i][j]; cell.X = i; cell.Y = j; } } } private void CreateRow(int i) { const int groupSize = 3; int warpCount = (i*groupSize)%_board.GetLength(0) + i/groupSize; var oneToNine = Enumerable.Range(1, 9) .WarpAround(warpCount) .Select(v => new Cell { Value = v, IsVisible = true }).ToArray(); _board[i] = oneToNine; } private Cell PickGroupCell(Cell[][] cells) { foreach (var cell in cells.SelectMany(c => c).Where(c => c.IsVisible).Shuffle()) { cell.IsVisible = false; if (cell.CanSolve(this)) { return cell; } cell.IsVisible = true; } return null; } private Cell GetVisibleCell() { var groups = _board.ViewAsNByM(3, 3).Select((g, idx) => new { Count = g.Sum(c => c.Count(s => s.IsVisible)), Cell = PickGroupCell(g) }).OrderByDescending(g => g.Count) .ToList(); return groups.TakeWhile(g => g.Count == groups[0].Count) .Select(g => g.Cell) .Shuffle() .FirstOrDefault(); } private bool CanSolveBoard() { var unsolvedCells = _board.SelectMany(cells => cells).Where(c => !c.IsVisible); return CanSolveBoard(unsolvedCells); } private bool CanSolveBoard(IEnumerable<Cell> unsolved) { var notSolved = unsolved.Where(cell => !cell.CanSolve(this)).ToList(); return notSolved.Count == 0 || unsolved.Count() != notSolved.Count; } private void EmptyUntilUniqueSolution() { var cell = GetVisibleCell(); if (cell == null) { return; } if (!CanSolveBoard()) { cell.IsVisible = true; return; } EmptyUntilUniqueSolution(); }}Utility methods used on the code, I do not require a review on those. But feel free to comment.public static class CollectionUtils{ public static IEnumerable<T[][]> ViewAsNByM<T>(this T[][] values, int m, int n) { var count = values.GetLength(0)*values[0].GetLength(0); for (int i = 0; i < count/(n*m); ++i) { var matrix = new T[m][]; for (int j = 0; j < m; ++j) { matrix[j] = new T[n]; for (int k = 0; k < n; ++k) { int idxRow = j + (i/(values[0].GetLength(0)/n))*m; int idxCol = (k + i*n)%values[0].GetLength(0); matrix[j][k] = values[idxRow][idxCol]; } } yield return matrix; } } public static T[][] Transpose<T>(this T[][] values) { var transposed = new T[values[0].GetLength(0)][]; for (int i = 0; i < values[0].GetLength(0); ++i) { transposed[i] = new T[values.GetLength(0)]; } for (int i = 0; i < values.GetLength(0); i++) { for (int j = 0; j < values[0].GetLength(0); j++) { transposed[j][i] = values[i][j]; } } return transposed; } public static IEnumerable<T> WarpAround<T>(this IEnumerable<T> values, int n) { return values.Skip(n).Concat(values.Take(n)); } private static readonly ThreadLocal<Random> Random = new ThreadLocal<Random>(()=>new Random(42)); public static IList<T> Shuffle<T>(this IEnumerable<T> col) { var list = col as IList<T> ?? col.ToList(); var random = Random.Value; for (int i = 0; i < list.Count; ++i) { //get a chance of staying in same place list.Swap(i, random.Next(i, list.Count)); } return list; } public static void Swap<T>(this IList<T> col, int idxSrc, int idxDest) { var aux = col[idxSrc]; col[idxSrc] = col[idxDest]; col[idxDest] = aux; }}Any suggestions are appreciated.
Linqy Sudoku game generator
c#;game;linq;sudoku
There is one thing I don't like about the SudokuGame... it's a god-class doing everything which means it's doing too much.I suggest refactoring the code so that the SudokuGame receives a SudokuBoard or some kind of a ISudokuBoardFactory. Then put everything sudoku-board releated into a SudokuBoard class that expects from you the size of the board etc.Additionally I'd implemeted a ISudokuSolver that can check whether a game can be won.I think it would also be a good idea to create another class that can only generate boards.Put it all together and you have nice modular sudoku game where you can test each unit separately and validate its functionality.
_reverseengineering.14814
I'm using IDA PRO to disassemble a function, which produces a control flow that looks like this:start_IE proc nearBuffer= dword ptr -230hvar_22C= byte ptr -22ChhFile= dword ptr -30hhInternet= dword ptr -2ChszAgent= byte ptr -28hdwNumberOfBytesRead= dword ptr -8var_4= dword ptr -4arg_0= dword ptr 8;Do stuff that has nothing to do with ebp+var22Cmov al, [ebp+var_22C]jmp short returnreturn:mov esp, ebppop ebpretnstart_IE endpI've cut out a lot of irrelevant code, but the only 2 times that var_22C appears in this procedure has been shown above.I'm having a difficult time finding out what value the data pointed to by var_22C will be since it's given no obvious assignment here.Code before/after the function call in the caller:mov ecx, [ebp+var_C]push ecx ; command charcall start_IEadd esp, 4mov [ebp+var_8], almovsx edx, [ebp+var_8]test edx, edxjnz short successIt only has 1 argument passed to it, which should be arg_0... We see that the return value from Var_22C is placed into [ebp+var_8] back in the caller afterwards.
How does this local var get assigned?
ida;stack variables;local variables
null
_codereview.153090
Suppose we have two sorted lists, and we want to find one element from the first, and the other element from the 2nd list, where the sum of the two elements equal to a given target. If there are multiple combinations, need to find all the combinations.Any bugs, performance improvement ideas in terms of algorithm time complexity or code style advice is highly appreciated. My basic idea is to scan the first list from the beginning, and scan the second list from the end, a similar approach to how we resolve the 2-sum classic problem in one list.def two_sum(list1, list2, target, result): i = 0 j = len(list2) - 1 while i < len(list1) and j >= 0: if list1[i] + list2[j] == target: result.append((list1[i], list2[j])) i += 1 j -= 1 while i < len(list1) and list1[i] == list1[i-1]: i += 1 while j >= 0 and list2[j] == list2[j+1]: j -= 1 elif list1[i] + list2[j] > target: j -= 1 else: i += 1if __name__ == __main__: list1 = [1,3,5,7] list2 = [2,3,4,5] result = [] two_sum(list1, list2, 6, result) print result
Two sum with two lists
python;algorithm;python 2.7
null
_codereview.169203
How can I write this function shorter?template<typename U, typename = typename std::enable_if<std::is_fundamental<U>::value>::type, typename = typename std::enable_if<!std::is_same<char, U>::value>::type, typename = typename std::enable_if<!std::is_same<void, U>::value>::type>void multiply(U&& u){};I want exclude several type like void or char, which don't must be number. I wrote code like this, but I think, that is better solution. (code of course is correctly)
SFINAE with several condition [Refactoring]
c++;c++14;c++17;sfinae
Seems short enough to me.It's impossible to know how to refactor any code without first knowing what it is supposed to do. All we know about this no-op function is that you want [to] exclude several type[s] like void or char. How many types? Which types? Why?The obvious shortening istemplate<class U, class = std::enable_if_t<std::is_fundamental_v<U>>, class = std::enable_if_t<!std::is_same_v<char, U> && !std::is_same_v<void, U>>>void multiply(U&&) {}i.e. just remove all the superfluous ::type and ::value, and replace typename by class because it's shorter (and you did ask for us to make it shorter!).Your naming the function multiply implies that maybe what you want istemplate<class U>auto multiply(U&& u) -> decltype(u*u, void()) {}Your comments about don't must be number imply that maybe what you want istemplate<class U, class = std::enable_if_t<std::is_arithmetic_v<U>>>void multiply(U&&) {}But we really can't know for sure unless you tell us what the code is supposed to do.
_unix.341397
Keepass auto type stopped working. When I looked into keyboard settings and tried to change the shortcut, I somehow deleted the record, so I don't know what command was there before. So I tried /usr/bin/cli /usr/lib/keepass2/KeePass.exe --auto-type and it didn't work. However when Keepass is closed, the shortcut starts it, so I see the problem lies in the auto type part.
Keepass2, Debian Wheezy and Xfce 4.10 auto type problem
debian;keyboard shortcuts;xfce
null
_cstheory.25485
For sorting networks, the 0-1 principle says that if it can sort any sequence of 0's and 1's, then it can sort any list.What if I want to build a comparison-swap network for merging two pre-sorted lists. Can I still rely on the 0-1 principle to determine if my network is correct?Note: If so, this means it's possible to determine whether a network is a merging network in polynomial time (since there are only polynomially-many pairs of sorted lists of zeros and ones)
Does the 0-1 principle apply to merge networks?
sorting network
$\def\et{\mathbin\&}$Yes, and this holds much more generally. Note that a comparator can be thought of as a pair of gates, one of which computes $\min\{x,y\}$, and the other $\max\{x,y\}$. A linearly ordered set is a distributive lattice with $x\land y=\min\{x,y\}$ and $x\lor y=\max\{x,y\}$. We have the following 01 principle:Let $C$ be a circuit with $\land$ and $\lor$ gates, and $\phi(u_1,\dots,u_n)$ a property of values of nodes of $C$ expressible as a conjunction of quasi-identities in the language of lattices (i.e., implications of the form $t_1=s_1\et\dots\et t_k=s_k\to t_0=s_0$, where $t_i$ and $s_i$ are terms using $\land$, $\lor$, and the variables $u_j$).If $\phi(u_1,\dots,u_n)$ holds whenever $C$ is evaluated in the $\{0,1\}$ lattice, then it holds whenever $C$ is evaluated in an arbitrary distributive lattice.This is an immediate consequence of the facts that the $2$-element lattice generates the quasivariety of distributive lattices (i.e., every distributive lattice can be embedded in a direct product of $2$-element lattices), and that values of nodes of $C$ are lattice terms in values of the input variables.Note that $t\le s$ is equivalent to $t\land s=t$, hence we can freely use inequalities instead of equalities in the statement above.Now, if $C$ is a comparator network with inputs $x_1,\dots,x_n,y_1,\dots,y_n$ and outputs $z_1,\dots,z_{2n}$, it automatically computes a permutation of the inputs, hence the property that it correctly merges sorted lists can be expressed by the conjunction of the quasi-identities$$x_1\le x_2\et\dots\et x_{n-1}\le x_n\et y_1\le y_2\et\dots\et y_{n-1}\le y_n\to z_i\le z_{i+1}$$for $i=1,\dots,2n-1$, hence if it works for $0$$1$ inputs, it also works over arbitrary linearly ordered sets.
_unix.219181
In the script below, I can't seem to make $var1 expand in the second statement. I've tried $var1, ${var1}, echo $var1 and '$var1'. It is inside a few sets of quotes and parentheses which I guess is what is causing the problem. Any ideas?#!/bin/bash# Get the AutoScalingGroupName for the NameNode ASGvar1=$(aws cloudformation list-stack-resources --stack-name abc123 | jq '.StackResourceSummaries[] | select(.ResourceType==AWS::AutoScaling::AutoScalingGroup)' | jq '.PhysicalResourceId' | tr -d '' | grep nn); echo $var1var2=$(aws autoscaling describe-auto-scaling-instances | jq -r '.AutoScalingInstances[] | select(.AutoScalingGroupName == $var1) | select(.AvailabilityZone == us-east-1a) .InstanceId'); echo $var2
Variable expansion inside parentheses and quotes
bash;shell script;quoting;variable
Variables in single quotes are not expanded. Try this...var2=$(aws autoscaling describe-auto-scaling-instances | jq -r '.AutoScalingInstances[] | select(.AutoScalingGroupName == '$var1') | select(.AvailabilityZone == us-east-1a) .InstanceId'); echo $var2
_webapps.281
Is there a way to find out who unfriended me on Facebook?
Determine who unfriended me on Facebook
facebook;friends
Intentionally, Facebook prevents sending out this info for privacy purposes. You are free to keep track of your friends though in some other form, and compare it to the current list to find out who is missing each week. who.removed.me will do this for you automatically
_webmaster.48030
I have an application written in Python running behind Apache and SSL. I am not seeing a secure flag on my cookie:apache Server version: Apache/2.2.15 (Unix)I have added a configuration line to my ssl.conf as:Header edit Set-Cookie ^(.*)$ $1;Secure;HttpOnlyI don't have enough points to post a screen shot of my session. Can anyone share their experience with this or provide any help?
How can I set a secure flag on cookies generated from a Python application?
https;apache2;cookie
null
_unix.14354
I'm writing an application to read/write to/from a serial port in Fedora14, and it works great when I run it as root. But when I run it as a normal user I'm unable to obtain the privileges required to access the device (/dev/ttySx). That's kind of crappy because now I can't actually debug the damn thing using Eclipse.I've tried running Eclipse with sudo but it corrupts my workspace and I can't even open the project. So I'd like to know if it's possible to lower the access requirements to write to /dev/ttySx so that any normal user can access it. Is this possible?
Read/Write to a Serial Port Without Root?
linux;fedora;not root user;serial port
The right to access a serial port is determined by the permissions of the device file (e.g. /dev/ttyS0). So all you need to do is either arrange for the device to be owned by you, or (better) put yourself in the group that owns the device, or (if Fedora supports it, which I think it does) arrange for the device to belong to the user who's logged in on the console.For example, on my system (not Fedora), /dev/ttyS0 is owned by the user root and the group dialout, so to be able to acesss the serial device, I would add myself to the dialout group:usermod -a -G dialout MY_USER_NAME
_codereview.135334
I have the following function, and I have a hunch it can be written more concisely in Ruby.def template_params filtered_params = params[:template].permit! filtered_params[:published] ||= false filtered_paramsendThe end result is that filtered_params has published: false if the params hash doesn't have published as a key.I'm wondering if there is some kind of conditional merge w/ Ruby to turn that code into a 1-liner.Essentially, the params hash includes what has been changed and when :published becomes false (it's a checkbox that gets unchecked), it naturally doesn't get included in the params hash. I wanted to pass in the fact that :published became false when it got unchecked. I do not need to pass in published: false by default, because whatever the default is, is fine. It is the changed state that I need, but from false to true. The alternative works: if the checkbox is checked, it becomes true and gets passed through without issue.This is more an exercise of how can I turn this bit of code into something more elegant and maybe a 1-liner. As it stands, it does exactly what I need it to do.
Conditional merge with Ruby to include a parameter if it hasn't been included
ruby;ruby on rails
You want to merge params with one or more default values. How about, well, #merge?{published => false}.merge(params[:template].permit!)Only trick, if you can call it a trick, is that the default hash must use string keys, not symbols, despite the params object accepting either. The resulting hash will also be keyed with strings only.Alternatively, you can use HashWithIndifferentAccess to get around this:defaults = HashWithIndifferentAccess.new({ published: false })filtered = defaults.merge(params[:template].permit!)And filtered will be a HashWithIndifferentAccess much like params produces.All that said, the better way to handle all this is to send the right parameters in the first place. With the code above you're always assuming that published should be set to false unless told otherwise. But there could be all sort of reasons for why only a subset of parameters are sent; if published is intentionally left out, it'll suddenly be filled in - perhaps wrongly - by the controller.Relatedly, if the parameter is required, raise an exception if it's missing and tell the client. It's not the controller's job to fill in the blanks when faced with incomplete information. Conversely, it's the client's job to send the parameters that are necessary or required.As I said in a comment, if you use Rails' regular checkbox helpers, they'll produce a hidden input with the checkbox's unchecked value, in addition to the checkbox input itself. If the checkbox is checked, it'll override the former, unchecked value. This is the typical (and better) way to solve this.So in short, if you want to merge to hashes, use #merge. But in this case, you probably don't want to do that.
_unix.179901
I need a script, that will run in terminal (under X11), and wait for a keyboard shortcut (happening anywhere in the desktop environment), once that shortcut (or key press sequence) happens, it will terminate with return code = 0.PS: I need this to tell byzanz when to stop recording my desktop.Possible candidates to use in that script are xev and xinput but I can't figure out how to put things together. Ie. xinput seems promising, but it's making me specify the device, which I want to happen automatically, and I don't know how to use it in a script that will terminate once a sequence on the output is found.
How to capture a keyboard shortcut
x11;keyboard;input
null
_unix.328381
I believe every Unix/Linux user wants his/her own computer free from key loggers. And I believe this cannot be done without some kind of OS-level support. The idea is that keypresses are only sent to the process who is actively accepting user input, and users should be aware of the process identity. Does Unix/Linux already have such (or other kinds of) security features against key loggers?
Does Unix/Linux have any security features against key loggers?
security
null
_softwareengineering.356021
I've created a Task class similar to the one found in .NET Framework v4, because I needed to handle some asynchronous tasks in some of our legacy v2-targetting software. The class is in the Acom.Threading.Tasks namespace, Acom being our company name.Now I'm wondering what is the best way to 'house' this sort of code that is not specific to an application - what assembly should it live in, and what should the assembly be called?I envisage new classes appearing at a very low rate, maybe one per year as a guess.We've considered creating a general catch-all assembly to contain it and future code, but then comes the problem of what to call the assembly. Names of the form Acom.Common.dll and Acom.Shared.dll could be used, but they don't really describe what the thing represents.What is best practice in this case?Please note that this question has been re-worded. It would be nice if it could be re-opened so that I, at least, could provide the answer to help others with a similar problem in the future.
What is the best practice for 'housing' code that is not application specific?
c#;.net;naming
null
_unix.291990
I did not find the answer other location, so seek help here.My code need compare stop with stop this is stand bash string.pi@raspberrypi:~/Voice $ ./test.sh | morestopstopMy code:#!/bin/bashcommand=stopwhile :do QUESTION=$(cat stt.txt) #stt,txt has command stop echo $QUESTION echo $command if [ $QUESTION == $command ]; then echo You said stop! break fidoneI had try different command=stop, the result is same.I try to put command=$('stop'), it's okay only one time, then it complains:./test.sh: line 2: stop: command not found.I don't know why it is suddenly stop working to set stop as command, not stop
How to compare abc with abc in a shell script?
shell script;variable;test
null
_cstheory.27152
I am currently trying to find EXPSPACE-complete problems (mainly to find inspiration for a reduction), and I am surprised by the small number of results coming up.So far, I found these, and I have trouble expanding the list:universality (or other properties) of regular expressions with exponentiation.problems related to vector addition systemsgames like go with superko, or unobservable games (see for instance this blog)some fragment of FO-LTL, in On the Computational Complexity of Decidable Fragments of First-Order-Linear Temporal LogicsDo you know other contexts when EXPSPACE-completeness appears naturally?
EXPSPACE-complete problems
cc.complexity theory;reference request;big list
Extending the example pointed out by Emil Jerabek in the comments, $\mathsf{EXPSPACE}$-complete problems arise naturally all over algebraic geometry. This started (I think) with the Ideal Membership Problem (Mayr–Meyer and Mayr) and hence the computation of Gröbner bases. This was then extended to the computation of syzygies (Bayer and Stillman). Many natural problems in computational algebraic geometry end up being equivalent to one of these problems. Also see the Bayer–Mumford survey What can be computed in algebraic geometry?
_datascience.9696
If I get some posts on reddict.com, how can I predict whether this post will (trending/hot/popular) in the future or not? I would like to use the hidden markov model to predict it, but I don`t know how to define the hidden states and observation sequence...can anyone give me any suggestion? Thanks~
How can I predict the post popularity of reddit.com with hidden markov model(HMM)?
markov
null
_unix.150957
How can I generate 10 MB files from /dev/urandom filled with:ASCII 1s and 0sASCII numbers between 0 and 9
Generating file with ASCII numbers using /dev/urandom?
random;ascii
ASCII numbers between 0 and 9< /dev/urandom tr -dc '[:digit:]' | head -c 10000000 > 10mb.txtASCII 1s and 0s< /dev/urandom tr -dc 01 | head -c 10000000 > 10mb.txt
_unix.312320
Trying to connect to a server. I've received a private key to login to that server which I added to id_rsa. However the client keeps attempting to pass that as the public key instead of id_rsa.pub. Is this because id_rsa.pub isn't in my ssh_config file?SERVER CONNECTION ATTEMPT debug1: Offering RSA public key: /root/.ssh/id_rsadebug3: send_pubkey_testdebug3: send packet: type 50debug2: we sent a publickey packet, wait for replydebug3: receive packet: type 51SSH CONFIG FILE (IDENTITY SECTION)root@etoorlan4c:~/.ssh# cat /etc/ssh/ssh_config# StrictHostKeyChecking ask# IdentityFile ~/.ssh/identity# IdentityFile ~/.ssh/id_rsaCONTENTS OF ~/.ssh/root@etoorlan4c:~/.ssh# lsauthorized_keys id_rsa id_rsa.pub known_hosts
SSH: Why is my system offering my private key when attempting public key authentication?
ssh
The private key was invalid. A single character was missing from it.The output changes as follows when a valid private key is used:debug1: Offering RSA public key: root@etoorlan4cdebug3: send_pubkey_testdebug3: send packet: type 50debug2: we sent a publickey packet, wait for replydebug3: receive packet: type 51debug1: Authentications that can continue: publickey,passworddebug1: Trying private key: sshkey.privatedebug3: sign_and_send_pubkey: RSA SHA256:jmMyCOppv3KKkRgiHI4s5h3I7LwyCgms8uSG06KClQ4debug3: send packet: type 50debug2: we sent a publickey packet, wait for replydebug3: receive packet: type 52debug1: Authentication succeeded (publickey).Authenticated to [remoteHost]([xxx.xxx.xxx.xxx]:22).
_unix.103270
I want to get the current Bandwidth of an interface say eth0 from the terminal. It better be as simple as possible. Say up 10 dn 30.Instead of giving out a lot of text like vnstat does. Edit: I need this for a command line program for auto-monitoring, not to view it manually.
How do I get the current bandwidth speed of an interface from the terminal?
monitoring;bandwidth
There are several tools that can do this. BmonOne that should be in most repositories for various distros is bmon.    It can be run in a condensed view too.           If you're looking for something else I'd suggest taking a look at this Linuxaria article titled: Monitor your bandwidth from the Linux shell. It also mentions nload as well as speedometer.Nload    Speedometer            IbmonitorIf you're looking for something more basic then you could also give ibmonitor a go. Though basic it has most of the features one would expect when monitoring bandwidth.            
_webapps.18319
Brizzly is a Twitter client. Though not the best of all the existing clients, what I see as the best in this app is that one can use it at work even if Twitter is blocked. I fail to understand how Brizzly actually does this. Normal Twitter clients usually talk to the Twitter API, and most of them fail to work at work places at which Twitter is blocked by the firewall. Brizzly too should follow the same procedure to consult Twitter API to display user timeline, but how does it manage to by pass the firewall and retrieve the tweets?
How does Brizzly retrieve tweets in spite of a Twitter firewall block?
twitter;twitter api
It's not going through your firewall when it talks to the Twitter servers. Brizzly retrieves content from the Twitter API through its own connection and then stores it on their server and presents it to you while you're logged in. (It only does this when you're using it, though, otherwise you'd end up using all of your Twitter API limit.)If your company doesn't allow usage of Twitter during the work day, I wouldn't recommend using Brizzly to get around it. Also, they may eventually figure it out and block it and similar sites, such as Hootsuite.
_unix.125522
I'm writing a library for manipulation Unix path strings. That being the case, I need to understand a few obscure corners of the syntax that most people wouldn't worry about.For example, as best as I can tell, it seems that foo/bar and foo//bar both point to the same place. Also, ~ usually stands for the user's home directory, but what if it appears in the middle of a path? What happens then?These and several dozen other obscure questions need answering if I'm going to write code which handles every possible case correctly. Does anybody know of a definitive reference which explains the exact syntax rules for this stuff?(Unfortunately, searching for terms like Unix path syntax just turns up a million pages discussing the $PATH variable... Heck, I'm even struggling to find suitable tags for this question!)
Path syntax rules
directory;filenames
There are three types of paths:relative paths like foo, foo/bar, ../a, .. They don't start with / and are relative to the current directory of the process making a system call with that path.absolute paths like /, /foo/bar or ///x. They start with 1, or 3 or more /, they are not relative, are looked up starting from the / root directory.POSIX allows //foo to be treated specially, but doesn't specify how. Some systems use that for special cases like network files. It has to be exactly 2 slashes.Other than at the start, sequences of slashes act like one.~ is only special to the shell, it's expanded by the shell, it's not special to the system at all. How it's expanded is shell dependent. Shells do other forms of expansions like globbing (*.txt) or variable expansion /$foo/$bar or others. As far as the system is concerned ~foo is just a relative path like _foo or foo.Things to bear in mind:foo/ is not the same as foo. It's closer to foo/. than foo (especially if foo is a symlink) for most system calls on most systems (foo// is the same as foo/ though).a/b/../c is not necessarily the same as a/c (for instance if a/b is a symlink). Best is not to treat .. specially.it's generally safe to consider a/././././b the same as a/b though.
_cs.29489
I have an alternative algorithm for the problem of finding a convex hull for a collection of points. It is somewhat similar but not the exact of Graham scan.Find a point that is guaranteed to be inside the convex hull, this can be done by finding the line connecting the left most and right most points. And then pick a point between the two end points.Use the point in (1) as origin and convert all other points into polar coordinate.Sort all other points in counter clockwise motion and iterate (same way one orders angles in radian of the unit circle)When the point has y coordinate higher than the origin, then the tangent value between the current point and the last point in the convex hull has to go up compared to the last tangent value. If not we need to wrap the previous points to some earlier point to satisfy this requirement.When the point has y-coordinate lower than the origin, then the tangent value has to go down.The running time is $O(n\log n)$ because that is of sorting and for each point in step 4 and 5, one only needs $O(\log n)$ to search for appropriate previous point.My question is this seems much simpler than Graham scan.Is there any problem in it (correctness) other than the running time in which iteration in Graham scan is only linear while it is $O(n\log n)$ here
Finding a convex hull for a collection of points
computational geometry
null
_codereview.122671
I will design a list with a Font-Awesome design arrows.My code already works fine, but I will improve it.ul.long_arrow_right_red,ul.long_arrow_right_gold {list-style: none;}ul.long_arrow_right_gold li:before {content:\f178; font-family: FontAwesome;display: block;float: left;width: 1.5em;color:gold;}ul.long_arrow_right_red li:before {content:\f178; font-family: FontAwesome;display: block;float: left;width: 1.5em;color:red;}<link rel=stylesheet type=text/css media=screen href=https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css /><ul class=long_arrow_right_gold> <li>Title <ul class=long_arrow_right_red> <li>Lorem</li> <li>Epsum</li> </ul> </li> <li>Title</li> </ul>Questions: How to use an extra class which define only the color for the li icon? The text inside shouldn't change the color. Existing other css code, which I use for text coloring:.red{color:red;}.gold{color:gold;}I think it would be better not do have duplicate following statements:font-family: FontAwesome;display: block;float: left;width: 1.5em;How to combine them with a different content: definition?If you have other improvement ideas, please tell me them.
CSS list-style with Font-Awesome toolkit
css
null
_unix.253759
I have debian system that auto mounts an entry in my fstab file when a usb drive is connected. This is done so as a read only deviceThe device is mounted to /media/usb1If i'm in the console and I cd /media/usb1 then unplug the device the contents of the directory are still listed, I'm assuming the umount command (or somethigng similar) fails. This does not happen if i'm not in that directory while pulling out the usb drive.I do understand that you should umount the drive before removing it, however this is going to run headless and that won't be an option (think automated picture screen). Is there a way to force the drive to unmount in a situation like this?I believe the OS is using udev & udisks to auto mount/unmount.
How do I automatically force a umount on a usb drive that has already been removed?
mount;udev;usb drive;unmounting;udisks
null
_codereview.26532
Consider a process composed of three algorithms: makeRuns, meld and traverse (each taking the output of the previous one as input): it is interesting to test each separately. Now consider three (or more) instances (e.g. singleton, twoPairs, SimplePair): it is interesting to test the behavior of the three algorithms on each of those instances. The result can be described as an array of (say) 3*3 tests. Is the code below the correct implementation of such a test? (I find the result of the tests to be lacking in clarity.)import unittest, doctestimport insertionRank##############################################################################class TestMTDRAG(unittest.TestCase): def test_singleton(self): Basic example [1]. run = makeRuns([1]) self.assertEqual(run,[Node(1,1)]) graph = meld(run) self.assertEqual(graph,Node(1,1)) lengths=traverse(graph) self.assertEqual(lengths,[1,0]) def test_TwoPairsExample(self): Two messages of distinct probabilities [1,2]. run = makeRuns([1,2]) self.assertEqual(run,[Node(1,1),Node(2,1)]) graph = meld(run) self.assertEqual(graph,Node(3,1,[Node(1,1),Node(2,1)])) lengths=traverse(graph) self.assertEqual(lengths,[0,2,0]) def test_SimplePairExample(self): Basic example of four equiprobable messages [1,1,1,1]. run = makeRuns([1,1,1,1]) self.assertEqual(run,[Node(1,4)]) graph = meld(run) self.assertEqual(graph, Node(4,1, [Node(2,2,[Node(1,4),Node(1,4)]), Node(2,2,[Node(1,4),Node(1,4)]) ])) lengths=traverse(graph) self.assertEqual(lengths,[0,0,4])##############################################################################class Node(object): A node in a MTDRAG (Moffat-Turpin Directed Rooted Acyclic Graph). def __init__(self, weight, frequency, children=[], minDepth=None, nbPathsAtMinDepth=0, nbPathsAtMinDepthPlusOne=0): assert frequency>0 self.weight = weight self.frequency = frequency self.children = children self.minDepth= minDepth self.nbPathsAtMinDepth = nbPathsAtMinDepth self.nbPathsAtMinDepthPlusOne = nbPathsAtMinDepthPlusOne def computeDepths(self,depthParent=-1,nd=1,ndp1=0): assert self.frequency>0 if self.minDepth==None: # Node is not yet labeled self.minDepth = depthParent+1 self.nbPathsAtMinDepth = nd self.nbPathsAtMinDepthPlusOne = ndp1 elif self.minDepth == depthParent: # Node labeled at same depth as parent self.nbPathsAtMinDepthPlusOne += nd else: assert(self.minDepth==depthParent+1) # Node labeled at depth + 1 of parent self.nbPathsAtMinDepth += nd self.nbPathsAtMinDepthPlusOne += ndp1 if self.nbPathsAtMinDepthPlusOne > 0: maxDepth = depthParent+2 else: maxDepth = depthParent+1 for child in self.children: maxDepth = max( maxDepth, child.computeDepths(depthParent+1,self.nbPathsAtMinDepth,self.nbPathsAtMinDepthPlusOne) ) return maxDepth def collectDepths(self,M): assert self.frequency>0 if self.children == []: M[self.minDepth] += self.nbPathsAtMinDepth M[self.minDepth+1] += self.nbPathsAtMinDepthPlusOne else: for child in self.children: child.collectDepths(M) def __eq__(self,node): assert self.frequency>0 if node == None: return False assert node.frequency>0 return self.weight==node.weight and self.frequency == node.frequency and self.children == node.children def __str__(self): assert self.frequency>0 if self.children == None: return (+str(self.weight)+, +str(self.frequency)+) else: return (+str(self.weight)+, +str(self.frequency)+, +str(self.children)+) def __repr__(self): assert self.frequency>0 return self.__str__() def copy(self): assert self.frequency>0 return Node(self.weight,self.frequency,self.children,self.minDepth,self.nbPathsAtMinDepth,self.nbPathsAtMinDepthPlusOne)##############################################################################def makeRuns(A): Compresses a list of INTEGER weights into a list of nodes, in sublinear time (if all weights are not distinct). A.sort() # Linear if already sorted output = [] position = 0 while position < len(A): weight = A[position] frequency = insertionRank.fibonacciSearch(A[position:],weight+1) output.append(Node(weight,frequency)) position += frequency return outputdef meld(leaves): Moffat and Turpin's algorithm to simulate van Leeuwen's algorithm on a compressed representation of a list of weights. assert(len(leaves)>0) graphs = [] source = leaves first = source[0] while first.frequency>1 or len(leaves)+len(graphs)>=2: if first.frequency>1: graphs.append(Node(first.weight*2,first.frequency//2,[first,first])) if first.frequency %2 == 1: first.frequency = 1 else: source.remove(first) else: #first.frequency == 1 but len(leaves)+len(graphs)>=2 source.remove(first) source = min(s for s in (leaves,graphs) if s) second = source[0] assert(second.frequency>0) if second.frequency==1: source.remove(second) graphs.append(Node(first.weight+second.weight,1,[first,second])) else: extract = second.copy() extract.frequency=1 second.frequency -= 1 graphs.append(Node(first.weight+extract.weight,1,[first,extract])) source = min(s for s in (leaves,graphs) if s) first = source[0] return(first)def traverse(graph): Computes an array containing the depth of the leaves of the graph produced by the algorithm meld(). if graph==None: return None maxDepth = graph.computeDepths() M = [0]*(maxDepth+2) graph.collectDepths(M) return M##############################################################################def main(): unittest.main()if __name__ == '__main__': doctest.testmod() main()##############################################################################
Two dimensional unit testing
python;unit testing
null