id
stringlengths
5
27
question
stringlengths
19
69.9k
title
stringlengths
1
150
tags
stringlengths
1
118
accepted_answer
stringlengths
4
29.9k
_webapps.27902
Is there a widget or some other feature which will automatically add related posts to my blog posts on Wordpress.com?I know that I can use Zemanta (in my case, via a Chrome plugin) to add related posts one-by-one. That might actually be all I want to do, but was interested in also exploring an automatic feature if it is available natively on Wordpress.com?Back in 2008, a feature was released called Possibly Related Posts (see Possibly an Announcement). Has this feature been discontinued?
Can I automatically add related posts to my posts on Wordpress.com?
wordpress.com;widgets
You cannot install any custom plugins on Wordpress.com for related posts. Unfortunately.The one I've used and abused is called Yet Another Related Posts Plugin. It's highly customizable, free, and has the widget that you want.As of June 2012, there is no feature built-in to Wordpress.com to display related posts.
_webmaster.62879
In your experience, have you ever had problems with duplicate content being caused by the following URLs:www.mysite.netwww.mysite.net/www.mysite.net/index.htmlDo you think that this could result in a duplicate content issue if my canonical link is constantly pointing to only this: www.mysite.net
Would the following URLs result in duplicate content if I only used one canonical link?
url;duplicate content;canonical url
No, not if their content is identical (or very nearly so), and they all have a canonical link element referencing www.mysite.net.However, that sort of issue happening site wide can be considered a crawl efficiency issue and the canonical link element doesn't really solve that. In your example, a search bot would crawl three pages when it really only needed to crawl one. Scale that up, and add other duplication issues, and it gets to be a problem.So for that sort of issue (we can include things like with/without the www subdomain, with/without HTTPS, etc.), it's usually better to use URL rewrites to 301 redirect back to the canonical form. The canonical link element is the weapon of choice when there's a lot of variation in the duplications you're managing, or you don't know in advance what they will be. Think of a shopping site where tens of product category refinement parameters can be added to a base URL in any order, for example. That doesn't mean don't add it unless you have that sort of problem, just don't rely on it to solve problems there are better solutions for.
_unix.43445
When I issue ps -elf|grep python for example on my system, I see these:1 S 1000 6020 6008 0 80 0 - 9914 poll_s Jul12 ? 00:00:01 python manage.py run_gunicorn -t 3600 -w 8 -b 127.0.0.1:80000 S 1000 22496 22491 0 80 0 - 10477 ep_pol 12:32 ? 00:00:10 /var/lib/mywebapp/env/bin/python /var/lib/mywebapp/env/bin/pserve development.iniWhat is the difference between poll_s and ep_pol?
Difference between poll_s and ep_poll WCHAN in ps output
linux;process;ps
null
_unix.354509
What is the function of bash shebang?What is the difference between executing a file using ./file or sh file?How does bash understand it?
What is the function of bash shebang?
bash;shell script;shell;scripting
The function of shebang is:Interpreter directives allow scripts and data files to be used as commands, hiding the details of their implementation from users and other programs, by removing the need to prefix scripts with their interpreter on the command line.What is the different between executing a file using ./file or sh file? A Bourne shell script that is identified by the path some/path/to/foo, has the initial line, #!/bin/sh -xand is executed with parameters bar and baz as some/path/to/foo bar bazprovides a similar result as having actually executed the following command line instead: /bin/sh -x some/path/to/foo bar bazNote: On 1980 Dennis Ritchie introduced kernel support for interpreter directives:The system has been changed so that if a file being executedbegins with the magic characters #! , the rest of the line is understoodto be the name of an interpreter for the executed file.Previously (and in fact still) the shell did much of this job;it automatically executed itself on a text file with executable modewhen the text file's name was typed as a command.Putting the facility into the system gives the followingbenefits.1) It makes shell scripts more like real executable files,because they can be the subject of 'exec.'2) If you do a 'ps' while such a command is running, its realname appears instead of 'sh'.Likewise, accounting is done on the basis of the real name.3) Shell scripts can be set-user-ID.Note: Linux ignores the setuid bit on all interpreted executables (i.e. executables starting with a #! line).4) It is simpler to have alternate shells available;e.g. if you like the Berkeley csh there is no question aboutwhich shell is to interpret a file.5) It will allow other interpreters to fit in more smoothly.More info : Wikipedia Shebang The #! magic, details about the shebang/hash-bang
_unix.175604
First, I have very basic knowledge on the SSL topic.Here is my setup. I have (1) of Public Facing Domain on LB and (2) of Internal Domains on each Web Servers. Like: [https://public.com][LB] | ------------------------------- | |https://web1.internal.com https://web2.internal.comSo that, yes, there also are INTERNAL ENCRYPTIONS just between LB & Two Nodes (Apaches). (REQUIRED)I am taking care of the Two Nodes (Apache Servers) but not the LB part. And was able to setup 2 Internal SSLs on these Apaches.Then my Security Team says (who is taking care of LB Part) I will have to:install the SSL Cert (of public.com) inside each of my Two Apaches, along with the Internal Domain SSLs.And they passed me the public.com.crt (Naming for example)What actually does it mean please, since I don't even need to have the Virtual Host for that Public Domain above. It doesn't even reach to my Apaches.How (where) do I setup the SSL of the LB inside my Internal Nodes (Apaches) please?
SSL (Hosted on LB) to be installed on the Downstream Apache Servers?
apache httpd;openssl;ssl;load balancing
null
_unix.369340
I am teaching someone how bash globbing works. I would like to show (via some bash debugging feature if possible) how bash expands the patterns prior to invoking the command. For instance I would like to do the following:ls -l file*.txtThen I would like bash to show what the file*.txt expanded to:ls -l file1.txt file2.txt file3.txt file4.txtI know how to do this using bash -x from within a script but I would prefer to do it in the interactive shell so that I don't have to introduce ideas about scripts. Is there a way to do this in interactive mode?
Is it possible to show how bash globbing works by doing?
wildcards
null
_codereview.3659
I'm working on set of methods that locate DVR surveillance footage, based on timestaps.The files are in the following format: <drive>\<year>\<month>\<day>\<camera>\<hour>-<minute>-<second>.<extension>Example:Z:\2011\07\02\000001\00-13-15.mkvthroughZ:\2011\07\02\000001\23-45-13.mkvThe videos are in 15ish minute increments, that start roughly around the turn of the hour.The edge case, as you could imagine, is around that turn of the hour mark. I have come up with two methods that get the job done, but are extremely convoluted, and frankly ugly.Can any one think of a less complex way to do this?EDIT: After some thought, I refactored it into three methods. Splitting out the path building as I had with the file name. It's better, but I still feel it can be simpler. This also resolves the 'change of day' issue I had mentioned below. public static string GetSecurityFootage(DateTime timeStamp, Camera camera) { string storageLoc = Initialization.DvrStorageLocation; // Just bail if we don't have a valid storage location. if (!Directory.Exists(storageLoc)) { return ; } // Get path and file name based on timestamp. string path = GetVideoPath(timeStamp, camera, storageLoc); string fileName = GetVideo(timeStamp, path.ToString()); if (fileName != && File.Exists(path + fileName)) { path = path + fileName; } // Try the end of the last hour/day. else { // Subtract from time minutes +1 to set time to last hour. timeStamp = timeStamp.AddMinutes(-(timeStamp.Minute + 1)); path = GetVideoPath(timeStamp, camera, storageLoc); fileName = GetVideo(timeStamp, path.ToString()); if (fileName != && File.Exists(path + fileName)) { path = path + fileName; } else { // If it's not it the last hour, we do not have footage. return ; } } return path; } private static string GetVideoPath(DateTime timeStamp, Camera camera, string storageLoc) { string pathSep = Path.DirectorySeparatorChar.ToString(); string cameraPath = ; string year = timeStamp.Year.ToString(); string month = timeStamp.Month.ToString(); string day = timeStamp.Day.ToString(); StringBuilder path = new StringBuilder(); // Paths are preceded by 0. if (day.Length == 1) { day = 0 + day; } if (month.Length == 1) { month = 0 + month; } switch (camera) { case Camera.Patio: cameraPath = 000001; break; case Camera.Counter: cameraPath = 000002; break; case Camera.Shed: cameraPath = 000003; break; case Camera.Cafe: cameraPath = 000004; break; case Camera.Lobby: cameraPath = 000005; break; default: cameraPath = 000002; //default to counter. break; } // Path to video. path.Append(storageLoc); if (!storageLoc.Trim().EndsWith(pathSep)) { path.Append(pathSep); } path.Append(year); path.Append(pathSep); path.Append(month); path.Append(pathSep); path.Append(day); path.Append(pathSep); path.Append(cameraPath); path.Append(pathSep); // The path doesn't exist, we will not have footage. if (!Directory.Exists(path.ToString())) { return ; } return path.ToString(); } private static string GetVideo(DateTime timeStamp, string path) { string hour = timeStamp.Hour.ToString(); int minute = timeStamp.Minute; //leave as int for comparison. string fileName = ; if (hour.Length == 1) { hour = 0 + hour; } // Get all the files in the dir, but just the file names. var files = Directory.GetFiles(path.ToString()).Select(f => Path.GetFileName(f)); // All files that start with the correct hour. var q = from f in files where f.Trim().StartsWith(hour) orderby f select f; // Now, loop the files for the higest that is still less than the minute we're looking for. foreach (var file in q) { int min = 0; int.TryParse(file.Substring(3, 2), out min); // Set file name for each loop; when done the highest should always be the last one set. if (min <= minute) { fileName = file; } } return fileName; }I guess there is no strike-through... disregard the following:One thing that is noticeable is that for the change of day, it will fail to find the footage. This isn't a huge deal, this is only a convenience feature for our POS. In this case, the user will just have to browse to the video manually. The change of hour is important, otherwise this feature is useless 1/4 of the time.
Any suggestions on how to clean up this convoluted file look-up method?
c#
Looking at how you try to solve this problem, you try to guess the expected file name of this point in time. Allow me to suggest another approach which is more natural and simpler IMHO.If all these videos are sorted, a footage is in a video if it's timestamp is within the time of this video, e.g. if you have a video Z:\2011\07\02\000001\13-45-13.mkv and the next video is Z:\2011\07\02\000001\14-00-32.mkv, and you are looking for the footage at 2011-07-02 13:52:07, you know that the footage it's in the first one. To do this, you need to Sort the videos by their starting date (which you will get by parsing the name).Search for the video containing this footage timestamp.This also handles all your edge cases :).But I still have some comments about your code.Don't do path.ToString() when path is already a string.String.format is more readable than StringBuilder in your case.What if you add another camera? You will have to modify and recompile your code. Consider defining cameras externally.
_unix.18725
I have been softy on windows as a font tool to make a bitmap font, it's essentially a modified version of profont I keep using, mostly because the original version is not perfect to me.I also made a proportional narrower version of profont, which I find extremely readable.I want to do the same for my Mac and I also want it to work on any *nix, so I'm opting for a way to make it work for *nix first.I can't understand why fontforge only allows you to make vectorized fonts, I want to make it pixel by pixel...
How to make a bitmap font for *nix environments?
fonts
null
_codereview.154241
I've used Decorator to create a Dataset class used to build a Dataset Basic Empty (ConcreteComponent) and Iris class (ConcreteDecorated) used to populate it.Decorator allows a user to add new functionality to an existing object without altering its structureFor Example Iris has a its own way to load and store the data in dataset structure. I've added also the name features to track the string name of there features.My purpose is to add more ConcreteDecorator, like Iris, that they have a own way to load and store file/data and to track the name features. The code run, but My Doubts are: dataset is an empty table (define only the data structure) and the population depends on concrete decorator that use it. It seems to me That does not Respect the SOLID Principles (for example DIP). What do you think about this simple implementation? COMPONENTpublic interface Dataset{ public double Distanza(int i, ArrayList<Double> centroide); public double getCella(int i, int j); public void inizializzaTabella(); public void stampaDataset(); public void setColonna( ArrayList<Double> colonnaValori); public ArrayList<ArrayList<Double>> getTabella(); public int getnFeature(); //ok public int getnRecord() ; public void setnFeature(int nFeature); public void setnRecord(int nRecord); public void setTabella(int Colonna, Double Valore); public String getNomeDataset(); public void setNomeDataset(String nomeDataset); public double[][] toMatrix(); public ArrayList<Integer> getFeatureUsate(); public void setNomiFeature(String[] nomiFeature);}CONCRETE COMPONENTpublic class DatasetConcreto implements Dataset{ private int nFeature; private int nRecord; private ArrayList<Integer> featureUsate; // quelle selezionate private String nomeDataset; private String[] nomiFeature; //public double Tabella [][]; private ArrayList<ArrayList<Double>> Mat; public double Distanza(int i, ArrayList<Double> centroide) { double Sum=0; for(int j=0; j<nFeature; j++) Sum+=Math.pow((centroide.get(j) - Mat.get(j).get(i)), 2); return Math.sqrt(Sum); } public double getCella(int i, int j) { return Mat.get(j).get(i); } public void inizializzaTabella() { Mat = new ArrayList<ArrayList<Double>>(); featureUsate = new ArrayList<Integer>(); for(int i=0; i< nFeature; i++) { Mat.add(new ArrayList<Double>()); featureUsate.add(i); // uso tutte le feature } } public void stampaDataset() { System.out.println(Le feature selezionate sono); for(int j = 0; j<nFeature; j++) System.out.println(nomiFeature[j].toString()); for(int i=0; i< nRecord; i++) { for(int j=0; j < nFeature; j++) { System.out.print( Mat.get(j).get(i)+ ); } System.out.println(\n); } } public ArrayList<Double> getRecord(int indiceRandom) { ArrayList<Double> record = new ArrayList<Double>(); for(int i=0; i<nFeature; i++) record.add( Mat.get(i).get(indiceRandom)); return record; } public DatasetConcreto(int nFeature, String Nome) { setnFeature(4); setNomeDataset(Iris.data); inizializzaTabella(); } public DatasetConcreto(ArrayList<ArrayList<Double>> MatInput, ArrayList<Integer> featureSelezionate, int nRecord) { Mat = new ArrayList<ArrayList<Double>>(); this.featureUsate = new ArrayList<Integer>(featureSelezionate); this.nRecord = nRecord; this.setnFeature(featureSelezionate.size()); for(int i=0; i<featureSelezionate.size(); i++) setColonna( MatInput.get( featureSelezionate.get(i))); } public DatasetConcreto() { } public void setColonna( ArrayList<Double> colonnaValori) { this.Mat.add(colonnaValori); } public ArrayList<ArrayList<Double>> getTabella() { return this.Mat; } public int getnFeature() { return this.nFeature; } public int getnRecord() { return this.nRecord; } public void setnFeature(int nFeature) { this.nFeature = nFeature; return; } public void setnRecord(int nRecord) { this.nRecord=nRecord; return; } public void setTabella(int Colonna, Double Valore) { Mat.get(Colonna).add(Valore); } public String getNomeDataset() { return this.nomeDataset; } public void setNomeDataset(String nomeDataset) { this.nomeDataset = new String(nomeDataset); } public double[][] toMatrix() { double[][] matrix = new double[this.getnRecord()][this.getnFeature()]; for(int i=0; i< nRecord; i++) { for(int j=0; j < nFeature; j++) { matrix[i][j] = Mat.get(j).get(i); } } return matrix; } public ArrayList<Integer> getFeatureUsate() {return this.featureUsate;} @Override public void setNomiFeature(String[] nomifeature) { this.nomiFeature = new String[nFeature]; this.nomiFeature = nomifeature; }}DECORATORpublic abstract class DatasetDecorator implements Dataset {protected Dataset dataset;public DatasetDecorator(Dataset dataset){this.dataset=dataset;}@Overridepublic double Distanza(int i, ArrayList<Double> centroide) { return this.dataset.Distanza(i, centroide);}@Overridepublic double getCella(int i, int j) { return this.dataset.getCella(i, j);}@Overridepublic void inizializzaTabella() { this.dataset.inizializzaTabella();}@Overridepublic void stampaDataset() { this.dataset.stampaDataset();}@Overridepublic void setColonna(ArrayList<Double> colonnaValori) { this.dataset.setColonna(colonnaValori);}@Overridepublic ArrayList<ArrayList<Double>> getTabella() { return this.dataset.getTabella();}@Overridepublic int getnFeature() { return this.dataset.getnFeature();}@Overridepublic int getnRecord() { return this.dataset.getnRecord();}@Overridepublic void setnFeature(int nFeature) { this.dataset.setnFeature(nFeature); }@Overridepublic void setnRecord(int nRecord) { this.dataset.setnRecord(nRecord);}@Overridepublic void setTabella(int Colonna, Double Valore) { this.dataset.setTabella(Colonna, Valore);}@Overridepublic String getNomeDataset() { return this.dataset.getNomeDataset();}@Overridepublic void setNomeDataset(String nomeDataset) {this.dataset.setNomeDataset(nomeDataset); }@Overridepublic double[][] toMatrix() { return this.dataset.toMatrix();}@Overridepublic ArrayList<Integer> getFeatureUsate() { return this.dataset.getFeatureUsate();}public void setNomiFeature(String[] nomifeature) {this.dataset.setNomiFeature(nomifeature);}}CONCRETE DECORATORpublic class Iris extends DatasetDecorator{ private final String[] nomiFeature = {LunghezzaSepalo, LarghezzaSetalo, LunghezzaPetalo, LarghezzaPetalo}; public Iris(String NomeFile, Dataset dataset) throws IOException { super(dataset); super.dataset.setnFeature(4); super.dataset.setNomiFeature(nomiFeature); super.dataset.inizializzaTabella(); //For init dataset from here super.dataset.setnRecord( CaricaDataset(NomeFile) ); } protected int CaricaDataset(String pathFile) throws IOException { int iRecord = 0; BufferedReader bufferLetto = null; String line = ; String cvsSplitBy = ,; try { bufferLetto = new BufferedReader(new FileReader(pathFile)); while ((line = bufferLetto.readLine()) != null) { if (line.length() > 0) { String[] cell = line.split(cvsSplitBy); this.addRow(cell); iRecord++; } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (bufferLetto != null) { try { bufferLetto.close(); } catch (IOException e) { e.printStackTrace(); } } } return iRecord; } // new row public void addRow(Object cell[]) { System.out.println(this.nomiFeature.length); for(int i=0; i<this.nomiFeature.length; i++) super.dataset.setTabella(i, Double.parseDouble(cell[i].toString())); }} TEST CLIENTpublic class Client { public static void main(String[] args) throws IOException { Dataset ds = new DatasetConcreto(); Dataset iris = new Iris(./src/Iris.data, ds); ds.stampaDataset(); }}
Is this a correct way to use Decorator and it respect SOLID principles?
java;object oriented;design patterns
null
_unix.166380
I cannot seem to retrieve a non-zero return code when calling the ftp macro. It doesn't matter what errors are encountered during the ftp macro execution e.g. directory doesn't exist, file doesn't exists etc.I'd love to know why.I'm using bash on Solaris. My .netrc file looks like so:machine myftp1 login xxxxxxxx password xxxxxxxxxmacdef getASCIIfiles cd $1 hash prompt off get $2Executing the following commandsecho \$ getASCIIfiles Scratch/mydir NON_EXISTANT_FILE.TXT | ftp -i myftp1 echo $?produces the following outputHash mark printing on (8192 bytes/hash mark). Interactive mode on. NON_EXISTANT_FILE.TXT: The system cannot find the file specified. 0Why is zero being returned?
Return code is always 0 after running echo \$ macroName | ftp -i mymachine
solaris;ftp;return status
The 'ftp' command does not seem to return other error codes than 0.An alternative solution would be to check the FTP return codes.There is some examples in how to do this here: https://stackoverflow.com/a/4442763
_webapps.54152
When someone creates a new Facebook account, they see a list of suggested friends. It's surprisingly accurate sometimes. How does Facebook obtain this data?Some guesses I've thought of so far:People that have searched for the email address used for this accountPeople who have sent Facebook invitations to the email address used for this accountPeople connected to accounts that were accessed from the computer used to create this accountAny others?
How does Facebook know how to suggest friends for new accounts?
facebook
null
_codereview.19238
This is function, that works correctly, but it seems to be too ugly.panel argument is never used for anything but pushing into refreshGamePanel,and it seems to be too much case statements. How can I cleanup this?runGameLoop :: Game -> Panel -> Curses GameResultrunGameLoop game panel = if victory game then return Victory else refreshGamePanel game panel >> render >> getPanelWindow panel >>= flip getEvent (Just 1) >>= \ event' -> case event' of Nothing -> runGameLoop game panel Just event -> case event of EventSpecialKey (KeyFunction 2) -> return Restart EventSpecialKey (KeyFunction 10) -> return Quit EventSpecialKey key' -> case keyToDirection key' of Nothing -> runGameLoop game panel Just dir -> runGameLoop (makeMove game dir) panel _ -> runGameLoop game panel
Haskell with too much case statements
haskell
null
_softwareengineering.251192
I have seen numerous projects have a file named commons for example:commomns.goI was wondering, why was this convention adopted and what did the meaning of naming a file or a package or something as commons?
Why are some files in programming projects named commons?
programming practices
null
_unix.115543
This is related to my other question: Kate has no window borders, and thus no minimize, maximize, and close buttonsIn KDE, after right-clickin on any window border, or it's entry in the task manager, I can select More Actions and then Fullscreen.Once in this mode, normal window manager commands such as alt-tab and alt-f4 no longer work. Moreover, the task bar and everything else remain permanently hidden until I quit the window via the File menu.How do I un-fullscreen a window managed by kwin?
How do I exit full screen after enabling via the right click context menu of kwin (KDE)?
kde;window manager;kde4;kwin;fullscreen
null
_codereview.92272
I know it is a simple game, but what I am doing here is practice what I took in an AI course. I'm also playing a little with the canvas and trying to improve the readability of my code and using JavaScript as an object oriented language.I divided my code into 3 main classes (objects). Board class which represents the board object and contain its properties like width and height and the canvas to draw with. Cell class which represents the individual cell object and contain its properties also. The app script. This is not a class, it is just a the script that makes use of the other scripts and runs the game.Is what I'm doing by dividing my code into these classes reasonable or it can be done in a simpler way?Is making these classes affecting the performance or not? Does my work need to be divided into more classes(objects)? What I can do better?Note: I have not implemented the minimax algorithm yet.index.html<html> <head> <title>Tic</title> <script src=js/jquery-2.1.3.min.js></script> <script src=js/Board.js></script> <script src=js/Cell.js></script> <script src=js/app.js></script> <link type=text/css rel=stylesheet href=css/bootstrap.min.css/> <link type=text/css rel=stylesheet href=css/style.css/> </head> <body> <div class=container> <div class=row style=text-align: center> <div class=col-md-6 col-md-offset-3> <div class=pin> <h1>Tic Tac Toc</h1> </div> </div> </div> <div class=row style=text-align: center> <div class=col-md-6 col-md-offset-3> <div class=pin id=content> <canvas id=canvas width=400 height=400></canvas> </div> </div> </div> </div> </body></html>app.js$(document).ready(function(){ var canvas = $(#canvas).get(0); var ctx = canvas.getContext('2d'); var data = { canvas : canvas, ctx : ctx, x : canvas.width/2-150, y : canvas.height/2-150, width : 300, height : 300, playerX: Abdulaziz, playerY: salmaaa }; var board = new Board(data); board.drawBoard(); $(#canvas).click({board: board, canvasId: canvas}, board.click);});Board.jsfunction Board(data){ data = (data === 'undefined') ? {} : data; if(data){ this.canvas = data.canvas; this.ctx = data.ctx; this.cell = []; this.isXTurn = true; this.gameStatus = turn; this.moves = 0; this.winningCombinations = [ [{x:0,y:0},{x:1,y:0},{x:2,y:0}],[{x:0,y:1},{x:1,y:1},{x:2,y:1}],[{x:0,y:2},{x:1,y:2},{x:2,y:2}], [{x:0,y:0},{x:0,y:1},{x:0,y:2}],[{x:1,y:0},{x:1,y:1},{x:1,y:2}],[{x:1,y:0},{x:1,y:1},{x:1,y:2}], [{x:0,y:0},{x:1,y:1},{x:2,y:2}],[{x:2,y:0},{x:1,y:1},{x:0,y:2}] ]; if(data.x){ this.x = data.x; this.y = data.y; this.width = data.width; this.height = data.height; this.cellWidth = this.width/3; this.cellHeight = this.height/3; this.playerX = data.playerX; this.playerY = data.playerY; }else{ this.width = 300; this.height = 300; this.x = this.canvas.width/2-this.width/2; this.y = this.canvas.height/2-this.height/2; this.cellWidth = this.width/3; this.cellHeight = this.height/3; this.playerX = Player X; this.playerY = Player Y; } for(var i=0 ; i<3 ; i++){ this.cell.push([]); for(var j=0 ; j<3 ; j++){ var data = { x: j*this.cellWidth, y: i*this.cellHeight, width: this.cellWidth, height: this.cellHeight, canvas: this.canvas, ctx: this.ctx }; var cell = new Cell(data); this.cell[i].push(cell); } } }else{ //undefined data object }}Board.prototype.drawBoard = function(){ //clear area to be drawn upon this.ctx.clearRect(this.x, this.y, this.width, this.height); //choose color of the stroke of the board and then drawing it this.ctx.fillStyle = #000000; this.ctx.strokeRect(this.x, this.y, this.width, this.height); //draw the lines that defines the cells of the board this.ctx.beginPath(); //left verticale line this.ctx.moveTo((this.x+this.width/3), this.y); this.ctx.lineTo((this.x+this.width/3), (this.y+this.height)); //right verticale line this.ctx.moveTo((this.x+2*this.width/3), this.y); this.ctx.lineTo((this.x+2*this.width/3), (this.y+this.height)); //upper horizontal line this.ctx.moveTo(this.x, (this.y+this.height/3)); this.ctx.lineTo((this.x+this.width), (this.y+this.height/3)); //bottom horizontal line this.ctx.moveTo(this.x, (this.y+2*this.height/3)); this.ctx.lineTo((this.x+this.width), (this.y+2*this.height/3)); //begin stroking the path then release it this.ctx.stroke(); this.ctx.closePath();};Board.prototype.getCell = function(coord){ var cHor = (coord.mouseX - coord.boardX)/this.cell[0][0].width; var cVer = (coord.mouseY - coord.boardY)/this.cell[0][0].height; return {h : parseInt(cHor), v: parseInt(cVer)};};Board.prototype.getCellCoord = function(cHor, cVer){ var cX = cHor * this.width/3; var cY = cVer * this.height/3; return {x : cX, y: cY};};Board.isInBounds = function(coord){ return (coord.mouseX > coord.boardX && coord.mouseX < coord.boardX+coord.width) && (coord.mouseY > coord.boardY && coord.mouseY < coord.boardY+coord.height);};Board.isWinCombo = function(combo, board){ return (board.cell[combo[0].x][combo[0].y].player === board.cell[combo[1].x][combo[1].y].player) && (board.cell[combo[1].x][combo[1].y].player === board.cell[combo[2].x][combo[2].y].player) && (board.cell[combo[0].x][combo[0].y].player !== );};Board.prototype.checkStatus = function(board){ if(board.moves === 9) return tie; for(var i=0 ; i<this.winningCombinations.length ; i++){ var combo = this.winningCombinations[i]; if(Board.isWinCombo(combo, board)) return win; } return turn;};Board.prototype.drawStatusBar = function(board, message){ board.ctx.clearRect(board.x, board.y+board.height+10, board.width, board.height/10); board.ctx.strokeRect(board.x, board.y+board.height+10, board.width, board.height/10); board.ctx.font = 20px serif; board.ctx.fillText(message, board.x+5, board.y+board.height+30);};Board.prototype.click = function(e){ //this a callback function so this identifier refers to //the canvas object that the event listener is attached to //not the board object var board = e.data.board; //e.originalEvent.layerX returns the position of the mouse relative to the canvas not the page or the screen //board.x returns the position of the board inside the canvas var coord = { mouseX: e.originalEvent.layerX, mouseY: e.originalEvent.layerY, boardX: board.x, boardY: board.y, width: board.width, height: board.height }; if(Board.isInBounds(coord) && board.gameStatus == turn){ var cell = board.getCell(coord); if(board.cell[cell.v][cell.h].player == ){ board.moves++; if(board.isXTurn){ board.cell[cell.v][cell.h].drawX(); board.isXTurn = !board.isXTurn; }else{ board.cell[cell.v][cell.h].drawO(); board.isXTurn = !board.isXTurn; } board.gameStatus = board.checkStatus(board); if(board.gameStatus == turn){ board.drawStatusBar(board, Player +((board.isXTurn)?X:O)+ Turn!!); }else if(board.gameStatus == win){ board.drawStatusBar(board, Player +((board.isXTurn)?O:X)+ Won!!); }else if(board.gameStatus == tie){ board.drawStatusBar(board, It is a Tie :D); } } }};Cell.jsfunction Cell(data){ data = (data === 'undefined')? {} : data; //$.extend(this, data); if(data){ this.x = data.x; this.y = data.y; this.width = data.width; this.height = data.height; this.ctx = data.ctx; this.canvas = data.ctx; this.empty = true; this.player = ; }else{ //should not construct the object }}Cell.prototype.clearCell = function(){ this.ctx.clearRect(this.x+this.width/2+2, this.y+this.height/2+2, this.width-5, this.height-5); this.empty = true; this.player = ; //should clear the array that represents the board};Cell.prototype.drawX = function(){ if(this.empty){ var x = this.x+(2*this.width/3); var y = this.y+(2*this.height/3); //begin drawing the path for the x this.ctx.beginPath(); //first line from the left this.ctx.moveTo(x, y); this.ctx.lineTo((x+(2*this.width/3)), (y+(2*this.height/3))); //second line from the right this.ctx.moveTo((x+(2*this.width/3)), y); this.ctx.lineTo(x, (y+(2*this.height/3))); //begin stroking the path then release it this.ctx.stroke(); this.ctx.closePath(); this.empty = false; this.player = x; }};Cell.prototype.drawO = function(){ if(this.empty){ var x = this.x+(this.width); var y = this.y+(this.height); var radius = this.width/3; //begin setting the path to stroke this.ctx.beginPath(); //set the path for the arc this.ctx.arc(x, y, radius, 0, 180); //begin stroking the path then release it this.ctx.stroke(); this.ctx.closePath(); this.empty = false; this.player = o; }};
Tic-Tac-Toe game with HTML5 canvas
javascript;jquery;html5;tic tac toe;canvas
Dead Codeelse{ //undefined data object }This isn't doing anything, so just delete it.EnumsRight here, you are using a string literal to specify the player who needs to move:this.player = x;Typically, you would use a player enum to specify the player.SpacingIf you put spaces around your operators, your code is easier to read, debug (especially when finding order-of-operations bugs), and maintain:this.ctx.moveTo((this.x+2*this.width/3), this.y);Early ReturnsRight here, you have some unnecessarily deep indentation:if(Board.isInBounds(coord) && board.gameStatus == turn){ var cell = board.getCell(coord); if(board.cell[cell.v][cell.h].player == ){ board.moves++; if(board.isXTurn){ board.cell[cell.v][cell.h].drawX(); board.isXTurn = !board.isXTurn; }else{ board.cell[cell.v][cell.h].drawO(); board.isXTurn = !board.isXTurn; } board.gameStatus = board.checkStatus(board); if(board.gameStatus == turn){ board.drawStatusBar(board, Player +((board.isXTurn)?X:O)+ Turn!!); }else if(board.gameStatus == win){ board.drawStatusBar(board, Player +((board.isXTurn)?O:X)+ Won!!); }else if(board.gameStatus == tie){ board.drawStatusBar(board, It is a Tie :D); } }}If I wrote this, I would use early returns at the top to use less indentation:if (!Board.isInBounds(coord) || board.gameStatus != turn) { return;}var cell = board.getCell(coord);if (board.cell[cell.v][cell.h].player != ) { return;}board.moves++;if (board.isXTurn) { board.cell[cell.v][cell.h].drawX(); board.isXTurn = !board.isXTurn;} else { board.cell[cell.v][cell.h].drawO(); board.isXTurn = !board.isXTurn;}board.gameStatus = board.checkStatus(board);if (board.gameStatus == turn) { board.drawStatusBar(board, Player +((board.isXTurn)?X:O)+ Turn!!);} else if (board.gameStatus == win){ board.drawStatusBar(board, Player +((board.isXTurn)?O:X)+ Won!!);} else if (board.gameStatus == tie){ board.drawStatusBar(board, It is a Tie :D);}
_webmaster.39446
I have just booked a domain name and it has only one page showing my Office Address (only text...no links) which I have already listed in Google Analytics after opeing my Google Analytics Account.Was this a correct action or mistimed to list a domain name / web site which has only one page? When is the best time to list a domain name /website in Google Analytics account?(Please note that I have completed Goolge Analytics Verification process also>)
When is the best time to list a domain name / website in Google Analytics account?
google analytics;google search console
I think there is no best time when it comes to using GA, as it depends on you as a site owner, because you are the only one who can decide when you can actually use the collected data about your traffic and visitors behavior.However there is no harm collecting early stage data which comes before launching the site, they won't held much value but they can easily be ignored and/or totally erased from your account.Anyway, having goals to achieve is a good sign for you to start collecting and using GA data.Long story short, there is no best time when it comes to collecting data, but best time to use that data is when you have some goals to achieve.Another question that came across my mind when i read yours is Does GA collected data make difference in your SEO / affect your ranking?According to Matt it doesn't (YouTube video)
_softwareengineering.317087
I have a series of reference codes that my end users create during the course of the day. These reference codes correspond to a transaction code that is stored in a database. As of now, there are 15 difference transaction codes.Here's an example:Tranasction Code - Reference CodeBB01 - 48912388C949 - X717-9999and so on...New transaction codes can be added at any time. Whether the transaction code is new or not, all corresponding reference codes must be in a certain format. I plan on using regular expressions to validate the reference codes using Javascript.Now here's the question.Am I better off doing something like thisvar transactionCode = $('input[name=TransactionCode]').val();var referenceCode = $('input[name=ReferenceCode]').val();// Do this type of test for all 15 types of reference codes until I// succeedif (transactionCode === 'BB01') { var results = /\d{8}/.test(referenceCode); // if results is true, blah blah blah}Create a SQL table of reference codes and matching regexs. Query the database and construct a javascript object (similar to a dictionary/hash of key value pairs) when needed where I pass the reference code as a key to retrieve the regex to validate against my transaction code.The second approach seems like overkill for a small data set. But the advantage is I don't have to hard-code my transaction codes when testing and when more codes are added or removed, I don't have to manually mess with them in JavaScript. Where as if I take the first approach, I have to hard code my transaction codes. Not only that, but if the transaction code ever changes, then I have to change the javascript.I wanted to get someone's feedback on this approach or another alternative if I'm missing something.
Validating transaction codes with reference codes... Best way to encode the validation rules?
c#;javascript
null
_codereview.133902
Consider, please, my code of the finalizer template:#include <functional>template<typename F, typename... Args>class finally{public: finally(F action, const Args&... args) : _action(std::bind(action, args...)) {} ~finally() { if(enabled) _action(); } bool enabled = true;private: std::function<void()> _action;};In particular I would enhance this template to avoid of using a typenames twice. Let's say we need to close some file on leaving some block of code. Then we declare an object:finally<int(int), int> f(close, some_file);Here I used the standard close function as an action. But I should use int twice in the <int(**int**), **int**>. Is there any way to avoid this?
C++ finalizer template
c++;c++11;template;variadic
null
_softwareengineering.349841
I have an architecture front-end / back-end, specifically an Android app and a backend. I want that the app user can see different prices and currencies depending on their geo-localization.So my Android app has a mechanism to know in which country the user is (based on geo-localization), then it queries the backend using ISO 3 country (GBR) and the backend returns a price (say 5.00). Then I need to get the currency () based on the country. The above mechanism is not neat and elegant but it does the job.The problem here is that every client (Android, iOS, Web app, etc), needs to implement the mechanism, while it seems easier if it was the backend to implement it once.Possible solutions:FE queries the BE by ISO 3 country, BE returns a string containing price and currency ( 5.00, 7.50 ), handling also the different position of the currency symbolFE queries the BE by latitude/longitude, then same as above.What are the pros/cons here?
Handle country specific properties such as price and currency
internationalization;localization;geospatial
null
_unix.310470
fstab:LABEL=Shared /home/howard/Shared/ ntfs permissions,rw,nosuid,nodev,relatime,uid=howard,gid=howard,allow_other,noatime,fmask=033,dmask=022 0 2Mount with:mount LABEL=Sharedmount reports:/dev/sda3 on /home/howard/Shared type fuseblk (rw,nosuid,nodev,noatime,user_id=0,group_id=0,default_permissions,allow_other,blksize=4096)Note permissions option was not honored, and instead default_permissions appears. (Also blksize=4096 is being added without my request.) Why does the permissions option get changed to default_permissions?I've tried both ntfs and ntfs-3g mount types. They both return with a fuseblk mount type.The permissions option allows each file's owner, group, and ugo_rwx permissions to be set independently. With default_permissions you can only set these one time for all files in the filesystem, and you can't individual set each file's user, group and permissions.Debian 8.5, Cinnamon 2.2.16, Linux Kernel 3.16.0-4-amd64
What is overriding the fstab permissions mounting option?
permissions;mount;fstab;options
null
_cs.1810
Are there any known problems in $\mathsf{NP}$ (and not in $\mathsf{P}$) that aren't $\mathsf{NP}$ Complete? My understanding is that there are no currently known problems where this is the case, but it hasn't been ruled out as a possibility. If there is a problem that is $\mathsf{NP}$ (and not $\mathsf{P}$) but not $\mathsf{NP\text{-}complete}$, would this be a result of no existing isomorphism between instances of that problem and the $\mathsf{NP\text{-}complete}$ set? If this case, how would we know that the $\mathsf{NP}$ problem isn't 'harder' than what we currently identify as the $\mathsf{NP\text{-}complete}$ set?
Are there NP problems, not in P and not NP Complete?
complexity theory;np complete;p vs np
Are there any known problems in NP (and not in P) that aren't NP Complete? My understanding is that there are no currently known problems where this is the case, but it hasn't been ruled out as a possibility.No, this is unknown (with the exception of the trivial languages $\emptyset$ and $\Sigma^*$, these two are not complete because of the definition of many-one reductions, typically these two are ignored when considering many-one reductions). Existence of an $\mathsf{NP}$ problem which is not complete for $\mathsf{NP}$ w.r.t. many-one polynomial time reductions would imply that $\mathsf{P}\neq\mathsf{NP}$ which is not known (although widely believed). If the two classes are different then we know that there are problems in $\mathsf{NP}$ which are not complete for it, take any problem in $\mathsf{P}$.If there is a problem that is NP (and not P) but not NP Complete, would this be a result of no existing isomorphism between instances of that problem and the NP Complete set? If the two complexity classes are different then by Ladner's theorem there are problems which are $\mathsf{NP}$-intermediate, i.e. they are between $\mathsf{P}$ and $\mathsf{NP\text{-}complete}$.If this case, how would we know that the NP problem isn't 'harder' than what we currently identify as the NP Complete set?They are still polynomial time reducible to $\mathsf{NP\text{-}complete}$ problems so they cannot be harder than $\mathsf{NP\text{-}complete}$ problems.
_softwareengineering.288585
In the book Effective Java he give the best Singleton pattern implementation in his, that is implement by a Enum. I have doubt to how to implement this pattern with a third party API. I'm using an third party API that provides an interface IRCApi that has a lot of methods like:public interface IRCApi{ void connect(); void disconnect(); void disconnect(String aQuitMessage); void joinChannel(String aChannelName); //...}My question: Is the code snippet below a valid implementation of that design pattern with all benefits cited by Joshua Bloch (multi thread support, facility to change, etc):public enum IRCApiSingleton { INSTANCE; private final IRCApi ircApi = new IRCApiImpl(false); public final IRCApi get() { return ircApi; }}using this way: IRCApiSingleton.get().connect();Or do I have to make my enum implement IRCApi and encapsulate all methods of an IRCApi implementation (there are about 40 methods), like:public enum IRCApiSingleton implements IRCApi { INSTANCE { private IRCApi impl = new IRCApiImpl(true); @Override public void connect() { impl.connect(); } @Override public void disconnect() { impl.disconnect(); } //... };}and use the INSTANCE directly?
Joshua Bloch Enum Singleton and Third Party APIs
java;design patterns;object oriented design;patterns and practices;singleton
Well, as I see it, IRCApiImpl has a public constructor making it difficult to call either way a classical singleton.Still, I'd say that if you follow the guideline of not creating another instance of IRCApiImpl at any other point or even better, making the class inaccessable, you can use either implementation.From a strict Software-Engineering point of view, the first implementation would be preferable, because It would allow less coupling and would not need to be changed when the API of IRCApiImpl changed.Personally though I'd prefer the second implementation, which saves you the .get() on every call.
_webmaster.107881
A business with two partners and a website have parted ways. The website is now just a single static page with contact info for the partners. Searches for these partners still returns this website, before other more relevant results from their new business ventures. Redirects are not a good idea because of the split.What is the best way to remove the old site from the internet? The question was asked of me in a Google-specific context, but a more general answer would be helpful.
shut shown a business's website, remove from seach
seo;search engines
null
_unix.29654
When I'm using tail -f and I want to return to the shell, I always use CTRL+C. Or when I am typing a command and feel like aborting it and starting over, I simply CTRL+C to get back to an empty command line prompt. Is this considered bad practice? I sometimes feel there might be a better way to break away from something, but really have no idea.
Is CTRL+C incorrect to use to return to command line?
linux;bash
Ctrl+C sends a SIGINT to the program. This tells the program that you want to interrupt (and end) it's process. Most programs correctly catch this and cleanly exit. So, yes, this is a correct way to end most programs.There are other keyboard shortcuts for sending other signals to programs, but this is the most common.
_unix.113573
I'm trying to understand the following in Linux. In windows we have the services that run or startup. When we install an application it could be installed as a service so that it starts automatically. But if an application is not installed as a service we usually can see it in the Start -> Programs menu. So we know what applications are installed. In Linux what is the equivalent? I understand that the equivalent services are in /etc/init where the services start/stop. But I assume that if I install a package it does not necessarily create a startup script in /etc/init right? So how does one know what has been installed and is available in Linux (like we can in Windows from Start -> Programs)? Note: I'm asking about CLI mode. I guess in a desktop version one can see the relevant icons in the various menus (e.g in Kubuntu from Application -> Internet -> Firefox).
How do we know what applications are installed in Linux?
linux;startup;services;application
Many questions. Let's take a couple and see if we can't clear things up.Q1I understand that the equivalent services are in /etc/init where the services start/stop. But I assume that if I install a package it does not necessarily create a startup script in /etc/init right?No when you install applications on Linux distros (ones that make use of package managers such as dpkg/APT, RPM/YUM, pacman, etc.), as part of the software being installed the package manager has a scripting feature similar to those found in Windows that can add scripts, create scripts, add users to the system, and start services after they're installed.Q2So how does one know what has been installed and is available in Linux (like we can in Windows from Start -> Programs)?Easy. The same package managers that I mentioned above have commands you can use to query the system to find out what applications have been installed, what files are related to these packages etc. etc.ExampleOn Red Hat based distros you can use the command rpm to find out information about the packages installed.$ rpm -aq | head -5libgssglue-0.4-2.fc19.x86_64pygame-1.9.1-13.fc19.x86_64perl-HTML-Parser-3.71-1.fc19.x86_64ibus-libs-1.5.4-2.fc19.x86_64libnl-1.1-17.fc19.x86_64To find out what files are part of a package:$ rpm -ql pygame | head -5/usr/lib64/python2.7/site-packages/pygame/usr/lib64/python2.7/site-packages/pygame-1.9.1release-py2.7.egg-info/usr/lib64/python2.7/site-packages/pygame/LGPL/usr/lib64/python2.7/site-packages/pygame/__init__.py/usr/lib64/python2.7/site-packages/pygame/__init__.pycHow can it show me just the executable pieces to that are included in the package (the applications)? Most of the time executables are installed in certain locations on Linux, /usr/bin or /bin are 2 such directories. I usually search the RPM packages like so for these:$ rpm -ql pygtk2 | grep /bin/usr/bin/pygtk-demo$ rpm -ql httpd | grep -E bin/|sbin/ | head -10/usr/sbin/apachectl/usr/sbin/fcgistarter/usr/sbin/htcacheclean/usr/sbin/httpd/usr/sbin/rotatelogs/usr/sbin/suexec
_unix.83242
I have a small script on a dev/staging server that runs services inside tmux. The script just creates a few sessions with a few windows each in which various services are running. How can I make this script run each time the system starts after reboot? I would like to have this script run as specified user.
Running script on system start as given user
scripting;startup;not root user
The quickest way is to put a command like su - john -c bla in /etc/rc.local (or whatever variant your distro uses.
_softwareengineering.78525
A large list of harmful stuff related to software development is presented on cat -v. Is Qt harmful? What would be the rationale for considering to Qt harmful? Why would Tcl/Tk be presented as a superior alternative?
Why would Qt be considered harmful?
gui;qt
That site is designed around the idea of simple implementations, rather than simple interfaces. This is referred to on that site as Unix style design vs MIT style design.As such, Qt is considered harmful because it strives to offer as simple an interface as possible, whilst increasing internal complexity. For example, QStrings share memory internally, under some circumstances, when copied. Tell me that's expected behavior and the simplest possible implementation. It's not. It's useful when you are storing large amounts of duplicate data in several QStrings, however, so the developers added that feature. As the maintainer of that website states, not implementing features is hard (paper). Looking at the list of harmful software at http://harmful.cat-v.org/software/ shows this is a common pattern: The author prefers software that is simple in implementation, does one thing, and does it well. Whether or not the author is correct in their assumptions about complex software is up to the reader, and many would disagree.Personally, I attempt to remove unnecessary complexity from programs I write when possible. However, in order to write useful software, you, as a programmer, often need to deal with such complexity as a matter of course. Your job, as said programmer, is to add the requested features with a minimal addition of complexity.
_codereview.117440
I made a simple 8 puzzle which is 3x3 grids unsorted. The user has to move only one number at any direction, which is next to an empty tile. If the user sorted numbers, he/she wins the game, otherwise he/she needs to restart the game.The game seems to work fine, but I would like to know how I can improve it further.#include <iostream>#include <cassert>#include <random>#include <algorithm>#include <array>#include <map>#include <numeric>#include <conio.h>#define _USE_MATH_DEFINES#include <cmath>#ifndef M_PI#define M_PI 3.141592653589793238462643383f#endif namespace{ enum KeyType { KUp = 72, KRight = 77, KLeft = 75, KDown = 80 }; enum Direction { Up, Down, Left, Right, DirectionCount }; std::mt19937 randomEngine() { std::array<std::mt19937::result_type, std::mt19937::state_size> seed_data; thread_local std::random_device source; std::generate(std::begin(seed_data), std::end(seed_data), std::ref(source)); std::seed_seq seeds(std::begin(seed_data), std::end(seed_data)); thread_local std::mt19937 seeded_engine(seeds); return seeded_engine; } float radian(Direction direction) { constexpr static std::array<float, Direction::DirectionCount> Radians { M_PI, // Up 0, // Down -M_PI / 2, // Left M_PI / 2 // Right }; return Radians[direction]; }}struct Vector{ Vector(unsigned int x, unsigned int y) :x(x) , y(y) {} unsigned int x, y;};class Puzzle{private: constexpr static auto MaxTiles = 9u; constexpr static auto Columns = 3u; using Pair = std::pair<Vector, unsigned int>; using TileHolder = std::array<char, MaxTiles>;public: Puzzle() { std::iota(mTiles.begin(), mTiles.end(), '1'); mTiles.back() = ' '; thread_local auto random = randomEngine(); std::shuffle(mTiles.begin(), mTiles.end(), random); } void update(Direction direction) { const auto& coord = getEmptyTileCoordinates(); auto x = static_cast<unsigned int>(coord.first.x - std::sin(radian(direction))); auto y = static_cast<unsigned int>(coord.first.y - std::cos(radian(direction))); if (x < 0u || x >= 3u || y < 0u || y >= 3u) return; std::swap(mTiles[y * Columns + x], mTiles[coord.second]); } bool isSorted() const { return std::is_sorted(mTiles.begin(), mTiles.end() - 1); }private: Pair getEmptyTileCoordinates() const { auto found = std::find(mTiles.cbegin(), mTiles.cend(), ' '); assert(found != mTiles.cend()); auto index = std::distance(mTiles.cbegin(), found); auto coord = Vector(index % Columns, index / Columns); return{ coord, index }; } void draw(std::ostream& stream) const { for (const auto& tile : mTiles) { auto index = &tile - &*(mTiles.begin()); stream << tile << ((index % Columns == Columns - 1) ? '\n' : ' '); } } friend std::ostream& operator<<(std::ostream& stream, const Puzzle& puzzle) { puzzle.draw(stream); return stream; }private: TileHolder mTiles;};class Game { using KeysMap = std::map<int, Direction>;public: Game() { mKeyBinding.emplace(KeyType::KUp, Direction::Up); mKeyBinding.emplace(KeyType::KDown, Direction::Down); mKeyBinding.emplace(KeyType::KLeft, Direction::Left); mKeyBinding.emplace(KeyType::KRight, Direction::Right); } void gameLoop() { display(); while (!mPuzzle.isSorted()) { if (_kbhit()) { userInput(); display(); } } result(); }private: void userInput() { auto found = mKeyBinding.find(_getch()); if (found != mKeyBinding.end()) mPuzzle.update(found->second); } void display() { system(cls); std::cout << mPuzzle; } void result() { std::cout << yey: it sorted!; std::cin.ignore(); } Puzzle mPuzzle; KeysMap mKeyBinding;};int main(){ Game game; game.gameLoop();}
Simple 8 Puzzle - ASCII
c++;c++11;game;sliding tile puzzle
I'll start with update.Since getEmptyTileCoordinates() returns a Pair, you can store that in coord instead of using a reference:auto coord(getEmptyTileCoordinates());For the direction offsets, you can just have arrays that store the x and y offsets for a particular direction rather than doing the math with floats.// in local namespaceconst int x_offset[] = {0, 0, -1, +1}; // Up, Down, Left, Rightconst int y_offset[] = {-1, +1, 0, 0};// in updateunsigned x = coord.first.x + x_offset[direction];unsigned y = coord.first.y + y_offset[direction];That would allow you to get rid of your radian function. And since x and y are unsigned, they'll never be less than zero and you don't need to check them for that (although the compiler will know this and likely will optimize away those comparisons).drawYou're doing a lot of work in draw to determine when to use a newline instead of a space. This can be simplified by using a counter.void draw(std::ostream& stream) const{ int column = 0; for (const auto& tile : mTiles) { column = (column + 1) % Columns; stream << tile << (column == 0 ? '\n' : ' '); }}
_cs.35558
$T(n+1)=T(n)+\lfloor \sqrt{n+1} \rfloor$ $\forall n\geq 1$ $T(1)=1$ The value of $T(m^2)$ for m 1 is? Clearly you cannot apply master theorem because it is not of the form $T(n)=aT(\frac{n}{b})+f(n)$So I tried Back Substitution:$T(n)=T(n-1)+\lfloor\sqrt{n}\rfloor$$T(n-1)=T(n-2)+\lfloor\sqrt{n-1}\rfloor$therefore,$T(n)=T(n-2)+\lfloor\sqrt{n-1}\rfloor+\lfloor\sqrt{n}\rfloor$$T(n)=T(n-3)+\lfloor\sqrt{n-2}\rfloor+\lfloor\sqrt{n-1}\rfloor+\lfloor\sqrt{n}\rfloor$..$T(n)=T(n-(n-1))+...T(n-k)+\lfloor\sqrt{n-(k-1)}\rfloor+...+\lfloor\sqrt{n-2}\rfloor+\lfloor\sqrt{n-1}\rfloor+\lfloor\sqrt{n}\rfloor$..$T(n)=T(1)+...T(n-k)+\lfloor\sqrt{n-(k-1)}\rfloor+...+\lfloor\sqrt{n-2}\rfloor+\lfloor\sqrt{n-1}\rfloor+\lfloor\sqrt{n}\rfloor$$T(n)=T(1)+...+\lfloor\sqrt{n-2}\rfloor+\lfloor\sqrt{n-1}\rfloor+\lfloor\sqrt{n}\rfloor$I'm stuck up here and the answer is given as - $T(m^2)=\frac{m}{6}(4m^2 - 3m + 5)$how to solve and reach the answer?
If $T(n+1)=T(n)+\lfloor \sqrt{n+1} \rfloor$ $\forall n\geq 1$, what is $T(m^2)$?
asymptotics;recurrence relation;recursion
Your problem is that you're ignoring the floors. Make sure that you know what $\lfloor x \rfloor$ means.It is not hard to check that$$ T(n) = \sum_{k=1}^n \lfloor \sqrt{k} \rfloor. $$Therefore$$\begin{align*}T(m^2-1) &= \sum_{k=1}^{m^2-1} \lfloor \sqrt{k} \rfloor \\ &=\sum_{r=1}^{m-1} \sum_{\ell=r^2}^{(r+1)^2-1} \lfloor \sqrt{\ell} \rfloor \\ &=\sum_{r=1}^{m-1} \sum_{\ell=r^2}^{(r+1)^2-1} r \\ &=\sum_{r=1}^{m-1} [(r+1)^2-r^2] r \\ &=\sum_{r=1}^{m-1} (2r+1)r \\ &=\sum_{r=1}^{m-1} 4\binom{r}{2} + 3\binom{r}{1} \\ &=4\binom{m}{3} + 3\binom{m}{2}.\end{align*}$$Therefore$$\begin{align*}T(m^2) &= 4\binom{m}{3} + 3\binom{m}{2} + m \\ &=\frac{4m(m-1)(m-2)}{6} + \frac{3m(m-1)}{2} + m \\ &=\frac{(4m^3-12m^2+8m) + (9m^2-9m) + (6m)}{6} \\ &=\frac{4m^3-3m^2+5m}{6}.\end{align*}$$
_unix.153879
The following picture is snapped in a real Linux environment.Why can Linux show a file name containing character '/'?
Why can Linux show a file name containing character '/'?
ls;filenames
It's not a / character (U+002F); it's some Unicode character that just looks similar.Tryls | hexdump -Cto see what it is.Some possibilities are FRACTION SLASH (U+2044), DIVISION SLASH (U+2215), MATHEMATICAL RISING DIAGONAL (U+27CB), and the combining solidus characters U+0337 and U+0338, but there's no way to tell which one from your screenshot.
_softwareengineering.287415
Lets say I have two arrays A and B A = {1,2,3}B = {12,11,67}and have max sum value S = 10How many maximum number of unique pairs can be formed between the two arrays who's sum is less than or equal to S. For e.g., the two possible values here are [1,11] [2,12] hence the answer is 2. If there are none, the answer is 0. My solution was to sort both the arrays and then go do if((Math.abs(A[i]-B[i]))<=S) { ans++; }Although it works for this case, clearly this is incorrect.
Find the maximum number of pairs of numbers that are in a range, between two arrays
java;algorithms;array
null
_unix.326928
I have a CSV formatted multi lines file with 5 columns (fields). I need to unify and corrected the corrupted first column which has lots of different formats of the code I need to unify. The complete final format of my code for the first column should be 00AB[0-9][0-9][0-9][0-9][0-9] which [0-9] could be any number such as 00AB21345. The first four digits i.e. 00AB should be always as it is. but the 5 digits after that (i.e.[0-9][0-9][0-9][0-9][0-9]) could be any number and if there would be any > 5 digits , the missing digits from far left should be substitute with 0. Example <111> --> <00AB00111> ; or <1111> --> <00AB01111>. To have an example let's say I have a following file :111 xx yy zzz ddd1111 xx yy zzz ddd11111 xx yy zzz dddA111 xx yy zzz dddA1111 xx yy zzz dddA11111 xx yy zzz dddAB111 xx yy zzz dddAB1111 xx yy zzz dddAB11111 xx yy zzz ddd0A111 xx yy zzz ddd0A1111 xx yy zzz ddd0A11111 xx yy zzz ddd0AB111 xx yy zzz ddd0AB1111 xx yy zzz ddd0AB11111 xx yy zzz ddd00A111 xx yy zzz ddd00A1111 xx yy zzz ddd00A11111xx yy zzz ddd00AB111 xx yy zzz ddd00AB1111 xx yy zzz ddd0AB11111 xx yy zzz ddd00AB12344 xx yy zzz ddd00AB34527 xx yy zzz ddd00AB56278 xx yy zzz ddd00AB98902 xx yy zzz dddTo cover all the possible scenario I made up the following very long awk script. The bold format represent the potential scenario could be find in my file which needed to be corrected.My request, dose any one know any awk script to address this in much smaller script? If so, would you explain it to me in details to learn :)##111 Awk -F',' '{if($0~/[0-9][0-9][0-9]/){print 001AB00suBstr($1,1,3),$2,$3,$4,$5;}else{print $1,$2,$3,$4,$5;}}' SC3.csv > y1.csv##1111Awk -F',' '{if($0~/[0-9][0-9][0-9][0-9]/){print 001ABsuBstr($1,1,4),$2,$3,$4,$5;}else{print $1,$2,$3,$4,$5;}}' y1.csv > y2.csv##11111Awk -F',' '{if($0~/[0-9][0-9][0-9][0-9][0-9]/){print 001AB suBstr($1,1,5),$2,$3,$4,$5;}else{print $1,$2,$3,$4,$5;}}' y2.csv > y3.csv##A111Awk -F',' '{if($0~/[A-Z][0-9][0-9][0-9]/){print 001suBstr($1,1,1) B00suBstr($1,2,4),$2,$3,$4,$5;}else{print $1,$2,$3,$4,$5;}}' y3.csv > y4.csv##A1111Awk -F',' '{if($0~/[A-Z][0-9][0-9][0-9][0-9]/){print 001suBstr($1,1,1) B0 suBstr($1,2,5),$2,$3,$4,$5;}else{print $1,$2,$3,$4,$5;}}' y4.csv > y5.csv##A11111Awk -F',' '{if($0~/[A-Z][0-9][0-9][0-9[0-9][0-9]/){print 001suBstr($1,1,1) B suBstr($1,2,6),$2,$3,$4,$5;}else{print $1,$2,$3,$4,$5;}}' y5.csv > y6.csv##AB111Awk -F',' '{if($0~/[A-Z][A-Z][0-9][0-9][0-9]/){print 001suBstr($1,1,2) 00 suBstr($1,3,5),$2,$3,$4,$5;}else{print $1,$2,$3,$4,$5;}}' y6.csv > y7.csv##AB1111Awk -F',' '{if($0~/[A-Z][A-Z][0-9][0-9][0-9][0-9]/){print 001suBstr($1,1,2)0 suBstr($1,3,6),$2,$3,$4,$5;}else{print $1,$2,$3,$4,$5;}}' y7.csv > y8.csv##AB11111Awk -F',' '{if($0~/[A-Z][A-Z][0-9][0-9][0-9][0-9][0-9]/){print 001suBstr($1,1,7),$2,$3,$4,$5;}else{print $1,$2,$3,$4,$5;}}' y8.csv > y9.csv##1A111Awk -F',' '{if($0~/[0-9][A-Z][0-9][0-9][0-9]/){print 00suBstr($1,1,2) ,B00 suBstr($1,3,5) ,$2,$3,$4,$5;}else{print $1,$2,$3,$4,$5;}}' y9.csv > y10.csv##1A1111 Awk -F',' '{if($0~/[0-9][A-Z][0-9][0-9][0-9][0-9]/){print 00suBstr($1,1,1) B0 suBstr($1,3,6) ,$2,$3,$4,$5;}else{print $1,$2,$3,$4,$5;}}' y10.csv > y11.csv##1A11111Awk -F',' '{if($0~/[0-9][A-Z][0-9][0-9][0-9][0-9][0-9]/){print 00suBstr($1,1,2) B suBstr($1,3,7) ,$2,$3,$4,$5;}else{print $1,$2,$3,$4,$5;}}' y11.csv > y12.csv##1AB111Awk -F',' '{if($0~/[0-9][A-Z][A-Z][0-9][0-9][0-9]/){print 00suBstr($1,1,1) suBstr($1,1,3)00 suBstr($1,4,6) ,$2,$3,$4,$5;}else{print $1,$2,$3,$4,$5;}}' y12.csv > y13.csv##1AB1111Awk -F',' '{if($0~/[0-9][A-Z][A-Z][0-9][0-9][0-9][0-9]/){print 00 suBstr($1,1,3) 0 suBstr($1,4,7) ,$2,$3,$4,$5;}else{print $1,$2,$3,$4,$5;}}' y13.csv > y14.csv##1AB11111Awk -F',' '{if($0~/[0-9][A-Z][A-Z][0-9][0-9][0-9][0-9][0-9]/){print 00 suBstr($1,1,8) ,$2,$3,$4,$5;}else{print $1,$2,$3,$4,$5;}}' y14.csv > y15.csv##11A111Awk -F',' '{if($0~/[0-9][0-9][A-Z][0-9][0-9][0-9]/){print 0 suBstr($1,1,3)B00 suBstr($1,4,6) ,$2,$3,$4,$5;}else{print $1,$2,$3,$4,$5;}}' y15.csv > y16.csv##11A1111Awk -F',' '{if($0~/[0-9][0-9][A-Z][0-9][0-9][0-9]/){print 0 suBstr($1,1,3)B0 suBstr($1,4,7) ,$2,$3,$4,$5;}else{print $1,$2,$3,$4,$5;}}' y16.csv > y17.csv##11A11111Awk -F',' '{if($0~/[0-9][0-9][A-Z][0-9] [0-9][0-9][0-9]/){print 0 suBstr($1,1,3)B suBstr($1,4,8) ,$2,$3,$4,$5;}else{print $1,$2,$3,$4,$5;}}' y17.csv > y18.csv##11AB111Awk -F',' '{if($0~/[0-9][0-9] [A-Z][[A-Z][0-9][0-9][0-9]/){print 0 suBstr($1,1,4)00 suBstr($1,5,7) ,$2,$3,$4,$5;}else{print $1,$2,$3,$4,$5;}}' y18.csv > y19.csv##11AB1111Awk -F',' '{if($0~/[0-9][0-9] [A-Z][[A-Z][0-9][0-9][0-9][0-9]/){print 0 suBstr($1,1,4)0 suBstr($1,5,8) ,$2,$3,$4,$5;}else{print $1,$2,$3,$4,$5;}}' y19.csv > y20.csv##1AB11111Awk -F',' '{if($0~/[0-9][0-9] [A-Z][[A-Z][0-9][0-9][0-9][0-9][0-9]/){print 0 suBstr($1,5,9) ,$2,$3,$4,$5;}else{print $1,$2,$3,$4,$5;}}' y20.csv > y21.csv`
How to use awk to correct and unify a corrupted file with multiple columns and lines?
linux;shell script;command line;awk
Maybe:awk 'sub(^0?0?A?B?,,$1) && $1=sprintf(00AB%05d,$1)'Delete any leading 00AB fragments from field 1, then convert it to 00AB followed by the rest of the number padded with zeros up to length 5.The expression is always true so the implicit { print } action fires. The sub is always true because the regular expression is nullable: a bit sneaky! The substitution takes place even if ^0?0?A?B? matches the empty string, because that is a successful match.
_unix.11389
One common workflow of mine is to open a manual page in a terminal, then another terminal in which to test things. The man page is formatted to the initial dimensions of the first terminal. When I now resize my windows (or have my WM do that for me automatically), there is either a gap to the right of the preformatted page, or lines wrap. At this point I usually q(uit) and !! (run again), which loses my position in the page.I assume the formatting process is quite CPU intensive, or maybe it stems from ancient times of fixed terminal sizes. The less pager dynamically reacts to terminal resize events, so it should be possible in theory.I tried perusing man pages, searching the Web, asking on IRC -- the whole lot -- but couldn't come up with anything.Can I trigger reformatting from withinor outside of the man utility?Is there a version of the man utilitythat resizes the page dynamically? Is there way to customize some partof the formatting/display process tomake it update on SIGWINCH?
Dynamically reformatting man pages on terminal dimension changes
terminal;man
The basic problem is that the formatting is done by one program and the paging is done by another. Even if the formatter were to get a signal that the window size has changed and reformat the text for the new window size, all it can do is feed new text down the pipeline to the pager. There's no way for the pager to know with certainty what position in the new stream corresponds to the position in the old stream it was currently displaying.What you need is for the pager to be able to do the reformatting. As @Robin Green said, that's HTML.If you want to use HTML but still work in a terminal, you can tell man(1) to output in HTML and call a text-mode browser to display it.man -Hlynx manThat will display the man(1) manpage in the lynx text-mode browser. Lynx does not directly respond to window size changes, but you can press ctrl-R and lynx will re-render the page for the new window size.There are two other text-mode browsers that I know of: links and elinks. You could experiment with those and lynx and determine which give you the best experience for browsing man pages. You may want to use a custom configuration just for man pages and invoke a script that invokes the browser with that specific configuration.You can put the man options you like into the MANOPT environment variable.$ export MANOPT=-Hlynx$ export MANOPT=-Hmanlynx # manlynx invokes lynx with a different configuration.You will need to install the groff package for man to be able to generate HTML.
_webmaster.59859
I am in charge of my companies website and one of my tasks is to improve SEO. Granted, I am new to this and have been researching for the past 6 months and had an idea. My plan is to build multiple websites and create a huge site using multiple domains. We offer different services and our main home page will have all of the services with links to the other websites which are the individual services so that I don't have to worry about duplicate page content.Example:www.companyname.com is the main sitewww.service#1.com is one of our serviceswww.service#2.com is another one of our services etc.Will this have an affect on our SEO in a positive way like I think or would it impact us negatively? and why?
Is having multiple websites a good idea or a bad one for SEO?
seo;multiple domains
Having different websites for different services wont affect you negatively but it wont give you any special SEO benefits. According to me its a waste of time. Having different websites will block your visitors to see your other services which will be a loss of advantage for your website and for your company. It will limit your visitors. If you have a single website with all your services as different pages it will give SEO weight to your website as Zistoloen said in his answer. If someone searched your company name he/she can easily identify all your services at a single place which will be user friendly.
_unix.120588
I have 2 identical server with exact disk partitions (OS CENTOS 6.4 both ) [My college central oracle server].Entire ORACLE HOME ( bin , control files, data files everything on oracle) is on 2nd Disk (which is not a OS disk)Since OLD server had reached end of life (from HP) a new HP machine with upgraded RAM (OLD system had 16 GIG where as new system as 64 GIG).Now Since All oracle Dependencies (RPM, libraries, environmental variables, JAVA, Users and groups) are already made on new server.So Now Question is ..Can I remove Disk [Oracle HDD] from OLD server and insert it on NEW server and just start Oracle (sqlplus / as sysdba or dbstart and lnsctrl).Can it will give any challenge.(I have cold backups, export backup, & RMAN backup too).I just want to give a try on above case.Will this work ??
Move Complete ORACLE from one system to another
centos;database
null
_codereview.120391
I'm having trouble with a current algorithm I'm writing that takes a corpa, a list of characters in sets (1 one or larger) with a frequency number attached to it. Against another list of character sets that need to be created using the most frequent occurrences of the combined sets... if that makes sense. I'll explain with an example. So lets say your corpa looks like this. (Just note that case does not matter as the actual data is in Korean, hence each character represents a Korean character.)A 56AB 7342ABC 3BC 116C 5CD 10BCD 502ABCD 23D 132DD 6The wordlist is (ignore the number):AAB 1123DCDD 83So the output of the script would be:Original Pois Makeup Freq_Max_DeltaAAB A AB [AB, 7342][A, 56] 7398DCDD D C DD [D, 132][DD, 6][C, 5] 143Currently I am basically doing this by ordering the corpa, then grabbing each individual line, getting all the combinations of each letter (this is redundant as it produces combinations which are not positionally correct) and then pulls out which combinations can make up the word. Then adds up the frequency of the set of combinations and then outputs the one with Freq_Max_Delta.I'm thinking that a large part of the problem is the number of nested loops that I'm using and the fact we are creating redundant data. I'm also looking into the possibility of cython and even using multiple threads for the tokenisation. The problem is some what similar to the Knapsack ProblemBelow is my code, also a portion of the inputs are located on my gist if you are interested in running it with what I'm using. The wordlist and the corpafrom argparse import ArgumentParserfrom collections import OrderedDictfrom itertools import combinationsdef order_worlist(corpa): dict_corpa = dict() print 'ordering corpa....' with open(corpa, 'r') as open_wordlist: for line in open_wordlist: line_arr = line.rstrip().split('\t') count = line_arr[-1] tx = line_arr[0] dict_corpa[tx] = int(count) open_wordlist.close() return OrderedDict(sorted(dict_corpa.items(), key=lambda t: t[1], reverse=True))def create_cominations(tx_dict, original_tx): tx_list = list() for k, v in tx_dict.items(): tx_list.append(k) output = list() for k, v in tx_dict.items(): y = lambda : sum([map(list, combinations(tx_list, i)) for i in range(len(tx_list) + 1)], []) output.append( y()) final_li = None try: for i in output[0]: if sorted(''.join(i)) == sorted(original_tx): if len(''.join(i)) == len(original_tx): sub = list() total = 0 for v in i: total += tx_dict[v] sub.append([v, tx_dict[v]]) if final_li is None: final_li = [] final_li.append([i, [sub], total]) if total > final_li[0][2]: final_li = [] final_li.append([i, [sub], total]) else: pass part_final = '' for part in final_li[0][1]: for v in part: part_final += '[' + v[0] + ', ' + str(v[1]) + ']' print '\t\t'.join(['For: ',original_tx ,' '.join(final_li[0][0]), part_final, str(final_li[0][2])]) except: print '\t\t'.join(['For: ', original_tx, '\t\tNothing Found']) def contains(small, big): for i in xrange(len(big)-len(small)+1): for j in xrange(len(small)): if big[i+j] != small[j]: break else: return (i, i+len(small)) return Falsedef find_best(original_tx, freq_tx, dict_corpa, results): for k, v in dict_corpa.items(): try_tx = k try_tx_freq = v containment = contains(try_tx, original_tx) if containment: start, end = containment results[.join(original_tx[start : end])] = try_tx_freq return OrderedDict(sorted(results.items(), key=lambda t: t[1], reverse=True))def main(): parser = ArgumentParser(description=__doc__) parser.add_argument(-w, --wordlist, help=, required=True) parser.add_argument(-c, --corpa, help=, required=True) agrs = parser.parse_args() corpa_dict = order_worlist(agrs.corpa) with open(agrs.wordlist) as txs: for tx in txs: freq_tx = tx.rstrip().split('\t')[1] tx = tx.rstrip().split('\t')[0] find_best_dict = find_best(tx, freq_tx, corpa_dict, dict()) create_cominations(find_best_dict, tx) if __name__ == '__main__': main()
Improving Speeds of Tokenisation of large word list for distinct combinations
python;combinatorics;set
null
_cstheory.11711
For all words of fixed length L over a given alphabet, I am interested in a practical algorithm that can give me a subset of maximal cardinality such that the Hamming distance between any two words in the subset equals D. (The following variation is also of great interest: ... Hamming distance between any two words in the subset is at least D.)Is there a mathematical result about the cardinality of such sets, depending on the alphabet, the length L of the words, and the minimum distance D?Thank you very much.
Maximum subset of words with Hamming distance D
ds.algorithms;co.combinatorics;coding theory
In coding theory, the quantity you are looking for is called $A_q(n, d)$, where $n$ is the length of vectors, $d$ is the minimum distance between them, and $q$ is the alphabet size (omitted when $q=2$). Characterizing $A_q(n,d)$ is a challenging open problem (with many basic questions remaining unanswered) but various asymptotic and non-asymptotic upper and lower bounds are known. See Chapter 17 of the book The Theory of Error-Correcting Codes by MacWilliams and Sloane for a summary of the most important ones.
_webmaster.17455
We are in 2011, search engines are now using hundreds or thousands of parameters to weight a page. The URL is only one of them, is it still so much of an impact in the search results? People are sharing URLs through URL shortener: short, long, ugly or nice URLs end up in the same way! People also share email by clicking on 'I like this', they don't copy paste URLs anymore, and when I do it and see people doing it, they never comment if an URL is long or short or anything...Is there still a need of having nice URL both for the users and search engines? If my rank on the search engine will change by 0.5% I don't really care... If I will make 2% of my user happy by having nice URLs I don't really care either...
When is it worth it to make my URLs pretty?
url rewriting;seo
null
_webapps.15149
I have a regular gmail account and a custom domain'd gmail account.I want to use Gmail's Check mail using POP3 function to retrieve the latter into my regular [email protected] but I cant get past this popup. It either says it had a problem connecting to pop.gmail.com or mail.customdomain.com timed out.One last note: I do not want to forward emails from one account to another.
Receive mail into Gmail from custom domain Google Apps
gmail;email;pop3
For gmail, the port should be 995 not 110.Also you have to make sure that pop is enabled on the account.However, as mjrider says, forwarding is much faster and it should cause any problems with conversation flow, providing you don't log into the secondary account directly and send emails from there (since these replies won't appear in your main account).I use both forwarding and pop access, but the latter is only for is an old account which I can't forward.
_unix.227410
I had the zsh scriptprintf '%s\0' www/scripts6/lib/* | xargs -0 -I{} -P 50 babel {} > {}and it worked (i think.). But I needed to actually copy the files to the scripts directory instead of scripts6. Also, I needed to add an extra path to the list of paths manually, so I tried doing this:paths=$(printf '%s\0' www/scripts6/lib/* | sed -e 's@www/scripts6/@@g')paths=$paths'main.js'$'\0'echo -n $paths | xargs -0 -I {} -P 50 babel www/scripts6/{} > www/scripts/{}That was a BIG ACCOMPLISHMENT for me. Anyway, the script makes the file named {} in the scripts directory (and nothing in the scripts/lib directory). This leads me to believe that only the first {} in the code gets replaced by the argument, and not the second one (and I have no explanation for the absence of files in the scripts/lib directory).How can I make the script work as expected?
zsh capture and pipe output to another command
zsh;xargs
Redirection happens before xargs executes. so your first example also creates a file named {}, because xargs never got the chance to replace the last {}.Also, while you do try to separate the filenames by nulls to treat filenames correctly, the effort is in vain once you use echo. echo in zsh interprets the C-style escapes(\t, \n, etc) by default. You would need the -E option to disable that.Try this and see if it does what you wantsetopt monitorfor f in www/scripts6/lib/*(e*'REPLY=${REPLY#www/scripts6/}'*) main.js; do; while (( $#jobstates >= 51 )); do sleep 1 done echo -E babel $f \> www/scripts/$f &doneIf the output seems ok, remove the echo -E and replace \> with >
_webmaster.104993
If I want my website to be crawled, do I need an empty disallow?Is there any difference betweenUser-agent: *Disallow:Disallow: /folder/and User-agent: *Disallow: /folder/I have seen a robots.txt where the first option is used but I dont understand why.
To allow crawling of all but a specific folder, do I need to include an empty disallow directive in robots.txt?
robots.txt
null
_reverseengineering.5945
I'm planning to buy my first mechanical keyboard, a KBT Poker II, and apart from the physical characteristics of it, another thing that caught my attention is that it sports reflashable firmware! Reversing and hacking on the firmware would be a fun personal project. (Unfortunately, the flasher is windows-only... I'm not sure how to deal with that, but that's another question.)Sadly though, when I tried poking around with the firmware files I couldn't make sense of it--I tried running a few Thumb disassemblers (as well as hacking up my own to learn more about Thumb) on parts of it that would seem to contain code (upon hexdump inspection), but they all came up with garbage instruction as far as a I could tell--certainly no function prologues/epilogues, and a lot of crazy immediates all over the place as well as absurd amounts of shifts and LDMs.Some technical information on the hardware inside the keyboard: it's built around a Nuvoton NUC122SC1AN, which features a Cortex-M0 CPU. The firmware files in question are supplied in an attachment to this forum post (by the keyboard manufacturer).What I have found, however, is the interrupt table located at $0000--its length exactly matches that of the one documented on ARM's website, including IRQs 0..31. However, another oddity here is that they all point to interrupts in the high memory--$ffff_fff00 and such. This area isn't included in the memory map of the NUC122, and ARM's spec has it as reserved, but I'm guessing it might be mapped to some internal memory containing the chip-flashing-receiving code and such, and that the interrupts either trampoline to user (firmware) code or the table gets overwritten with interrupt handlers supplied by the firmware. Anyway, I'd probably be able to figure that out once I have some code to look at.I've tried binwalking the files, and it came up empty for all of them.To be clear, what I'm looking for in an answer here is guidance to where I find the actual executable code in one of the firmware files above (supplied by the manufacturer itself, so there should be no legal isues here), because I'm really not getting it. I should add that I'm relatively new to the world of reversing. Thanks!
Finding the actual Thumb code in firmware
disassembly;binary analysis;firmware
I downloaded the archive you referenced and the first thing I noticed was that the firmware files are very heavy in the 0x80 - 0xff range. Inverting each byte resulted in a much nicer byte distribution and looked like it had some structure but still not quite right. I assume that since they went as far as inverting the bytes, they might have done some bit-manipulation such as XOR.Since this file is a firmware update, there is usually a header or a footer. It looks like there is a header of offsets or something, but nothing made sense. Scrolling further through the file, around byte 35000, there appears to be a block of structured data, followed by a block of 0xff and then a 16-byte footer:003F1F0: 84 95 74 64 B4 63 13 14 00 00 00 00 3C DC C5 6C ..td.c......<...The first 8 bytes look like a good place to start. Going through a few common XOR strategies resulted in nothing. Then I noticed that these bytes have a low nibble of 3, 4 or 5 which would place them in the printable ASCII range. So swap the nibbles of each byte (aka rotate left 4 bits) ... :003F1F0: 48 59 47 46 4B 36 31 41 00 00 00 00 C3 CD 5C C6 HYGFK61A........Bingo! Since the firmware updater window title is HY USB Firmware Downloader, I think this is a winner. Loading the resulting file into IDA, Cortex M-0 Thumb 2 settings, and sure enough, we have valid code starting at offset 0x0120 and ASCII string block at offset 0x32121.Summary: Decode the .bin files by processing each byte as:rotate left 4 bits and invert: c = (((c & 0x0f) << 4) | ((c & 0xf0) >> 4)) ^ 0xff
_cstheory.25302
Shamir's secret sharing scheme is a well known way to convert a secret into a polynomial and distribute points in this polynomial. Some of these points can then be regrouped to reconstruct the original polynomial and subsequently the secret.The regrouping process can be summarized as finding $p(0)$ in a polynomial knowing only the degree and pairs $(x_i, y_i)$ such that $p(x_i) = y_i$.My question is: how do I do this efficiently? All implementations I've seen so far are $O(n^2)$ because they recompute the polynomial using Lagrange, with a few optimizations. Are there known faster ways?
Efficient Shamir secret sharing reconstruction
cr.crypto security;time complexity;polynomials
null
_unix.66537
I'd like to know how many binary and source packages Red Hat provides with their current RHEL 6.4 Release.
How many packages does RHEL 6 provide?
rhel
For the record, there is no easy way to get the number of packages in RHEL. As Nils and vonbrand pointed out, it is important to say, that it does not say anything about the distribution and that there are a lot of additional channels/repos in RHEL.Nevertheless, to answer the orignal question, this is what I came up with (run on a RHEL 6.4 system):Binary packages:yum list | egrep (rhel-x86_64-server-6|RedHatEnterpriseLinux) | wc -l--> 3742 packagesSource packages: wget -q -O - http://ftp.redhat.com/pub/redhat/linux/enterprise/6Server/en/os/SRPMS/ | grep 'src.rpm' | perl -p -e 's,.*href=([a-zA-Z0-9-_.+]+?)-[0-9].*.*,$1,' | sort -u | wc -l--> 2187 packages
_codereview.64102
I'm building an iOS app for test-taking and I want to be sure of my model before proceeding. I found this post very helpful and tried to implement a simplified version for Core Data. Here are some of my assumptions: Each User can take multiple testsEach User has one set of answers per Test taken Each Test has one UserEach Question has many answers Here is my Core Data model:Overall, what do you think of my database schema? Is it sufficient to handle a simple test-taking app? Also, are Test_Questions and User_Answers necessary? I could, in theory, have a relationship directly between Test andQuestion? Test -->> Question. I would like to know which is better. Here are my model headers for Test_Questions and User_Answers:Test_Questions.h@class Question, Test;@interface Test_Questions : NSManagedObject@property (nonatomic, retain) Test *test;@property (nonatomic, retain) NSSet *questions;@end@interface Test_Questions (CoreDataGeneratedAccessors)- (void)addQuestionsObject:(Question *)value;- (void)removeQuestionsObject:(Question *)value;- (void)addQuestions:(NSSet *)values;- (void)removeQuestions:(NSSet *)values;@endUser_Answers.h@class Answer, User;@interface User_Answers : NSManagedObject@property (nonatomic, retain) User *user;@property (nonatomic, retain) NSSet *userAnswersSet;@end@interface User_Answers (CoreDataGeneratedAccessors)- (void)addUserAnswersSetObject:(Answer *)value;- (void)removeUserAnswersSetObject:(Answer *)value;- (void)addUserAnswersSet:(NSSet *)values;- (void)removeUserAnswersSet:(NSSet *)values;@end
Core Data model for test-taking iOS app
objective c;database;ios;core data
null
_unix.276461
I just came back to my recently installed (overnight last night, just started using it today) openSUSE installation to find it frozen on the lock screen. After various attempts to get it to unfreeze I pressed ctrl + alt + f1, booted into bash and ran startx, only to find the following error message:To make matters worse, after running the startx command for the second time, the system won't even return to the Linux prompt. Anyone got any idea what's going on and how to fix it?Update: managed to get back to Linux prompt with Ctrl + Alt + F3...Update: trying to run Xorg separately and attempting to check the Xorg logs doesn't help either:Update: after running rcxdm stop command to restart the KDE and xserver instances, the machine shows the following error:Additional error screenAnd will not accept any command-line input at all.
openSUSE frozen on login screen, refuses to return to GUI
linux;bash;kde;opensuse;startx
Finally got the system working again by pressing Ctrl + Alt + F3 one more time, which got me back to the root terminal. From there I ran startx again; this time KDE started and I'm now back into my system (minus all cached information, everything I was working on, and for some odd reason the sound drivers...).
_unix.88265
One of the first things I heard about Linux is that it doesn't get any kind of malware. Now, I see it can get malware through WINE and e-mail (although I don't even open attachments or follow links from entities I don't know). So, as far as this goes, one simply should use common sense regarding e-mail, and chose carefully what to run on WINE (and possibly use a separate account for it).Linux is further protected by the fact that all files are set to not be executable, so even if you get malware, it can't execute. This is what I used to think, but it turns out that in KDE and Gnome environments (according to what I read; it's from 2009, so I don't know if it also happens elsewhere or if it was fixed) have special treatment for something called launchers, that can only have one command, but this may run a malicious script.I'd like to know exactly why (if) launchers get special treatment (today and in 2009), how do they look on the terminal (do they seem normal files; what happens if you enter ls -l, etc.), and if this has received any attention from the developers of these platforms.
Has the launcher security issue in KDE and Gnome been fixed?
linux;security;gnome;kde
I'm not sure what you mean by Lanuchers, but from your description you seem to refer to .desktop files, also called desktop entries, which is a freedesktop.org standard.There are just simple text files with the extension .desktop that have a special INI-like format. It is true that desktop entries are Executables in the sense that they will run something if a user clicks on them. It is hard for desktop entries to masquerade as other types of files - even though they can display any icon available on the system, their full file name extension is always visible when shown as a file.I don't really see a lot of abuse for these - because users are not normally allowed to change the system, you can't just have a desktop entry execute rm / -rf. Some (probably) possible scenarios:get a user to download (or save an email attachment) a desktop entry that does calls the user's graphical sudo with a destructive system command (such as rm / -rf) - this can't possibly fool even the simplest of users, as it shows a big scary dialog that requires the user to type in their password and usually shows very clearly what will happen if they do this. This is not MS-Windows UAC, in Linux system operations are scary because people are not expected to do them every day.get a user to download a malicious program and also, in addition, a desktop entry file that includes a command to execute the malicious software - this indeed has the potential to destroy user data, but it can't infect other parts of the system or other users, so once you recover from your stupidity using your latest backup, you should be good to go.Also - please note that all such exploits require users to download something to their hard drives, locate it in their Download directory and double click it. I believe it is hard to claim that a user can do this by mistake, so I would not consider support desktop entries to be a security issue, and I expect other developers to have the same opinion.
_webapps.18961
I'm part of an organization on Trello, and would like to remove myself. How do I do so?(This is a frequently asked question being posted by a member of the Trello team.)
How can I remove myself from a Trello organization?
trello
Suppose you'd joined the Twilight Fan Club organization on Trello ... but later decide that you don't actually like Twilight all that much, and would like to leave the organization.Go to the organization page (https://trello.com/twilight)Find your avatar in the list of membersClick on your avatar, and bring up this menu:... and then click Remove from OrganizationNote: Roughly the same process can be followed to remove yourself from a board.
_unix.146370
I accidentally used sgdisk -R=/dev/sdb /dev/sda instead of sgdisk -R=/dev/sda /dev/sdb after replacing a broken drive in a raid. Can I recover from this or is all data lost now?
how to reverse the effect of sgdisk -R=/dev/sdb /dev/sda?
raid;gpt
null
_scicomp.5602
I'm trying to solve a system non linear-equations:$$\frac{\partial K(\mathbf{\lambda})}{\partial \lambda_i} - c_i = 0$$for $i = 1, \dots, 15$, using Newton's method:$$\lambda^{k + 1} = \lambda^k + p^{k+1}$$$$p^{k+1} = - J(\lambda_k)^{-1} \big (\nabla_\lambda K(\lambda_k) - \mathbf{c}\big ).$$I know that the Jacobian has to be positive definite in my problem, but in practice it is often quite bad conditioned ( $k(J) \approx 10^{15}$ ). I am perturbing it's eigenvalues but still the algorithm doesn't manage to satisfy the convergence criterion:$$\bigg |\frac{\partial K(\mathbf{\lambda})}{\partial \lambda_i} - c_i \bigg |= 0$$for some of the equations, while others converge quite rapidly. Increasing the number of iterations doesn't change anything.My supervisor suggested me to use a blocked scheme where, if some of the equations have converged you keep iterating on the equations that have not. I don't quite understand how to use Newton's algorithm on a subgroup of equations so I would like to ask if somebody knows how this can be done. Alternatively I would appreciate suggestions on how to deal with this problem.Thanks!EDIT:I must add that I'm using line search with objective function:$$f(\lambda) = K(\mathbf{\lambda}) - \mathbf{\lambda}^T \mathbf{c}$$which should be fine because it is convex (in theory though because the Hessian is almost singular). I'm checking whether the step is decreasing the objective enough, that is I check:$$f(\lambda^k + \alpha p^k) < f(\lambda^k) + \gamma \, \alpha \, (\nabla_\lambda K(\lambda_k) - \mathbf{c}\big )^T p^k $$with $\gamma = 10^{-4}$. If the condition is not true I divide $\alpha$ by 2. Most of the time the condition is true in the first step, so I rarely have to halve the step.EDIT 2It seems to be converging if I use a QR decomposition to solve the linear system, without perturbing the eigenvalues of $J$. Not sure whether I should trust the output though!
Non-linear root finding when the Jacobian is almost singular
nonlinear equations;condition number;newton method;roots
Assuming your jacobian isn't too large, it's a good idea to solve for your newton direction by QR factorization when your jacobian has a large condition number. It is numerically stable since it breaks the problem into two separate systems with the minimum error amplification factor allowed by the original problem. See here for details.This enables you to obtain the best possible approximation of the newton direction at each step in your algorithm. If you are using line-searching with backtracking and Armijo's sufficient decrease condition, this should guarantee convergence to the true root (assuming your function $f$ is smooth).
_webmaster.10865
How can I reliably test my site on all old versions of Internet Explorer ranging from IE6 all the way up to version IE11?
How can I test my site in IE6, IE7, IE8, IE9, IE10 and Internet Explorer 11
internet explorer;testing
Hitting F12 on IE8 it should start the Developer Tools that allows you to emulate IE7 (not IE6) using the Browser Mode.I suppose on IE9 you will be able to emulate back at least until IE7, but I'm only supposing because now it irritates me the simple idea to have to buy W7 in order to test this.UPDATE: as specified by Jeff Atwood: IE9 emulates back until IE7 too.UPDATE 2: as suggested by Nick in comments below, if you want to be 100% sure to emulate the old IE browsers you can use VMs provided by Microsoft (incredibly they are also provided for free). As a side note, keep in mind that testing on VMs is more time consuming than using IE Developer Tools, IMHO VMs testing might be worth when testing something that's JS/CSS greedy like a web app or a complex website, not for simple sites that use jQuery and some CSS.
_unix.86700
When preparing for the Red Hat Certified Engineer certification examination, I came across this quote in my study notes about the sudo command.By default, the policy is maintained as a flat text file, /etc/sudoers(although other, possibly remote, backend databases are also supported).I have never heard of this piece of information until recently and a quick Google search does not turn up anything useful with regards to this.Is this particular quote accurate? If so, how do I make the appropriate changes to configure sudo to use an alternative(presumably centralized) database for its policies?
What alternative backends does sudo support and how is it configured?
linux;rhel;sudo
null
_softwareengineering.230826
In a hypothetical economy there are currency units that can represent thousands of different values. So, for example there might be coins worth 1c, 3c, 5c, 7c, 7.5c, 80c, 8001.5c etc.Given a list of all of the possible denominations and an arbitrary value how would one return a list of coins representing the smallest number of coins needed to match that value.For bonus points, imagine that you have arbitrary finite quantities of each currency. So you may have only two 3c coins but thirty 18c coins.Sounds like a nightmare compsci class problem but it's something I ran into recently on a personal project of mine.The economy is a barter economy (tf2) in which every type of item has a distinct value relative to other items. I have an Item class where items have a Value attribute and this attribute is a double that represents the value of the item relative to a base item which has a value of 1. I'm trying to come up with a way so that if someone makes an offer of a value of 30 I can then look through a list of around 1200 item objects and find the smallest set of objects which combine in value to match 30.I cannot think of a remotely efficient way to do this, but I figured the problem was interesting enough that someone would like to ponder over it with me. My program is in c# but even a psuedocode brainstorm would be helpful.
Least Change Problem with Thousands of Denominations
c#;algorithms;efficiency
Mostly you have to do it the hard way in trying every combination, but if you sort the list first, there's a lot of pruning you can do.First of all, the greedy algorithm on the Change-making problem wikipedia page (choosing the largest denomination not greater than the total amount remaining) is fairly efficient with the right data structures, and will often, but not always, give you the optimal answer. Even when the answer is not optimal, it will usually be close, and is therefore useful as a first step for pruning.Say the greedy algorithm gives an answer of four items. You now only have to check combinations of three or fewer items.The other pruning you can do is on the item values. If your total is 30, you know you don't have to test any combinations containing items valued 31 or more. If your first selection has value 20, you know your second selection must have a value less than or equal to 10. Again, this pruning is fairly efficient on a sorted list with the right data structures.This problem is also a good candidate for memoization, where you store intermediate results rather than recalculating them on every iteration.Also, the order you perform the search makes a big difference. If you start with the largest items first, you can prune a lot of paths more quickly. No need to cycle through all combinations of $1 items first.So while at first glance the problem seems intractable, if you're smart about the order you go in and do some pruning, you should be able to find answers in a reasonable amount of time in practice. At the very worst, you might have to cut off the calculation after a certain time period, but if you order it correctly, you will have a solution that is close to optimal even if you haven't had enough time to prove it is definitely optimal. For the purposes of a game trade, that might be good enough.
_unix.75797
I feel a little silly having to ask this, but: In Solaris you can issue a passwd -sa command which gives you (more or less) the same output as passwd -S userName does, except it prints out the status information for all users it finds in /etc/passwd. What is the equivalent GNU/Linux command? I'm trying to put together simple instructions for someone else to baseline a server, and part of that is them identifying the password aging configured on all accounts. I can for loop over cut -f1 -d: /etc/passwd but I was hoping there was a simple command I could give him.
Equivalent of passwd -sa in RHEL?
linux;rhel;password
null
_unix.129491
I'm having issue similar to this:How to copy files as Jenkins post build action if i don't have privileges to destination directoryI'm willing to move/copy/rsync files from jenkins workspace to/var/www/app with rights setted toapache:apacheI've added jenkins to group apache, but the instance of jenkins cannot copy files to /var/www/app.I've also tried with setting privileges of /var/www/app to apache:jenkins but still, Jenkins keep spitting out error: Permission denied or Operation not permittedPS: Forgot to add OS is centOS ;)EDIT 1: This is log from jenkins script runnig:[workspace] $ /bin/sh -xe /tmp/hudson1379987233097some_more_numbers.sh + sh /path_to_sh_script/script.sh sending incremental file list application/ rsync: failed to set permissions on /var/www/app/application: Operation not permitted (1)And this is the script itself :)#!/bin/bash rsync -avzh /path/to/jenkins/jobs/app/workspace/default/application /var/www/app ;rsync -avzh /path/to/jenkins/jobs/app/workspace/default/library /var/www/app ; rsync -avzh /path/to/jenkins/jobs/app/workspace/default/public /var/www/app ;
Privileges for jenkins at apache's folder
permissions;apache httpd;group;privileges;jenkins
After a long and fruitful discussion in the comments, and following this link the user managed to solve the problem adding--no-perms --omit-dir-timesto the rsync options.Preliminary attempts to solve the issue:I guess if security does not concern you for a short period of time, you can trychmod a+rwx /var/www/app and then try to write to this directory. Note that if there are subdirectories you must do it recursively with:chmod --recursive a+rwx /var/www/app If it's successful, then you can start removing permissions gradually and this will help you pinpoint the problem. Verify that the user jenkins is already a group member of apache with groups apache
_unix.195643
Most documentations about LVM have roughly these steps:fdisk /dev/sdbpvcreate /dev/sdb1vgcreate fileserver /dev/sdb1lvcreate --name share --size 40G fileservermkfs.ext4 /dev/fileserver/shareIn some documentations I have seen as well that they did another fdisk between lvcreate and mkfs. And in another documentation I have seen that they left the first fdisk away as well. I tested now on one of my machines where I didn't do any fdisk at all and it works.My question is now is the fdisk needed at all on secondary (non boot) hard-disks? And why? And does the fdisk between lvcreate and mkfs give any advantage?
Is fdisk needed with lvm?
lvm;fdisk
You do not need to create a partition table on a disk (neither the traditional kind created with fdisk nor the GPT kind created with, e.g. gdisk), you could make the whole block device into an LVM PV if you wanted to. However, other tools or other operating systems might accidentally mistake that device for an unformatted hard disk and offer to format it, so it can be error-prone. Basically there is hardly any downside to creating a partition table with one big partition on it occupying the whole disk and it's a bit safer, so why not do it.If the disk is intended to be bootable then you will definitely require a partition table.As for creating an inner partition table on an LVM LV, that is unnecessary and very unusual. It is not expected that you would do this. The only exception would be if the LVM is expected to be presented to a virtual machine as a raw block device. In that case, the VM might expect to put a partition table on it.
_softwareengineering.118376
I'm wondering about functional or non-functional requirements. I have found lot of different definitions for those terms and I can't assign some of my requirement to proper category.I'm wondering about requirements that aren't connected with some action or have some additional conditions, for example:On the list of selected devices, device can be repeated.Database must contain at least 100 itemsCurrency of some value must be in USD dollar.Device must have a name and power consumption value in Watts.are those requirements functional or non-functional ?
Functional or non-functional requirement?
requirements
Functional requirements define what the system or application will do - specifically in the context of an external interaction (with a user, or with another system).When placing a new order, the system shall display the total cost and require confirmation from the user. That is a functional requirement; it describes a function of the system.Refer to Wikipedia: Functional Requirement for more details.Non-functional requirements are any requirements that don't describe the system's input/output behaviour. Note that we are still talking about requirements, not implementation details, so just because we're using the phrase non-functional doesn't mean that anything is fair game to put in that section.The most common types of non-functional requirements you'll see relate to system operation (availability, continuity, DR), performance (throughput, latency, storage capacity), and security (authentication, authorization, auditing, privacy).These are all cross-cutting concerns that impact every feature yet aren't really features themselves; they're more like feature metadata, helping describe not just whether the system does what it's supposed to but also how well it does it. Don't take that analogy too far, though - it's just an analogy.Non-functional requirements are not subjective or hand-wavey, contrary to what some people here seem to be suggesting. In fact, they should actually have a hard metric attached to them (i.e. response time of no more than 100 ms). NF requirements are also not implementation details or tasks like upgrade the ORM framework - no clue where anyone would get that idea.More details at Wikipedia: Non-Functional Requirement.To specifically address the examples in the question:On the list of selected devices, device can be repeated.Clearly a functional requirement. Describes what the system's output looks like.Database must contain at least 100 itemsSounds like a business rule, so also a functional requirement. However, it seems incomplete. What is the reason for this rule? What will happen/should happen if the database contains fewer than 100 items?Currency of some value must be in USD dollar.Functional requirement, but not really a properly-stated one. A more useful wording would be: The system shall support one currency (USD). Obviously this would be amended if more than one currency needed to be supported, and then the requirement would have to include information about currency conversions and so on.Device must have a name and power consumption value in Watts.Not really any kind of requirement, this is more like a technical specification. A functional requirement would be stated as the power rating is assumed to be in Watts. If there's more than one UOM, then as with the currency, the functional requirements should have sections about unit conversions, where/how they are configured, etc. (if applicable).
_softwareengineering.48189
There is a basic website (homepage and 5 subpages) with static content, we want to add something like a slideshow of current offers with custom images that would change every month. We also want to include an image gallery with effects like Lightbox.The person who is going to add/modify/delete the images in the two new modules doesn't want to deal with FTP. According to your experience, should we install a CMS (Joomla/Drupal) for this or just create a our own basic image management system to upload/select/delete the images?
CMS vs homebrew system for implementing an image slideshow
architecture;development approach
Due to the simple nature of your site and the limited CMS-type needs, I would not implement a full CMS and just create a simple, upload/modify/delete page for the monthly offers.If you plan or expect more CMS-type activities to begin taking place in the future you might want to consider setting up a CMS though.Also consider that training the user. Your custom built offer-updater would most likely be much simpler for the end-user, less complexity. EditImplementing a full CMS would most likely take a good bit more time to setup raising the cost to your client/company.
_softwareengineering.313674
ContextPerhaps I'm just use to C-esque styled languages but having a sigil in front of a variable (e.g. $VAR) always strikes me as weird.QuestionWhy do some languages such as Perl and shell scripting have sigils in front of the variable names? I can see it making sense for older languages like Basic (1960s) where the interpreter might not be smart enough to know what type of variable we are referring to. Looking at C in the 1970s, we see that is all but gone. In the 1980s, shell and Perl appeared and use the sigil notation yet Tcl, Erlang and others like C++ don't. In the 1990s, we see Python and Ruby not having sigils at all. Perhaps they do exist, but I haven't seen a recently developed programming language use sigils. I have, however, seen language do other stuff such as decorators from python @staticmethod that can look like sigils but is used in a different context.I don't code a lot in Perl but for bash, printf is a function and wrapped in a command substitution, $(printf ...) creates sprintf from C. With both of these options, I don't see gains of say using This ${magic}String over printf This %sString $magic especially when strings get really long. Similarly, ${#STR} is confusing, especially to newer programmers that don't know what that piece of code does, whereas len str is easier to read. Perhaps I'm just nitpicking over something that doesn't matter and everyone just accepts and moves on.
Why did languages such as shell scripting and perl use $ in front of variable names?
coding style;language design;language features
In the 1990s, we see Python and Ruby not having sigils at all.Ruby doesn't have sigils? Ruby is the king of sigils!$ is a global or pseudo-global variable,@ is an instance variable,@@ is a class hierarchy variable, and(not technically a sigil, but similar in spirit) an uppercase letter is a constant variable.And in the two cases where there isn't a sigil, there is an ambiguity between variables and methods:foois that a method call or a variable? Ruby says: both! If it has parsed (not executed) an assignment before, it assumes, it's local variable, otherwise it assumes, it's a method call. So:foo # method callif false foo = 42 # it doesn't matter that this isn't executed, only parsedendfoo # local variable# => nil# un-initialized local variables evaluate to nilOkay, and what if I want to call a method named foo now? Well, I need to make it clear to Ruby that I intend to call a method:foo() # pass an argument list, only methods can take argumentsself.foo # provide an explicit receiver, however doesn't work for private methodsThis poses another problem: if I have a function assigned to a variable, how do I call that function? I can't do it with foo(), because that calls a method named foo, I have to say foo.().For constants, the situation is similar. Foo is always interpreted as a constant, in order to treat it as a method call, you have to say Foo() or self.Foo.In Python, this ambiguity is resolved by always requiring an explicit receiver for anything which isn't a variable, and always requiring parentheses for calls. So, a local variable is always foo, a method call is always self.foo(), and calling a function stored in a local variable is always foo(). An instance variable is always self.foo.ECMAScript solves it by having a single namespace for functions and variables, so that it is impossible to have both a function and a variable named foo:let foo = 42;function foo() {};// TypeError: Identifier 'foo' has already been declared
_cogsci.10695
Is there any website or journal that publishes most significant recent studies and articles in psychology? I have access to EBSCO database, but there are thousands of articles and most of them of almost no importancy and I have no idea how to find those good and important ones.
Where to find recent most important studies and researches?
study cognitive sciences
By definition all journals publish recent studies because they are publishing all the time (either on a monthly/qaurterly basis). Sometimes, journals publish articles online months before in print. However i think your question is about finding the best articles, rather than journals, and there are a few tricks.If you have access to any good search engine (google scholar, web of science, scopus), you can perform searches in there, and then rank articles by number of citations. This will give you the most important and talked about studies, although by nature they will be quite old studies, since in order to be the most cited they have to be out for a while. Another good trick is to use webofscience / webofknowledge feature which lets you look at articles that have cited a specific paper. Say you find a classic study that you want to find more recent research on, webofknowledge will let you find recent studies that have cited that paper. Alternatively a good place to start is looking through review articles or textbooks first. You can find these by adding review to your search terms, e.g. (Social learning AND animals AND review).Finally, looking at the web pages of important researchers in a given field would be a good place to find recent research, usually they will have fairly up to date lists of their recent research If you've done a bit of reading then you should be able to identify key researchers in a given field.
_unix.244972
This is a simple question:Is there anyone out there who has installed any Linux distro on a HP Omen 15 laptop and have it work to satisfaction. I couldn't find it amongst the certified units on Ubuntu's website and am therefore a bit worried.
HP Omen 15 and Linux
linux;distribution choice;distributions
the latest 64 bit Puppy works great for me, but only as a dual-boot to Windows, since the Nvidia drivers for it suck and no keyboard/fan control. Should note that controls set up in Windows stick after booting to Linux, though. Battery life is top shelf, speed beats the pants off of Windows. The only real downside is the touchscreen is FUBAR on Puppy. May as well forget it's there. For productivity/writing/etc, it's amazing, but don't try to use it for gaming. If you want to game on this thing, dual boot Win7/8/10. As a refreshing side note, the issue with constant crashes on the Intel GPU doesn't happen on Puppy. I use it for work and pretty much only boot Win10 for games.
_cs.19474
I'm trying to organise a large reunion though facebook. Over the years we've all drifted apart, and so there isn't anyone who is still facebook friends with everyone.You need to be facebook friends to invite someone to the facebook event and I have invited all the people that I can. I also know that each of the uninvited people has at least one friend amongst the invited people, and by checking for 'mutual friends' I can know who they are.In order to get everyone invited to the reunion I'm going to ask some of the invited people to invite the uninvited people.My question is, does anyone happen to know an algorithm to find the minimum number of invited people that are required to message all of the uninvited people? I don't need anything super detailed, just something to point me in the right direction.
Minimum number of people required to invite everyone to a reunion
algorithms
null
_unix.37355
I have a media server with a folder called Series. (/media/Expansion2/Series/)In it, I have (surprise!) TV series. These are just the show names, e.g., /media/Expansion2/Series/The Big Bang Theory/Inside each show's folder (and this is where the problem lies) I have season folders. I currently have a mixture of the following 2 conventions (along with a few more, probably):/media/Expansion2/Series/The Big Bang Theory/The Big Bang Theory Season 1/media/Expansion2/Series/The Big Bang Theory/Season 2In the end, I want to rename all folders to just Season #.As a regex, I would probably say something like s/.*(Season \d)/$1Only applicable to folders, not files. I should probably also mention that this is for about 50+ show sub folders, so it needs to start at the /media/Expansion2/Series/ level and look into each series :)
Recursively rename subdirectories that match a regex
shell;directory;regular expression;rename
On Debian and derivatives (including Ubuntu):find /media/Expansion2/Series/ -type d -exec rename -n 's/.*(Season \d)/$1/' {} ;The rename command is part of the Perl package. It is not provided by other distributions, they instead provide the standard Linux rename command which is not useful here.If rename -n (-not really) displays what it wants to do, and it's all right for you, omit the -n and make it happen.
_webmaster.74109
There is a competitor whose domain name is like this restaurantsinchicago.com and when I search at Google Restaurants in Chicago the first result is that site and it appears at the right side where Google Business are shown as Restaurants in Chicago with his image because he named his company with that name also in Google My Business this obviously has great advantage over the other competitors. My question is if you can name your business in Google My Business in such way because your domain name is also named like that?
Can you name your business in Google My Business as a search query term if your domain name is also named like that?
seo;google;google places
No, you are categorically not allowed to title your business name on Google My Business (formerly Google Places and Google Local Business) with anything other than your physical registered business name even if your domain name is something different.Google's quality guidelines for local business confirm this:Your name should reflect your business real-world name, as used consistently on your storefront, website, stationery, and as known to customers.
_unix.241931
ConfigurationDebian Linux 8.2, 64bit, Xmonad 0.11When it startedI recently upgraded my system (to debian8), so I had to make some adjustments to my xmonad.hs configuration - namely changing managehooks for GStreamer'sgst-launch windows from:, title =? gst-launch-0.10 --> doFloatto:, title =? gst-launch-1.0 --> doFloatI'm using title instead of className because gst-launch-1.0 windows haveonly this properties:$ xprop_NET_WM_DESKTOP(CARDINAL) = 6WM_NAME(STRING) = gst-launch-1.0WM_STATE(WM_STATE): window state: Normal icon window: 0x0_MOTIF_WM_HINTS(_MOTIF_WM_HINTS) = 0x2, 0x0, 0x1, 0x0, 0x0WM_PROTOCOLS(ATOM): protocols WM_DELETE_WINDOWWhat it doesI'm encountering very strange behaviour, which I haven't seen with theold gst-launch-0.10 windows. When gst-launch-1.0 window (usually quitesmall - 400x300) starts it is one of following cases with decreasingprobability:adds the window as another tile (no floating at all) and stretches itscontent to fill this tile (keeping aspect ratio), the rest of the tile isblackadds the window as another tile (no floating at all) but draws only in thetop left corner of this tile (no stretching), the rest of the tile showsX-Window backgroundwith less than 10% probability it floats the window properlyWhat I've trieddoFullFloat and doCenterFloat do exactly the same thing (except it'scentered or full in the last case)What I suspectI'm pretty sure the problem is in using only WM_NAME/title instead ofWM_CLASS/className/appName, because the title can be changed during thelifetime of the window. I think the gst-launch-1.0 window starts with someother (or none) title and after some time it switches to gst-launch-1.0.Then it's only matter of luck if xmonad catches the original title or thefinal gst-launch-1.0.QuestionIs there some way to wait a while in manageHook so I could be sure to catchthe final window WM_NAME/title ?Or any other idea?Additional info:Apparently this has been fixed in gstreamer - https://bugzilla.gnome.org/show_bug.cgi?id=750455 - but unfortunately I need to use gstreamer which comes with debian.
How to float a window which has WM_NAME but no WM_CLASS
xmonad
null
_softwareengineering.142860
Say a company wants to keep development of new features of a piece of software internal, but wants to make the source code for previous versions public, up to and including existing public features, so that other people can benefit from using and modifying the software themselves, and even possibly contribute changes that can be applied to the development branch.Is there a term for this sort of arrangement, and what is the best way of accomplishing it using existing version control tools and platforms?
Is there a term for quasi-open source proprietary software?
open source;version control;terminology
I don't know the name but for implementation following setup might work: Create two repos on github (replace with any other platform doing the same), one public, one private. Keep latest version X in private one, and v.X-1 on public one. When releasing new version, update public one from private one. This way you will be able to easily use version control, and also allow users of public repo send you their contributions via pull requests, and then be able to merge it to you private repo, submit issues, etc. This also will give you the options to allow paid users to do the same for your private code - give them either read-only or even read-write access.
_codereview.106571
I was recently given a Sudoku Puzzle to solve, and since I began solving many Sudoku puzzles after, I decided to attempt to create a Sudoku Puzzle viewer with JavaFX. I am not done yet, but have decided to split it into parts so that it is easier to fix future problems. Part 1 is the Sudoku class. The Sudoku class does:Represents a legal (follows each row, column, and box may only contain each digit from 1-9 only once) Sudoku puzzleAllows to check and edit squares, as long as the puzzle stays legalCan get a random puzzle (may change to generate puzzle)The code is below:import java.io.BufferedReader;import java.io.File;import java.io.FileReader;import java.io.IOException;import java.util.Arrays;import java.util.Random;public class Sudoku { public static final int SUDOKU_SIZE = 9; public static final int SUDOKU_SQUARE_SIZE = 3; private static final int ROW_TEST = 0; private static final int COL_TEST = 1; private static final int SQ3_TEST = 2; private static final int NUM_OF_PUZZLES = 1; private final int[][] puzzle; private static final Random random = new Random(); /** * Creates a new Sudoku Puzzle from a 9x9 board. If array is larger than * 9x9, then it will ignore the elements out of range. Note that it will * still take puzzles that are unsolvable or solved, but will throw an * {@link java.lang.IllegalArgumentException IllegalArgumentException} if * the puzzle is illegal. The puzzle is illegal if it does not follow the * standard Sudoku rules: Each row, column, and box may only contain one of * each number from 1-9. * * @param board * the board to copy from */ public Sudoku(int[][] puzzle) { checkBoard(puzzle); this.puzzle = Arrays.copyOf(puzzle, SUDOKU_SIZE); for (int i = 0; i < SUDOKU_SIZE; i++) { this.puzzle[i] = Arrays.copyOf(puzzle[i], SUDOKU_SIZE); } } private void checkBoard(int[][] puzzle) { boolean[] alreadyHasNumber = new boolean[SUDOKU_SIZE]; for (int i = ROW_TEST; i <= SQ3_TEST; i++) { for (int j = 0; j < SUDOKU_SIZE; j++) { for (int k = 0; k < SUDOKU_SIZE; k++) { int num = getNumFromTest(puzzle, i, j, k); if (num != -1) { if (!alreadyHasNumber[num]) { alreadyHasNumber[num] = true; } else { throw new IllegalArgumentException( Puzzle is not legal.); } } } for (int k = 0; k < SUDOKU_SIZE; k++) { alreadyHasNumber[k] = false; } } } } private int getNumFromTest(int[][] puzzle, int testType, int i, int j) { switch (testType) { case ROW_TEST: return puzzle[i][j] - 1; case COL_TEST: return puzzle[j][i] - 1; case SQ3_TEST: return puzzle[(i / SUDOKU_SQUARE_SIZE) * SUDOKU_SQUARE_SIZE + j / SUDOKU_SQUARE_SIZE][i % SUDOKU_SQUARE_SIZE * SUDOKU_SQUARE_SIZE + j % SUDOKU_SQUARE_SIZE] - 1; default: return 0; } } /** * Returns the digit in the specified square, 0 if empty. * * Calling with arguments (0, 0) will get the digit on the top left corner, * and (8, 8) will point to the bottom right corner. (8, 0) will point to * the top right corner, while (0, 8) will point to the bottom left corner. * * Note that in (x, y), x is the column number and y is the row number. * * @param x * the column which the digit is to be taken from * @param y * the row which the digit is to be taken from * @throws IllegalArgumentException * if x or y is out of range * @return the digit in the specified square */ public int getDigit(int x, int y) { if (!isInRange(x) || !isInRange(y)) { throw new IllegalArgumentException( the given square is out of range); } return puzzle[y - 1][x - 1]; } /** * Sets the specified square's number to the specified digit. * * Calling with arguments (0, 0) will get the digit on the top left corner, * and (8, 8) will point to the bottom right corner. (8, 0) will point to * the top right corner, while (0, 8) will point to the bottom left corner. * * Note that in (x, y), x is the column number and y is the row number. * * This method will return <code>false</code> if the set is illegal. The set * is illegal if it changes the puzzle in a way that forces it to not follow * the standard Sudoku rules: Each row, column, and box may only contain * one of each number from 1-9. * * @param x * the column number of the square to set the digit * @param y * the row number of the square to set the digit * @param digit * the digit to set the square to * @throws IllegalArgumentException * if x or y is out of range * @return <code>true</code> if successful (legal set), <code>false</code> * otherwise. */ public boolean setDigit(int x, int y, int digit) { if (!isInRange(x) || !isInRange(y)) { throw new IllegalArgumentException( the given square is out of range); } if (getDigit(x, y) != digit) { if (digit < 1 || digit > SUDOKU_SIZE) { throw new IllegalArgumentException(digit is out of range); } // check row boolean[] alreadyHasNumber = new boolean[SUDOKU_SIZE]; alreadyHasNumber[digit - 1] = true; for (int i = 1; i <= SUDOKU_SIZE; i++) { if (i != x) { int num = getDigit(i, y) - 1; if (num != -1) { if (!alreadyHasNumber[num]) { alreadyHasNumber[num] = true; } else { return false; } } } } for (int i = 0; i < SUDOKU_SIZE; i++) { if (i != digit - 1) { alreadyHasNumber[i] = false; } } // check column for (int i = 1; i <= SUDOKU_SIZE; i++) { if (i != y) { int num = getDigit(x, i) - 1; if (num != -1) { if (!alreadyHasNumber[num]) { alreadyHasNumber[num] = true; } else { return false; } } } } for (int i = 0; i < SUDOKU_SIZE; i++) { if (i != digit - 1) { alreadyHasNumber[i] = false; } } // check box for (int i = 0, j = (x - 1) - ((x - 1) % SUDOKU_SQUARE_SIZE), k = (y - 1) - ((y - 1) % SUDOKU_SQUARE_SIZE); i < SUDOKU_SIZE; i++) { int tempX = j + i % SUDOKU_SQUARE_SIZE; int tempY = k + i / SUDOKU_SQUARE_SIZE; if (tempX != x - 1 && tempY != y - 1) { int num = puzzle[tempY][tempX] - 1; if (num != -1) { if (!alreadyHasNumber[num]) { alreadyHasNumber[num] = true; } else { return false; } } } } } return true; } public static Sudoku getRandomPuzzle() { return new Sudoku(readFile(random.nextInt(NUM_OF_PUZZLES) + 1)); } private static int[][] readFile(int puzzleNum) { // TODO File file = new File(puzzle + puzzleNum); int[][] result = new int[Sudoku.SUDOKU_SIZE][Sudoku.SUDOKU_SIZE]; try (BufferedReader reader = new BufferedReader(new FileReader(file))) { for (int i = 0; i < Sudoku.SUDOKU_SIZE; i++) { String[] line = reader.readLine().split( ); for (int j = 0; j < Sudoku.SUDOKU_SIZE; j++) { result[i][j] = Integer.parseInt(line[j]); } } } catch (IOException e) { e.printStackTrace(); } return result; } private boolean isInRange(int i) { return i > 0 && i <= SUDOKU_SIZE; }}Some concerns:In the setDigit() and checkBoard() class, there is a boolean array alreadyHasNum. After each loop, should this array reset, or should I create a new one?Does the logic make sense? (As in, does the way I handle row/column numbers and board checking make sense)Anything else?
Sudoku Puzzle Part 1: Sudoku Class
java;sudoku;javafx
A few things right off the top.If you have any ambitions about discovering solutions to the puzzles, then you should first read Knuth's Dancing Links paper and Norvig's sudoku essay.private int getNumFromTest(int[][] puzzle, int testType, int i, int j) { switch (testType) { case ROW_TEST: return puzzle[i][j] - 1; case COL_TEST: return puzzle[j][i] - 1; case SQ3_TEST: return puzzle[(i / SUDOKU_SQUARE_SIZE) * SUDOKU_SQUARE_SIZE + j / SUDOKU_SQUARE_SIZE][i % SUDOKU_SQUARE_SIZE * SUDOKU_SQUARE_SIZE + j % SUDOKU_SQUARE_SIZE] - 1; default: return 0; }}Major code smell here -- you are using a switch to change behavior. That almost always means there is an underlying class that you haven't discovered yet. In this case, you have evidence of a constraint/specification interface that has three distinct implementations.for (int i = ROW_TEST; i <= SQ3_TEST; i++) Major symptom here - you are enumerating over indexes, not because you want an int, but because you want to get something else that the int lets you have (in this case, the constraint I mentioned earlier). This strongly implies that you should be reading from a collection - a Set if there is no particular order, a List if the order matters.private void checkBoard(int[][] puzzle) { boolean[] alreadyHasNumber = new boolean[SUDOKU_SIZE]; for (int i = ROW_TEST; i <= SQ3_TEST; i++) { for (int j = 0; j < SUDOKU_SIZE; j++) { for (int k = 0; k < SUDOKU_SIZE; k++) { int num = getNumFromTest(puzzle, i, j, k); if (num != -1) { if (!alreadyHasNumber[num]) { alreadyHasNumber[num] = true; } else { throw new IllegalArgumentException( Puzzle is not legal.); } } } for (int k = 0; k < SUDOKU_SIZE; k++) { alreadyHasNumber[k] = false; } } }}This code here is a mess, because you are writing about how to do it without writing out what you are trying to do first. So let's walk through it carefully; the rule you are trying to validate is that no number should appear more than once in any related grouping of cells. In particular, notice that the no duplicates part doesn't care which group of cells we're talking about -- there are always going to be nine cells in the group, and no number should appear more than once in the group.This suggests that there should be a function that takes a list of up to 9 numbers, and makes sure there is no duplication there, and also there's a thing that takes a 9x9 grid and gives you some nine cells in the same group. Actually, 27 things -- there are 9 that each know how to select a different row, 9 that know how to select a different column, 9 that know how to select a different square. So your validation check is really something likefor (Selector s : selectors) { CellValues cellValues = s.getCellValues(board); if ( ! noDuplicates.isSatisfiedBy(cellValues) ) { throw new IllegalArgumentException(...); }}More general notes// Convention: ALLCAPS for static data members unless you have a compelling// reason.private static final Random RANDOM = new Random();public static Sudoku getRandomPuzzle() { return new Sudoku(readFile(RANDOM.nextInt(NUM_OF_PUZZLES) + 1));}Really bad idea, because introducing random numbers in this way makes it very hard to construct a reliable test of this code. At a minimum, you want to separate the random number generation from how you use it, so that you can write a test without the randomness.public static Sudoku getRandomPuzzle() { return getPuzzle(RANDOM.nextInt(NUM_OF_PUZZLES));}public static Sudoku getPuzzle(int puzzleId) { return new Sudoku(readFile(puzzleId + 1));} Better still, allow somebody to pass you a Random -- there's no particular reason here that only your RNG should be used.public static Sudoku getRandomPuzzle() { return getPuzzle(RANDOM);}public static Sudoku getRandomPuzzle(Random random) { return getPuzzle(random.nextInt(NUM_OF_PUZZLES));}public static Sudoku getPuzzle(int puzzleId) { return new Sudoku(readFile(puzzleId + 1));} Of course, there's no particular reason that the source of the puzzle needs to be a File; there's room for an abstraction here of a puzzle Factory or Repository (or maybe both).
_cstheory.21882
Most dependent typed systems have a strict positivity conditions for inductive types. Does anybody know an example where violation of the condition leads to inconsistency in the system?
Example of where violation of strict positivity condition in inductive types leads to inconsistency
lo.logic;type theory;dependent type
It is actually possible to relax strict positivity and remain consistent. For instance, it suffices to only have a positivity condition. That is, we can accept type definitions like$$ T \triangleq \mu\alpha. (\alpha \to 2) \to 2$$where recursive type variables occur to the left of an even number of arrows and retain consistency.However, theories permitting this sort of inductive type do not have set-theoretic models -- you cannot interpret types as sets and terms as elements of sets. In this case, we are saying that $T$ is isomorphic to its double-powerset (i.e., $T \simeq \mathcal{P}(\mathcal{P}(T))$), and this violates Cantor's theorem. Since dependent type theories are often used to formalize mathematics, their designers are usually hesitant to add principles which are not compatible with a set-theoretic semantics, even if they are consistent.EDIT: I'm adding this edit in response to Andrej's question. The type $T$ is consistent if you add it to (say) Agda; there are no problems with it at all. We only have a problem if we combine non-strict positivity with excluded middle.The intuition for why is safe is (IMO) best seen through the lens of parametricity. In System F, we can show using parametricity that for any definable functor $F$, the type $\mu F \triangleq \forall \alpha.\; (F\alpha \to \alpha) \to \alpha$ is indeed an inductive type. Now, recall that a definable functor $F$ is a type operator $F : \ast \to \ast$, together with an operator $$\mathrm{map} : \forall \alpha,\beta.\;(\alpha \to \beta) \to F\;\alpha \to F\;\beta$$satisfying the functoriality conditions (i.e., $\mathrm{map}\;id = id$ and $\mathrm{map}\;f\;\circ \mathrm{map}\;g = \mathrm{map}\;(f \circ g$). Now, we can define a type operator for the double powerset$$C = \lambda \alpha.\; (\alpha \to 2) \to 2$$and because $\alpha$ occurs only positively, we can also define a map operator for it:$$map_C = \lambda f : \alpha \to \beta, a' : (\alpha \to 2) \to 2, k : \beta \to 2.\; a' \;(\lambda a:\alpha.\; k\;(f\;a))$$So we know that $T = \mu C$ is a legitimate inductive type.
_unix.333478
Reading about acl statement in bind's ARM found the following:localnets:Matches any host on an IPv4 or IPv6 network for which thesystem has an interface. When addresses are added or removed,the localnets ACL element is updated to reflect the changes.for which the system has an interface - sound like a nosense.I understand what network interface is, but don't understand aforementioned text.Could you please tell the meaning of the above quote, and what is the difference between localhost and localnets?Thanks
What is the difference between localhost and localnets in named configuration
dns;bind;bind9
I guess localhost refer to one IP address which is by default 127.0.0.1, but, localnet refer to every network that you have an IP address from it on interface on your machine.For example, if you have two interfaces and every one have its IP from different network so localnets can match all networks.eth0 ip 10.0.0.1 netmask 255.0.0.0eth1 ip 192.168.0.1 netmask 255.255.255.0So localnets match (10.0.0.0\8, 192.168.0.0\24).
_webapps.80734
I usually respond to email in Thunderbird, and there I know how to intersperse a response or comment within the message.How does one do that in Gmail (in the browser)?
How to intersperse responses within body of Gmail message?
gmail
Some of this will depend on your personal settings. Assuming yours are close to mine, here's one way to do what you want to do.Reply to the message (as normal)Click the button that looks like an ellipsis at the bottom of your reply pane.(If you hover your mouse it will tell you that it will Show trimmed content)This will expand the quoted text for you. Quoted text is indicated by a line on the left marginPlace your cursor in the spot where you want to break up the quote and hit Enter twice. This will form a break in the quoted text. Add whatever part of your reply you need to here.Repeat for each individual break in the quote where you want to write.Finish by cleaning up the other bits. You may want to remove your correspondent's signature, and perhaps the default heading above the quote. My signature is set to appear above the quoted text, so I generally move it if I do this.If, for some reason, part of the reply becomes unquoted, you can re-apply the quote format by selecting the text you want to change and using the Quote tool under Formatting options (or Ctrl-Shift-9).
_softwareengineering.114728
My t-sql teacher told us that naming our PK column Id is considered bad practice without any further explanations. Why is naming a table PK column Id is considered bad practice?
Why is naming a table's Primary Key column Id considered bad practice?
sql;naming;tsql
I'm going to come out and say it: It's not really a bad practice (and even if it is, its not that bad).You could make the argument (as Chad pointed out) that it can mask errors like in the following query:SELECT * FROM cars car JOIN manufacturer mfg ON mfg.Id = car.ManufacturerId JOIN models mod ON mod.Id = car.ModelId JOIN colors col ON mfg.Id = car.ColorIdbut this can easily be mitigated by not using tiny aliases for your table names:SELECT * FROM cars JOIN manufacturer ON manufacturer.Id = cars.ManufacturerId JOIN models ON models.Id = cars.ModelId JOIN colors ON manufacturer.Id = cars.ColorIdThe practice of ALWAYS using 3 letter abbreviations seems much worse to me than using the column name id. (Case in point: who would actually abbreviate the table name cars with the abbreviation car? What end does that serve?)The point is: be consistent. If your company uses Id and you commonly make the error above, then get in the habit of using full table names. If your company bans the Id column, take it in stride and use whatever naming convention they prefer.Focus on learning things that are ACTUALLY bad practices (such as multiple nested correlated sub queries) rather than mulling over issues like this. The issue of naming your columns ID is closer to being a matter of taste than it is to being a bad practice.A NOTE TO EDITORS : The error in this query is intentional and is being used to make a point. Please read the full answer before editing.
_softwareengineering.179982
I often encounter the following statements / arguments:Pure functional programming languages do not allow side effects (and are therefore of little use in practice because any useful program does have side effects, e.g. when it interacts with the external world).Pure functional programming languages do not allow to write a program that maintains state (which makes programming very awkward because in many application you do need state).I am not an expert in functional languages but here is what I have understood about these topics until now.Regarding point 1, you can interact with the environment in purely functional languages but you have to explicitly mark the code (functions) that introduces side effects (e.g. in Haskell by means of monadic types). Also, as far as I know computing by side effects (destructively updating data) should also be possible (using monadic types?) even though it is not the preferred way of working.Regarding point 2, as far as I know you can represent state by threading values through several computation steps (in Haskell, again, using monadic types) but I have no practical experience doing this and my understanding is rather vague.So, are the two statements above correct in any sense or are they just misconceptions about purely functional languages? If they are misconceptions, how did they come about?Could you write a (possibly small) code snippet illustrating the Haskell idiomatic way to (1) implement side effects and (2) implement a computation with state?
Misconceptions about purely functional languages?
functional programming;haskell
For the purposes of this answer I define purely functional language to mean a functional language in which functions are referentially transparent, i.e. calling the same function multiple times with the same arguments will always produce the same results. This is, I believe, the usual definition of a purely functional language.Pure functional programming languages do not allow side effects (and are therefore of little use in practice because any useful program does have side effects, e.g. when it interacts with the external world).The easiest way to achieve referential transparency would indeed be to disallow side effects and there are indeed languages in which that is the case (mostly domain specific ones). However it is certainly not the only way and most general purpose purely functional languages (Haskell, Clean, ...) do allow side effect.Also saying that a programming language without side effects is little use in practice isn't really fair I think - certainly not for domain specific languages, but even for general purpose languages, I'd imagine a language can be quite useful without providing side effects. Maybe not for console applications, but I think GUI applications can be nicely implemented without side-effects in, say, the functional reactive paradigm.Regarding point 1, you can interact with the environment in purely functional languages but you have to explicitly mark the code (functions) that introduces them (e.g. in Haskell by means of monadic types).That's a bit over simplifying it. Just having a system where side-effecting functions need to be marked as such (similar to const-correctness in C++, but with general side-effects) is not enough to ensure referential transparency. You need to ensure that a program can never call a function multiple times with the same arguments and get different results. You could either do that by making things like readLine be something that's not a function (that's what Haskell does with the IO monad) or you could make it impossible to call side-effecting functions multiple times with the same argument (that's what Clean does). In the latter case the compiler would ensure that every time you call a side-effecting function, you do so with a fresh argument, and it would reject any program where you pass the same argument to a side-effecting function twice.Pure functional programming languages do not allow to write a program that maintains state (which makes programming very awkward because in many application you do need state).Again, a purely functional language might very well disallow mutable state, but it's certainly possible to be pure and still have mutable state, if you implement it in the same way as I described with side-effects above. Really mutable state is just another form of side-effects.That said, functional programming languages definitely do discourage mutable state - pure ones especially so. And I don't think that that makes programming awkward - quite the opposite. Sometimes (but not all that often) mutable state can't be avoided without losing performance or clarity (which is why languages like Haskell do have facilities for mutable state), but most often it can.If they are misconceptions, how did they come about?I think many people simply read a function must produce the same result when called with the same arguments and conclude from that that it's not possible to implement something like readLine or code that maintains mutable state. So they're simply not aware of the cheats that purely functional languages can use to introduce these things without breaking referential transparency.Also mutable state is heavily discourages in functional languages, so it isn't all that much of a leap to assume it's not allowed at all in purely functional ones.Could you write a (possibly small) code snippet illustrating the Haskell idiomatic way to (1) implement side effects and (2) implement a computation with state?Here's an application in Pseudo-Haskell that asks the user for a name and greets him. Pseudo-Haskell is a language that I just invented, which has Haskell's IO system, but uses more conventional syntax, more descriptive function names and has no do-notation (as that would just distract from how exactly the IO monad works):greet(name) = print(Hello, ++ name ++ !)main = composeMonad(readLine, greet)The clue here is that readLine is a value of type IO<String> and composeMonad is a function that takes an argument of type IO<T> (for some type T) and another argument that is a function which takes an argument of type T and returns a value of type IO<U> (for some type U). print is a function that takes a string and returns a value of type IO<void>.A value of type IO<A> is a value that encodes a given action that produces a value of type A. composeMonad(m, f) produces a new IO value that encodes the action of m followed by the action of f(x), where x is the value produces by performing the action of m.Mutable state would look like this:counter = mutableVariable(0)increaseCounter(cnt) = setIncreasedValue(oldValue) = setValue(cnt, oldValue + 1) composeMonad(getValue(cnt), setIncreasedValue)printCounter(cnt) = composeMonad( getValue(cnt), print )main = composeVoidMonad( increaseCounter(counter), printCounter(counter) )Here mutableVariable is a function that takes value of any type T and produces a MutableVariable<T>. The function getValue takes MutableVariable and returns an IO<T> that produces its current value. setValue takes a MutableVariable<T> and a T and returns an IO<void> that sets the value. composeVoidMonad is the same as composeMonad except that the first argument is an IO that does not produce a sensible value and the second argument is another monad, not a function that returns a monad.In Haskell there's some syntactic sugar, that makes this whole ordeal less painful, but it's still obvious that mutable state is something that language doesn't really want you to do.
_codereview.59160
I just went through a very easy online example creating a Rock-Paper-Scissors game, but it seemed like it was not a great use of computing power.It seemed like I was writing out results for every possible outcome instead of declaring properties or attributes for variables that will dictate the results depending on the situation.Could an index or something be used to set up the variables?var rock = [rock, paper, scissors];var paper = [paper, scissors, rock];var scissors = [scissors, rock, paper]; index 0 1 2Player 1 could select a variable, then player 2 could select a string in the index, and the position of the selection in the index would determine the winner (0 = tie, 1 = p1Loss, 2 = p1Win). Is this possible?I think the code in the example below would start to get messy and bloated if you were to expand on the choices/options. i.e. Instead of 3 options you have 9, any one of which will beat 4 options and loose to the other 4.I guess I'm just wondering if there is a better way to do this that would scale better with larger numbers.I've included the code from the example below:var user1Choice = prompt(Do you choose rock, paper or scissors?);var user2Choice = prompt(Do you choose rock, paper or scissors?);var compare = function(choice1, choice2) { if (choice1 === choice2) { return its a tie; } else if (choice1 === rock) { if (choice2 === scissors) { return rock wins; } else { return paper wins; } } else if (choice1 === paper) { if (choice2 === rock) { return paper wins; } else { return scissors wins; } } else if (choice1 === scissors) { if (choice2 === paper) { return scissors wins; } else { return paper wins; } }}compare(user1Choice, user2Choice)
Index mechanics for Rock Paper Scissors
javascript;optimization;beginner;game;rock paper scissors
Your ideaYour idea is nice, but it will cause problems when extending the game. For example, we will add spock and lizard:var spock = [spock, paper, lizard, scissors, rock];Now, index 1 and 2 mean p1Loss, and index 3 and 4 mean p1Win. This can easily cause bugs in the future.Maybe a better ideaYou could instead maintain arrays that say what items beat. For example:var spockBeats = [scissor, rock];Then, check at the beginning if the input of the users is equal, return tie if it is. If it is not, find the appropriate array for user1 (I would use a switch instead of many if-else) and see if it contains the choice of user2.In this case, extending the game is easier. New item? Add a new array and a new switch option, and add the item to some of the other arrays.In case you really want to extend the game (I mean like adding a couple dozen or more options), this approach too would become somewhat annoying. In that case you might want to read up on graph theory, as this is basically just a directed graph. I think that an adjacency matrix might work well then.For rock, paper, scissor, the matrix would look like this (it contains duplicate information, but I don't think that memory is a concern and removing it would make it harder to use): R P SR 0 -1 1 P 1 0 -1S -1 1 0And you use it like this:Player1 plays paper, Player2 plays rock.Look in the paper row for the value under rock. it is 1 and player1 wins. -1 would mean they lose, and 0 means tie.For just rock, paper, scissors this is overkill, but for a lot more options this might work well.Comments on current codeI would save the strings (rock, paper, scissors) in fields at the top of the file. It's an easy source of bugs because of typosI would return which player won, not with what choice they won. Or both, but the current way seems just odd to me
_unix.145576
I'm on a mac (osx 10.9.3) running CentOS7 in virtualbox. I would like to access the website hosted on the virtual machine. Browsing to the Guest IP returns webpage not available.I'm able to ping and ssh to the VM.I've set bridged adapter for the network settings in the VM.I've given /etc/httpd/conf/httpd.conf Listen 80 and host IP address.telnet and curl to Guest IP returns connection refused.I'm guessing it's a firewall / iptables configuration problem where I need to allow the host. How do I configure CentOS firewall / iptables to allow host?
Unable to access website hosted on virtual machine
centos;iptables;virtualbox;firewall;webserver
null
_codereview.6210
I was hoping someone could provide some feedback with regards to this:import java.util.InputMismatchException;import java.util.Scanner;public class Bank { protected double myBalance = 10.40; protected double bankBalance = 1000000; protected double creditRating = 0.1; private static final int PIN = 1234; boolean access = false; protected Scanner s = new Scanner(System.in); public Bank() { int pin = 0000; int option; System.out.print(Please enter your 4 digit pin code: ); try { pin = s.nextInt(); } catch (InputMismatchException e) { System.out.print(Invalid character entered, bye bye...); } if (pin != PIN) { System.err.println(Incorrect PIN entered, please try again later.); System.exit(0); } access = true; System.out.println(Welcome to JCBank please choose from the following options); System.out.println(); System.out.println(Withdraw (1)\tDeposit (2)\tCheck Balance (3)\tApply for Loan(4) \tQuit (5)); System.out.println(); do { option = s.nextInt(); } while(!selectOption(option)); } public boolean selectOption(int option) { switch (option) { case 1: System.out.println(You would like to withdraw); System.out.println(); break; case 2: System.out.println(You would like to Deposit); System.out.println(); break; case 3: System.out.println(Your account balance is + myBalance); System.out.println(); break; case 4: System.out.println(Please wait whilst we perform a credit check.); try { checkCreditRating(); } catch (InterruptedException e) { System.out.println(How embarrassing, the system is currently unavailable. Try again later.); } System.out.println(); break; case 5: System.out.println(Successfully logged out, see you soon!); System.out.println(); return true; default: System.out.println(Invalid option, please choose another option.); System.out.println(); return false; } System.out.println(Please choose another option.); return false; } public void deposit(double amount) { myBalance += amount; } public void withdraw(double amount) { if (myBalance > amount) { System.out.println(Your funds have been successfully withdrawn.); } else { System.out.println(You don't have the funds to complete this transaction); } } public void checkCreditRating() throws InterruptedException { Thread.sleep(1000); if (creditRating <= 0.0) { System.err.println(Sorry, we can't lend you any money at this time.); return; } System.out.print(Please enter your loan amount: ); double amount = s.nextDouble(); if (amount > bankBalance) { System.err.println(We are unable to loan you such an amount.); } double amountToPayBack = (20/100)*amount; System.out.println(The amount to payback is + amountToPayBack); } public double checkAccountBalance() { return myBalance; }}
Bank transaction system
java;beginner;finance
null
_cstheory.19231
I only have a (very) introductory knowledge about the Hardness of Approximation and PCP theorem, and I am wondering if it has any specific implications (or can somehow be studied) with Zero Knowledge Proofs?
How are PCPs and ZKPs related?
pcp;zero knowledge;intuition
PCPs are very often used to construct ZKPs, especially for NP-complete languages. The idea is simple: you commit to every bit of PCP separately, and then the prover makes random queries to the PCP. Given the query and committed bit, you prove in ZK that the bits in concrete locations would make the prover to accept. Since the number of queries is small, the proof is relatively efficient.The main problem tends to be the computational complexity: generating a PCP for an arbitrary NP language is efficient only in theory, and thus people look for more efficient solution.A recent related paper, that does something in between is by Bitansky and others (TCC 2013) where they study linear PCPs and their relation to ZK. Since linear PCPs (see their paper) are less stringent than general PCPs, they can be constructed more efficiently.
_unix.180179
Often I want to skim through a document or piece of code, which I do with page down (Ctrl-D) and page up (Ctrl-U), but it feels like I am violating the spirit of Vim using emacs-like chords/control keys. Is there a non-control key method of skimming through a document?
Moving by page without chords in Vim
editors;cursor;vim
Ctrl-D, Ctrl-U, Ctrl-F, Ctrl-B are pretty standard for this, but there are a few other ways I've found useful:Ctrl-E and Ctrl-Y scroll one line down and one line up, respectively, without moving the cursor (unless it would be moved off the screen, of course). These are handy because they accept counts, i.e., 5Ctrl-E will Expose five more lines at the bottom of the screen.zz (lowercase!) scrolls the text to place the line the cursor is on in the center of your screen (or window in gvim)zt scrolls to place the current line at the top of your screenzb scrolls to place the current line at the bottom of your screenAnd H, M and L place the cursor respectively on the top, middle and bottom lines currently on the screen.This means that Lzt scrolls down one page (minus one line) and Hzb scrolls up one page (minus one line), while Lzz and Hzz mirror pretty closely the behavior of Ctrl-D and Ctrl-U.Although honestly, I usually just use Ctrl-D and Ctrl-U. :)
_cs.46975
I am looking up some material for my thesis in CS (development of a module to integrate a genetic algorithm in a system developed by other students).My actual current task is to make a comparative analysis of several libraries for genetic algorithms.After this comparison I will choose one of these libraries and an algorithm.I want to know if you can give me any tips or best practice to perform such comparison. Which approach to the task would you recommend?
Comparing different implementations of genetic algorithms
algorithm analysis;genetic algorithms;experimental analysis
null
_softwareengineering.345328
This is more about architecture question. I will be developing microservice in Lumen or Slim, it will not be accessible from the public. The private microservice will be dealing private stuff. Laravel backend will communicate with microservice via REST API (Private / Internal use only). Users will know nothing about microservice.If Frontend website (public) ever get hacked, it will minimise damage from accessing private stuff on the microservice.However I want users to use Public API to communicate from public Frontend which then execute requests to microservice. To me this seem to duplicated API Requests - One for Public, and other one for Private (Backend to Microservice)? Or is it nothing wrong with that design?
Is exposing a public API that calls a private API a good practice?
architecture;rest;api;security;microservices
This is a pretty solid design.This way you will have the ability to change or replace your micro-service for something else while the public api will stay the same.
_cs.10903
Do you know of any kind of decomposition of graphs that involves centers, especially in the context of parametrized complexity? If so, please provide some reference. If not, do you see any reason (other than the potentially large size of centers) why such a notion isn't fruitful (e.g. subsumed by other notion)?I'm looking for something similar to this:Let $G=(V,E)$ be an undirected graph. Its central decomposition isIf $G$ is not connected: the set of central decompositions of its connected components.If $G$ is self-centered (radius equals diameter): $G$If $G$ is connected and not self-centered and its center is $C$: the pair $(I,O)$ where $I$ is the central decomposition of $G[C]$ and $O$ is the central decomposition of $G[V\setminus C]$ (induced subgraphs of center and its complement)Its central width shall be the size of largest self-centered graph which appears in its central decomposition.The notion may also use other concepts (like complements, trees etc.), but it should use centers recursively. There is no need for uniqueness.I'm not looking for e.g. path distance decompositions (see here) where the root is the center, i.e. a map $d$ of a path $\{p_0,\dots,p_k\}$ to $V$ where $d(p_i)=\{v\in V\mid \min_{c \in C}\mathrm{dist}(v,c) = i\}$ ($C$ being the center of $G$).
Decomposition of graphs that uses centers
complexity theory;graph theory;reference request;parameterized complexity
null
_softwareengineering.277807
I've been using rails' erb template for my views, but I've recently been trying to incorporate React as my front end framework. I'm a little lost on how front end frameworks are supposed to be used.e.g. Using React to render a static buttonvar AddProspects = React.createClass({ displayName : 'AddProspects', render: function() { return ( <button type=button className=btn btn-info pull-right btn-block data-toggle=modal data-target=#uploadModal> <i className=fa fa-plus></i> Upload Prospects </button> ); }});React.render(<AddProspects />, document.getElementById(#add-prospects));e.g. Using normal html<button type=button class=btn btn-info pull-right btn-block data-toggle=modal data-target=#uploadModal> <i className=fa fa-plus></i> Upload Prospects</button>Using React in this example seems to be a overkill. Should I be using React for the whole view? Should React be rendering everything from static html to dynamic data from the server side? Or is it better to use it just for elements that interact with the server and leave static stuff to plain html?
Best use of the React frontend framework
javascript;html;front end
React is focused on using plain html.That is why you can just type HTML tags inside your react code. The idea is to keep it simple.Simple answer is: Yes, you should write a lot of plain HTML. When you need to program some piece to use it inside React, then define it on ReactJS. I believe a greate rule of thumb is: When in doubt, think what will be messier (Harder to maintain the code later), and do things the other way. :D
_codereview.122989
Given the following input values from a form, create a method or methods to validate the input based on their requirements. Throw an exception if any data is invalid.1.1 name: is required 1.2 must be first name AND last name2.1 email is required 2.2 is a valid email address3.1 twitter is optional 3.2 is a Twitter handleThe input data will be in the following format:$input = [ 'name' => '...', 'email' => '...', 'twitter' => '...'];This is the code snippet I worked on. How can I improve my code? I am not allowed to include or use any other files.<!DOCTYPE html><html><head> <title>PHP Form Validation</title></head><body><?php$name = '';$email = '';$twitter = '';$nameError =;$emailError =;$twitterError =;class dataException extends Exception { public function errorMessage() { $message = $this->getMessage(); return $message; }}try{ if(isset($_POST['submit'])) { if (empty($_POST[name]) && empty($_POST[email])) { throw new dataException('Name and Email are required'); } if (empty($_POST[name])) { throw new dataException('Name is required'); } else { $name = test_input($_POST[name]); // check name only contains letters and whitespace if (!preg_match(/^[a-zA-Z ]*$/,$name)) { throw new dataException('Only letters and white space allowed'); } else { if(str_word_count($name)!=2) { throw new dataException('FirstName and LastName is required'); } } } if (empty($_POST[email])) { throw new dataException('Email is required'); } else { $email = test_input($_POST[email]); // check if e-mail address syntax is valid or not if (!preg_match(/([\w\-]+\@[\w\-]+\.[\w\-]+)/,$email)) { throw new dataException('Email is invalid'); } } //checked vs internet. $twitter = test_input($_POST['twitter']); if (!isset($_POST['twitter']) || $_POST['twitter'] === '') { $twitter = ''; } else { if (!preg_match('/^(\@)?[A-Za-z0-9_]+$/', $twitter)) { throw new dataException('Invalid twitter handle'); } } }}catch (dataException $e){ echo 'Caught exception: ', $e->getMessage(), \n;}function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data;}//php code ends here?><form action= method=post>Name (FirstName and LastName):<input type=text name=name value=<?php echo htmlspecialchars($name);?>>* <?php echo $nameError;?><br><br>E-mail:<input type=text name=email value=<?php echo htmlspecialchars($email);?>>* <?php echo $emailError;?><br><br>Twitter:<input type=text name=twitter value=<?php echo htmlspecialchars($twitter);?>> <?php echo $twitterError;?> <br> <br><input type=submit name=submit type=submit value=Submit></form></div></body></html>
PHP form validation for name, email, and Twitter handle
php;beginner;validation;form;php5
FilteringI'm not a fan of the test_input function. I don't know why w3schools recommends using it, but it's the wrong approach to XSS (you should encode when echoing, not when retrieving user input), and it messes with your data (\' becomes ' without any need for it; maybe you want to have <, for example because you want to send an email to foo<[email protected], not to foo&lt;[email protected], etc.).Email ValidationEmail validation is difficult.that being said, yours doesn't work as intended. For example, it sais <>'[email protected] is valid. This is because it only checks if any part of the email address match the pattern, which [email protected] does.StructureYour code is quite nested, which makes it hard to read. For example, if I want to know what happens if submit is not set, I need to scroll down quite a bit. It turns out that nothing happens in that case. You can rewrite your code like this to avoid this issue:function proccesForm([optionally some arguments]) { if(!isset($_POST['submit'])) { return; }}You can use the same principle for your other checks as well:function validateForm([optionally some arguments]) { if(!isset($_POST['submit'])) { return; } if (empty($_POST[name]) && empty($_POST[email])) { throw new dataException('Name and Email are required'); } if (empty($_POST[name])) { throw new dataException('Name is required'); } validateName($_POST[name]; if (empty($_POST[email])) { throw new dataException('Email is required'); } validateEmail($_POST[email]; validateTwitter($_POST[email]; }Now your code is a lot more readable. Note that I also extracted sub-tasks to their own function. This increases readability, reusability, and testability.Miscclass names should start with an upper-case letter.you have xError variables, but never use them. For an exercise it might be fine, but considering usability, your validation seems non-optimal. Of course, a first validation should happen via js, but even the secondary server-side validation should print all errors. It is quite annoying for a user to enter all fields, get an error that the name is invalid, fix that error, resubmit the form, only to be told that the email is also invalid. You should report all errors at once.I'm also not so sure if exceptions are really the way to go here. First of all, user input not matching a filter doesn't seem that exceptional to me. Additionally, it seems to make it additionally complex to report more than one error at a time (which is probably why you check for the existence of name and email twice).
_webmaster.34632
I am working on a site that takes a governmental data base, provides a number of statistical and other summaries and also post the original data.However this data (mostly long pieces of text) is also published on the official governmental site (without the added value of summaries).Should I worry about google ranking due to this duplication? What is the preferred way to point to the official source of the information?There is no advertisement on my site. My site is .com. The governmental site is .bg.EDIT: There is additional markup for the text, generated after searching it for keywords, so just providing a link to it will not suffice.
Duplicating content from another site and adding value (summaries, statistics) - ranking and courtesy
duplicate content
null
_unix.368748
I am unable to enter anything at the login screen it just freezes directly after the page shows. The cursor inside the login form blinks about 10 times then it stops. I cant move the mouse or use the keyboard.I already entered the secure mode and triggered update, upgrade and dist-upgrade via the root shell it made no difference.I appreciate any help.
Ubuntu 16.04 - GUI freezes on login start page
ubuntu;gui
We were able to solve it by starting the shell in secure mode and executing the following commands. apt-get update apt-get install xserver-xorg-input-all apt-get install ubuntu-desktop apt-get install ubuntu-minimal apt-get install xorg xserver-xorg apt-get install xserver-xorg-input-evdev //I think this packet was the problem apt-get install xserver-xorg-video-vmware reboot
_unix.326675
I recently installed Linux Mint 18 on my ThinkPad T460p. Having a dual monitor set-up with a internal HiDPI display and a full HD external display connected via Display Port, I tried to adjust the scaling factor of the internal one while leaving the external one untouched.For that matter, I first ran xrandr -q to check the respective ports, and, subsequently,xrandr --output eDP-1-1 --auto --output DP-1-2-8 --auto --scale 2x2 --right-of eDP-1-1As a result, the following error messages were printed:X Error of failed request: BadValue (integer parameter out of range for operation)Major opcode of failed request: 140 (RANDR)Minor opcode of failed request: 26 (RRSetCrtcTransform)Value in failed request: 0x40Serial number of failed request: 47Current serial number in output stream: 48The same was printed when runningxrandr --output eDP-1-1 --auto --output DP-1-2-8 --auto --panning 3840x2400+2560+0 --scale 2.0x2.0 --right-of eDP-1-1To me, these error messages are entirely cryptic. The lack of information on the opcodes makes this a difficult, almost undebugable problem for me. For the commands, I followed the instructions given on ArchWiki.What intuitively might be of interest to that problem is that instead of running nouveau, I run the proprietary nvidia (nvidia-367, to be precise) drivers to power my GeForce 940MX. Thanks for your input.
Scaling only HiDPI display with xrandr in dual monitor set-up
linux mint;xrandr;displayport
null
_softwareengineering.59173
Who wants to work in a fast-paced environment? Not me! I want a civilized environment where people have a sense of balance. Higher quality work gets done that way and work life isn't full of stress and anguish.
Why do ads for s/w engineers always say they offer a fast-paced environment?
development environment
It's code for We change our minds a lot about what we want from the software, and if we hire you we don't want you to complain about it. In fact, we expect you to put in a lot of overtime to implement our latest whim decision because we're fast paced. You've been warned.In programmer-speak, it means we have no specs, unit tests, or for that matter, anyone still around who remembers why our software is the way it is.
_softwareengineering.178919
I'm due to meet with a developer/sales person from a new 3rd party resource we're about to start using. The main topic I'll be interested in, is their API as I will be the developer making use of it and explaining it to the rest of the team.What questions would you recommend asking?Things I'm already thinking about are:What happens and how will I be notified when they depreciate a method? Is there ever any downtime?Who will I deal with first when I have API issues?
Questions to ask a 3rd party API provider
api;documentation;third party libraries
null
_softwareengineering.87399
If I wanted to make a mobile version of a website, what are the most common screen resolutions that I should be testing on?
What screen resolutions should we test on when developing for mobile devices?
web development;mobile
null
_scicomp.20275
I was wondering if there is a Fortran library that contains a solver for the Sparse LSE(linear equality-constrained least squares) problem$$min_{x}\|Cx-d\|^2 \text{ subject to } Ax=b$$where $A$ and $C$ are large and sparse.For dense linear systems, LAPACK has the subroutine DGGLSE, but I am looking for a solver for sparse systems.
Fortran solver for the Sparse LSE problem
sparse;fortran;constrained optimization;least squares
null
_unix.26302
On Debian 6, I uninstalled Ruby 1.8 and installed 1.9.1. Now if I run which ruby it doesn't output anything. Why can't it find ruby anymore?
Why doesn't 'which ruby' output anything?
debian;ruby
Look for it:find / -name ruby 2> /dev/nullIf you get a positive location, make sure that the directory is in your $PATH. If you don't get any output, your Ruby installation didn't go as planned.
_cs.48834
A controlled not gate matrix looks like this:$$\begin{bmatrix}1 & 0 & 0 & 0 \\0 & 1 & 0 & 0 \\0 & 0 & 0 & 1 \\0 & 0 & 1 & 0 \\\end{bmatrix}$$That works great when you only have two qubits and you want to use the first qubit as the control, and the second qubit as the input to be flipped (or not).Is there a method to convert this matrix to use for instance if you had 3 qubits, and wanted to use qubit 1 as the control and qubit 3 as the input that is possibly flipped?Thinking about it logically, I can come up with this:$$\begin{bmatrix}1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 \\0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \\0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 \\0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 \\\end{bmatrix}$$Is there a better, more formal/generalized way to convert multi qubit gates to use any specified qubits, rather than the first $N$ in an $N$ qubit circuit?
Applying a multi qubit quantum gate to specific qubits
quantum computing
Expand-n-SwapIf you want to apply a gate to a subset of the qubits:Expand operations up to $2^n$x$2^n$ with the tensor product / Kronecker product.Use swap gates to make the target qubits consecutive.Swap to a simple order, apply, swap back.It can be tedious to do all those large matrix multiplications, but swap matrices are sparse and the idea is very straightforward.Controls are EasierIn the case of adding controls to an operation (which applies to the specific example you gave), there's an easier trick. Just expand the operation like normal, but then replace any parts of the matrix that correspond to control-failed inputs with what the identity matrix would be.This is a bit easier to keep track of if you introduce a fake control value $c$ that overrides the tensor product's usual behavior, so that instead of $\begin{bmatrix} c \end{bmatrix} \otimes U = c \cdot U$, you have $\begin{bmatrix} c \end{bmatrix} \otimes U = c \cdot I$ (in other words: when an entry is $c$ you don't tile $U$ over the entry and scale $U$ by the entry; you use $I$ instead of $U$).Define the operation of a qubit-must-be-ON control to be $C = \begin{bmatrix} c&0 \\ 0&1 \end{bmatrix}$. A no-op is $I$, and a NOT is $X$. Then the operation from your question could be computed like this (assuming big-endian order):$CNOT_{3 \rightarrow 1} = C \otimes I \otimes X$$= \begin{bmatrix} c&0 \\ 0&1 \end{bmatrix} \otimes \begin{bmatrix} 1&0 \\ 0&1 \end{bmatrix} \otimes \begin{bmatrix} 0&1 \\ 1&0 \end{bmatrix}$$= \begin{bmatrix} c\otimes\begin{bmatrix} 1&0 \\ 0&1 \end{bmatrix}&0\otimes\begin{bmatrix} 1&0 \\ 0&1 \end{bmatrix} \\ 0\otimes\begin{bmatrix} 1&0 \\ 0&1 \end{bmatrix}&1\otimes\begin{bmatrix} 1&0 \\ 0&1 \end{bmatrix} \end{bmatrix} \otimes \begin{bmatrix} 0&1 \\ 1&0 \end{bmatrix}$$= \begin{bmatrix} \begin{bmatrix} c&0 \\ 0&c \end{bmatrix} & \begin{bmatrix} 0&0 \\ 0&0 \end{bmatrix} \\ \begin{bmatrix} 0&0 \\ 0&0 \end{bmatrix}&\begin{bmatrix} 1&0 \\ 0&1 \end{bmatrix} \end{bmatrix} \otimes \begin{bmatrix} 0&1 \\ 1&0 \end{bmatrix}$$= \begin{bmatrix} c&0&0&0 \\ 0&c&0&0 \\ 0&0&1&0 \\ 0&0&0&1 \end{bmatrix} \otimes \begin{bmatrix} 0&1 \\ 1&0 \end{bmatrix}$(note: going to use a single zero to ambiguously mean a 2x2 zero matrix where convenient)$= \begin{bmatrix} c\otimes \begin{bmatrix} 0&1 \\ 1&0 \end{bmatrix} &0&0&0 \\ 0&c \otimes \begin{bmatrix} 0&1 \\ 1&0 \end{bmatrix}&0&0 \\ 0&0&\begin{bmatrix} 0&1 \\ 1&0 \end{bmatrix}&0 \\ 0&0&0&\begin{bmatrix} 0&1 \\ 1&0 \end{bmatrix} \end{bmatrix}$$= \begin{bmatrix} \begin{bmatrix} c&0 \\ 0&c \end{bmatrix} &0&0&0 \\ 0&\begin{bmatrix} c&0 \\ 0&c \end{bmatrix}&0&0 \\ 0&0&\begin{bmatrix} 0&1 \\ 1&0 \end{bmatrix}&0 \\ 0&0&0&\begin{bmatrix} 0&1 \\ 1&0 \end{bmatrix} \end{bmatrix}$$= \begin{bmatrix}c&0&0&0&0&0&0&0 \\0&c&0&0&0&0&0&0 \\0&0&c&0&0&0&0&0 \\0&0&0&c&0&0&0&0 \\0&0&0&0&0&1&0&0 \\0&0&0&0&1&0&0&0 \\0&0&0&0&0&0&0&1 \\0&0&0&0&0&0&1&0 \end{bmatrix}$(now we're done with the tensor products and don't need the $c$'s anymore)$\rightarrow \begin{bmatrix}1&0&0&0&0&0&0&0 \\0&1&0&0&0&0&0&0 \\0&0&1&0&0&0&0&0 \\0&0&0&1&0&0&0&0 \\0&0&0&0&0&1&0&0 \\0&0&0&0&1&0&0&0 \\0&0&0&0&0&0&0&1 \\0&0&0&0&0&0&1&0 \end{bmatrix}$Make sense?
_unix.100676
I have currently a set of seds that's working well except for one thing.The particular expression I'm having an issue with is:sed -i '/[^}.to]\.to[[:space:]]/ s/\(\S\)/expect(\1/' ../_spec_seded/$fileRight now this works fine.Basically it looks for .to and insert expect at the start of the expression.In particular, it excludes }.to when looking to match on .to which works.Now I want to also exclude 'this' or 'that' from the search match. In my case }.to or end.toi.e. instead of/[^}.to]\.to[[:space]]/should I have:/[^}.to|^end\.to]\.to[[:space]]//[^}.to][^end\.to]\.to[[:space]]//[(^}.to|end\.to)]\.to[[:space]]//[^(}.to|end\.to)]\.to[[:space]]/would I even need to escape parens if using them like/[^\(}.to|end\.to\)]\.to[[:space]]/or even the | as well?/[^\(}.to\|end\.to\)]\.to[[:space]]/I'm trying to make the match work on:stuff.to do thingstuff).to do thingthis.to thatall.all.all.to dopretend.do # Note this edge case! (pretend contains end!) but not onthis will be here }.to dolast.end}.to doall.this at the end.tonone at allend.toandall.this at the end.to # i.e. no spaces before as it is the start of the line.Negating with OR's generally (all languages) seems tricky (due to false positives).
sed - how to exclude multiple patterns in the match
sed;regular expression
Pending your response to my comment on the question, here's my answer:First of all, [^}.to] doesn't do what you seem to think. It will not match lines that don't have the pattern }.to. It matches lines that have any character other than ., }, t or o. In other words, many lines.To make things easier, let's have sed print nothing by default then tell it to print everything except those lines matching the patterns you want to exclude:sed -n '/\(\bend\|}\.to\)/!p' your_fileThis will print all lines not containing end.to at a word boundary (i.e. allend.to doesn't count) or }.to.If, in addition you want to print only those lines that match \.foo[[:space:]], simply delete lines matching unwanted patterns and add a conditional print:sed -n '/\(\bend\|}\.to\)/d;/\.to[[:space:]]/p' your_fileOf course, between the match and the print, you can apply whatever substitution you feel like:sed -n '/\(\bend\|}\.to\)/d;/\.to[[:space:]]/s/foo/bar/g;p' your_file
_softwareengineering.239070
In a centralized web service we break down the components into various small Git repos by software modules, e.g. authentication module, authorization module, data access module etc. (around 15 repos at the moment)The good thing is it is easy to manage the smaller code base, however, our productivity has decreased a lot since quite a lot of changes need to be update several repos at once. Also, deployment is more difficult as there are multiple versions of module involved, we always need to think about the dependency.I am considering to merge all the modules back to a single repo, because our services must require all the modules to exists, they are not optional for our servicewe are not a big team (3 people actually) and the overhead in maintaining too many repos does not worth it, they all need to have knowledge on all the code basesWhat do you think? Any pros and cons if we merge into a giant repo?
Merging around 15 small Git repos of non-optional centralized web service components to a single large repo
design;git;release management;modules;gitflow
null
_cogsci.13151
I'm looking for a toolbox to model visual search performance in a singleton search task based on line orientations (you need to find a line that is most different from all others in it's orientation). The desirable features would be:Feature-detectors that resemble real neurons.Memory for distribution of distractors in feature space during previous trials.Is there something like that? I also know that sometimes similar tasks are studied in texture discrimination. Maybe there is something close to what I need in that domain?
Toolbox for modelling visual search performance
vision;cognitive modeling;computational modeling
null
_datascience.22439
To train a Deep neural network, why training Restricted Boltzmann Machine(RBM) layer-wise first and then apply BP algorithm through the network? Comparing to random initiating all the weights+bias in all layers and then apply BP algorithm, is there a quantitative reason(proof) that pretrained RBM is better than random weights assignment? I found a lot of case(datasets) studies about these two training methods saying RBM is better than random.(Some documents argued that RBM also could help avoiding local minimizers when running gradient descent, but didn't offer any proof)
Why Restricted Boltzmann Machine(RBM) is better than random initiating?
machine learning;deep learning
null
_unix.328759
I'm using Exagear desktop to run Skype on RPI3 (Raspbian/Debian). I have some naive users also using the system because of which I want to load both of them on boot (maybe delayed startup service).I understand how to create a script to be run on startup and also possibly delay it so the dependencies are completely loaded but I don't know how to script to have skype startup withing exagear in the same startup script. Right now what I do to luanch them is to use the GUI shortcut to run exagear -> it opens a terminal -> I verify 'arch' has switched over from arm to x86-> run 'skype'.I'm a newbie and would appreciate any guidance. Any updates?
Delayed script to boot exagear and skype using RPI3 on debian
startup;init.d;architecture;skype;delay
null
_unix.119935
Say I'd like to use the file -f - command inside a script, and send some input using the stdin, when I'm finished I'd like to terminate it gracefully, but unfortunately I haven't found any way to do this (and yes I did read the man page :) ).
file(1) command termination when using the -f - option
command line;files;stdin
You only need to send EOF signal when you finished. To do that, you need to press CTRL + D:$ file -f -test.pytest.py: a /usr/bin/python script, ASCII text executabletest.pl test.pl: a /usr/bin/perl script, UTF-8 Unicode text executable<CTRL + D here>or you can send to file inside shell script via HERE DOC:file -f - <<EOFtest.pltest.pytest.awkEOF
_cs.22745
In Introduction to the Theory of Computation by Sipser, Savitch's theorem is explained as an improvement to a naive storage scheme for simulating non-deterministic Turing machines (NTM). I am going to quote the text verbatim, because quite frankly I don't fully understand it (which is why I was unable to really ask my question in enough detail):We need to simulate an $f(n)$ space NTM deterministically. A naive approach is to proceed by trying all the branches of the NTMs computation, one by one. The simulation needs to keep track of which branch it is currently trying so that it is able to go on to the next one. But a branch that uses $f(n)$ space may run for $2^{O(f(n))}$ steps and each step may be a nondeterministic choice. Exploring the branches sequentially would require recording all the choices used on a particular branch in order to be able to find the next branch. Therefore, this approach may use $2^{O(f(n))}$ space, exceeding our goal of $O(f^2(n))$ space. (Sipser, Introduction to the Theory of Computation 334)He goes on to describe Savitch's use of a subroutine called $CANYIELD$, a TM that decides whether some configuration $c_2$ is reachable from some other configuration $c_1$ in $t$ steps. It is recursively defined, so that $CANYIELD(c_1, c_n, t)$ results in two recursive calls $CANYIELD(c_1, c_m, t/2)$ and $CANYIELD(c_m, c_n, t/2)$, and so on until the distance between configurations is $0$ or $1$, or it is deemed unreachable. I think this can also be described as $STCON$ on a configuration graph of the TM in question.So, there are two questions I have.I understand how the size of each level and the depth of $CANYIELD$ results in no more than $O(f^2(n))$ use of space, but I don't understand how the intermediate configuration $c_m$ is found. Is this just not important given that all we care about is space? How do we know that the space used to obtain $c_m$ is negligible?I don't understand why we need $2^{O(f(n))}$ space in the naive approach. Why can't we forget about branches we've executed, so that we are still using at most the space required to go all the way down one branch?
The crux of Savitch's Theorem
complexity theory;space complexity
null
_webmaster.71467
My site can be accessed by either http://example.com or http://beta.example.com. The sub domain beta is the same site but a different version and I want users to be able to use the beta but any links gained on the beta domain I want the link juice to pass to the main domain. How can this be done?
Allow users to access my beta subdomain but pass link juice to the main site
seo;redirects;robots.txt;backlinks
Never treat Googlebot any different than actual site visitorsYou should never treat Google bot any different from actual users. Redirecting Googlebot using user agent or other similar tactics and not users will likely harm your site as its against Google's guideline rules.Cosmetic changes say hello to canonical linksIf the beta site has the same content but different cosmetic changes through CSS then you should use canonical links pointing to the master pages that way any links gained on beta will pass to the main domain.If the content is differentIf the content is actually different then you should not attempt to redirect Juice as this again will not go well with Google, if you want the juice to flow to the main site then you should run it on the main domain with a sub folder /beta/.
_softwareengineering.127714
If you decide Program to An Interface trumps YAGNI and decide to create a supertype where you don't envision anything other than one obvious implementation - is there a convention for naming the obvious concrete type? E.g. this morning I wrote a a class called PlainOldConversionReport and I wonder if that name betrays ignorance of convention. Would there a more normal name, in Object Oriented development generally or .Net or C# specifically, to give to a non specialized subtype of IConversionReport?
Naming conventions for the only envisioned implementation of an interface
object oriented;naming;interfaces
If there is no obvious name for the specialization in the single implementation, my teams have always normally used Impl as a suffix. If there is an obvious name, I would stick with it even if it will be the only implementation.