id
stringlengths 5
27
| question
stringlengths 19
69.9k
| title
stringlengths 1
150
| tags
stringlengths 1
118
| accepted_answer
stringlengths 4
29.9k
⌀ |
---|---|---|---|---|
_unix.295060 | I've seen on various Linux systems where instead of the real device node (for example: /dev/sda1), the root device appears as /dev/root, or instead of the real filesystem, mtab says it is a filesystem called rootfs (which appears as a real filesystem in /proc/filesystems, but doesn't have code in <linux-kernel-source-tree>/fs). Various utilities have been made to use certain attributes to determine the real root device node (such as rdev, and the Chromium OS rootdev). I can find no logical explanation to this other than reading somewhere that very-small embedded devices don't always have to have a /dev device node for their root device. (Is this true, and if so, is that the answer to my question?) Why does mtab sometimes say /dev/root (and I think I might have seen it say rootdev once) instead of the real device node, and how can I make it always say the real device node? The kernel first mounts the root device following the root parameter in the cmdline, then init/systemd re-mounts it according to the fstab, correct? If so, then I presume init maintains mtab. If my theory is correct, how can I make init write the real root device node to mtab? I noticed that /etc/mtab is actually a symbolic link to /proc/mounts, which would mean mtab is maintained by the kernel. So how do I configure/patch a kernel to, instead of saying the root devices node path is /dev/root, have mtab contain the real device node? | Why on some Linux systems, does the root filesystem appear as /dev/root instead of /dev/in mtab? | linux;root filesystem | This is generally an artifact of using an initramfs.From the kernel documentation (https://www.kernel.org/doc/Documentation/filesystems/ramfs-rootfs-initramfs.txt)What is rootfs?Rootfs is a special instance of ramfs (or tmpfs, if that's enabled), which is always present in 2.6 systems. You can't unmount rootfs for approximately the same reason you can't kill the init process; rather than having special code to check for and handle an empty list, it's smaller and simpler for the kernel to just make sure certain lists can't become empty.Most systems just mount another filesystem over rootfs and ignore it. The amount of space an empty instance of ramfs takes up is tiny.Thus rootfs is the root filesystem that was created for the initramfs, and can't be unmounted.In regards to /dev/root, I'm less certain on this, but if I recall correctly /dev/root is created when using an initrd (not the same as an initramfs). |
_webmaster.72851 | i am italian, i got a D-U-N-S number for my individual company (partita iva for those who know what it is).Now Apple is asking me to enroll as an individual cause the D-U-N-S number is attributed to an individual physic person, why i can't enroll as company since for the italian law i am a company?Also why i must enroll as an individual since my company can accept payments by the law, what i lose as legal entity enrolling for an individual account?Thank you | Apple Developer Program enrolling with a p.iva and the company name | registration;apple | null |
_softwareengineering.69768 | We have three developers, one system administrator, and an artist that primarily work on a single website (forum) on our spare time to consistently develop features for the forum (but there are other projects that we work on). Because our system administrator recently joined, we dropped managed hosting for a single server and decided to rent out two unmanaged servers (one for testing and the other for production).In the old server, we simply used Git as a middleman for pushing updates from the non-unified developer team into the server without conflicting updates. Pull other developer updates. Push our own updates. Revert if something breaks.Since we have two servers now, we plan to push updates to the development server and somehow have it push updates to the production server. Developer(s) -> development server (bare) -> production serverWe want to keep the repositories in the development server and the work tree of the web site on the production server (web server). Is there an efficient way to do this without pushing from the dev server to production? Is there a better workflow for two servers in general?P.S. The development team consists of high school teenagers and some college kids that have never developed on teams for for-profit businesses. | Workflow on Development and Production Servers for a Consistently Updating Website | git;collaboration;workflows | What is probably easiest to do is:Use Git on the development server and have a version running there corresponding to the current master (a checkout from the repository). Everyone can merge changes into this version and if it breaks, the development server breaks and it's clear that action is required.The production server is a remote checkout from the development server. Whenever the development server is at a stable point (or ready to release a new version), just log into the production server and do a git pull.This is easy because when something does go wrong, you can just revert the production server with a single git revert command.Furthermore, you can automate this by creating a hook on the production server to automatically pull changes based on anything you define. How this works in your specific situation will depend on how your actual release process works. Personally, I would just update it manually (you can even create a simple script so you don't actually have to log into the production server), since it's just one command and you generally want to be there whenever you update a production server :)Also: do remember to secure the production server so your repository files are not served by the web server. This is trivial and your system administrator can configure this. |
_unix.88329 | I want to monitor a HP 7500 switch power supplies. I have my OID, given by the HP web interface. So I create a snmptt.conf.hp, I create a service, passive and volatile, add this OID to a trap, and linked trap to service, then service to host.I configured snmptt.conf, in order to log as /var/log/snmptt.log, and snmptt_unknown.log. With log_enable = 1, and debugging = 1 ... But nothing happens! No log at all! No smptt*.log or snmptrapd.log ...By looking with tcpdump, I'm sure that traps arrive well. But Nagios.log tell me this:Warning: The results of service 'Service_Trap_PowerSupply_KO' on host 'XX.XX.XX.XX' are stale by 0d 0h 0m 59s (threshold=0d 0h 5m 0s). I'm forcing an immediate check of the service.Warning: The results of service 'Service_Trap_PowerSupply_OK' on host 'XX.XX.XX.XX' are stale by 0d 0h 0m 59s (threshold=0d 0h 5m 0s). I'm forcing an immediate check of the service.So name of my services look ok. On trap for KO the other for OK. When we unplug on powersupply, this is recorded in nagios.log. | Nagios trap snmptt fails to trigger | nagios;snmp | null |
_unix.186631 | The question is, if there is a way to simplify the structure of the xkb configuration related to keyboard layouts?As explained in further detail below there are 5 independent places in which a reference to a keyboard-layout-variant is stored (evdev.xml, evdev.lst, base.xml, base.lst, and inside the respective layout description files in /usr/share/X11/symbols/). It would be much simpler if there was only as many as needed (it is not helpful to store the same information in .lst and .xml as all additions or deletions of keyboard layouts need ot be done several times at 5 places)Of course it also makes the whole configuration less clear to users (as it is confusing to have to set the very same configuration in a needless redundant fashion at several places). Maybe there is a way this can be simplified? If there was this would be the desired answer to this question. Given that there are many different distributions I would hope that not all have this xkb configuration setup. This is how the xkb configuration looks on my GNU/Linux (Ubuntu 12.04LTS) box. In order to add a new keyboard layouts to be used in my a respectable large number of many files must modified. /usr/share/X11/xkb/rules/evdev/usr/share/X11/xkb/rules/evdev.xml /usr/share/X11/xkb/rules/evdev.lst/usr/share/X11/xkb/rules/base /usr/share/X11/xkb/rules/base.xml/usr/share/X11/xkb/rules/base.lstIt seems to me that essentially base version of the files are copies of the evdev files it would be interesting to know if they could be made symbolic links like those files/usr/share/X11/xkb/rules/xorg/usr/share/X11/xkb/rules/xorg.lst/usr/share/X11/xkb/rules/xorg.xmlPerforming this little tests:1. user@box:/$ cat /usr/share/X11/xkb/rules/evdev.lst | grep Greek gr Greek simple gr: Greek (simple) extended gr: Greek (extended) nodeadkeys gr: Greek (eliminate dead keys) polytonic gr: Greek (polytonic)2. user@box:/$ cat /usr/share/X11/xkb/rules/evdev.xml | grep Greek <description>Greek</description> <description>Greek (simple)</description> <description>Greek (extended)</description> <description>Greek (eliminate dead keys)</description> <description>Greek (polytonic)</description> ofencito@freak:/usr/share/X11/xkb/rules$ shows that both files contain virtually the very same data (which makes the same iformation being stored in 4 separate locations - even disregarding the symbolic links mentioned earlier).Eventually the keyboard layouts are then themselves stored in a filesystem structure at /usr/share/X11/xkb/symbols, which agains stored references tothe language layout and variant in files named in accordantly. To keep our greek example there is a file /usr/share/X11/xkb/symbols/gr. Looking at this yields:user@box:/$ cat /usr/share/X11/xkb/symbols/gr | grep xkb_symbolsxkb_symbols basic { name[Group1] = Greek;xkb_symbols simple { name[Group1] = Greek (simple);xkb_symbols bare {xkb_symbols extended { name[Group1] = Greek (extended);xkb_symbols polytonic { name[Group1] = Greek (polytonic);xkb_symbols nodeadkeys { name[Group1] = Greek (eliminate dead keys);At this point the very same information has been reduntantly stored in 5 locations. Is there a way to simplify this mess? Since I am most familiar only with Ubuntu I wonder of course if other distributions might have found less confusion ways to deal with the keyboard layout? | How can the xkb layout settings be simplified? | configuration;keyboard;xkb | null |
_softwareengineering.175399 | Hey guys I am really new to the C++ programing I have a little knowledge in C and a bit more in C++, but I do not know them enough to call myself a programmer. I am working as a PHP Web Developer I like being a crafts man and creating things so that is the reason to combine the programming with web development. I think that I could really benefit from both of them and so... My question is:Is it a good Idea to learn C++ with Qt or not?Can you give me pros and cons of both?Note: I do not want to become a programmer and give up the web development I want to combine them both. | Programming C++ using Qt4 | c++;programming practices;qt | For learning C++, Qt has some good things and some bad things.The good:It provides the building blocks for everything you might want to do with C++, from network programming and threads to OpenGL and displaying web content.It has a few tricks up it sleeves to make things a little easier. For example, it uses the parent hierarchy to handle object deletion makes memory leaks much less common. It also uses signals and slots to provide a somewhat sensible way to write event-driven programs.The bad things are mostly corollaries of the good things:Because it has everything wrapped up into a nice, cohesive whole, you are de facto encouraged to only use its things. For instance, you'll be using QString and QList instead of std::string and std::list, because that's what you'll get from Qt classes and that's what Qt classes expect you to provide.When you eventually write non-Qt code with C++, you'll be missing some of the safety nets. You will really have to be responsible with your memory deallocation, and you'll have to learn the other patterns for doing event-driven code in C++.Without Qt, you'll have to find some external or system library (e.g., outside the C++ standard) for: threads, network programming, GUI programming, graphics rendering (to the screen or to image files), XML parsing, rendering web content, etc. Qt includes classes for all of those things. But if you want to eventually become a generic C++ programmer, you'll need to learn how to program without it. |
_unix.194017 | I am new to unix shellI am learning array by following codesource_array_list[0]=asource_array_list[1]=asource_array_list[2]=asource_array_list[3]=asource_array_list[4]=asource_array_list[5]=asource_array_list[6]=asource_array_list[7]=aa=0while [$a -le 6]do echo just before loop target_array[a]=source_array_list[$a] echo ${source_array_list[$a]} a=`expr $a + 1`doneNow this is not working and giving the error [0: not found.Please guide me to solve it. | Unix Shell : Array assignment not working | bash;shell script;ksh | you need a space after '[' because '[' is a command see here https://stackoverflow.com/questions/9581064/why-should-be-there-a-space-after-and-before-in-the-bash-scriptYou also need ${} around the array variable reference, so you should have:source_array_list[0]=asource_array_list[1]=bsource_array_list[2]=csource_array_list[3]=dsource_array_list[4]=esource_array_list[5]=fsource_array_list[6]=gsource_array_list[7]=hwhile [ $a -le 6 ]do target_array[a]=${source_array_list[$a]} echo ${source_array_list[$a]} a=`expr $a + 1`doneyou could also simplify this a bit by doing the following source_array_list=( 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h')target_array=()for element in ${source_array_list[@]}do target_array+=(${element}) echo ${element}doneecho ${target_array[@]} |
_cogsci.3571 | I've heard that our eyes accommodate between colors too far from each other in the visible spectrum. I imagine it's not a true focal point accommodation, but rather linked with how brain processes the information. Is this true?What I'm trying to find out is, whether using color for emphasis, for example both blue and yellow (which are fairly far from each other in the spectrum), for text underlining, doesn't make the brain focus only at one color at once. Like when you're looking for some object on your messy table, thinking it's of blue color and not noticing it's right in front of your eyes, because it was red.Another example would be a document with some emphasized words in blue, some in yellow - and let's say the author wanted to make sure both colors are regarded as important (just in different context). Now question is, can the eye/brain focus on both colors at once? I don't mean if we can do it deliberately by trying hard, but rather if it's more likely for the brain to focus only at one color at a time, unconsciously.By what I've heard, if I understand it correctly. If we want to use two different colors for emphasis, we should use colors that are close to each other in the EM spectrum (while still making sure, they are high contrast in regard to the background)Refer to the two paragraphs taken from wikipedia I stylized.I'd summarize the question like this. Is there difference in how we regard those two paragraphs? Are we more likely to skip some words when they are highlighted with colors too far away from each other in the EM spectrum, therefore, is it better to use colors closer to each other?EDIT: I changed the luminance of the colors to be the same for all of them (70%, used HSL Color Picker). As pointed by John, the different luminance might have played a part in the perception.View of the relative EM wavelength spread (images taken from Gimp) | Do eyes accommodate to color? | perception;vision;color | I don't think it is a matter of color/hue. Do you have a source for this hypothesis? If you were able to measure this effect then I would think it happens because of the importance rating a reader develops for a certain group of highlighted words, e.g. all blue highlighted words are important to me.The user Pete made a good comment in my opinion by pointing out the contrast issue. The attention of humans is foremost guided by luminance contrast. Then comes hue and then saturation. The colors you chose have a different luminance value and therefore attract attention differently.Here's a link to compare the (relative) luminance values of your color sets. |
_webmaster.98616 | How to embed items of a different data type? Schema.org explains it here: https://schema.org/docs/gs.htmlI use Googles markup helper (www.google.com/webmasters/markup-helper/) that creates automatically the code. I have this code simplified and I choose data type Article:<div class=post><img src=1.png><h1>Title of the post</h1> <div> <p>This is the body of the post</p></div> <p>Author of the post</p></div><!-- end schema Article -->Google gives me this:<div itemscope itemtype=http://schema.org/Article><img itemprop=image src=1.png><h1 itemprop=headline name >Title of the post</h1><div itemprop=articleBody > <p>This is the body of the post</p></div><span itemprop=author itemscope itemtype=http://schema.org/Person><p itemprop=name>Author of the post</p></span></div><!-- end schema Article -->I am confused on the last span. I understand that author belongs to the data type Person and not Article. But why it introduces the itemprop=name here? It seems redundant. For me, one of those options makes more sense:<p itemprop=author itemscope itemtype=http://schema.org/Person>Author of the post</p>Or perhaps:<span itemscope itemtype=http://schema.org/Person><p itemprop=author>Author of the post</p></span>Why Googles markup helper gives itemprop=name, is it an error?Are my solutions ok? Can anyone explain in a simple way how to embed a different data type in Schema.org?(Where I write Author of the post I mean any name, John Doe, for instance)UPDATE:Now I realize that Schema Article (Blog and BlogPosting too) do have the property Autor. In fact https://schema.org/Article Example 1 (bottom of the page) gives this:<div itemscope itemtype=http://schema.org/Article> <span itemprop=name>How to Tie a Reef Knot</span> by <span itemprop=author>John Doe</span></div>So, I suppose that there is no need to embed author from Person. Googles markup helper must have a software problem. Am I right? | How to embed a Schema.org data type? | html5;schema.org;microdata | The HTML is not correct, because a span cant have a p as child. It should probably be a div, i.e.:<div itemscope itemtype=http://schema.org/Article> <div itemprop=author itemscope itemtype=http://schema.org/Person> <p itemprop=name>Author of the post</p> </div></div>The problem you seem to have is likely the same one from your comment to my answer to your other question. How Microdata worksI think you have to understand how Microdata works:The itemscope attribute creates an item. (Here is something.)The itemtype attribute specifies the type of that item. (This something is a Person.)The itemprop attribute specifies the property this item has. (This something, which is a Person, has the name Alice.)The temprop always belongs to the nearest itemscope parent! So in your example, the author property does not belong to the Person item, it belongs to the Article item.It says: Here is an Article. This Article has an author, which is a Person. This Person has a name.Your first suggestion<p itemprop=author itemscope itemtype=http://schema.org/Person>Author of the post</p>You provide the author property, and you say that the author is a Person (good), but then you dont provide any property about that Person. How should a consumer know that the element content (Author of the post) is the name of that person, and not the persons address/birthday/description/etc.? (Schema.orgs Person type can have many properties.)Microdata ignores any content that is not an itemprop value. The value of the author property in your suggestion is the Person item, not the string Author of the post. A Microdata parser will never see that string (unless you put it as value to an itemprop).Your second suggestion<span itemscope itemtype=http://schema.org/Person><p itemprop=author>Author of the post</p></span>This means: There is a Person which is authored by Author of the post. But the Person has no author, of course. (And Schema.org doesnt define an author property for Person.)Another problem: For consumers its not clear that this Person represents the author of the Article. You have to use an itemprop attribute to add it to the Article.A possible alternative (not recommended)Instead of <div itemprop=author itemscope itemtype=http://schema.org/Person> <p itemprop=name>Author of the post</p></div>you could use<div itemprop=author>Author of the post</div>but its not recommended/expected (by Schema.org).The key difference here is that this author property has text (instead of another item!) as value. The obvious problem of using a text value: You cant provide more information (in the form of properties) about this author (e.g., the authors website URL, etc.).Why its not recommended? Because Schema.orgs author property is defined to get an Organization or a Person value. |
_softwareengineering.219758 | I have a client server application. Assume I work as a Support executive, resolving customer tickets. We(our support team) have got two tickets to work on. Ticket 1: Client Liver raised a ticket to update his phone number.Ticket 2: Same Client Liver raised a second ticket to update his email ID.I am working on ticket 1:Opened application, clicked edit Customer Info buttton, entered new phone number. I did not save the form(Edit form). In between, I left for CUPPA.My colleague is looking at ticket 2: He has edited the Customer information and updated with new email id: Its persisted in database.When, I come back and save my ticket with phone number update, it would overwrite his changes i.e.., his email ID change is lost or not updated for that Customer Liver. Is there a way that when a get back to my work/page after CUPPA break, can I see the email ID with updated value?How to prevent this? What is the approach? Possible design ideas? How to ensure that there is no data loss? | How to update User interface form through database update | java;design;web applications;mvc | null |
_codereview.156496 | I am new to bash scripting. Could you please give a review of this code that copies recently modified files from one directory to another in bash? The main commands are in my bash_aliases file. Main code#!/bin/bash# Aliases filecpRecent(){ . ./helperlib.sh __processoptions $@ if (( $? == 0 ));then __getrecentfiles __processlines local numOfCopiedFiles=0 for line in ${!filelist[@]}; do cp $line ${filelist[$line]} (( ++numOfCopiedFiles )) done echo You have copied $numOfCopiedFiles file(s) unset files unset filelist fi return}mvRecent(){ . ./helperlib.sh __processoptions $@ if (( $? == 0 )); then __getrecentfiles __processlines local numOfMovedFiles=0 for line in ${!filelist[@]}; do mv $line ${filelist[$line]} (( ++numOfMovedFiles )) done echo You have copied $numOfMovedFiles files unset files unset filelist fi return}The helperlib.sh#!/bin/bash# File: helperlib.sh # Brief: Library for cpRecent, mvRecent commands# Error codesno_args=You need to pass in an argumentinvalid_option=Invaild option:no_directory=No directory found# Return values fullpath=directories=numfiles=interactive=typeset -a filestypeset -A filelist# Advise that you use relative paths__returnfullpath(){ local npath if [[ -d $1 ]]; then cd $(dirname $1) npath=$PWD/$(basename $1) npath=$npath/ #Add a slash npath=${npath%.*} #Delete . fi fullpath=${npath:=}}__usage(){cat <<End-Of-Message_______________________________________________________________________________Copies/Moves the n most recent file(s) in a directory to another directory wheren is user specified. <cpRecent/mvRecent> [-d D1,D2] [-n NUM] [-ih] -d D1,D2 The directory that is copied/moved from is D1 while the directory that is copied/moved to is D2 The directories would need to be in relative paths -n This specifies an integer num of files -i This allows the user to edit the name of the file to be copied or moved -h Shows this entire wall of text An example of how to use the command: cpRecent -d Documents,. -n 3 (This means that copy the three(3) most recent files in Documents to the folder I am currently in)_______________________________________________________________________________End-Of-Message}__processoptions(){ OPTIND=1 while getopts :d:n:ih opt; do case $opt in d ) IFS=',' read -r -a directories <<< $OPTARG;; n ) numfiles=$OPTARG;; i ) interactive=1;; h ) __usage; return 1;; \? ) echo $invalid_option -$OPTARG >&2 ; return 1;; : ) echo $no_args; __usage >&2 ; return 1;; * ) __usage >&2; return 1;; esac done shift $((OPTIND-1)) # Check for errors (( ${#directories[@]} != 2 )) && echo $invalid_option Number of directories must be 2 && return 2 __returnfullpath ${directories[0]} directories[0]=$fullpath __returnfullpath ${directories[1]} directories[1]=$fullpath if [[ -z ${directories[0]} || -z ${directories[1]} ]]; then echo $no_directory return 3 fi [[ numfiles != *[!0-9]* ]] && echo $invalid_option Number of files cannot be a string && return 4 (( $numfiles == 0 )) && echo $invalid_option Number of files cannot be zero && return 4 return 0 }__getrecentfiles(){ local num=-$numfiles # Get the requested files in directory(skips directories) if [[ -n $(ls -t ${directories[0]} | head $num) ]]; then # For some reason using local -a or declare -a does not seem to split the string into two local tempfiles=($(ls -t ${directories[0]} | head $num)) for index in ${!tempfiles[@]}; do echo $index ${tempfiles[index]} [[ -f ${directories[0]}${tempfiles[index]} ]] && files+=(${tempfiles[index]}) done fi}__processlines(){ local name local answer if [[ -n $interactive ]]; then for index in ${!files[@]}; do name=${files[index]} read -n 1 -p Old name: $name. Do you wish to change the name(y/n)? answer # Need to leave a space in between the variables [[ $answer == y ]] && read -p Enter new name: name local dirFrom=${directories[0]}${files[index]} local dirTo=${directories[1]}$name filelist+=([$dirFrom]=$dirTo) done else for index in ${!files[@]}; do local dirFrom=${directories[0]}${files[index]} local dirTo=${directories[1]}${files[index]} filelist+=([$dirFrom]=$dirTo) done fi} | Copy recently modified files from one directory to another | beginner;bash | null |
_codereview.126292 | I have finally found some time to redo the last tic tac toe game I posted. I have gotten rid of Magic Numbers as well as any typos(if their are any please point them out but I think i rid myself of them...hopefully). I have updated the way the code is implemented as well as added a header titled Constants. This choice was to get rid of my magic number issues and if it is was a poor idea please correct me on it and show me the proper way to create cross file constants. (I tried to use constants as differing types of error codes. Is this a good idea?) One more thing, should I implement the input type checking in my Data class or leave it where it is to match MVC design pattern. (If my design does not implement this pattern please tell me how I should do it.)Constants.h#ifndef CONSTANTS#define CONSTANTSenum boardSpaces : size_t { space1 = 0, space2 = 1, space3 = 2, //used to access board spaces in container space4 = 3, space5 = 4, space6 = 5, space7 = 6, space8 = 7, space9 = 8}; const int errRecognize = 0; //error unrecognizable input i.e. number or char out of rangeconst int errType = 1; //error data type of user input faildconst int errBoard = 2; //error space of board has been marked#endifData.h#ifndef DATA#define DATA#include <string>class Data{ std::string boardData; const char player1; const char player2;public: const int MAX_TURNS = 9; const int board_dim = 3; //dimensions 3X3 Data(); ~Data() = default; std::string printBoard() const; void markBoard(const size_t&,const char&); void gameReset(); bool checkWin(const char&) const; bool checkCatsGame(const int&) const; char boardSpaceValue(const size_t&) const; char player1Mark() const; char player2Mark() const;};#endifData.cpp#include Data.h#include Constants.hData::Data(): player1('X'), player2('O'){ boardData = 123456789;}void Data::markBoard(const size_t &position,const char &playerMark) { boardData[position-1] = playerMark;}std::string Data::printBoard() const{ return boardData;}//returns value of a praticular space on boardchar Data::boardSpaceValue(const size_t &index) const { return boardData[index-1];}char Data::player1Mark() const{ return player1;}char Data::player2Mark() const{ return player2;}bool Data::checkWin(const char &mark) const{ //check columns and rows for win //code came from Edward@ codereview for (unsigned i = 0; i < board_dim; ++i) { bool rowwin = true; bool colwin = true; for (unsigned j = 0; j < board_dim; ++j) { rowwin &= boardData[i*board_dim + j] == mark; colwin &= boardData[j*board_dim + i] == mark; } if (colwin || rowwin) return true; } //check for across patterns, one space between each marked space for solution... if (boardData[space3] == boardData[space5] && boardData[space5] == boardData[space7]) return true; if (boardData[space1] == boardData[space5] && boardData[space5] == boardData[space9]) return true; return false;}bool Data::checkCatsGame(const int &turnCnt) const{ if (turnCnt < MAX_TURNS) return false; else return true;}void Data::gameReset() { boardData = 123456789;}Game.h#ifndef GAME#define GAME#include Data.h#include Screen.hclass Game{ Data board; Screen view;public: Game() = default; ~Game() = default; void turn(const char&); void run(); bool getReplayInput();};#endif // !GAMEGame.cpp#include Game.h#include Constants.h#include <iostream>void Game::turn(const char &mark) { bool inputCheck = false; size_t posChoice; while (!inputCheck) { //checks data type if (std::cin >> posChoice) { if (posChoice < 10 && posChoice > 0) { char spaceCheck = board.boardSpaceValue(posChoice); //checks if space has been marked if (spaceCheck != 'X' && spaceCheck != 'O') { board.markBoard(posChoice, mark); inputCheck = true; } else { view.errorMsg(errBoard); //Space has already been marked } } else { view.errorMsg(errRecognize); //Space not within board range } } else { view.errorMsg(errType); //incorrect data type std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } }}bool Game::getReplayInput() { bool inputCheck = false; char yesOrNo; while (!inputCheck) { if (std::cin >> yesOrNo) { yesOrNo = toupper(yesOrNo); if (yesOrNo == 'Y') { return true; } else if (yesOrNo == 'N') { return false; } else { view.errorMsg(errRecognize); } } else { view.errorMsg(errType); std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } }}void Game::run() { bool gameWin = false, tie = false, playAgain = false; int turnCnt = 0; //setup view.welcomeMsg(); view.draw(board.printBoard()); //gameplay while (!gameWin && !tie) { turnCnt++; char playerMark = ((turnCnt % 2) ? board.player1Mark() : board.player2Mark()); view.signalUserInput((playerMark == 'X') ? 1 : 2); turn(playerMark); gameWin = board.checkWin(playerMark); tie = board.checkCatsGame(turnCnt); view.draw(board.printBoard()); } //signal winner if (gameWin) { view.gameWinMsg(turnCnt); } //signal tie game else { view.gameTieMsg(); } //check if user wishes to replay playAgain = getReplayInput(); if (playAgain) { board.gameReset(); run(); }}Screen.h#ifndef SCREEN#define SCREEN#include <string>class Screen{public: Screen() = default; ~Screen() = default; void errorMsg(const int&) const; void signalUserInput(const int&) const; void welcomeMsg() const; void draw(const std::string &) const; void gameWinMsg(const size_t&) const; void gameTieMsg() const;};#endifScreen.cpp#include Screen.h#include Constants.h#include <iostream>void Screen::errorMsg(const int& errNumber) const{ if (errNumber == errRecognize) { std::cout << Input not recognized, try again:\n; } if (errNumber == errType) { std::cout << Incorrect data type, try again:\n; } if (errNumber == errBoard) { std::cout << Board space has already been marked, try agian:\n; }}void Screen::signalUserInput(const int &player) const{ std::cout << Player << player << please select a space to mark: ;}void Screen::welcomeMsg() const { std::cout << Welcome to tic tac toe, player1 will be 'X' and player2 will be 'O'\n;}void Screen::gameWinMsg(const size_t& turnCnt) const{ if (turnCnt % 2) { std::cout << Player 1 wins the game!\nPlay again? Y/N: ; } else std::cout << Player 2 wins the game!\nPlay again? Y/N: ;}void Screen::gameTieMsg() const{ std::cout << Tie!\nGame over!\nPlay again? Y/N: ;}void Screen::draw(const std::string &board) const{ std::cout << << board[space1] << << | << << board[space2] << << | << << board[space3] << \n << ___|___|___\n << << board[space4] << << | << << board[space5] << << | << << board[space6] << \n << ___|___|___\n << << board[space7] << << | << << board[space8] << << | << << board[space9] << \n\n;}Source.cpp#include Game.h#include <iostream>void pause() { std::string pause; std::cout << Press any key followed by enter to continue...; std::cin >> pause;}int main() { Game game; game.run(); pause();} | Tic Tac Toe C++ follow up | c++;object oriented;tic tac toe | null |
_codereview.14325 | I wrote a predicate used in a remove_if call that deletes shared_ptr's of type StemmedSentence from an vector of sentences. The predicate:class EraseSentenceIf { ArrayStemmedSnippet * m_ass;public: EraseSentenceIf(ArrayStemmedSnippet *ass) : m_ass(ass) { } bool operator()(const std::shared_ptr< ArrayStemmedSnippet::StemmedSentence>& s) { std::shared_ptr<ArrayStemmedSnippet::StemmedSentence> tmp = s; // --- set StemmedSentnce object in ArrayStemmedSnippet class s->setParent(m_ass); // --- if true delete this sentence) if (s->trimStopWords()) { tmp.reset(); return true; } return false; }};The remove_if call:EraseSentenceIf esi(this);sentences.erase( std::remove_if( sentences.begin(), sentences.end(), esi), sentences.end());Declaration:std::vector<shared_ptr<StemmedSentence> > sentences;The construction of the sentences objects looks like this:sentences.push_back(shared_ptr<StemmedSentence>( new StemmedSentence(index, i - 1 )));The code seems to run fine, valgrind / gdb does not moan. I just want to get sure that I handle the deletion (or release) of the shared_ptr in a correct way. Can somebody please confirm this? Maybe I can improve something or I overlooked an important point. Thanks for your comments! | Is this predicate valid to delete single shared_ptr's? | c++;c++11 | Within the predicate you make a copy of the shared_ptr hence incrementing the reference count: std::shared_ptr<ArrayStemmedSnippet::StemmedSentence> tmp = s;A few lines later you explicitly reset this copy (note that this does not release any memory unless it's the last living shared_ptr referring to the pointee): // --- if true delete this sentence) if (s->trimStopWords()) { // NOT NECESSARY -- reference count will be decremented when tmp falls out of scope tmp.reset(); return true; }The actual deletion occurs when the shared_ptr residing inside the vector is destroyed (assuming it's the last remaining copy):sentences.erase( std::remove_if( sentences.begin(), sentences.end(), esi), sentences.end());So, everything will work fine as it is but the tmp variable in the predicate is unnecessary. |
_unix.139955 | I have the following problem:When I'm trying to execute ls as user abc with the following command I get an error:xyz@host:~/temp$ sudo -u abc ls[sudo] password for xyz:Sorry, user xyz is not allowed to execute '/bin/ls' as abc on host.But if I do su abc and then execute ls I have no problemCan anyone help? | Problem executing command as a different user with sudo -u | sudo;su | You should configure sudo security policy to allow user xyz exec something as user abc. Read 'man sudoers' and use visudo command to configure /etc/sudoers.For example let's allow user xyz exec /usr/bin/whoami as user abc without password. Add this string into /etc/sudoers (with visudo, don't edit /etc/sudoers directly):xyz ALL = (abc) NOPASSWD: /usr/bin/whoamiAnd now test it:xyz@host:~$ sudo -u abc /usr/bin/whoamiabc |
_unix.371685 | I recently installed CentOS 7.3.1611, which doesn't come with many packages, even when you add useful repos like EPEL, NUX, CERT Forensic Tools, etc.In particular, gnumeric is not included, and the latest version of gnumeric (1.12.32) won't compile unless you upgrade the dependencies outside of yum, which I wanted to avoid.Through trial and error, I found gnumeric 1.10.17 will compile, and I'm pretty it's the highest version that will.Is there a site that lists which versions of which software will compile with CentOS 7.3.1611 or, more generally, with a given OS version?I tried to be clever by Google searching: gnumeric 1.10.17 7.3.1611 centos (and several variants), and virtually all of the results were directly or indirectly from distrowatch.comI visited https://distrowatch.com/?newsid=09666 (for CentOS 7-1611, which I'm pretty sure is the same thing as 7.3.1611), but gnumeric isn't listed there. Apparently, however, there are similar distros that bundle gnumeric 1.10.17, strengthening my belief that there's a major change after that version.Since I'll have to go through the pain myself, I wouldn't creating a page on the CentOS wiki or whatever, but was wondering if someone had already done this. | Find source code compatible with CentOS 7.3.1611 | centos;compiling;version | null |
_webapps.62624 | Yesterday I went to reply to a comment and was told I was temporarily blocked, I can't remember exactly what the message said but after regaining access to my account it told me my account may have been used by spammers and it told me to check my activity log.What confuses me after looking at my activity log is that the day before I got blocked I only liked 3 pictures, liked one post and commented on one post. My password is a 50 character, secure password, I have 2 step verification turned on, I don't 'like' any pages and don't click dodgy looking links so my account can't have been compromised, especially being as 2 step verification is enabled. Can someone shed some light on this for me? I know I was only 'temporarily blocked' but does anyone know how many times you can get blocked before your account is permanently blocked or deleted? I'm worried about using the service now as I don't want to get my account permanently banned or deleted. | Why was I temporarily blocked from Facebook for liking 5 statuses? | facebook | null |
_unix.371443 | Sample Log : type=SERVICE_START msg=audit(1497515461.023:2020433): pid=1 uid=0 auid=4294967295 ses=4294967295 msg=' comm=systemd-tmpfiles-clean exe=/lib/systemd/systemd hostname=? addr=? terminal=? res=success'type=SERVICE_STOP msg=audit(1497515461.023:2020434): pid=1 uid=0 auid=4294967295 ses=4294967295 msg=' comm=systemd-tmpfiles-clean exe=/lib/systemd/systemd hostname=? addr=? terminal=? res=success'What is so specific to the command systemd-tmpfiles-clean that makes it restart audit daemon? | Why does linux audit daemon restart periodically with the following log? | services;daemon;linux audit | null |
_codereview.121967 | How can I reduce the lines I use with this code block?if ((test.contains(1.jpg) || test.contains(1.png)) && (maxP == false)){ page++; add = 1; if (QFile().exists(basepath + spage + .jpg)){ p_left = basepath + spage + .jpg; } else if(QFile().exists(basepath + spage+ .png)){ p_left = basepath + spage + .png; } if (QFile().exists(basepath + QString::number(page + 1) + .jpg)){ p_right = basepath + inc + .jpg; } else if(QFile().exists(basepath + QString::number(page + 1) + .png)){ p_right = basepath + inc + .png; } } else if ((test.contains(1.jpg) || test.contains(1.png)) && (maxP == true)){ gpage = max; add = 1; if (QFile().exists(basepath + smax + .jpg)){ p_left = basepath + smax + .jpg; } else if(QFile().exists(basepath + smax + .png)){ p_left = basepath + smax + .png; } if (QFile().exists(basepath + QString::number(page + 1) + .jpg)){ p_right = basepath + sinc + .jpg; } else if(QFile().exists(basepath + QString::number(page + 1) + .png)){ p_right = basepath + sinc + .png; } } | Conditionally set strings if files exist | c++;qt | I see a number of things that may help you improve your code.Use named constantsThere are a number of constant strings which are used repeatedly. If they're used more than once, it's probably a sign that you should use named constants instead.constexpr static char[] JPG_EXT{.jpg};constexpr static char[] PNG_EXT{.png};Consolidate tests in compound if statementsRight now the code is basically this:if ((test.contains(1.jpg) || test.contains(1.png)) && (maxP == false)){ // do things} else if ((test.contains(1.jpg) || test.contains(1.png)) && (maxP == true)){ // do other things}This can be simplified like this:if ((test.contains(1.jpg) || test.contains(1.png)) { if (maxP) { // do other things } else { // maxP must be false // do things }}Consolidate code where only the data changesThe code currently has repeated patterns like this:if (QFile().exists(basepath + smax + .jpg)){ p_left = basepath + smax + .jpg;}It then repeats, but with slightly different data. That suggests further consolidation:if ((test.contains(1.jpg) || test.contains(1.png)) { QString leftbase, rightbase; if (maxP) { gpage = max; leftbase = basepath + smax; rightbase = basepath + sinc; } else { page++; leftbase = basepath + spage; rightbase = basepath + inc; } add = 1; if (QFile(leftbase + JPG_EXT).exists()) { p_left = leftbase + JPG_EXT; } else if (QFile(leftbase + PNG_EXT).exists()) { p_left = leftbase + PNG_EXT; } if(QFile(basepath + QString::number(page + 1) + JPG_EXT).exists()){ p_right = rightbase + JPG_EXT; } else if(QFile(basepath + QString::number(page + 1) + PNG_EXT).exists(){ p_right = rightbase + PNG_EXT; }}Use a function for repeated actionsIf you find yourself writing similar code multiple times, it might be a sign that you could use a function. In this code, I'd write this:void setIfJpgOrPngExists(const QString& querybase, const QString& answerbase, QString &target) { if (QFile(querybase + JPG_EXT).exists()) { target = answerbase + JPG_EXT; } else if (QFile(querybase + PNG_EXT).exists()) { target = answerbase + PNG_EXT; }}if ((test.contains(1.jpg) || test.contains(1.png)) { QString leftbase, rightbase; if (maxP) { gpage = max; leftbase = basepath + smax; rightbase = basepath + sinc; } else { page++; leftbase = basepath + spage; rightbase = basepath + inc; } add = 1; setIfJpgOrPngExists(leftbase, leftbase, p_left); setIfJpgOrPngExists(basepath + QString::number(page + 1), rightbase, p_right);} |
_unix.275422 | How can I use sed to substitute a space with an _ only when it occurs in a text file after the string title= and between For example (lines in a text file):title=This is the title of my book img=scr </header><!-- .entry-header -->title=Today is a beautiful day img=scr </header><!-- .entrrrrkkky-header -->Desired modified text file after sed:title=This_is_the_title_of_my_book img=scr </header><!-- .entry-header -->title=Today_is_a_beautiful_day img=scr </header><!-- .entrrrrkkky-header -->Basically, the space would only be substituted for a _ when it occurs between the after the string title=The name of the text file is arbitrary - say file.txt | Using sed to replace spaces in text files with _ only when between after specific string | text processing;sed | null |
_unix.38728 | I installed monodevelop from the repositories because I want to try the mono-D plugin, but when I go to the Gallery in Add-in Manager, it says No add-ins foundI tried adding http://mono-d.alexanderbothe.com/ as a repository, but it requires monodevelop version 2.95 and the one in the repository is version 2.6:The selected add-ins can't be installed because there are dependency conflictsThe package 'Ide v2.9.5' could not be found in any repository | how to install monodevelop with d language add-in on Mint 12 | linux mint;mono | It looks like monodevelop 2.95 is a development release, so won't find it in the repository. Monodevelop 3.0 has just been released (May 14, 2012). I think this is the version you need. You can download it from MonoDevelop web page. No prebuilt package is available for Ubuntu/Mint right now, so you best option is to build it from the source (using the previous version of mono presumably). If you are new to building packages from source, it is actually a straightforward process (once you have all the build tools/libraries installed):downloaduntar./configuremakesudo make installAlternatively you can wait for a prebuilt package. |
_unix.97094 | I am using gnome-terminal in LXDE. When I have several gnome-terminal windows open, after some time the cursor in the inactive window starts to blink as well, as if the inactive window was actually active. This only happens with gnome-terminal. Other terminal emulators such as LXTerminal work fine.see video of the problem here: http://youtu.be/nRBehoJ1L7YI am aware of this bug. But this should have been fixed in my version of xserver-xorg-core 1.12.4-6. I am using Debian Wheezy and gnome-terminal 3.4.1.1-2 I am wondering if this could be caused because I am using gnome-terminal on LXDE. Could there be some gnome component missing? I have no way of testing if the same problem exists on Gnome. | gnome-terminal: cursor blinks in inactive window | debian;gnome terminal;lxde | You can switch to terminator.It is an awesome full featured terminal emulator. It is a bit ugly (in my opinion) when you install, but can easily customize it and even made it look like gnome-terminal. |
_cs.41925 | Consider the following adaptation of the traveling salesman problem:Given a complete, undirected graph $G$ with nonnegative edge weights, color each vertex either red or blue. Find the shortest path that visits all vertices exactly once (does not need to return to starting vertex), but does not visit vertices of the same color more than 3 times in a row (i.e. the path$$red \to blue \to blue \to blue \to red$$is valid but$$red \to blue \to blue \to blue \to blue$$is not. Assume that there are the same number of red and blue vertices.I'm trying to come up with an algorithm to at least approximate a shortest path given this constraint. My initial thought was the following (besides simply trying all $|V|!$ different paths):Greedy Approach: Choose a starting vertex $v_0$ and at each step, simply choose the vertex $v_1$ that minimizes $d(v_0, v_1)$. However, keep a record of the colors of $v_{i}$, $v_{i-1}$, and $v_{i-2}$ at each step, and if the optimal choice of the next vertex $v_{i+1}$ violates the color constraint, choose the next best vertex.The only problem I see with this is that you can 'run out' of vertices of a given color. That is, you could reach a point where there are more than $3$ vertices remaining, but they are all of the same color. This would make it impossible to complete the path.My Question: Does anyone have any suggestions on algorithms to try? Maybe a modification to my suggested greedy approach to make it complete, or another paradigm all together?(I know that this problem is $NP$-complete - that's why I'm seeking an approximation algorithm.) | Seeking Efficient Approximation Algorithm for Adaptation of TSP | algorithms;np complete;approximation;traveling salesman | null |
_codereview.29362 | There are many PHP PDO classes out there, agreed. However I find they do not allow for flexibility. So I created one that helps reduce development time as little as it may be but it does the job (maybe apart from the disconnect part, but it allows to trace whether database is connected via $database->isConnected). Can you please point out any flaws and any possible improvements?<?php class db { public $isConnected; protected $datab; public function __construct($username, $password, $host, $dbname, $options=array()){ $this->isConnected = true; try { $this->datab = new PDO(mysql:host={$host};dbname={$dbname};charset=utf8, $username, $password, $options); $this->datab->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $this->datab->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); } catch(PDOException $e) { $this->isConnected = false; throw new Exception($e->getMessage()); } } public function Disconnect(){ $this->datab = null; $this->isConnected = false; } public function getRow($query, $params=array()){ try{ $stmt = $this->datab->prepare($query); $stmt->execute($params); return $stmt->fetch(); }catch(PDOException $e){ throw new Exception($e->getMessage()); } } public function getRows($query, $params=array()){ try{ $stmt = $this->datab->prepare($query); $stmt->execute($params); return $stmt->fetchAll(); }catch(PDOException $e){ throw new Exception($e->getMessage()); } } public function insertRow($query, $params){ try{ $stmt = $this->datab->prepare($query); $stmt->execute($params); }catch(PDOException $e){ throw new Exception($e->getMessage()); } } public function updateRow($query, $params){ return $this->insertRow($query, $params); } public function deleteRow($query, $params){ return $this->insertRow($query, $params); } } //USAGE /* Connecting to DataBase $database = new db(root, , localhost, database, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8')); Getting row $getrow = $database->getRow(SELECT email, username FROM users WHERE username =?, array(yusaf)); Getting multiple rows $getrows = $database->getRows(SELECT id, username FROM users); inserting a row $insertrow = $database ->insertRow(INSERT INTO users (username, email) VALUES (?, ?), array(yusaf, [email protected])); updating existing row $updaterow = $database->updateRow(UPDATE users SET username = ?, email = ? WHERE id = ?, array(yusafk, [email protected], 1)); delete a row $deleterow = $database->deleteRow(DELETE FROM users WHERE id = ?, array(1)); disconnecting from database $database->Disconnect(); checking if database is connected if($database->isConnected){ echo you are connected to the database; }else{ echo you are not connected to the database; } */ | Class for reducing development time | php;object oriented;mysql;pdo | Personally, I must say that close to all PDO derived/based classes I've seen so far suffer from the same problem: They are, essentially, completely pointless.Let me be clear: PDO offers a clear, easy to maintain and neat interface on its own, wrapping it in a custom class to better suit the needs of a particular project is essentially taking a decent OO tool, and altering it so that you can't reuse it as easily in other projects. If you were to write a wrapper around MySQLi, I could understand the reasoning, but PDO? No, I'm really struggeling to understand the logic behind that unless:You were to write a table mapper class to go with it, that establishes a connection between the tables you query, and the data models into which you store the data. Not unlike how Zend\Db works.MySQL is, as you well know, not as flexible as PHP is in terms of data-types. If you are going to write a DB abstraction layer, common sense dictates that layer reflects that: it should use casts, constants, filters as well as prepared statements to reflect that.Most mature code out there also offerst an API that doesn't require you to write your own queries:$query = $db->select('table') ->fields(array('user', 'role', 'last_active') ->where('hash = ?', $pwdHash);These abstraction layers often (if not always) offer another benefit, they build the queries for you, based on what DB you're connection to. If you're using mysql, they'll build a MySQL query, if you happen to switch to PostgreSQL, they'll churn out pg queries, without the need to rewrite thousands of queries. If you want to persist and write your own abstraction layer, make sure you offer something similar, too. If you don't, you're back to square one: embarking on a labour intensive, pointless adventure that won't be worth it.An alternative approach is to extend the PDO class. Again, this has been done before and is, in theory, perfectly OK. Although, again this might be personal, it does violate one principle which is upheld by many devs I know: Don't extend, or attempt to change an object you don't own. PDO is a core object,so it's pretty clear you don't own it.Suppose you were to write something like:class MyDO extends PDO{ public function createProcedure(array $arguments, $body) { //create SP on MySQL server, and return }}And lets assume that, after some serious debugging, and testing, you actually got this working. Great! But then what if, some time in the future, PDO got its own createProcedure method? it'll probably outperform yours, and might be more powerful. That, in itself isn't a problem, but suppose it's signature were different, too:public function createProcedure (stdClass $arguments){}That would mean you either have to ditch your method, and refactor your entire code-base to sing to the tune of PDO's latest and greatest hit, or you'd have to alter your method to:public function createProcedure(array $arguments, $body){ $arguments = (object) $arguments;//create stdClass //parse $body and: $arguments->declare = $body[0]; $arguments->loops = (object) array('loop1' => $body[1], 'loop2' => $body[2]); $arguments->body = (object) array( 'main' => $body[3], 'loop1_body' => $body[4], 'loop2_body' => $body[5] ); return parent::createProcedure($arguments);}That would mean that, for all code you wrote, you're actually having to call 2 methods, turning your once so clever createProcedure method into dead weight. So what, you might say? Well, don't think you're out of the woods just yet, because This alternative method above is illegal, it can't be written, it can't work, it shouldn't work, it's just all shades of wrong, here's why:The Liskov principle states that a child (the class extending PDO) may not alter the signature of inherited methods if those alterations constitute a breach of contract, meaning the expected types (type-hints) may not be stricter than or different to the types defined in the parent (ie: array vs stdClass is not allowed). Additional arguments are allowed, provided they're optional.If the PDO method itself takes but a single argument of the type stdClass, then your child class may only add optional arguments, and should either drop the type-hint, or uphold it (ie: hint at stdClass, which would break all existing code), or don't hint at all (which is as error-prone as it gets).What's more, after a couple of months, people might use third party code (frameworks), that rely on the createProcedure method, and pass it an instance of stdClass. You'll have to change your method again, to the vague, and error prone signature:public function createProcedure($arrOrObject, $body = null){ if ($arrOrObject instanceof stdClass) { return parent::createProcedure($arrOrObject); } if ($body === null) { //What now?? } //parse body}If $body is null, and $arrOrObject is an array, the user might have structured the $arrOrObject array in the same way as PDO would like to see the object structured, in which case json_decode(json_encode($arrOrObject)); would do the trick (not casting, because a cast doesn't cast recursive), but it's just as likely that the code calling your method contains a bug. What to do? convert to an object, and try-catch, with the extra overhead that might cause?This leads me to the last, and for now biggest omission:When using a wrapper object, it's generally a good idea to implement a (slow) magic __call method, that checks if a method call was meant for the wrapper object, or if it was meant for the wrapped object.Using your object, I might want to set another attribute on the PDO extension, but since you failed to implement the setAttribute method, I can't change the charset, nor can I change how PDO deals with NULL values. Which can only be considered to be a glaring omission. Especially since you expect the user to pass bare PDO constants to the constructor. Basically, the least you should do is add:public function __call($method, array $arguments ){ return call_user_func_array($this->datab, $arguments);}This way, you semi-expose the actual wrapped object to the user, in the sense that, methods you haven't implemented can still be used. New methods that might be implemented in the future will automatically be accessible, too.What's more, you'll be able to validate/check the arguments and log which methods are used by the users, so that you could fine-tune your class to better reflect the way it is being used.Recap:Building an abstraction class on a user-friendly raw-API like PDO is, IMHO, like a broken pencil: PointlessExtending PDO means you don't have to create pass-through methods that call the wrapped API (like creating a prepare method), but it does mean there is a chance you'll have to refactor your code whenever PDO changesIf you still feel like using a wrapper object, either consider wrapping it around something less well known, but in some respects better (mysqli_* is what I'm hinting at), but implement the magic __call and, if required __callStatic methods.Again, if you're going to procede: work on an entire abstraction layer, that allows for users to map tables to data models, and take it from there. Ensure that those data-models can be used easily to build HTML forms, for example in order for those forms to be linked to the DB in the blink of an eye, bot don't forget about sanitizing your data, of course.On the code itself:There is one thing you have to fix about your code, above all else, and that's your constructor:I might choose to construct an object like so:$database = new db(user, pwd, host, mydb, array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ));Setting the default fetch-mode to fetch objects, and the new instance of PDO will be passed the correct attribute array. Sadly, right after constructing that PDO object, you're deciding that the default fetch-mode should've been PDO::FETCH_ASSOC, because 2 lines further down:$this->datab->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);I'd hate to use that code. Also, this just doesn't add up:try{ $this->datab = new PDO(mysql:host={$host};dbname={$dbname};charset=utf8, $username, $password, $options); $this->datab->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $this->datab->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);} catch(PDOException $e){ $this->isConnected = false; throw new Exception($e->getMessage());}Try-catch-throw? Why? The connection failed, the PDOException tells me why, that's what I want to know, why catch that exception, and throw a new, more general one? What if I passed PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT to the constructor, and the connection failed? You're probably better of replacing it with this:$this->datab = new PDO($connString, array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'//careful with this one, though));foreach($options as $attr => $value){ $this->datab->setAttribute($attr, $value);}And let the exception go. If the connection to the DB fails, the script can't do what it's supposed to do anyway. The PDOExceptions are usefull in a scenario where you're using transactions. If 999 queries succeeded, but the 1000th query failed, rather than inserting partial data, catching the exception, and rolling back the transaction is what you do, but catching an exception to rethrow it again is just silly.But, again, I'm not going to stop you from doing what you want, perhaps you can prove me wrong and actually make something great. But in order to do that, you must know what's out there already:As always start with the theory, wiki's a great place to startthe ORM wikiThe ActiveRecord Pattern wikidoctrineAnd all of its projectsNot in the least, its ORMPropel, haven't used it, but N.B. recommended itPHPActiveRecordZend\Db\Adapter and all of the components in the Zend\Db namespaceEven the old Zend_Db has something going for it, still |
_unix.335584 | I am trying to rename a folder with files which contain a datestamp like this: string_DD-MM-YYYY_hhmm.pdfto this format:string_YYYY-MM-DD_hhmm.pdfso that they sort by date when sorted by filename.Example: PB_KAZ_KtoNr_0463266665_01-02-2014_0341.pdf should become PB_KAZ_KtoNr_0463266665_2014-02-01_0341.pdf. I found this similar question but it's regarding DDMMYYYY format instead of DD-MM-YYYY and the answeres are way to complicated for my situation. As the string always is the same in content and length (24 characters) a simple command, that splits and reassembles the string by positions would be sufficient. Thanks in advance! | How to batch rename files and convert datestamp from DD-MM-YYYY to YYYY-MM-DD? | bash;shell script;ubuntu;rename;timestamps | With Perls rename (standalone command):rename -n 's/(.*)_(.*)-(.*)-(.*)_(.*.pdf)/$1_$4-$3-$2_$5/' *.pdfIf everything looks fine remove -n. |
_unix.23988 | I need to create an md5 hash of every directory and file inside of one main directory. The only thing that is keeping me from success is figuring out a way around files with a space in the path.I am using find for the recursive listing (I have read that find is the best way of doing this):c5-26-1# find /root/newdir/root/newdir/root/newdir/1/root/newdir/2/root/newdir/3/root/newdir/4/root/newdir/5/root/newdir/newdir2/root/newdir/newdir2/1/root/newdir/newdir2/2/root/newdir/new/root/newdir/dir/root/newdir/new dirWhen I try this with md5 I get two different outcomes, neither of which work:c5-26-1# md5 $(find /root/newdir) # same outcome using for loopMD5 (/root/newdir) = bc79a580f6c932937f6fcd454747db72MD5 (/root/newdir/1) = 94ca98295946310ce88e185ea57486d5MD5 (/root/newdir/2) = 8432051f64459be5a5e73dc2abd91795MD5 (/root/newdir/3) = d41d8cd98f00b204e9800998ecf8427eMD5 (/root/newdir/4) = d41d8cd98f00b204e9800998ecf8427eMD5 (/root/newdir/5) = d41d8cd98f00b204e9800998ecf8427eMD5 (/root/newdir/newdir2) = 722165901468b9596dbdddfe118759fbMD5 (/root/newdir/newdir2/1) = d41d8cd98f00b204e9800998ecf8427eMD5 (/root/newdir/newdir2/2) = d41d8cd98f00b204e9800998ecf8427eMD5 (/root/newdir/new) = 89d042c5f9d6ba485a654b543685ea86MD5 (/root/newdir/dir) = 148538718feba14839f5d1072854c5f4MD5 (/root/newdir/new) = 89d042c5f9d6ba485a654b543685ea86MD5 (dir) = 148538718feba14839f5d1072854c5f4or c5-26-1# find -X /root/newdir | xargs md5find: /root/newdir/new dir: illegal pathMD5 (/root/newdir) = bc79a580f6c932937f6fcd454747db72MD5 (/root/newdir/1) = 94ca98295946310ce88e185ea57486d5MD5 (/root/newdir/2) = 8432051f64459be5a5e73dc2abd91795MD5 (/root/newdir/3) = d41d8cd98f00b204e9800998ecf8427eMD5 (/root/newdir/4) = d41d8cd98f00b204e9800998ecf8427eMD5 (/root/newdir/5) = d41d8cd98f00b204e9800998ecf8427eMD5 (/root/newdir/newdir2) = 722165901468b9596dbdddfe118759fbMD5 (/root/newdir/newdir2/1) = d41d8cd98f00b204e9800998ecf8427eMD5 (/root/newdir/newdir2/2) = d41d8cd98f00b204e9800998ecf8427eMD5 (/root/newdir/new) = 89d042c5f9d6ba485a654b543685ea86MD5 (/root/newdir/dir) = 148538718feba14839f5d1072854c5f4How do I account for directories with spaces? | create md5 hash from a recursive file listing when some paths have spaces | find;filenames;xargs;recursive | xargs is rarely useful, because it expects input quoted in a highly peculiar way that no common tool produces. And as you've noticed mycommand $(find ) is no good, because it first concatenates all the file names and then splits at whitespace.Use the -exec primary of find to make it execute md5 with no intervening shell that would require quoting. If your implementation of find is reasonably current, then you can make it do what xargs is famous for, which is to invoke the md5 program once per batch of arguments.find /root/newdir -type f -exec md5 {} +If your find doesn't support -exec {} +, replace the + by \;. This makes find invoke md5 for each file in turn. It's slightly slower, but available everywhere. |
_softwareengineering.313312 | So master-slave replication is great, but it leaves the master as a single-point of failure. What is the strategy to solve this problem, if there is one?I'm looking for the computer science theory behind it, not for a product that magically supports it.Ok, the slave could become the new master, but what's the theory behind this fail-over transition? How it is done? | In a master-slave replication mechanism, how do you avoid / cope with the fact that the master is a single point of failure? Is there a solution? | database;data replication | null |
_webmaster.88324 | I want to move/create some sub-domains like so:example.com moves to apps.example.comcommunity.example.com moves to example.comThe apps sub-domain is new. The existing community sub-domainwill no longer be needed.I've already created the apps subdomain and moved the site that was at example.com to apps.example.com.I've also moved the site community subdomain so it now resides at example.com.Now I just need to figure out the best way to handle the redirects. For some reason I'm just having a tough time wrapping my mind around this and hoping for some help :)To sum up:Redirect original example.com posts to apps.example.comRedirect original community.example.com posts to example.comAnd, of course, ensure that all new posts on either site are going to be found in the right place!These are WordPress sites - and there are plugins but not sure if that's best.What would you all recommend? | 301 redirecting when swapping subdomains | redirects;301 redirect | null |
_vi.10929 | I've tried thisau BufWinEnter * if &l:buftype != 'nofile' | map <buffer> <CR> <Plug>(easymotion-prefix) | endifbut somehow this isn't working (easymotion isn't working). While this worksau BufWinEnter * map <buffer> <CR> <Plug>(easymotion-prefix) | How to add buffer-local mapping only if not in command-line-window | key bindings;autocmd | I'm not sure, but I think that | endif is in the {rhs} of the mapping command :map. To remove it, you could wrap the mapping in a chain and execute it, maybe like this:au BufWinEnter * if &l:buftype != 'nofile' | exe map <buffer> \<CR> \<Plug>(easymotion-prefix) | endif |
_reverseengineering.3164 | I have bought a USB frame grabber (Hauppauge WinTV HVR 1900) for a personal research project. A SDK exists, but unfortunately the company does not seem too keen on distributing it. I have to extract frames from a video stream in my software, and although it works perfectly with my webcam stream, it does not work with the frame grabber (that works perfectly with the bundled soft).The frame grabber has an integrated MPEG-2 encoder, so the output stream should be MPEG-2, but since it does not work, I guess it is not standard. VLC is able to read the stream, though. Since it seems I will have to reverse engineer to get my soft to read the output stream, and as I have never done that kind of thing, could someone please give me a hint on how to proceed about that? I mostly have experience with the python language. | Frame grabber reverse engineering | hardware | null |
_webmaster.17490 | I am trying to setup a website for this design studio and need to put in a widget which would allow people to Like, +1, follow on twitter etc. I have been writing code for some years now, but I am relatively new to web development. I was wondering if a widget or some online tool exists that would let me generate html/script code for this. | widget / template code for +1, Like, Follow on Twitter etc | facebook;twitter;social networks;google plus one | Addthis is what you're looking for. |
_codereview.23911 | Is this code correct?This code was adapted from this alphabeta pseudocode. AlphaBeta search is often mentioned but getting the code 100% correct is tricky.IGame is an interface with two methods: getScore() - evaluates the current game state from the viewpoint of the AI generateMoves() - creates possible moves from the current game state.class Search{ Move bestMove; Move findBestMove(int ply, IGame g) { bestMove = null; alpha_beta(ply, g, Integer.MINIMUM, Integer.MAXIMUM); return bestMove; } int alpha_beta(int depth, IGame g, int alpha, int beta) { if (depth == 0 || g.isGameFinished()) return g.getScore(); Move[] gameMove = g.generateMoves(); for (int i = 0; i < gameMove.length; i++) { g.execute(gameMove[i]); int score = -alpha_beta(depth - 1, -beta, -alpha); g.undo(gameMove[i]); if (alpha < score) { alpha = score; bestMove = gameMove[i]; } if (beta <= alpha) return alpha; } return alpha; } } | Java alphabeta search | java;search;ai | null |
_codereview.14752 | I have a central domain assembly which contains various rich domain models. Lots of business logic, etc. To keep this example simple, here's probably the simplest one:public class Location{ private int _id; public int ID { get { return _id; } private set { if (value == default(int)) throw new ArgumentNullException(ID); _id = value; } } private string _name; public string Name { get { return _name; } set { if (string.IsNullOrWhiteSpace(value)) throw new ArgumentNullException(Name); _name = value; } } public string Description { get; set; } private string _address; public string Address { get { return _address; } set { if (string.IsNullOrWhiteSpace(value)) throw new ArgumentNullException(Address); _address = value; GeoCoordinates = IoCContainerFactory.Current.GetInstance<Geocoder>().ConvertAddressToCoordinates(Address); } } public Coordinates GeoCoordinates { get; private set; } private Location() { } public Location(string name, string address) { Name = name; Description = string.Empty; Address = address; } public Location(int id, string name, string description, string address, Coordinates coordinates) { if (coordinates == null) throw new ArgumentNullException(GeoCoordinates); ID = id; Name = name; Description = description; Address = address; } public class Coordinates { public decimal Latitude { get; private set; } public decimal Longitude { get; private set; } private Coordinates() { } public Coordinates(decimal latitude, decimal longitude) : this() { Latitude = latitude; Longitude = longitude; } public override bool Equals(object obj) { if (obj == null) return false; if (!(obj is Coordinates)) return false; var coord = obj as Coordinates; return ((coord.Latitude == this.Latitude) && (coord.Longitude == this.Longitude)); } public override string ToString() { return string.Format(Latitude: {0}, Longitude: {1}, Latitude.ToString(), Longitude.ToString()); } }}For a number of reasons, I don't want to use these domain models as my presentation models in my MVC application. At first I was just creating very similar DTOs for the models to use as presentation models. Something like this:public class LocationViewModel{ public int ID { get; set; } public string Name { get; set; } public string Description { get; set; } public string Address { get; set; } public decimal Latitude { get; set; } public decimal Longitude { get; set; }}However, that doesn't make sense for every view situation. A Create action, for example, shouldn't have an ID property. A Delete action doesn't need all of that information. And so on.So now I'm ending up with presentation models that are one-to-one with the presentations themselves. Something like this:public class LocationCreateViewModel{ public string Name { get; set; } public string Description { get; set; } public string Address { get; set; }}public class LocationDetailsVieWModel{ public int ID { get; set; } public string Name { get; set; } public string Description { get; set; } public string Address { get; set; } public decimal Latitude { get; set; } public decimal Longitude { get; set; }}And so on, customized for the views that bind to them. This became further useful as I could use data annotations to make cleaner use of the ASP.NET MVC tooling. Something like this:public class LocationCreateViewModel{ [Required] public string Name { get; set; } public string Description { get; set; } [Required] public string Address { get; set; }}These can get more complex, but the point is that I'm keeping them on the presentation models because I don't feel they have a place in the business domain. I think it would be misleading to have a [Required] annotation on a class property if it doesn't actually make it required unless interpreted by a very specific set of tools. And since lots of other things use these domain models, not just this one MVC website, then I want to make sure the logic is really baked in to the models and not loosely applied for an assumed set of tools.A recurring piece of functionality in this setup is to convert between presentation models and domain models. So presentation models which need to convert to domain models have instance methods on them:public Location ToDomainModel();And presentations models which need to be built from domain models have static methods on them:public static ConstructFromDomainModel(int id);public static ConstructFromDomainModel(Location location);The original goal in all of this was to separate concerns. A lot. But I wonder if I've taken a wrong turn in that effort. This isn't necessarily an unmanageable amount of code, but I don't want it to become unmanageable. There's sort of a class explosion going on as more and more gets added. And the unit tests are increasing at an even faster rate (which will become a question all its own once I sort out this question).Is there a better way? Are there known patterns which would be better followed and still maintain the separation of concerns in a tool-agnostic approach? | Separating Models and ViewModels | c#;asp.net mvc 3 | null |
_cs.63604 | I have new logic which has syntax and semantics in usual natural languages and I have to create theorem prover/solver/reasoner for this logic. Is there framework or tool set that can generate such prover from the formal definition of grammar and semantics? I have heard about Isabelle/HOL, is this right set of tools. Is such generation a common path to proceed. Are the metalogical framework, prover compilers suitable for any kind of new logic?Of course, I can create parser and encode all the algorithms by myself from scratch but this is not the common practice, I guess? | Framework or tools to generate theorem prover/solver/reasoner for new logic | logic;sat solvers;automated theorem proving;reasoning;smt solvers | null |
_cstheory.33202 | I am a pretty proficient software engineer, but I don't know much theory.I want to learn more theory.Particular topics that I am interested in are:computational complexity, formal languages, and type theory.But I am at a loss as for how to begin learning about these fields.What resources would you recommend to someone who wants to learn more theory through self-study? Are there any theoretical computer science self-study guides for software engineers? | Theoretical computer science self-study resources for programmers | soft question;teaching;books | It's a wide field with a few quite different areas.I'd start with some of the most fundamental ideas about what computers are: Hopcroft and Ullman, Introduction to Automata Theory, Languages and Computation.The reason I'd recommend that in particular, is their emphasis on proofs. They guide you through a rigorous way of thinking. That's the difference between writing programs and being scientific. |
_unix.37863 | I don't have much Linux or networking experience, but I'm trying to SSH into an Ubuntu virtual machine from outside of my home network. The Ubuntu virtual machine (running inside VirtualBox) is running a Debian desktop. I did some research and found I had to forward port 22 from the router to the virtual machine.-I changed the network setting on the VM to bridge.-I'm forwarding the port to the VM.-I checked (http://www.yougetsignal.com/) to show the port as open.But when I try to connect it is still not working.ssh username@<public-ip-address>-- connection refusedIs there anything I have to do inside the virtual machine to allow incoming connections? Or forward any port?If there is anything I'm doing wrong, any help would be greatly appreciated!! | SSH into Ubuntu VM remotely | ubuntu;ssh;networking;router;port forwarding | null |
_unix.180711 | Recently I happend to experience a quite unpleasant power outagewhich caused my system to go down unexpectadly. After power cameback the system came back as well and other than a fsck being requiredall seemed fine. The unedifying surprise hit me when I first triedto access my pass password store - it complained about gpg being broken;so I checked with plaingpgand got this:gpg: failed to create temporary file `/home/meUser/.gnupg/.#lk0x14368b8.meBox.13459': Not a directorygpg: keyblock resource `/home/meUser/.gnupg/secring.gpg': general errorgpg: failed to create temporary file `/home/meUser/.gnupg/.#lk0x14379f0.meBox.13459': Not a directorygpg: keyblock resource `/home/meUser/.gnupg/pubring.gpg': general errorDoes this mean that gnupg is broken on my system now or is this somethinguser specific? I guess my password store is gone, just wondering how to fix gpg to set up a new store. | gnupg broken after power outage | gpg | Your folder /home/meUser/.gnupg is gone. You have to restore it from lost+found or backup. |
_unix.143790 | In the old days, all X11 applications would take standard command-line arguments to specify things like foreground/background color. Is there a way to do that today for GTK applications? In particular I'm interested in controlling the colors of zenity dialogs.I use Xfce with Fedora 20, if that matters.If it can't be done on command line, I'm open to hearing about alternatives. I don't know how to do this at all (even though command line would be preferable). | GTK: Specify application foreground and background color on command line | gnome;xfce;desktop;gtk;zenity | null |
_softwareengineering.141086 | Almost all of the mobile phones, except the ones being produced by Intel, use ARM based processors while desktop/server industry is dominated x86 processors. What features does one provide over the other with regards to the domination they have in their respective sectors? | Why does ARM processors dominate Mobile platforms while x86 dominates Desktop/Server platforms | mobile;operating systems;server;kernel;x86 | ARM concentrated on power consumption from the beginning. This has given them a huge advantage in almost anything that's battery powered.The popularity of x86 is primarily for historic reasons -- it's been there forever, and it's been good enough that most of the market has had little reason to switch to anything else. |
_unix.216798 | I have a dynamically allocated virtual disk, which was initially 40GB.I increased the disk size from 40 GB to 100GB first and then also updated the partition using GParted as described here,https://www.rootusers.com/use-gparted-to-increase-disk-size-of-a-linux-native-partition/But still the disk size does not update,df -h showsFilesystem Size Used Avail Use% Mounted on/dev/mapper/I0--vg-root 35G 33G 1.3M 100% /none 4.0K 0 4.0K 0% /sys/fs/cgroupudev 2.4G 4.0K 2.4G 1% /devtmpfs 485M 564K 484M 1% /runnone 5.0M 0 5.0M 0% /run/locknone 2.4G 4.0K 2.4G 1% /run/shmnone 100M 0 100M 0% /run/user/dev/sda1 236M 44M 180M 20% /boot/home/iadm/.Private 35G 33G 1.3M 100% /home/iadm | VDI size increase not reflecting | filesystems;virtualbox;gparted | The root partition is on an LVM logical volume (LV) named root in a volume group (VG) named I0-vg, so you must first expand the underlying physical volume (PV), then expand the LV, then expand the filesystem:pvresize /dev/<pv_dev>lvresize --extents +100%FREE I0-vg/rootresize2fs /dev/mapper/I0--vg-rootwhere <pv_dev> is the block device of your LVM PV. |
_unix.77894 | Cron:* */6 * * * /path/to/commandI want this cron to run once in every 6 hour.Whats wrong with the above cron definition, and why? | When will this cron run | cron | You have to specify a minute value in the first column. The star there makes it run on each minute value.10 */6 * * * /path/to/commandwill make it run 10 minutes past the hour, every six hours (on all days).From man 5 crontab: A field may be an asterisk (*), which always stands for 'first-last'. This implies all possible values. |
_webapps.57669 | I am trying to get this formula to work=countifs(J6:J365, =David & Victor, K6:K365, =g3)where G3 is a date value (e.g., 02/24/14).I am trying to count the instances in my spreadsheet where David & Victor had any activity on that date. It is an on-going sheet so the date changes as the week progresses. The formula works if I write it this way:=countifs(J6:J365, =David & Victor, K6:K365, =02/24/14)However this means that I have to modify the formula too many times. Can someone help me figure out how else I can do this? | Using cell reference with COUNTIFS formula | google spreadsheets | null |
_codereview.142463 | Here is a short program web scraping program written in Node.js. I'm just getting to grips with node and this is the first thing I've written with it. I'm liking it so far though I guess I'm kinda missing the point with the whole asynchronous aspect.This is supposed to be an extremely basic project. I'm just a beginner with this stuff. I know the program is pretty brittle in terms of what it could do with a real scrape but I'm happy that I've managed to put things together in not too much time (I only just started coding a few months ago).However, I'm having an absolute nightmare getting my head around promises and how I can make them work with this project with minimal libraries. So, I'm probably going to offend some of you for my 'band-aid-like' timeout functions.How would I rework this with promises without completely rewriting my code?//TASK: Create a command line application that goes to an ecommerce site to get the latest prices. //Save the scraped data in a spreadsheet (CSV format).'use strict';//Modules being used:var cheerio = require('cheerio');var json2csv = require('json2csv');var request = require('request');var moment = require('moment');var fs = require('fs');//harcoded urlvar url = 'http://shirts4mike.com/';//url for tshirt pagesvar urlSet = new Set();var remainder;var tshirtArray = [];// Load front page of shirts4mikefunction firstScrape(){ request(url, function(error, response, html) { if(!error && response.statusCode == 200){ var $ = cheerio.load(html); //iterate over links with 'shirt' $('a[href*=shirt]').each(function(){ var a = $(this).attr('href'); //create new link var scrapeLink = url + a; //for each new link, go in and find out if there is a submit button. //If there, add it to the set request(scrapeLink, function(error,response, html){ if(!error && response.statusCode == 200) { var $ = cheerio.load(html); //if page has a submit it must be a product page if($('[type=submit]').length !== 0){ //add page to set urlSet.add(scrapeLink); } else if(remainder == undefined) { //if not a product page, add it to remainder so it another scrape can be performed. remainder = scrapeLink; } } }); }); } }); secondScraper();}firstScrape();function secondScraper(){ setTimeout(function () { request(remainder, function(error, response, html) { if(!error && response.statusCode == 200){ var $ = cheerio.load(html); $('a[href*=shirt]').each(function(){ var a = $(this).attr('href'); //create new link var scrapeLink = url + a; request(scrapeLink, function(error,response, html){ if(!error && response.statusCode == 200){ var $ = cheerio.load(html); //collect remaining product pages and add to set if($('[type=submit]').length !== 0){ urlSet.add(scrapeLink); } } }); }); } }); lastScraper(); }, 2000);}function lastScraper(){ //call lastScraper so we can grab data from the set (product pages) setTimeout(function(){ //scrape set, product pages for(var item of urlSet){ var url = item; request(url, function(error, response, html){ if(!error && response.statusCode == 200){ var $ = cheerio.load(html); //grab data and store as variables var price = $('.price').text(); var imgURL = $('.shirt-picture').find('img').attr('src'); var title = $('body').find('.shirt-details > h1').text().slice(4); var tshirtObject = {}; //add values into tshirt object tshirtObject.Title = title; tshirtObject.Price = price; tshirtObject.ImageURL = imgURL; tshirtObject.URL = url; tshirtObject.Date = moment().format('MMMM Do YYYY, h:mm:ss a'); //add the object into the array of tshirts tshirtArray.push(tshirtObject); } }); } convertJson2Csv(); }, 2000);}function convertJson2Csv(){ setTimeout(function(){ //The scraper should generate a folder called `data` if it doesnt exist. var dir ='./data'; if(!fs.existsSync(dir)){ fs.mkdirSync(dir); } var fields = ['Title', 'Price', 'ImageURL', 'URL', 'Date']; //convert tshirt data into CSV and pass in fields var csv = json2csv({ data: tshirtArray, fields: fields }); //Name of file will be the date var fileDate = moment().format('MM-DD-YY'); var fileName = dir + '/' + fileDate + '.csv'; //Write file fs.writeFile(fileName, csv, {overwrite: true}, function(err) { console.log('file saved'); if (err) throw err; }); }, 2000);} | Basic web scrape project written in NodeJS | javascript;node.js;web scraping;promise | null |
_webapps.25542 | If people are following me, but I'm not following them back, do their tweets show up on my Twitter timeline? | Do I see tweets from users that I don't follow, even if they follow me? | twitter | The only way Tweets turn up in your timeline is if someone you are following Tweets or retweets.If someone is following you then your Tweets show up in their timeline - not the other way round.Tweets from people you're not following will turn up in your timeline if they mention you (@Lucy) - but with the latest reorganisation of the Twitter web interface they'll probably only appear on the @connect tab. |
_codereview.55627 | We have machine hostname as -dbx111.dc1.host.comdbx112.dc2.host.comdcx113.dc3.host.comdcx115.dev.host.comHere dc1, dc2, dc3 and dev are our datacenter and we will be having only four datacenter as of now. And also it might be possible that machine hostname can have more dots in between separated by another domain in future.Now I need to find out which datacenter my current machine is in as I will be running below code on the actual machine. And also I have two flows as of now: USERFLOW and DEVICEFLOW.public enum FlowTypeEnum { USERFLOW, DEVICEFLOW}Problem Statement: If my machine is in DC1 and flow type is USERFLOW then I need to return /test/datacenter/dc1 but if flow type is DEVICEFLOW then I need to return /testdevice/datacenter/dc1But if my machine is in DC2 and flow type is USERFLOW then I need to return /test/datacenter/dc2 but if flow type is DEVICEFLOW then I need to return /testdevice/datacenter/dc2.And if my machine is in DC3 and flow type is USERFLOW then I need to return /test/datacenter/dc3 but if flow type is DEVICEFLOW then I need to return /testdevice/datacenter/dc3.But if my machine datacenter is in DEV, and flow type is USERFLOW then I need to return /test/datacenter/dc1 but if flow type is DEVICEFLOW then I need to return /testdevice/datacenter/dc1.The only difference between USERFLOW and DEVICEFLOW is - For USERFLOW, I need to use /test and for DEVICEFLOW, I need to use /testdevice and other things are same. TestingEnum class -public class TestingDatacenter { public static void main(String[] args) { String LOCAL_POOK = DatacenterEnum.getOurlocation().toLocalPook(FlowTypeEnum.USERFLOW); System.out.println(LOCAL_POOK); }}DatacenterEnum class -public enum DatacenterEnum {DEV, DC1, DC2, DC3; public static DatacenterEnum getOurlocation() { return ourlocation; } public static String forCode(int code) { return (code >= 0 && code < values().length) ? values()[code].name() : null; } private static final DatacenterEnum ourlocation = compareLocation(); private static DatacenterEnum compareLocation() { String currenthost = getHostNameOfServer(); if (currenthost != null) { if (isDevMachine(currenthost)) { return DC1; } for (DatacenterEnum dc : values()) { String namepart = . + dc.name().toLowerCase() + .; if (currenthost.indexOf(namepart) >= 0) { return dc; } } } return null; } public String toLocalPook(FlowTypeEnum f) { String prefix = ; // below if else, looks pretty odd, may be it can be improved better? if (f.equals(FlowTypeEnum.DEVICEFLOW)) { prefix = /testdevice; } else if (f.equals(FlowTypeEnum.USERFLOW)) { prefix = /test; } if (this == DEV) { return prefix + /datacenter/dc1; } return prefix + /datacenter/ + name().toLowerCase(); } private static final String getHostNameOfServer() { try { return InetAddress.getLocalHost().getCanonicalHostName().toLowerCase(); } catch (UnknownHostException e) { // log an exception } return null; } private static boolean isDevMachine(String hostName) { return hostName.indexOf(. + DEV.name().toLowerCase() + .) >= 0; }}I'm opting for code review to see whether there is any better way of doing this. Is there anything which can be simplified and improved? | Efficiently returning the string basis on current datacenter | java;optimization;enum | final is meaningless on static methods :private static final String getHostNameOfServer() {For the following :// below if else, looks pretty odd, may be it can be improved better?if (f.equals(FlowTypeEnum.DEVICEFLOW)) { prefix = /testdevice;} else if (f.equals(FlowTypeEnum.USERFLOW)) { prefix = /test;}there are 2 alternativesmake a getPrefix() method on FlowTypeEnum, reducing the above code to :prefix = f.getPrefix();FlowTypeEnum could then look like this :public enum FlowTypeEnum { USERFLOW(/test), DEVICEFLOW(/testdevice); private final String prefix; FlowTypeEnum(String prefix) { this.prefix = prefix; } public String getPrefix() { return prefix; }}make a map that maps the the FlowTypeEnum instances to a prefix, reducing the above code to :prefix = mapToPrefix.get(f);In both cases you might even inline the prefix variable.Try to make code resistant to likely changes. In this case, server names and paths are likely to change. Pull these from config files.All these static methods don't seem to be at home on the DatacenterEnum, they don't really operate on DatacenterEnum instances. Perhaps they need to find a home on a new class, where they can be non static.It is unwise to hard code the data centers as enum instances. It simply won't scale. Renaming, removing or adding data centers in the field will require a new release.Use more meaningful names for variables : dc -> dataCenterf -> flowTypeReplace this :currenthost.indexOf(namepart) >= 0by the more readable :currenthost.contains(namepart) |
_softwareengineering.131520 | We are faced implementing a registration workflow with many branches. There are three main flows which in some conditions lead to one another. Each flow has at least four different steps; some steps interact with the server, and every step adds more information to the state. Also the requirement is to have it persistent between sessions, so if the user closes the app (this is a mobile app), it will restore the process from the last completed step with the state from the previous session.I think this could benefit from the use of the strategy pattern, but I've never had to implement it for such a complex case. Does anyone know of any examples in open source or articles from which I could find inspiration? Preferably the examples would be from a live/working/stable application.I'm interested in Java implementation mostly; we are developing for Java mobile phones: android, blackberry and J2ME. We have an SDK which is quite well separated from platform specific implementations, but examples in C++, C#, Objective-C or Python would be acceptable. | Can you point me to a nontrivial strategy pattern implementation? | learning;object oriented;design patterns;strategy | null |
_webapps.87856 | I'm trying out Backblaze B2. In order to use the b2 command line tool, I'm following the quick start directions at Create An Account. This page says:This page displays the account ID that you'll need to access your account. Make a note of it while you're here.but I can't see anything resembling an account ID on my page. (Yes, I have enabled the B2 Cloud Storage and have used the web interface to create buckets and upload files.) The example account page shown on the quick start page also doesn't show anything like an account ID. Where can I find my account ID and application key? | How can I get my Account ID on Backblaze B2? | account management | You'll want to go here:https://secure.backblaze.com/b2_buckets.htmthen you'll see the link to Show Account ID and Application Key |
_softwareengineering.349594 | On a lot of e-commerce websites, they have the main product image then multiple alternative images for the same product shown below. I was wondering what's the general idea behind how best to implement something like this? E.g. Here's a page where there is a main product image and multiple alternative views: https://www.macys.com/shop/product/lucky-brand-womens-eesa-block-heel-booties?ID=2902941&CategoryID=25122&tdp=cm_app~zMCOM-NAVAPP~xcm_zone~zPDP_ZONE_A~xcm_choiceId~zcidM05MAS-ccb609ca-512c-41fe-a118-caeb79dba76f%40H7%40customers%2Balso%2Bshopped%2425122%242902941~xcm_pos~zPos3I'm looking for a possible dynamic solution that dynamically fetches all alternative images for a product and shows them in a slider fashion underneath the main product image. Not looking for code but overall concept implementation breakdown like in steps and how you would approach this problem? I imagine, a have access to a main/base url that soemthing like product.com/images/ and I have to fetch data using a url with something like boots/1/image1.jpg where 1 and image1.jpg have to be dynamic content. So I have to fetch all those products using a url that way and then set the image to a collection of imageviews dynamically. Would something like that work per se? I will be using Xamarin and C# for the implementation. | How to setup e-commerce alternative images for one product? | c#;e commerce;xamarin | null |
_unix.344172 | I am using unix shell script and have an Input File with data as:3:abc1:xyz1:abc2:def10:xyzMy expected output is:4:abc11:xyz2:defi.e. Find unique string on each line after delimiter and add up the numbers before that. How to do this? | Count numbers present in each line for unique String using shell script | bash;shell script;text processing;awk | Here is a solution using awk. It accumulates the values into an array.awk -F : '{count[$2]+=$1} END {for (key in count) print key, count[key]}' awk_data.txtAnd here is a version, using a bash script:#!/usr/bin/env bashdeclare -A countwhile read line; do key=${line##*:} cnt=${line%%:*} count[$key]=$(($cnt + ${count[$key]=0}))done < $1for K in ${!count[@]}; do echo $K ${count[$K]}; doneAnd another bash version from the comments, using IFS=:#!/usr/bin/env bashdeclare -A countwhile IFS=: read -r cnt key; do count[$key]=$(($cnt + ${count[$key]=0}))done < $1for K in ${!count[@]}; do echo $K ${count[$K]}; done |
_scicomp.11265 | On a recommendation from Mathematica.SE, I am posting this on Computational Science.SE:I am trying to quantify stiffness of an ODE by relating it to the fine-ness with which NDSolve treats it's time step.BACKGROUNDFor the uninitiated:Essentially, when an ordinary differential equation is stiff and we attempt to solve it with NDSolve in Mathematica, it would employ a stiff solver to detect and reconcile stiffness.I use the stiff equation shown on wikipedia to demonstrate this. This equation is solved using BDF (backward difference formulation/formula) which is a recognized method to solve stiff equations.Equation and solution using NDSolve with BDFtMax=100;rSol=r/.NDSolve[r'[t]==-15 r[t]&&r[0]==1,r,{t,0,tMax},Method->{BDF,MaxDifferenceOrder->5}][[1]]Plots of solution r vs t{Plot[rSol[t],{t,0,100},PlotRange->{{0,tMax},Automatic}],LogPlot[rSol[t],{t,0,100},PlotRange->{{0,tMax},Automatic}]}Fig 1Fig 2Fig 1 shows that up to t=29.9 or so, there is considerable stiffness (unstable oscillations) that is reconciled by ensuring that the time step is sufficiently small.THE REAL QUESTION:What would be a good plot to quantify this stiffness and internal reconciliation/changing of time step? How can I best quantify stiffness graphically in Mathematica? | Stiff Equations - What to plot as a qualitative or quantitative measure of stiffness | finite difference;stiffness | null |
_unix.219402 | In h vim-script-intro.It says - will be interpreter as minus or negative depends on the situation.Thus echo -1 1 will result -1 1, and echo -1 -1 will result -2. Drove by my curiosity, I tried googled and stackoverflow-searched a bit about how to modify echo -1 -1 so that it can echo -1 -1, but no result found.Is it able to do that? How? | Is it able to echo parallel negative numbers in vim? | vim | null |
_cogsci.8023 | Is pruning defined as neural apoptosis or are connections (neural synapses) simply separated? At what rate, if known, does this occur in individuals (ages 18+)? | How actively does your brain physically prune connections? | neurobiology;memory;neurology | null |
_unix.47066 | I was originally of the impression that$ ./myprogmoo[CTRL-D]is exactly the same as$ echo moo > cow$ ./myprog < cowBut I found that myprog always counts one more \n in the second version than in the first. Why is this?Turns out wc does the same thing...$ wc -lmoo[CTRL-D]0(Apparently zero lines is possible?)$ echo moo > cow$ wc -l < cow1Can anyone explain this to me? | Does input redirection ( | io redirection;newlines | echo appends a newline, unless you tell it not to, by putting -n first or \c at the end, or putting -e first and \c at the end or... you really don't want to know all the varieties of echo. Use printf moo > cow and you'll have a file with zero lines. |
_cstheory.4117 | I'm a UK student who will soon be going to university and would like some advice from people who have already done this on what course to take. I really enjoy the theoretical side of computer science, especially the more mathematical concepts. I do enjoy the other area such as algorithm design and programming as a hobby, but I wouldn't really want to be a programmer/tech support/algorithm designer as a job. Those sort of jobs are just not for me. I would prefer a research type job, maybe in quantum computing. I currently' finishing my A-levels in physics and further maths, and I'm expecting A*s in both fields. Sorry if all this is a bit vague, but I would like some ideas from people about what the best degree is to take to get where I want, and what sort of jobs are out there. Also, if anyone knows what's some universities in UK to study this sort of thing at , I'd very much appreciate the advice. | Is a CS degree for me? | soft question;advice request;career | null |
_unix.193537 | Our system runs with Debian 6 squeeze (2.6.32) Kernel with N2600 hardware. I know the version is old. An upgrade is in later plans.Recently, we tried connecting multiple monitors (CRT and HDMI), and we had no luck in making this display controllable and also were not able to set the resolution to more than 800x600.On Googling, it was found that there were some graphic driver (Cedarview drivers) issues with the kernel.I am a little bit new at applying drivers patches to the kernel, so I am requesting some guidance with this.Processor: Atom N2600 with Cedarview OS: Debian 6Kernel: 2.6.32TRIAL 2:For last one week i am struggling to make my dual display work.Earlier it was with 2.632 kernel and my previous mail thread Upgrading guidance for Cedarview driver in Debian 6 - 2.6.32 Kernel and various forums confirmed me that possibility of achieving with 2.6.32 is ZERO. .Now the board has been updated with 3.4.106 kernel with wheezy.But, when i try to run Xorg -configure , it exits with an error message.created screens does not match number of detected devicesXorg -configure http://pastebin.com/G7sFuRYNxorg.0.log : http://pastebin.com/68WQ8ZfvMy requirement does not even worry about screen resolution all i wanted is to control my X display like on/offlspci info : http://pastebin.com/zBVesvmSBoard type : ATOM N2600request some guidance and troubleshooting ideas, | Upgrading guidance for Cedarview driver in Debian 6 - 2.6.32 | debian;linux kernel;drivers | null |
_unix.119997 | I don't want to lose any data, so I'm asking if the solution Novell offers is safe to try. If not, are there safe alternatives?Step-by-tedious-step:I have two volume groups: main and Rand; Rand is what I boot from while main is an older group.main/home stopped mounting due to a possible bad superblock. (this error)I found this Novell link suggesting vgcfgrestore yesterday, so I tried it. No bueno.I then ran fsck.jfs on /dev/main/home, which allowed it to mount. Success!This morning, I see errors. df -h shows /dev/mapper/Rand-root has 0 bytes free. Deleting a debian .iso--and more-- fails to change that. (20+ gigs were free yesterday.)vgscan, pvscan--a lot of utilities fail to work due to a disk full error.I reboot. df -h still reports 0 bytes free, but vgscan and pvscan work now.Something one of those utilities returned led me to try vgcfgrestore Rand. No change in df -h and now main/home (mounted at /mnt/10.10/) starts spewing I/O errors.Reboot. A BIOS/SMART error on a disk along with a pvscan error saying can't find device with uuid=uZ1fiS-5Wo4-VNzC-gzs0-ekVz-Bepn-1MZe82, which blkid identifies as /dev/sdb5.fdisk -l shows:Disk /dev/sdb: 120.0 GB, 120034123776 bytes255 heads, 63 sectors/track, 14593 cylindersUnits = cylinders of 16065 * 512 = 8225280 bytesSector size (logical/physical): 512 bytes / 512 bytesI/O size (minimum/optimal): 512 bytes / 512 bytesDisk identifier: 0x00039f8aDevice Boot Start End Blocks Id System/dev/sdb1 * 1 32 248832 83 LinuxPartition 1 does not end on cylinder boundary./dev/sdb2 32 14594 116969473 5 Extended/dev/sdb5 32 14594 116969472 8e Linux LVMNote: sector size is 4096 (not 512)The Novell link says my problem fits Symptom 2 and provides a solution, but says nothing about fdisk reporting a partition error. (Which may be causing the SMART error.)The Novell solution says to first identify the device, then run pvcreate with the UUID and device as parameters, then vgcfgrestore, vgscan, vgchange -ay, and fsck.If I try this, is there a chance pvcreate will damage anything?Also, for the pvcreate command, should I use /dev/sdb or /dev/sdb5 as the device?Output:~ sudo vgscan steven@Rand[sudo] password for steven: Reading all physical volumes. This may take a while... Found volume group Rand using metadata type lvm2 Couldn't find device with uuid uZ1fiS-5Wo4-VNzC-gzs0-ekVz-Bepn-1MZe82. Found volume group main using metadata type lvm2------------------------------------------------------------~ sudo pvscan steven@Rand Couldn't find device with uuid uZ1fiS-5Wo4-VNzC-gzs0-ekVz-Bepn-1MZe82. PV /dev/sdb5 VG Rand lvm2 [111.55 GiB / 0 free] PV unknown device VG main lvm2 [1.36 TiB / 0 free] PV /dev/sda1 VG main lvm2 [465.76 GiB / 461.76 GiB free] Total: 3 [1.93 TiB] / in use: 3 [1.93 TiB] / in no VG: 0 [0 ]------------------------------------------------------------~ blkid steven@Rand/dev/sdb1: UUID=ba9a3955-0b9c-4660-9852-0f9f405d2f8e SEC_TYPE=ext2 TYPE=ext3 /dev/sdb5: UUID=uZ1fiS-5Wo4-VNzC-gzs0-ekVz-Bepn-1MZe82 TYPE=LVM2_member /dev/sde1: LABEL=My Book UUID=A2CA0AEBCA0ABC13 TYPE=ntfs /dev/sdf1: UUID=5F8C6ED4773C3763 TYPE=ntfs ------------------------------------------------------------~ sudo lvs Couldn't find device with uuid uZ1fiS-5Wo4-VNzC-gzs0-ekVz-Bepn-1MZe82. LV VG Attr LSize Origin Snap% Move Log Copy% Convert root Rand -wi-ao 106.98g swap_1 Rand -wi-ao 4.56g home main -wi--- 1.35t root main -wi--- 2.00g swap main -wi--- 4.00g tmp main -wi--- 512.00m usr main -wi--- 6.00g var main -wi--- 2.00g ------------------------------------------------------------~ sudo lvscan ACTIVE '/dev/Rand/root' [106.98 GiB] inherit ACTIVE '/dev/Rand/swap_1' [4.56 GiB] inherit Couldn't find device with uuid uZ1fiS-5Wo4-VNzC-gzs0-ekVz-Bepn-1MZe82. inactive '/dev/main/swap' [4.00 GiB] inherit inactive '/dev/main/root' [2.00 GiB] inherit inactive '/dev/main/usr' [6.00 GiB] inherit inactive '/dev/main/var' [2.00 GiB] inherit inactive '/dev/main/tmp' [512.00 MiB] inherit inactive '/dev/main/home' [1.35 TiB] inherit------------------------------------------------------------~ sudo pvs Couldn't find device with uuid uZ1fiS-5Wo4-VNzC-gzs0-ekVz-Bepn-1MZe82. PV VG Fmt Attr PSize PFree /dev/sda1 main lvm2 a- 465.76g 461.76g /dev/sdb5 Rand lvm2 a- 111.55g 0 unknown device main lvm2 a- 1.36t 0 ------------------------------------------------------------~ blkid/dev/sdb1: UUID=ba9a3955-0b9c-4660-9852-0f9f405d2f8e SEC_TYPE=ext2 TYPE=ext3 /dev/sdb5: UUID=uZ1fiS-5Wo4-VNzC-gzs0-ekVz-Bepn-1MZe82 TYPE=LVM2_member /dev/sde1: LABEL=My Book UUID=A2CA0AEBCA0ABC13 TYPE=ntfs /dev/sdf1: UUID=5F8C6ED4773C3763 TYPE=ntfs ------------------------------------------------------------~ sudo vgs Couldn't find device with uuid uZ1fiS-5Wo4-VNzC-gzs0-ekVz-Bepn-1MZe82. VG #PV #LV #SN Attr VSize VFree Rand 1 2 0 wz--n- 111.55g 0 main 2 6 0 wz-pn- 1.82t 461.76g------------------------------------------------------------~ sudo vgscan Reading all physical volumes. This may take a while... Found volume group Rand using metadata type lvm2 Couldn't find device with uuid uZ1fiS-5Wo4-VNzC-gzs0-ekVz-Bepn-1MZe82. Found volume group main using metadata type lvm2------------------------------------------------------------~ sudo pvscan Couldn't find device with uuid uZ1fiS-5Wo4-VNzC-gzs0-ekVz-Bepn-1MZe82. PV /dev/sdb5 VG Rand lvm2 [111.55 GiB / 0 free] PV unknown device VG main lvm2 [1.36 TiB / 0 free] PV /dev/sda1 VG main lvm2 [465.76 GiB / 461.76 GiB free] Total: 3 [1.93 TiB] / in use: 3 [1.93 TiB] / in no VG: 0 [0 ]------------------------------------------------------------ | Is pvcreate destructive? Attempting to recover an lvm2 volume group | linux;data recovery;lvm;jfs | pvcreate writes PV metadata onto the device/partition, I think most would call that destructive however, since it's part of the LVM planning and layout it's also constructive. pvcreate could be destructive to data areas if any of the following parameters were changed to increase the metadata size or location.Depending on the command line options passed to pvcreate, one can write multiple copies of the metadata via --[pv]metadatacopies change the metadata size via --metadatasize change the data alignment via --dataalignment shift the start of the data area an additional alignment_offset via --dataalignmentoffset recreate a previous PV by specifying the UUID --uuid Also from the pvcreate man page.To see the location of the first Physical Extent of an existing Physical Volume use pvs -o +pe_start Typically, the metadata is written in the first few blocks of the device, up to the first usable PE, shown by pvs -o +pe_start and can be partially viewed by the following cmd. dd if=/dev/sdb5 bs=4096 count=4 |less Using less instead of od because much of the metadata is clear text and less does a good job of handling both binary and text data.Personally, I always set metadata copies to be more than one. |
_unix.316137 | I want to loop through thousands of folders all which contain a file called output(foldernumber).txt and check which of these output files DO NOT contain a keyword and have the script write out a list of these output files, so further analysis can be completed on them.This is what I have so far:a=1b=1for i in ~pwd ;do(cd $i/ && grep -L 'keyword' output$a.txt >> ../list.txt)a=$((a+b))doneErrors given say the output files do not exist and a blank list.txt file is made. Any advice please? | Loop round folders to find and list which folders contain a file excluding a keyword, in bash? | find;file search | find . -type f -regex .*/output[0-9]*\.txt -exec grep -L 'keyword' '{}' +or find . -type f -regex .*/output[0-9]*\.txt -print0 | xargs -0 grep -L 'keyword' |
_cogsci.16170 | Is it possible that the measured rise in average IQ in the last century is related to the discovery that drinking alcohol during pregnancy can result in birth defects, including issues with brain development?Has any work been done on this question? | Is the Flynn effect related to the discovery of Fetal Alcohol Syndrome? | abnormal psychology;intelligence | null |
_webmaster.95153 | What steps have you taken? Would love to get some useful insight. | What's the best way to secure wordpress site? | wordpress | null |
_softwareengineering.50381 | I am a sandwich training student in a company that has a little informatics service who develop web appUntil today, they work with simple php, a little CSS and no version control. So, the code becomes unmaintainable.The project manager would like to use php object, and i am the only one with some knows in it. But i am still a beginner with no experience in web dev, and after some search i am afraid to building a php MVC alone.So my question is : Should i convince the team to start using a framework like symfony ( i'm feeling ok to use it ) with the big change it impose to the team, or simply bring a better work structure with version control and tools like an ORM ?Thanks for your helpEDITED : with the hope it's now understandable | What tools or way to start a web project | web development;development process;web framework | You want to change 2 thing technology and process. My advice is not to change them at once ,there is a real change this is a to big step for the team resulting in a fall back to the old habits. I would recommend to start with the process and introduce version control. In this way changes are better traceable and when changing the technology you can fall back on source control when needed. |
_unix.230579 | Is the purpose of rsyslogd to handle logging of applications in userspace? For example i have 5 Jboss instances running on a server with custum applications running inside them. They all produce there own logfiles. I now want to aggregate the 5 files into one and send this aggregated stream of logfiles out on the network. Is this sort of thing what rsyslogd is constructed for? | rsyslogd used with any application or only Linux system logging? | logs;rsyslog | null |
_unix.171306 | TLDRHave I confused git-annex into thinking one machine is actually two?BackgroundI have a git-annex repository that has copies on three machines: Watt, Einstein, and Heisenberg in addition to a special remote on S3. Einstein is a server, and has both external public IPs and internal private (RFC1918) ones. Watt is on the LAN, and uses Einstein's LAN IP. Heisenberg is a laptop, so uses one of its public IPs (so it can still sync even when remote).When I run git-annex map on Watt, this is what I get:(Note that HeisenbergW5 is one of Heisenberg's host names, it has multiple interfaces...)The QuestionThat looks awfully like git-annex doesn't realize the Einstein that Heisenberg is sync'ing with is the same as the one Watt is sync'ing with (but, oddly, only in one direction). Do I need to worry about this, or is it just a minor issue with git-annex map? | Why doesn't git-annex map realize Einstein is one repository? | git annex | null |
_softwareengineering.179719 | I was wondering if there's some software to manage a XP project. I'm starting a school project and I want to follow this methodology, but, we don't have a place to work. Each one works at home (in pairs), therefore I can't follow XP ambient patterns.So, anyone knows of any software to manage this? | Is there some software to manage a XP Project? | project management;patterns and practices;extreme programming | XP is agile and extreme. If management is bad, XP makes the worst enemy out of it, so that the management is undefined :)CardsCRC cards can be used regardless of the process for as long as you follow OOP, same for prototyping which I'd expect mentioned here. PrototypingIn XP, the idea is typically first coded as a small prototype and then either thrown away for a better idea, or refactored into the final solution. (details)Pair ProgrammingThis is one important aspect of XP which you won't achieve by remote collaboration. A couple of programmers (not a love couple) sits at the same table with just one keyboard. While one person writes the code the other is meant to correct him or suggest useful improvements. (details)ReportingXP is iterative and incremental. There can be a release plan with features on the CRC cards and the schedule in which they are meant to be implemented. For every planned release, pile up some cards. Be careful not to exceed the available slot. You need to be measuring whether all those cards fit in, as explained in the next point.Release & Iteration PlanningFirst take one CRC card which you consider a small task, implement it, measure it, and then try to size the card to other cards. How many times bigger are the tasks on other cards compared to the card you've taken for your sizing? Use this technique to roughly estimate the size, so that you can stuff the right amount of work into each iteration.RisksThe biggest risk of XP, in my opinion, is unnecessary rework caused by unclear / unstable requirements or too much refactoring caused by the two programmers striving for perfection. Secondly, there is a risk the two programmers won't get along well. This may happen surprisingly often, providing they haven't been working together previously in this setup. XP is still a big experiment. I wouldn't consider it as reliable and dependable as conventional techniques such as the Unified Process.ApplicabilityThis is up to you to decide. Where may XP apply well and why?Software ToolsAlthough I am unaware of any specific XP project management software, other software may fit the purpose, such as CASE tools supporting CRC modelling and any Agile release / iteration planning software.For example:QuickCRC, Visual Paradigm, others. (CRC)Atlassian Greenhopper, VersionOne, Extreme Planner (Release / Iteration planning)Since you are collaborating remotely, consider also using some team collaboration software, such as Atlassian JIRA. |
_unix.147684 | I have been trying to ssh -X to my cluster running OpenSUSE 11.2. It used to work well for me. But now I get this message:X11 connection rejected because of wrong authentication.Failed to open the X11 display!So I tried to check the ownership and permission of the .Xauthority file usingsudo ls -al .Xauthorityand I get to see that the file is empty with size 0:-rw------- 1 <my-user-name> users 0 2014-07-31 10:03 .XauthorityWhen I log in with ssh -XvI get the following when i try to open xlockdebug1: client_input_channel_open: ctype x11 rchan 3 win 65536 max 16384debug1: client_request_x11: request from ::1 53267debug1: channel 1: new [x11]debug1: confirm x11X11 connection rejected because of wrong authentication.debug1: channel 1: free: x11, nchannels 2Error: Can't open display: localhost:10.0How would I fix this? | .Xauthority file is empty | ssh;x11;opensuse;xauth | null |
_codereview.47918 | Looking for help refactoring the following code to follow a Functional Programming paradigm.The first function builds a configuration object with default settings and optional presets, while the buildResourcePath will assemble a URL for the image service.getSizedUrl and getSizedSkuUrl returns a URL that will be used for an image tag.var imgSvcPath = './imageSizer.svc'; /** * configureImg * Build a configurtion object with sane defaults applied that can be used to construct a url for the ImageResizer service */function configureImg( options ){ options = options || {}; var defaults = { type: null, src: '', width: 120, height: null }, // use Image presets if an option.type provided presets = options.type ? Images.getPresets( options.type ) : {}; return $.extend( defaults, options, presets );};/** * buildResourcePath * Construct a url for the ImageResize service to be used for the src of <img /> */function buildResourcePath( svcName, options ){ // imageSizer.svc/GetResizedImage?path=[path]&size=[size]&quality=[quality] var resourcePath = [], conf = configureImg( options ), src = ( conf.skuId !== undefined ) ? '?sku=' + conf.skuId : '?path=' + encodeURI( conf.src ), size = '&size=' + ( conf.height ? 'h|' + conf.height : 'w|' + conf.width ), quality = conf.quality ? '&quality=' + conf.quality : ''; resourcePath.push( imgSvcPath, svcName, src, size, quality ); return resourcePath.join( '' );};/** * getSizedUrl * return src of <img /> for GetResizedImage */var getSizedUrl = function( options ){ if( 'undefined' === typeof options.src ) { console.error( 'upi.Services.Image::getSizedUrl configuration options must provide an image src string' ); } return buildResourcePath( 'GetResizedImage', options );};/** * getSizedSkuUrl * return src for an <img /> for GetResizedSkuImage */var getSizedUrlForSku = function( skuId, options ){ if( 'undefined' === typeof skuId ) { console.error( 'upi.Services.Image::getSizedSkuUrl configuration options must provide sku ID' ); } options = options || {}; options[ 'skuId' ] = skuId; return buildResourcePath( 'GetResizedSkuImage', options );};Image = { getSizedUrlForSku: getSizedUrlForSku, getSizedUrl: getSizedUrl}; | Refactor module for calls to internal image service | javascript;functional programming;url | null |
_unix.22747 | I'm trying to find files which are owned and have the primary group of root. Is there a parameter available to search for files like this? It's critical that all files in a certain directory not be owned by root, so I'd like to check periodically to make sure that someone on the server isn't accidentally creating files owned by root (namely me). Sure, chown -R user:user /path works, but I'd like to be able to check. | Finding files by their owner and file permissions | find | man find: -group gname File belongs to group gname (numeric group ID allowed). -user uname File is owned by user uname (numeric user ID allowed). |
_codereview.166332 | I have recently made a text based survival game.I hope that I can improve the game but I am not sure where I can improve it. Please do help me out and thank you for playing, hope you enjoy!PS It is NOT EASY, don't expect to get over it the first time#importimport random#functionsdef GenerateRandomScene(): scenes = ['Riverside','Top of the Mountain','Middle of Forest','Mountain Side']#desert excluded water = [True,False] startitems = ['Match','Match','Match','Match','Match','Pocket Knive','Jacket','Full Bottle of Clean Water','Full Bottle of Clean Water','Energy Bar','Banadges','Walking Stick','Journal','Match','Tea Leaves','Cooking Set'] randomstarting1 = ['Magnesium Fire Starter', 'Warming Pack', 'Sleeping Bag', 'Axe', 'Torch'] randomstarting2 = ['Batteries', 'Bucket', 'Vaseline', 'Hygiene Kit', 'String', 'Camp Set'] sceneforplayer = random.choice(scenes) if sceneforplayer == 'Riverside': water = True elif sceneforplayer == 'Desert': water = False else: water = random.choice(water) startitems.append(random.choice(randomstarting1)) startitems.append(random.choice(randomstarting2)) return [[random.randint(50,100),sceneforplayer,water],startitems]def GenerateRandomExplore(scene): itemscanbeobtained = ['Berries', 'Mushrooms', 'Tree Bark', 'Plant Fibre', 'Dead Grass', 'Dead Hare', 'Bones','Water Puddle'] retlist = [] if scene == 'Riverside': for i in range(random.randint(0,3)): retlist.append(random.choice(itemscanbeobtained)) return retlist elif scene == 'Top of the Mountain': itemscanbeobtained.remove('Berries') itemscanbeobtained.remove('Mushrooms') itemscanbeobtained.remove('Dead Hare') itemscanbeobtained.append('Dead Birds') itemscanbeobtained.append('Bait') itemscanbeobtained.append('Bird Nest') for i in range(random.randint(0,3)): retlist.append(random.choice(itemscanbeobtained)) return retlist elif scene == 'Middle of Forest': itemscanbeobtained.append('Bait') itemscanbeobtained.append('Bird Nest') for i in range(random.randint(0,3)): retlist.append(random.choice(itemscanbeobtained)) return retlist elif scene == 'Desert': itemscanbeobtained = ['Catti', 'Dead Catti Skin', 'Tree Bark', 'Stick', 'Well', 'Bones'] for i in range(random.randint(0,3)): retlist.append(random.choice(itemscanbeobtained)) return retlist else: itemscanbeobtained.remove('Berries') itemscanbeobtained.remove('Mushrooms') itemscanbeobtained.remove('Dead Hare') itemscanbeobtained.append('Dead Birds') itemscanbeobtained.append('Bait') itemscanbeobtained.append('Bird Nest') for i in range(random.randint(0, 3)): retlist.append(random.choice(itemscanbeobtained)) return retlistdef GetWood(inventory): if 'Axe' in inventory: minnum = 3 maxnum = 7 else: minnum = 1 maxnum = 5 return random.randint(minnum,maxnum)def Hunting(location,inventory,water): fishingrod = SearchItem('Fishing Rod',inventory) hygiene = SearchItem('Hygiene Kit',inventory) prey = ['bear','lion','cheetah','deer','cow','pig','fox','wolf','rabbit','toad','','',''] if fishingrod != 0 and water: prey.append('fish') if hygiene != 0: for i in range(2): prey.append('deer') prey.append('cow') prey.append('pig') prey.append('fox') prey.append('wolf') prey.append('rabbit') prey.append('toad') desertprey = ['camel','','','','','','','scorpian','poisonous scorpian'] if location == 'Desert': appear = random.choice(desertprey) if appear == 'poisonous scorpian': return [appear,'lethal'] else: return [appear,'True'] else: appear = random.choice(prey) if appear in ['bear','lion','cheetah']: success = random.choice(['True','False','False','False','False','False','False','False','False','False','False']) if success == 'False': injury = random.choice(['leg','arm','chest','broken ribs','broken leg','neck','lethal']) return [appear,injury] else: return [appear,success] else: return [appear,'True']def Menu(hydration,heat,hour,watersource,dndeterminer,dist,hunger): if hour > 12: hour = hour - 12 if dndeterminer == 0: dndeterminer = 1 elif dndeterminer == 1: dndeterminer = 0 if dndeterminer == 1: print There are +str(12-hour)+ hours of night time left else: print There are +str(12-hour)+ hours of day time left print '1. Chop Trees' print '2. Make Fire' print '3. Discover' print '4. Read The Rule of 3' print '5. Rest' print '6. Hunt' print '7. Walk' print '8. Craft' print '9. View Inventory' print '10. Drink Water' print '11. Eat' print '12. Use Items' print '13. Build Shelter' if watersource: print There are Water Sources around You print '14. Get Water' print 'Hydration: '+str(hydration) print 'Body Heat: '+str(heat) print Hunger: +str(hunger) print 'Distance between Civilisation: '+str(dist)+ ' km' print return [raw_input('Action >>> '),hour,dndeterminer]def Ruleof3(): print '3 mins without air' print '3 hours without shelter' print '3 days without water' print '3 weeks without food' print '3 months without hope'def Intro(): print Welcome! print This game is all about your survival techinques print Always Remember the rule of 3 Ruleof3() scene = GenerateRandomScene() print Your charactor is trapped in a +scene[0][1] print The distance to civilisation is +str(scene[0][0])+ km print Your aim is to help your charactor survive DisplayInventoryTry2(scene[1]) return scenedef Walk(dist,hydration,heat,inventory,dndeterminer): if 'Walking Stick' in inventory: maxwalking = 8 else: maxwalking = 5 if dndeterminer == 1 and (Torch not in inventory or Fire Torch not in inventory): maxwalking = 2 walked = random.randint(1,maxwalking) dist -= walked hydration -= 10 heat += 10 return [walked,hydration,heat]def DisplayInventoryTry2(inventory): amtcount = [] amtcountunique = [] for i in range(len(inventory)): if inventory[i] not in amtcountunique: amtcount.append([inventory[i],1]) amtcountunique.append(inventory[i]) else: for x in amtcount: if inventory[i] == x[0]: x[1]+=1 print You have: for i in amtcount: print str(i[1])+ x +str(i[0])def DrinkWater(inventory): amtcount = [] amtcountunique = [] water = [] for i in range(len(inventory)): if inventory[i] not in amtcountunique: amtcount.append([inventory[i], 1]) amtcountunique.append(inventory[i]) else: for x in amtcount: if inventory[i] == x[0]: x[1] += 1 for i in amtcount: if i[0] in [Full Bottle of Clean Water,Full Bottle of Dirty Water]: water.append(i) if water[0][0] == Full Bottle of Dirty Water: water[0],water[1] = water[1],water[0] print You have: if len(water) != 0: for i in range(len(water)): print str(i+1)+. + str(water[i][1])+ x +str(water[i][0]) print Which water would you want to drink? waters = raw_input(>>> ) if waters == '1': if water[0][1] - 1 >= 0: inventory.remove('Full Bottle of Clean Water') inventory.append('Empty Bottle') return [50, inventory] elif waters[0] == '2': if water[1][1] - 1 >= 0: inventory.remove('Full Bottle of Dirty Water') inventory.append('Empty Bottle') if random.randint(1,10) < random.randint(1,10): return [30,inventory] else: print The water is contaminated. Hydration - 30! return [-30,inventory] else: print Invalid Choice, No Such Choice Exists else: print You have no water suppliesdef CheckValidBody(hydration): if hydration > 100: hydration = 100 return hydration else: return hydrationdef CheckValidHunger(hydration): if hydration < 0: hydration = 0 return hydration else: return hydrationdef SearchItem(item,inventory): amtcount = [] amtcountunique = [] for i in range(len(inventory)): if inventory[i] not in amtcountunique: amtcount.append([inventory[i], 1]) amtcountunique.append(inventory[i]) else: for x in amtcount: if inventory[i] == x[0]: x[1] += 1 for i in amtcount: if i[0] == item: amount = i[1] try: return amount except: return 0def ReplaceItem(item,changeto, inventory): inventoryx = inventory inventoryx.remove(item) for i in range(len(inventory)-len(inventoryx)): inventory.append(changeto) return inventoryxdef MakeFire(inventory): inventoryx = FireLightingMethod(inventory) if inventoryx == inventory: print You cannot light fire as you do not have enough tinder return [0,inventory] else: print 'Fire Lighted!' print 'Body Heat + 30!' return [30,inventoryx]def SearchFood(inventory): food = ['berries', 'mushrooms', 'bear flesh', 'lion flesh', 'cheetah flesh', 'deer flesh', 'cow flesh', 'pig flesh', 'fox flesh', 'wolf flesh', 'rabbit flesh', 'toad flesh', 'camel flesh', 'scorpian flesh', 'poisonous scorpian flesh', 'fish'] energy = [15,15,40,70,70,40,50,40,20,20,40,20,40,20,20,60] ownedfood = [] for i in inventory: if i in food: ownedfood.append(i) if len(ownedfood) == 0: print You do not have any food else: DisplayInventoryTry2(ownedfood) print What do you want to eat? consume = raw_input(>>> ).lower() for i in ownedfood: if consume == i: owned = True else: owned = False if not owned: print You do not have this food else: inventory.remove(consume) if consume == 'rabbit flesh': inventory.append('rabbit skin') for i in range(len(food)): if food[i] == consume: energy = energy[i] return [inventory,energy]def CraftingList(): print >>> Crafting List <<< print 1. Tinder: 1 x Wood > 3 x Tinder print 2. String: 1 x Plant Fibre > 1 x String print 3. String: 1 x Dead Grass > 1 x String print 4. String: 1 x Cloth > 2 x String print 5. Cloth: 1 x Clothes > 3 x Cloth ***Tearing Clothes will increase the rate of heat loss! print 6. Bow Drill: 1 x String, 2 x Wood > 1 x Bow Drill print 7. Bone Knive: 1 x Bone, 1 x String > 1 x Bone Knive print 8. Bandage: 1 x Cloth > 3 x Bandage print 9. Fire Torch: 1 x Wood, 1 x String, 1 x Vaseline, 1 x Tree Bark > 1 x Fire Torch print 10. Fishing Rod: 1 x Wood, 1 x String, 1 x Knive > 1 x Fishing Rod print 11. Water Bottle: 1 x Rabbit Skin > 1 x Water Bottle print Which one do you want to craft? print return raw_input(>>> )def CraftItem(inventory,required_materials,crafted): amtcount = [] amtcountunique = [] consumestr = for i in range(len(required_materials)): if required_materials[i] not in amtcountunique: amtcount.append([required_materials[i],1]) amtcountunique.append(required_materials[i]) else: for x in amtcount: if required_materials[i] == x[0]: x[1]+=1 for i in amtcount: consumestr = consumestr + str(i[1])+ x +str(i[0]) + craftedstr = str(crafted[1])+ x +str(crafted[0]) print Crafting +str(craftedstr)+ will consume +str(consumestr) print Are you sure? confirmation = raw_input(Y / N >>> ) if confirmation.lower() == y: try: for i in required_materials: inventory.remove(i) for i in range(int(crafted[1])): inventory.append(crafted[0]) return inventory except: print You are missing some indgredients return inventorydef FireLightingMethod(inventory): lightingitems = ['Bow Drill', 'Match', 'Magnesium Fire Starter', 'Batteries'] ownedlighting = [] for i in inventory: if i in lightingitems: ownedlighting.append(i) print You have these lighting items: DisplayInventoryTry2(ownedlighting) print Which one do you want to use to light? tolight = raw_input(>>> ).lower() found = False for i in ownedlighting: if tolight == i.lower(): removeitem = i found = True if not found: print You cannot light fire as you do not have the item for i in inventory: if i == 'Tinder': if tolight == 'match': inventory.remove(removeitem) else: pass inventory.remove('Tinder') return inventorydef UseableItemsOutput(inventory): useableitems = ['Tea Leaves','Warming Pack','Energy Bar'] useableowned = [] for i in inventory: if i in useableitems: useableowned.append(i) if len(useableowned) != 0: print 'You own these useable items:' DisplayInventoryTry2(useableowned) print >>> Which one do you want to use? <<< use = raw_input(Please type in the full item name >>> ).lower() for i in useableowned: if use == i.lower(): inventory.remove(i) return [inventory,i] break else: print 'You do not own any useable items'def UsedItem(hydration,heat,hunger,useitem): import time useableitems = ['Tea Leaves', 'Warming Pack', 'Energy Bar'] if useitem not in useableitems: print Error 001, item to use is not in the Useable Items List! print Creating Crash Log. f = open('CrashLog: Error 001','a+') f.writelines(time.asctime()) f.writelines('Item To Use: '+useitem) f.close() raise ValueError,'item to use is not in the Useable Items List!' else: if useitem == useableitems[0]: hydration = 100 print Hydration Restored to 100 elif useitem == useableitems[1]: heat = 100 print Heat Restored to 100 elif useitem == useableitems[2]: hunger -= 30 print Hunger - 30 return [hydration,heat,hunger]#Variablesinform = Intro()dist = inform[0][0]scene = inform[0][1]watersource = inform[0][2]startingitems = inform[1]hour = 0dndeterminer = 0hydration = 100heat = 100hunger = 0shelter = Falseclothing = True#__main__while dist > 0: if hydration > 0 and heat > 0 and hunger < 100: print if not clothing: #for minising heat -= 5 action = Menu(hydration,heat,hour,watersource,dndeterminer,dist,hunger) hour = action[1] dndeterminer = action[2] action = action[0] if action == '1': if dndeterminer == 0: wood = GetWood(startingitems) else: wood = random.randint(0,2) for i in range(wood): startingitems.append('Wood') print str(wood) + ' log(s) are obtained' hour += 1 heat += 10 heat = CheckValidBody(heat) hydration -= 15 hunger += 5 hydration = CheckValidBody(hydration) print You used 1 hour to collect some logs elif action == '2': fire = MakeFire(startingitems) startingitems = fire[1] heat += fire[0] try: startingitems = ReplaceItem('Full Bottle of Dirty Water','Full Bottle of Clean Water', startingitems) print Water Purified! except: pass elif action == '3': if dndeterminer == 0: discover = GenerateRandomExplore(scene) discover_str = '' else: discover = [Nothing] discover_str = '' if discover != []: for i in discover: discover_str = discover_str + i + ' ' startingitems.append(i) print discover_str + 'is/are obtained' else: print Nothing is found hour += 1 heat += 10 heat = CheckValidBody(heat) hydration -= 10 hunger += 10 hydration = CheckValidBody(hydration) print You have used 1 hour to explore around you elif action == '4': # this line is used for minising Ruleof3() elif action == '5': hour += 5 print You have used 5 hours to rest, energy is restored hydration -= 5 if shelter: pass else: heat -= 15 if 'Sleeping Bag' in startingitems: heat += 20 hunger += 15 heat = CheckValidBody(heat) hydration = CheckValidBody(hydration) elif action == '6': captured = Hunting(scene,startingitems,watersource) hour += 1 if captured[1] == 'True' and captured[0] != 'poisonous scorpian': if captured[0]: print You saw a +captured[0]+ and you captured it startingitems.append((captured[0]+' flesh')) print 'You have used 1 hour to hunt' hydration -= 15 hydration = CheckValidBody(hydration) heat += 15 heat = CheckValidBody(heat) else: print You didn't see anything elif captured[1] == 'False': print You saw a +captured[0]+ and it escaped... bad luck! else: print You saw a +captured[0]+ and it attacked you, causing a +captured[1]+ injury! if captured[1] in ['broken ribs','lethal','neck']: print You died dist = 0 hunger += 20 elif action == '7': walked = Walk(dist,hydration,heat,startingitems,dndeterminer) hour += 4 dist -= walked[0] hydration = walked[1] hydration = CheckValidBody(hydration) heat = walked[2] heat = CheckValidBody(heat) watersource = random.choice([True,False]) print You have used 4 hours to walk +str(walked[0])+ km hunger += 20 elif action == '8': craft = CraftingList() if craft == 1: startingitems = CraftItem(startingitems, [Wood], [Tinder, 3]) elif craft == 2: startingitems = CraftItem(startingitems, [Plant Fibre], [String, 1]) elif craft == 3: startingitems = CraftItem(startingitems, [Dead Grass], [String, 1]) elif craft == 4: startingitems = CraftItem(startingitems, [Cloth], [String, 2]) elif craft == 5: startingitemsx = CraftItem(startingitems, [Clothes], [Cloth, 3]) if startingitemsx != startingitems: clothing = False startingitemsx = startingitems elif craft == 6: startingitems = CraftItem(startingitems, [String,Wood,Wood], [Bow Drill, 1]) elif craft == 7: startingitems = CraftItem(startingitems, [Bone,String], [Bone Knive, 1]) elif craft == 8: startingitems = CraftItem(startingitems, [Cloth], [Bandage, 3]) elif craft == 9: startingitems = CraftItem(startingitems, [Wood,Vaseline,String,Tree Bark], [Fire Torch, 1]) elif craft == 10: startingitems = CraftItem(startingitems, [Wood,String,Knive], [Fishing Rod, 1]) elif craft == 11: startingitems = CraftItem(startingitems, [Rabbit Skin], [Water Bottle, 1]) else: print This is not a valid choice elif action == '9': #this line is used for minising DisplayInventoryTry2(startingitems) elif action == '10': water = DrinkWater(startingitems) try: hydration += water[0] hydration = CheckValidBody(hydration) startingitems = water[1] except: pass elif action == '11': print Energy Bars are in Use Items Section. It has an amazing buff! food = SearchFood(startingitems) try: startingitems = food[0] hunger -= food[1] CheckValidHunger(hunger) except: pass elif action == '12': check = UseableItemsOutput(startingitems) startingitems = check[0] used = check[1] useitem = UsedItem(hydration,heat,hunger,used) hydration = useitem[0] heat = useitem[1] hunger = CheckValidHunger(useitem[2]) elif action == '13': if 'Camp Set' in startingitems: hour += 1 else: hour += 4 print Shelter Built, Rest would not decrease heat. elif action == '14': if watersource: emptybottles = SearchItem('Empty Bottle',startingitems) if emptybottles == 0: print You do not have empty bottles else: startingitems = ReplaceItem('Empty Bottle',Full Bottle of Dirty Water,startingitems) print str(emptybottles)+' x Empty Bottles has been filled up to '+str(emptybottles)+' x Full Bottle of Dirty Water' hunger += 5 else: print This is not a valid input else: # this line is used for minising print This is not a valid input! else: dist = 0 if hydration <= 0: print You died of thirst print GAME OVER... elif heat <= 0: print You died of hypothermia print GAME OVER... elif hunger >= 100: print You have starved to death print GAME OVER...if dist <= 0 and hydration > 0 and heat > 0 and hunger < 100: print WELL DONE! print YOU SURVIVED!!!!!Well, you might ask what happened to the desert? I think the desert is a bit too troublesome because there are different logics to the normal game. This game is inspired by the android game Survive.Please do enjoy playing my game, and if there are anything to improve please do comment so I can improve it! | A Survival Game | python;game;adventure game;python 2.6 | StyleThere's a standard coding style recommendation for Python called PEP8.It's strongly recommended to follow that as much as possible.Avoid assigning to a different typeThis statement assigns a simple value to a variable that was originally list:action = action[0]This is a bad practice that makes it harder to understand the code.It's better to use a different name,and avoid reassigning a value to a different type.Unnecessary conditionsInstead of this:if hydration < 0: hydration = 0 return hydrationelse: return hydrationIt would be simpler and better like this:if hydration < 0: hydration = 0return hydrationFragile menusThe menu handling in Menu and in CraftingList is very fragile.The text presented to the user is a hard-coded text.The code that uses these menus checks the choice by hard-coded values,such as 1, 2, and so on.The problem with this is that if you later need to make a change to a number in the text, you have to remember to change everywhere it is used.The worst is if you need to insert a new menu option in the middle,let's say position 3, and then you have to shift all other options and all the code that uses them.You may also mistake a condition by using the incorrect number that doesn't correspond to the intended choice.It would be better to encapsulate the menu choices in a data type,let's call it a MenuItem.Each MenuItem instance could have a number by which users can select them,and a text that is displayed.The menu could be built from the list of MenuItem instances,instead of a hardcoded text.And then the code checking the selected value could be intention revealing, for example:if craft == items.bow_drill: # ...elif craft == items.bone_knife: # ...And so on.This kind of approach will eliminate the hard-coding,and many potential errors in future modifications, oversight,and improve the readability.Magic valuesThere are many values that appear at multiple places in the code,for example the names of the scenes like Top of the Mountain.The problem with that is if one day you decide to make a small change,you have to remember to make that change in multiple places.It's better to create constants for such hardcoded values,so the concrete values are written at one place,and whenever you need to use it,you refer to it using the constant.Don't repeat yourselfThis chunk of code appears twice:itemscanbeobtained.remove('Berries')itemscanbeobtained.remove('Mushrooms')itemscanbeobtained.remove('Dead Hare')itemscanbeobtained.append('Dead Birds')itemscanbeobtained.append('Bait')itemscanbeobtained.append('Bird Nest')for i in range(random.randint(0, 3)): retlist.append(random.choice(itemscanbeobtained))return retlistIt would be better to avoid such duplication of logic by extracting to a helper function.Note that in Python you can define functions within functions,so when a block of code is duplicated within a function and never used outside,then the helper function could be inside the function that uses it. |
_unix.350896 | I have a problem with used space and available disk space in lvm.Please see this results :[root@localhost ~]# vgs VG #PV #LV #SN Attr VSize VFree VolGroup 3 3 0 wz--n- 6.78t 736.00m[root@localhost ~]# pvs PV VG Fmt Attr PSize PFree /dev/sda2 VolGroup lvm2 a--u 3.50t 0 /dev/sdb1 VolGroup lvm2 a--u 2.50t 0 /dev/sdb2 VolGroup lvm2 a--u 798.72g 736.00m[root@localhost ~]# lvs LV VG Attr LSize Pool Origin Data% Meta% Move Log Cpy%Sync Convert lv_home VolGroup -wi-ao---- 6.73t lv_root VolGroup -wi-ao---- 50.00g lv_swap VolGroup -wi-ao---- 4.90g[root@localhost ~]# df -hFilesystem Size Used Avail Use% Mounted on/dev/mapper/VolGroup-lv_root 50G 2.5G 45G 6% /tmpfs 4.9G 0 4.9G 0% /dev/shm/dev/sda1 477M 28M 425M 7% /boot/dev/mapper/VolGroup-lv_home 6.7T 5.8T 531G 92% /home[root@localhost ~]# df -ThFilesystem Type Size Used Avail Use% Mounted on/dev/mapper/VolGroup-lv_root ext4 50G 2.5G 45G 6% /tmpfs tmpfs 4.9G 0 4.9G 0% /dev/shm/dev/sda1 ext4 477M 28M 425M 7% /boot/dev/mapper/VolGroup-lv_home ext4 6.7T 5.8T 529G 92% /home[root@localhost ~]# archx86_64as you see I assigned about 6.7T to /home via lvm but I can't use more than 6.3T ( difference of Used and Avail in df ) space.I would be glad if someone could help me.Thanks | Inappropriate used and available space in lvm and disk free | partition;lvm;disk | I think that the part of storage in lake in the Logical Volume, is the part reseved of root rescue, the 5% reserved for root for emergency situation, this part is 5% by default, it's set when its you create the file system.look, with dumpe2fs -h /dev/mapper/VolGroup-lv_home | grep -i reserved , will give you the amount of blok reserved, you multiply the value by the size of the block, and you will get the size in bits, you convert to Gb and you will find the lost space.to have the lost space back to 0% or 1% do this and print us the result of df after :tune2fs -m 1 /dev/mapper/VolGroup-lv_homeor , for freeing the total space reserved do this :tune2fs -m 0 /dev/mapper/VolGroup-lv_home |
_webmaster.4148 | I'd like to start putting ads on my site but I'm quite fussy about the way things look so I'd like to have attractive adverts that work as a feature of the website as opposed to the nasty garish ones you occasionally see out there.BuySellAds.com do what I'm looking for. They don't accept your site unless it gets more than 100,000 hits per month so I can't use them. The ads on http://net.tutsplus.com/ are the sort of thing I'm looking to include in my site.What are my options here? Which companies offer this kind of service?I would use AdSense but I don't like the look of the text ads, in-fact I know that I don't even read them if I see them. I do however spend a lot of my time looking at, and clicking on, the attractive image based ads you see on sites like smashing mag and freelance switch | Putting adverts on my website | advertising | Most people prefer text ads since they're less obtrusive and don't take up any significant bandwidth. But AdSense also offers graphic ads if I'm not mistaken.Your other option is to sell your ad space manually, which is what the tutsplus sites do. However, that's a network of very large sites that has plenty of ad space as well as traffic to sell. Not many people are going to be coming to you directly for purchasing ad space if you're getting less than 100k page views per month, unless you're the dominant site in some niche market. |
_datascience.20074 | I am a college student(rising senior) and became interested in Natural Language Processing last semester. I decided to focus on studying this area this summer and become skilled in this area. I wanted to get some advice for studying this particular subject.Right now, I am taking Andrew Ng's Machine Learning course on Coursera to get a sense of how Machine Learning works. After finishing this course, I am planning to take Standford's CS224n NLP course on Youtube and do its class activities. I am assuming AWS and Tenserflow is also important since they are included as topics of CS224n.I want to know if my summer plan sounds reasonable. If not, could you please give me an advice of how to make a better plan. If this sounds reasonable, it would be great if you can add more or specify which part is particularly important in these areas. | Please let me know if I am on the right track to being an NLP Expert | machine learning;nlp;tensorflow | You are definitely doing a great job of getting your basics down. I really like Patrick Winston's AI Course, he does a great job of conceptualizing the math behind these problems, which is the only place I think Ng lacks. Find a ton of papers you think are interesting, and read them top to bottom. Here is one from spotify on NLP(super awesome)Most importantly, IMO, the thing you need to start doing is applying the stuff you learn, to problems you think are interesting. Do a few run throughs of other stuff on github and then start doing your own!Good luck, hope that was helpful:) |
_softwareengineering.212286 | I'm trying use the PSR conventions in all my projects, but today I view some code of my co-worker and I disagree.if ($cond == 1 AND $cond == 2) { // to-do}For me, the correct is:if (($cond == 1) AND ($cond == 2)) { // to-do}What is the correct use of the PSR? | Multiple conditions in a function using PSR | php;coding standards | Per the PHP Framework Interop Group's PSR definitions, this particular case is not addressed:http://www.php-fig.org/psr/2/I don't see any guidance on the usage of logical operators as words, i.e. and, or, not, etc versus symbols, i.e. &&, ||, ! within boolean expressions.If I were to follow precedence and make my own extension of the above PSR reference, I could only conclude that the word AND should be written as and given the preference for lower case when using reserved words... |
_webmaster.28248 | We've been examining a number of different SEO tools recently. Several of these tell us that some of our page title's, urls and meta descriptions are too long. We've also been told that some of our pages have too many links on them.I guess our first question is - is any of that feedback true! Can URL's etc actually be too long and if so how much does this affect ranking?Secondly can you have too many links on a page and if so, how many is too many? | Length of Page Title, URL, Meta Description and total number of links on a page | seo | That feedback may be true. It also may not be true. If the person giving you the feedback didn't justify their criticism with why this is the case then they may not have any idea of what they're talking about. When someone tells you what's wrong with something but doesn't tell you how or why the criticism is useless. It also fails to establish the critic as a possible knowledgeable person on the topic. So the best I can do is give you some general guidelines pertaining to the above issues and you can then decide if they apply to or not.Meta descriptions, which are not used in your pages' rankings but may be shown in Google's search results when your pages are listed, does not have an official length requirement. However, since Google will only display so many characters in their search results you should try to limit your meta description content to meet that length. I think that content is about 160 characters in length but don't have anything official handy to back that up. (If someone can clarify this for me I would greatly appreciate it). So if your meta descriptions are too much longer then this length then you may want to consider shortening them. Definitely read up on Google's tips for meta descriptions.Page titles should accurately describe what a page is about. It should contain keywords that you want to rank well for but you do not want to stuff them in there needlessly and, besides looking spammy and stupid, hurt your chances of ranking well for exact match queries. So long titles are normal and can be good for SEO if done properly. But if all of your titles are very long you're probably doing something wrong like putting search engines ahead of users. Write natural page titles (like the title of a book) and don't stuff keywords into them. Definitely read up on Google's guidelines for page titles.URLs, like page titles, can be long naturally but usually are not. Good usability would dictate that you keep them short so users can more easily remember them and type them into their browser. But if you create slugs based on the title of your page, which is a good idea, a long page title will result in a long URL. Just like with titles, that's ok. Just keep in mind there are limits to how long URLs can be and if you exceed it you may run into some technical problems (which also may affect those pages' ability to be indexed).Too many links on a page is subjective. Google recommends Keep the links on a given page to a reasonable number. Basically why do you have so many links on a page? Is it a sitemap or table of contents? If so, then having a lot of links on a page is natural. If it's because you're linking to everything you possibly can for the sake of linking, then you're doing it wrong. Heavily cross-linking your internal pages is a good thing for SEO so definitely do so liberally but naturally and usefully. As far as external links go, linking to sites your citing or contain quality content is a good thing and may even help your rankings. A quality page probably will have several links these. But if you have a lot of links to external sites on lots of pages you may want to consider your guidelines for what pages deserve to be linked to and which do not. It's subjective so that's about as good as an answer as I can give. There is no hard number for links on a page either internal or external, but reasonable is a good guideline to go by. |
_vi.10263 | Here is the command:vnoremap <C-S-S> :s/\v([.!?])\s+/\1\r\r/g<CR>`<i<ESC>The command takes a text selection and divides it into sentences separated by new lines. Why would this work in gvim and not vim? | Why does this command work in gvim but not in (terminal) vim? | gvim;visual mode | null |
_softwareengineering.45856 | I'm a student and in my spare time I'm working for a big enterprise as Java developer. The job is good, but the problem is, my boss writes very strange code. I don't want to complain, but some issues are in my opinion really strange. For example:he doesn't know any booleans. All boolean conditions are Strings called YesOrNo and then in the condition he uses if (YesOrNo == Yes)there are a lot of very strange characters in method names and variables like or all loops are infinite loops in the style of for(;;). Then at the end of the loop the condition is tested and if the conditions is fulfilled break; is called.I don't know if I should tell him that I think this isn't a good practice, since he is my boss and decides how and what to do. On the other hand some of his examples are really very weird.Any hints how to cope with? And is this only me who thinks that's bad style? | How to tell your boss that his programming style is really bad? | code quality;management;code reviews;communication | Ask him to explain his code to youTell him you've never seen X programmed that way before, and ask him why he codes it that way. Show him the way you code it, and tell why you do it that way (best practices, better performance, less chance of errors, easier for other programmers to read/maintain, etc). Be sure to prepare all your arguments in advance, and focus on why your method is best instead of why his method is worst. Afterwards, see if he still supports his method over yours.If he is open to improvement, he will likely change his way of coding. If he still prefers to use his style of coding over yours, you are not likely to change his opinion. |
_datascience.6192 | The intention of my project is to create customer profiles and it is related to advertisements. There are two types of activities: one is the advertisements that customers solely clicked on, and the other one is the advertisements that customers clicked on and purchase the product afterwards. I have lists of keywords describing the advertisements and those are the information for me to cluster customers in groups for creating customer profiles. I had a post about the second type of the activities before:I am trying to classify/cluster users profile but don't know how with my attributes By logc 's suggestion, I used the sales amount of the product customer purchased to create the customers profile, such as customer #1234 purchased a bracelet for $20 and the bracelet has keywords: fashion, gold and accessories, here is the way to represent this customer as followed:I used the dataset like this to do the kmeans clustering after applying PCA and it worked well, but now I was told to add the information about the first activity about solely clicking, then I am lack of ideas of the algorithm. As there is no numeric meaning of those advertisements solely clicked on, I tried LDA by considering each customer as a document and combining all the keywords of advertisements customer clicked on or purchased about into this document. The result is more about topics other than customers. I also tried taking the keywords in activity one as the dummy variables and then combining this with the numeric variables of activity two to do the clustering. I can't tell whether it's good and I am thinking that whether the dummy variables part made the data very sparse,so that it wouldn't work well for Kmeans.The WSSSE of this upadated combination case is very large. Any suggestions for my case? Thanks a lot! | algorithm and validation ideas of customers profiling (kmeans clustering) | clustering;algorithms;k means | null |
_unix.147400 | Update #1:I just gave an extra layer of testing, writing a shell script (.sh, #!/bin/bash) and a php script to be executed by php's cli.Bash works.It seems that it's not the Apache's HTTP context, but PHP itself that is causing the problems. Because a simple php raider.php run from root's shell has the same 2 problems mentioned originally.I am building an appliance that has an WebOS on top of. WebOS is being hosted with Apache running as http:http. Since WebOS needs access to OS (root), sudoers are set up - to allow http ALL with NOPASSWD. Please don't educate about processes being run as root - the environment is controlled, and has been working for 2 years now with over 40 units shipped and no problems reported.Commands are run by php (mod_php5 for Apache) with proc_open from a HTTP request context.Every command seems to be working fine, except for mdadm --create. When I attempt to create an array there are random outcomes depending on the RAID level I have chosen to make.Previously I've had a namespacing problem, but that's not the case anymore. The problem started to appear after some OS updates (don't know when exactly, this is the old version of the WebOS that isn't working and had to be brought up as of recent and, apparently, needs to be fixed - there is also a new version which works ok (it has a different command execution cycle)).I am using mdadm_udev initramfs hook to assemble RAID's upon start. I have left /etc/mdadm.conf empty, because mdadm_udev seems to assemble the RAID's properly based on their metadata. The only catch, though, is that when it assembles them, it names the raid based on <hostname>:<raidname>.Due to the catch above, I am using mdadm --create /dev/md/<hostname>:stoneshare ..., which seems to be running fine from CLI no matter what's the user (non-root users run as sudo and succeed), the problems come when ran through HTTP context.Scenario #1, RAID0:<?php$command = sprintf('sudo mdadm --create /dev/md/%s:stoneshare --level 0 --raid-devices 2 /dev/sdb1 /dev/sdc1');proc_open($command, /* ... */, /* ... */);RAID gets created, but, where CLI makes the RAID on /dev/md127 and symlinks to /dev/md/<hostname>:<sharename>, by running the above script, I end up with /dev/md127 with no link:[root@stone ~]# mdadm --detail --scanARRAY /dev/md127 metadata=1.2 name=stone:stoneshare UUID=7329e458:96be442a:84f616d8:fd4ba42e[root@stone ~]# ls -la /dev/md*brw-rw---- 1 root disk 9, 127 Jul 30 11:48 /dev/md127Scenario #2, RAID1:<?php$command = sprintf('sudo mdadm --create /dev/md/%s:stoneshare --level 1 --assume-clean --raid-devices 2 /dev/sdb1 /dev/sdc1');proc_open($command, /* ... */, /* ... */);Check:[root@stone ~]# mdadm --detail --scanARRAY /dev/md/stone:stoneshare metadata=1.2 name=stone:stoneshare UUID=7329e458:96be442a:84f616d8:fd4ba42e[root@stone ~]# ls -la /dev/md*brw-rw---- 1 root disk 9, 127 Jul 30 11:48 /dev/md127/dev/md:total 0drwxr-xr-x 2 root root 60 Jul 30 12:17 .drwxr-xr-x 19 root root 3080 Jul 30 12:17 ..lrwxrwxrwx 1 root root 10 Jul 30 12:17 stone:stoneshare -> /dev/md127Weirdly, but the symlink is created, there is a different problem though - upon RAID's creation, randomly either /dev/sdb1 or /dev/sdc1 is automatically marked as faulty. The RAID gets created and started, but is running with 1 drive. Sometimes neither of the drives is marked faulty and RAID is created with no problems at all.I have handpicked, what I found as relevant information for the device failure:[root@stone ~]# journalctl -xbJul 30 11:39:43 stone kernel: md: bind<sdb1>Jul 30 11:39:43 stone kernel: md: bind<sdc1>Jul 30 11:39:43 stone kernel: md/raid1:md127: active with 2 out of 2 mirrorsJul 30 11:39:43 stone kernel: created bitmap (8 pages) for device md127Jul 30 11:39:43 stone kernel: md127: bitmap initialized from disk: read 1 pages, set 14903 of 14903 bitsJul 30 11:39:43 stone kernel: md127: detected capacity change from 0 to 1000068874240Jul 30 11:39:43 stone kernel: md127: unknown partition tableJul 30 11:39:43 stone systemd[1]: Starting MD array monitor...Jul 30 11:39:43 stone systemd[1]: About to execute: /usr/lib/systemd/scripts/mdadm_env.shJul 30 11:39:43 stone systemd[1]: Forked /usr/lib/systemd/scripts/mdadm_env.sh as 457Jul 30 11:39:43 stone systemd[1]: mdmonitor.service changed failed -> start-preJul 30 11:39:43 stone systemd[457]: Executing: /usr/lib/systemd/scripts/mdadm_env.shJul 30 11:39:43 stone systemd[457]: Failed at step EXEC spawning /usr/lib/systemd/scripts/mdadm_env.sh: No such file or directoryJul 30 11:39:43 stone systemd[1]: Received SIGCHLD from PID 457 ((m_env.sh)).Jul 30 11:39:43 stone systemd[1]: Child 457 ((m_env.sh)) died (code=exited, status=203/EXEC)Jul 30 11:39:43 stone systemd[1]: Child 457 belongs to mdmonitor.serviceJul 30 11:39:43 stone systemd[1]: mdmonitor.service: control process exited, code=exited status=203Jul 30 11:39:43 stone systemd[1]: mdmonitor.service got final SIGCHLD for state start-preJul 30 11:39:43 stone systemd[1]: About to execute: /sbin/mdadm --monitor $MDADM_MONITOR_ARGSJul 30 11:39:43 stone systemd[1]: Forked /sbin/mdadm as 460Jul 30 11:39:43 stone systemd[1]: mdmonitor.service changed start-pre -> runningJul 30 11:39:43 stone systemd[1]: Job mdmonitor.service/start finished, result=doneJul 30 11:39:43 stone systemd[1]: Started MD array monitor.Jul 30 11:39:43 stone kernel: md: md127 still in use.Jul 30 11:39:43 stone kernel: md/raid1:md127: Disk failure on sdb1, disabling device. md/raid1:md127: Operation continuing on 1 devices.Jul 30 11:39:43 stone mdadm[460]: mdadm: No mail address or alert command - not monitoring.Jul 30 11:39:43 stone systemd[460]: Executing: /sbin/mdadm --monitor --scanJul 30 11:39:43 stone systemd[1]: Received SIGCHLD from PID 460 (mdadm).Jul 30 11:39:43 stone systemd[1]: Child 460 (mdadm) died (code=exited, status=1/FAILURE)Jul 30 11:39:43 stone systemd[1]: Child 460 belongs to mdmonitor.serviceJul 30 11:39:43 stone systemd[1]: mdmonitor.service: main process exited, code=exited, status=1/FAILUREJul 30 11:39:43 stone systemd[1]: mdmonitor.service changed running -> failedJul 30 11:39:43 stone systemd[1]: Unit mdmonitor.service entered failed state.Jul 30 11:39:43 stone systemd[1]: mdmonitor.service: cgroup is emptyJul 30 11:39:43 stone kernel: RAID1 conf printout:Jul 30 11:39:43 stone kernel: --- wd:1 rd:2Jul 30 11:39:43 stone kernel: disk 0, wo:1, o:0, dev:sdb1Jul 30 11:39:43 stone kernel: disk 1, wo:0, o:1, dev:sdc1Jul 30 11:39:43 stone systemd[1]: Got disconnect on private connection.Jul 30 11:39:43 stone kernel: RAID1 conf printout:Jul 30 11:39:43 stone kernel: --- wd:1 rd:2Jul 30 11:39:43 stone kernel: disk 1, wo:0, o:1, dev:sdc1Jul 30 11:39:43 stone kernel: md: unbind<sdb1>Jul 30 11:39:43 stone kernel: md: export_rdev(sdb1)Thought, I doubt that mdmonitor is essential for creating the RAID.Both RAID's are perfectly assembled when ran from CLI, no problems encountered. Drives, per S.M.A.R.T. are healthy.The UUID's in reality are not equal, I just made the examples up out of a single RAID.What am I doing wrong here, that is causing such inconsistencies? | mdadm inconsistencies when run programmatically | arch linux;sudo;php;mdadm | null |
_softwareengineering.314062 | I got following exercise:An algorithm takes 0.5 ms for input size 100. How large a problem can be solved in 1 min if the running time is the following:linearO (N log N) ...So the algorithm can process 100 items in 0.5 ms therefore 100*(2*1000*60) = 12 000 000 items processed for linear time.Now how to solve 12 000 000 = O(N log N) for N?N = 2^(12 000 000/N) And I'm stuck with how to eliminate the exponential N.Also the exercise goes on:Order the following functions by growth rate, and indicate which, if any, grow at the same rate.:N, square root of N, N^1.5, N^2 , N log N, N log log N, N log^2 N, N log (N^2), 2/N, 2N, 2N/2, 37,N^3, N^2 log N As I don't have any solutions as reference here is mine:2/N < sqrt(N) < 37< N=2N/2 < 2N < N log log N < N log N < N log (N^2) < N log^2 (N) < N^1.5 < N^2 < N^2 log N Would be cool if someone could have look at it and correct me where i might be wrong. | How to solve O (N log N) and more | complexity | null |
_unix.225617 | Newbie here:I visited a friend's firm yesterday where they exclusively use Linux and one of the things that they implemented is that everyone's actual desktop / machine (they are a team of 20 people) are at some remote data-center and on their office PC they merely logon to their desktops and can view their environments as if they are working off a local PC. It wasn't like Windows' Remote Desktop (which essentially pops up a window on one desktop that shows a different PC's desktop), but in their entire desktop itself appears for the first time after log in as if it was always there (but really it resides at the remote location). What is this concept called?They were using a variety of Linux, but mostly Red Hat. | desktop at a remote location | remote desktop | This is VDI, as larsks noted - the bits on the local desk can be either thin clients or full-fledged desktop machines. |
_scicomp.11531 | I know the Neumann B.C. is implicit in FEM language. However, I have seen at least two ways to impose Dirichlet B.C.e.g. for the following problem 1D,$$\nabla^2 u + \nabla u= 0, u_{left}= 1, u_{right}=0$$1) set first and last row of assembled A to 0 at left hand side, set A(1,1)=1,A(end,end)=1, and specify the boundary value 1 and 0 in right hand side vector b.2) set first row&column, last row&column of assembled A to 0 at left hand side, then do the same thing as above.these two methods are different, the first is more intuitive(probably preferred by finite difference user), while the second sounds more rigorous because we are setting the boundary element.I know these two ways may generate different results for some specific case. Could any body give some insight? | FEM: which is the correct way to impose Dirichlet B.C | finite element;finite difference;numerical analysis | null |
_codereview.44467 | I am trying to create an AngularJS directive that will give information to the user about the text they are inputting such as the number of characters they must or may enter and so on and so forth.To cut a long story short, I would be very grateful if someone could help me improve the javascript code for my directives. As of now the only thing the directives do is provide the user with the number of characters in the textarea.Code is hosted on Github and located in this repository.Here are my directives:'use strict';angular.module('myApp.directives', []) .directive('enhanced', function () { return { restrict: 'A', controller: 'enhancedCtrl', scope: {}, transclude: true, template: '<div ng-transclude></div>' }; }) .controller('enhancedCtrl', ['$scope', function ($scope) { var info = function () { var size = 0; return { getSize: function () { return size; }, setSize: function (newSize) { size = newSize; } }; }(); var callback; this.registerSizeChangedCallback = function (callback) { this.callback = callback; }; this.notifyObserver = function () { this.callback(); }; this.setSize = function (size) { info.setSize(size); this.notifyObserver(); }; this.getSize = function () { return info.getSize(); }; }]) .directive('enhancedTextarea', function () { return { restrict: 'A', require: '^enhanced', scope: true, replace: true, template: '<textarea></textarea>', link: function ($scope, $element, $attrs, enhancedCtrl) { $scope.$watch($attrs.ngModel, function (newVal) { enhancedCtrl.setSize(newVal.length); }); } }; }) .directive('notice', function () { return { restrict: 'A', require: '^enhanced', replace: true, scope: {}, template: '<div>{{size}} characters</div>', link: function ($scope, $element, $attrs, enhancedCtrl) { enhancedCtrl.registerSizeChangedCallback(function () { $scope.size = enhancedCtrl.getSize(); }); } }; });And my html:<!doctype html><html lang=en ng-app=myApp><head> <meta charset=utf-8> <title>My AngularJS App</title> <link rel=stylesheet href=css/app.css/></head><body><div ng-controller=myCtrl> <div enhanced> <div enhanced-textarea ng-model=text></div> <h3>{{text}}</h3> <div notice></div> </div></div><script src=lib/angular/angular.js></script><script src=js/directives.js></script><script src=js/controllers.js></script><script src=js/app.js></script></body></html>Can someone please provide feedback about both:My usage of the AngularJS frameworkMy usage of Javascriptedit: I have greatly changed the api of my directive since my original post. Please have a look at the following commit. I am looking for people willing to help me on this lone-directive open-source projet... Everyone welcome! | Building a set of AngularJS directives to provide the user information about their input | javascript;angular.js | null |
_codereview.129187 | I am currently working with this code to automate some tasks for senior staff members that are not very adept in Excel. Wondering if VBA is simply not a very quick code or if my code is clunky and slow.For clarity, I would think with how simple this code is it could run in under a second or two. Maybe this is overzealous?Sub Paste()'---Paste Macro'---2016-05-23Dim sht1 As WorksheetDim sht2 As WorksheetDim LastRow As LongDim LastRow2 As LongDim LastColumn As LongDim StartCell1 As RangeDim StartCell2 As RangeDim rng1 As RangeDim rng2 As RangeSet sht1 = GetWSFromCodeName(Sheet10)Debug.Print sht1.NameSet sht2 = GetWSFromCodeName(Sheet8)Debug.Print sht2.NameSet StartCell1 = Range(A2)Set StartCell2 = Range(B2)'Find Last Row and Column LastRow = sht1.Cells(sht1.Rows.Count, StartCell1.Column).End(xlUp).Row LastColumn = sht1.Cells(StartCell1.Row, sht1.Columns.Count).End(xlToLeft).Column LastRow2 = sht2.Cells(sht2.Rows.Count, StartCell1.Column).End(xlUp).Row'Select Range And Copy into Final Formula Sheet sht1.Range(StartCell1, sht1.Cells(LastRow, LastColumn)).Copy Destination:=sht2.Cells(LastRow2 + 1, 2)'Convert Text in Column C of Final Formula Sheet to Numbers to Allow Advisor Code to Apply Set rng1 = Range(sht2.Cells(LastRow2, 3), sht2.Cells(LastRow2 + LastRow - 1, 3)) With rng1 .NumberFormat = 0 .Value = .Value End With'Copy Advisor Function down to meet with new Pasted in Data With sht2 Set rng2 = .Cells(LastRow2, 1) End With With rng2 .Copy Destination:=Range(sht2.Cells(LastRow2, 1), sht2.Cells(LastRow2 + LastRow - 1, 1)) End WithEnd Sub'---This Function allows the worksheet name to change in the workbook as it allows the 'user to set Worksheets to codename variables. By using this function the user can input a 'codename for a worksheet and the function will call the worksheet name of the corresponding 'codename, allowing the user to set worksheet variables to codenames without losing 'functionality usually associated with such variables.'---2016-05-23Public Function GetWSFromCodeName(CodeName As String) As Worksheet Dim WS As Worksheet For Each WS In ThisWorkbook.Worksheets If StrComp(WS.CodeName, CodeName, vbTextCompare) = 0 Then Set GetWSFromCodeName = WS Exit Function End If Next WSEnd Function | Copy, Paste And Format | performance;vba;excel | The 3 lowest-hanging VBA performance fruit are: Application.ScreenUpdating = False Application.EnableEvents = False Application.Calculation = xlManualJust make sure to restore them at the end of your sub, and/or if your method encounters an error and stops, else your senior people won't be able to use Excel afterwards and will blame you for breaking it.Used like so:Sub/Function () Application.ScreenUpdating = False Application.EnableEvents = False Application.Calculation = xlManual < Code > Application.ScreenUpdating = True Application.EnableEvents = True Application.Calculation = xlAutomatic '/ Assuming it was set to automatic to begin withEnd Sub/FunctionAnd with some (very basic) error handling:Sub/Function () On Error Goto CleanFail Application.ScreenUpdating = False Application.EnableEvents = False Application.Calculation = xlManual < Code > Application.ScreenUpdating = True Application.EnableEvents = True Application.Calculation = xlAutomatic '/ Assuming it was set to automatic to begin withCleanExit: Exit Sub/FunctionCleanFail: '/ Resets the Application settings, *then* raises the error On Error Goto 0 Application.ScreenUpdating = True Application.EnableEvents = True Application.Calculation = xlAutomatic '/ Assuming it was set to automatic to begin with Err.Raise(Err.Number) '/ Or insert your own error handling hereEnd Sub/Function |
_codereview.14174 | I need some useful functions that faster than the original. (Original - C++'s functions)For example:#include <time.h>#include <stdio.h>#include <Windows.h>struct TestMemory { double a,b,c;};void* __TestMemory__Sample=0;int WINAPI WinMain(HINSTANCE h1,HINSTANCE h2,LPSTR str,int i) { AllocConsole(); __TestMemory__Sample=calloc(1,sizeof(TestMemory)); TestMemory* test=(TestMemory*)malloc(sizeof(TestMemory)); clock_t c1=clock(),c2; for (int i=0;i<100000000;i++) memcpy(test,__TestMemory__Sample,sizeof(TestMemory)); c1=clock()-c1; c2=clock(); for (int i=0;i<100000000;i++) memset(test,0,sizeof(TestMemory)); c2=clock()-c2; printf(memcpy: %d\nmemset: %d\nradio: %f (set/cpy),c1,c2,c2/(float)c1); getchar();}Output:memcpy: 1410memset: 3250radio: 2.304965 (set/cpy)This function replace the current way to zero memory.What it does:Create a global pointer, first set with zeroed memory.When you want to allocate zeroed memory, allocate memory with malloc and then copy the zeroed memory (global variable) to this memory. | Zeroing memory on Windows | performance;c;memory management;windows;winapi | null |
_unix.263556 | I have a router running uhttpd by default and there is a process using lighttpd I would like to run instead. Since both processes share the same port, I would like to kill uhttpd then start up lighttpd automatically (by setting up the script that contains the commands as a cron job that runs on reboot).When I run the commands I would like to go into the script individually, they work. When I put them in a script, I get an error message telling me the port number is in use. The commands are:killall uhttpd/etc/init.d/lighttpd startThe simple script I have so far is:#!/bin/shkillall uhttpdsleep 5 #To give the device time to release the port/etc/init.d/lighttpd start | How do I create a simple script to kill uhttpd and then start lighttpd? | shell;router;lighttpd;uhttpd | I would not wait for 5 seconds and hope that will work, you might wait too long, or too short. You can use nc -z to test whether the port is (still) being used and do the following (I assume they are fighting about port 80):#!/bin/bashfor i in $(seq 5); do if ! nc -z localhost 80; then break fi echo $i sleep 1doneif nc -z localhost 80; then killall -9 uhttpd sleep 1fiif ! nc -z localhost 80; then /etc/init.d/lighttpd startelse echo 'port not free'fiIf after 5 times waiting the process is still not killed, kick it out with more force and only start lighttpd if the port is free. You should investigate if something is restarting uhttpd (e.g. the process that starts it in the first place). Maybe the sleep 5 you are using leaves enough time that it restarts (e.g. look at the uhttpd process number before you run your script and after). |
_softwareengineering.238430 | Is boxing of primitives required in OO languages to keep them consistent with the rest of the object system (generics etc.)?Or is it avoidable - is it possible to avoid any additional performance cost of having both primitives and objects in a language?One solution I can come up on the spot is having references big enough to store values of every possible primitive type.Are there other (better) solutions and are there implemented in popular languages? | Do you have to have boxing of primitives in OO language? | object oriented;language design;boxing | Because of the way processors are architected, you need boxing at some level in order to get both reasonable efficiency and a unified type model. However, the boxing doesn't need to be manually specified by the programmer, and in some languages it is handled automatically behind the scenes for you. Take Scala, for example. Int is derived from an AnyVal, which is derived from an Any, which is Scala's top-level class. Syntactically, you can treat it like any other object, but the compiler will treat it like a primitive in appropriate contexts, internally doing boxing and unboxing as necessary. The point is, the programmer doesn't have to care. Even nicer, in Scala this is implementing using implicits, so programmers can seamlessly implement their own custom automatic boxing and unboxing if the built-in ones aren't sufficient. If you're not fortunate enough to be using a language like Scala, generics can obviate the need for manual boxing in many situations. |
_codereview.169870 | This decorator adds the elapsed time to a function's attributes when applied.My concerns:Is the code pythonic?Could this code be useful?Should I just use the timeit module?Is the code easy to read and understand?The code:''':Date: 7/21/17:Version: 1:Authors: - Ricky L Wilson'''import datetimedef time_func(function): This decorator calculates the amount of time a function takes to execute. When time_func is applied to a function it records how long the function takes to finish and add the elapsed time to the functions attributes. - **parameters** :param function: The function you want to add the elapsed time attribute to. :Example: @time_func def example(name, **kwargs): meta = type(name, (object,), kwargs) return meta example('foo') print example.elapsed 0:00:00.000052 def new_func(*args, **kwargs): # Start the clock. start = datetime.datetime.now() # Execute the function and record the results. function_result = function(*args, **kwargs) # Calculate the elapsed time and add it to the function # attributes. new_func.elapsed = datetime.datetime.now() - start # Returned the function with the added elapsed attribute return function_result return new_func | Decorator to measure execution time of a function | python;python 2.7;meta programming;benchmarking | null |
_softwareengineering.159160 | I'm looking for some pointers on class design for a global application.Let's say I have to make a class structure to manage products, and the products are sold in different countries. Some of the fields for the product will have the same value across all countries (eg. product code, ERP Description) I will call these international fields, and some fields will be specific to a single country (eg. Local Description), lets call these local fields. Of course, some local fields will be the same for groups of countries (es. weight : 1 kilogram / 2 pounds). Also I expect that not all countries will have values for all fields.Which fields are international and which fields are local may change from one installation to another and I am reluctant to bake this into the design as I'm sure it will bite me later on.So, I'm trying to figure out how to structure the objects so that I can use a product at an international level and always refer to the same product, but also maintain and use the local information when necessary? Just to be clear, I'm not talking about user-locale, number or date formatting etc. The source data is coming from different database schemas (one for each country). The end product will be written in C#.I'm wondering if anyone has experience or can point me to a pattern that would provide a good solution to this before I go and reinvent the wheel? | Class design for internationalized object | design;internationalization | I assume you have a database of some sort. I'd create a factory class that creates the objects (e.g. Product) from the data in the database.Let's say your designing the Product class. It has some of your international fields:public class Product{ private string ean;}For internationalized things like weights I'd write some structs Weight that allows you to set the unit (pounds, kilograms). Use one consistent unit of weight in your database (for example kilograms) and use that to create the object. Then code your ToString to return the value localized in the specified unit. This is similar to how DateTime can take a date/time in UTC and 'localized' it to the user's timezone.When there is no weight, use for example a weight of -1 and declare this as static readonly Weight None = new Weight(-1).public class Product{ private string ean; private Weight weight; private DateTime availableFrom;}public struct Weight{ private static readonly Weight None = new Weight(-1); private int weightInKG; public Weight(int weightInKG) { this.weightInKG = weightInKG; } public WeightUnit Unit { get; set; } public string ToString() { /* Implement */ }}Then, if you have pieces of text that are localized (translated) then I'd just use strings. The factory class should get the appropriate localized string from the database. If there is no such string, use null.public class Product{ private string ean; private Weight weight; private DateTime availableFrom; private string description;}Lastly, if you have information that is always used together localized (for example, specs for the product) then create a class Specs (or a hierarchy SpecsBase MonitorSpecs HardDiskSpecs if there are multiple kinds) for this. When there are none, use null. You can share these objects among multiple products if the information is the same. Again, the factory should take care of creating it.You can also use these objects for fields that might be international or local depending on the installation.public class Product{ private string ean; private Weight weight; private DateTime availableFrom; private string description; private Specs specs;}For all objects, override the ToString method to return the right (localized) strings. |
_webmaster.48683 | Is it a problem to change the meta keywords dynamically depending on the content of the page / website?for example if it is a news website and this weeks top articles are about elephants in japan I would change the keywords accordingly, and when that article is less popular I would replace them with other key wordsTechnically I know it is not a problem. How do search engines treat this kind of behvaior? I know that if the keyword list is too long they can ban websites.. What about the rate of change for the keywords? | Dynamic Meta Keywords | seo;search engines;meta keywords | null |
_webmaster.44972 | I'm new to form validation and I have been lucky over the years. I would like to update my method of form creation in my sites. I was curious to know what is standard and if there is a preexisting solution to my needs? My goal this week is to learn how to validate an email address and check for spam.I can create forms in HTML5 without issues but I don't know if JavaScript form validation with PHP form validation is standard. I did run across this from my searches and appears to be a good start, but I want to know more. | New to website form validation | php;javascript;forms;validation | The linked article is from 2009. Since then some improvements have been made in regards to form validation. One being that HTML 5 already has built-in form validation, but fails in older browsers with no HTML 5 support.Of course there are javascript libraries which helps you with the validation part like:Parsley.js (Javascript) orjQuery Validation Engine (Javascript) orValidation (PHP)I suggest you take a look on the different implementation methods and what you can do with them.For Spam checking, well, that's another story. There aren't very good standalone libraries which are any good (at least not in my experience). Of course, you could always go with integrating the pretty awesome Akismet to detect spam after form submission or integrate some third-party services like reCAPTCHA. |
_unix.281660 | POSIX seems to define that a shell should be able to evaluate like a calculator the expression $(( a * b)) where * is a binary operator +, - or *. I programmed such a calculator for my own shell and scripted a test for it. $ $((32 * 32))$((32 * 32))Result = 1024But when I run the test I can't fetch the output (1024) from the shell. I want to test in the script that the shell actually computes the right result instead of a manual inspection. Now my test works with a manual inspection but I want to programatically check that the result is correct. printf ********************* TEST Arithmetics ... .\nYou should see the number 4096 below #read _valgrind --leak-check=yes ./shell .<< EOFecho $((64 * 64))EOFThis is the output from the test:********************* TEST Arithmetics ... .You should see the number 4096 below 'PATH' is set to /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin.stdin is a file or a pipe4096==31803== ==31803== HEAP SUMMARY:==31803== in use at exit: 79,725 bytes in 167 blocks==31803== total heap usage: 502 allocs, 335 frees, 228,175 bytes allocated==31803== ==31803== LEAK SUMMARY:==31803== definitely lost: 0 bytes in 0 blocks==31803== indirectly lost: 0 bytes in 0 blocks==31803== possibly lost: 0 bytes in 0 blocks==31803== still reachable: 79,725 bytes in 167 blocks==31803== suppressed: 0 bytes in 0 blocks==31803== Reachable blocks (those to which a pointer was found) are not shown.==31803== To see them, rerun with: --leak-check=full --show-leak-kinds=all==31803== ==31803== For counts of detected and suppressed errors, rerun with: -v==31803== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 1 from 1)==31805== Memcheck, a memory error detector==31805== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.==31805== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info==31805== Command: ./shell .==31805== UpdateThis works, write it to file and look in the file for the number 1024. #!/bin/ksh#read _./shell .<< EOF > tmp.txtecho $((32*32))EOF | Checking that $((a * b)) evaluates in my own shell | ksh;c;openbsd;posix;testing | if [ 1024 == $((32*32)) ]; then echo The test workedelse echo The test failedfiThis ought to work; if your shell does not use $(( )) for arithmetic, the strings will not match. You can also shorthand it with:[ 1024 == $((32*32)) ] || echo I can't math! |
_cs.79515 | I am contemplating the project of writing a compiler. I am wondering if, aside from the availability of easy google results, it is easier to write a compiler for a more explicit/verbose language such as ada, compared to a very compact language such as APL, for example.I should add that i am especially interested in whole-program optimization.Edit: my question boils down to do highly abstracted symbols/keywords (as in APL, where a single operator represents a function) make it easier to write a compiler, or is a language with a more traditional syntax (where a function includes a variety of operators) easier? | Is writing a compiler for a compact language easier? | programming languages;compilers;program optimization | In almost every case, the more compact languages like APL will be harder write a compiler for:On the front end (parser), in the worst case, you have a ton bunch of special cases for your symbols in your parser, and in the best case, you treat them as generic symbols, in which case you're in the exact same parsing position as a language that hasIn the back-end, with type checking, optimizers, etc., you either treat your symbols as standard library functions, in which case you're in the exact same place as a more verbose language, or you treat them as parts of the language, in which case you will have a bunch of special cases in your type checker, code generation, etc.In general, compilers are easiest for smaller languages. This is why most languages feature syntactic sugar, where some features are translated into a subset of your original language at compile time (for example, eliminating for-loops by turning them into while-loops). Many languages also keep code-generation and optimization simpler by compiling their language into a smaller intermediate language after parsing or type checking, then optimizing and compiling that language into machine code.I should add that i am especially interested in whole-program optimization.Syntax will not influence this in the slightest. Parsing is generally the least interesting part of writing a compiler, since there's many solutions for parsing, and once you have things into an Abstract Syntax Tree, what concrete syntax you used is entirely irrelevant. That is, two languages that parse to isomorphic ASTs will be exactly the same for difficulty to optimize.The only case where having a more compact language could help optimization is if you have a bunch of special cases of known optimizations (e.g. fusion rules) for your operators, but you could just as easily write special cases for standard library functions of a more verbose language. |
_softwareengineering.153163 | I am just messing around, trying to figure out how stuff works and right now I have a couple questions about HTML, JS and CSS engines.I know there are two major JavaScript engines out there - V8 and JavaScriptCore (WebKit's JS engine as far as I know). Is that correct? And what are the main HTML + CSS renderers out there? Let's say I want to build a web browser using V8 (I saw it has some documentation and stuff + I like the way it works), what are the best options for me?Partially another question. Is there any bare browser that uses V8 and runs on Ubuntu at least?P.S. I am a Ubuntu user and prefer C++. | HTML, JS, CSS Engines | web development;c++ | JS engines [1, 2]:v8JavaScriptCore/SquirrelFishSpiderMonkey (Mozilla, C++)Rhino (Mozilla, Java)Tamarin (Flash)Chakra (IE9; not open source)Rendering Engines:WebkitGecko (Mozilla)Presto (Opera, not open source, not usable standalone)Trident (IE9)A quite simple option would be to use Webkit as a rendering engine as it quitewidely used in many different projects. Chrome/chromium is using v8 and runs on Ubuntu.[1] http://en.wikipedia.org/wiki/JavaScript_engine[2] http://en.wikipedia.org/wiki/List_of_ECMAScript_engines |
_unix.239852 | I have the following bash scriptif [[$NODE_NAME = Node1]]then dir=../../testfithat I use in Jenkins execute shell prompt.It gives me an error saying Slave1 command not found.I just want to check if the $NODE_NAME variable equals the value Slave1. How do I do that in bash? | if else bash script | bash;jenkins | null |
_webmaster.71752 | I don't want my site to be analyzed on WooRank or builtwith.com.Is there any way I can do that by editing the robots.txt file or any other possible way? | I don't want my site to be analyzed on WooRank or builtwith.com | robots.txt | null |
_reverseengineering.1370 | I am using JD-GUI to decompile Java JAR files, but the problem is that it leaves many errors, such as duplicate variables which I have to fix myself and check to see if the program still works (if I fixed the errors correctly).I also tried Fernflower, but that leaves blank classes if it's missing a dependency.I'd like to know which decompiler:gives the least amount of errorsdeobfuscates the most. | What is a good Java decompiler and deobfuscator? | decompilation;tools;java;jar | My apologies for the belated reply. I have been working on a new, open source Java decompiler. Feel free to check it out.I have not tested it against any obfuscated code, but I have seen it decompile many methods that JD-GUI failed to handle. Note that it's a work in progress, and I'm sure you will find plenty of code that it will fail to decompile. |
_unix.249959 | I have Windows 8, then I would install Linux Mint with USB live so i created partitions /home, / and swap then i started the installation.But after the restarting i still dont see any bootloader to select between WIndows and LInuxMint 17Here is my boot-info : http://pastebin.com/GgWBPq7JSO how can i get a bootloader ? | How can I get a bootloader with WIndows 8 and LinuxMint | grub | null |
_webmaster.76096 | I can't edit a page using the imagemap tag when logged in.This is for a mediawiki installation where all editors must be logged in.Page is athttp://mediawiki.owenks.uk/wiki/index.php?title=ImageMapPageIf I change the permissions and allow all users to edit, then I can save the page. But if I change permissions back to $wgGroupPermissions['*']['edit'] = false;then login and try to edit the page, I get a blank screen after hitting Save Page.I tried to ask on the mediawiki help site but was unable to post.Any suggestions?MediaWiki 1.24.1PHP 5.6.4 (cgi-fcgi)MariaDB 5.5.41-MariaDB-1~wheezy | Can I use ImageMap and require editors to login in mediawiki? | mediawiki | Was nothing to do with ImageMap. Was a conflict with GraphViz extension. Removing the GraphViz extension put everything back to normal. |
_softwareengineering.203719 | When building a REST service with the HATEOAS constraint, it's very easy to advertise the existence of resources through linking. You make a GET to the root of my site and I respond with the root document listing all the first-tier resources:{ users: { href: /users } questions { href: /questions }}Clients which understand how to read these href values could perform GET requests on those and discover all the current resources available in the application.This works well for basic lookup scenarios, but doesn't indicate whether a resource is queryable. For example, it may be reasonable to perform:GET /users?surname=SmithAre there any formats that could express this query ability with enough information that a client could form a coherent query without needed prior knowledge of the resource?Additionally, is there any way to express that a client is allowed to perform a POST to a given location with an expected location. For example, it could be expected that a client perform the following to create a new question resource:POST /questions{ title: Are there strategies for discovering REST services using HATEOAS?, body: When building a REST service with the HATEOAS constraint, it's very...}When using HTML as the format for human consumption, we can express a lot of this through use of forms and written prompts to allow a human to discover the operations they are allowed to perform on a service.Are there formats which are capable of similar things for clients? | Are there strategies for discovering REST services using HATEOAS? | design;rest;hateoas | How would you know what kind of inputs are acceptable? That is to say, if your client has no prior knowledge, how would you define the semantics of surname? You're starting to get into the territory of needing something like OWL. I think it's more practical to expect your clients to understand the semantics of well-known mime-types; say, for example, text/vcard for people. |
_softwareengineering.249501 | I start a new project this summer, consisting in developing a web version of a proprietary desktop ERP. The main goal of my company is to be able to propose a web version of its ERP, with all advantages it involves (mobility, possibility of selling SaaS versions, modern look and components ...), without losing any business feature. By this, I mean that us developers can't rework the business side of the app. The main goal is to be able to translate same processes into web application.Business layer of the older version is not directly reusable, since it's really GUI-dependent. Those business process were rewritten as UML diagrams, which will be used as support for us to develop the new app.The problem I meet is that I don't know how to deal with process that need user interactions. For example :On validation of a sale order, the validation process checks all products it contains, verifying if there is available stock, and then perform different operations. If there is no stock available, the user is asked if he wants to cancel the order, remove this product or select another one equivalent. It works like a Javascript alert or confirm : current thread (ie validation process) is on hold, waiting for user interaction. After user's choice, it finishes dealing with the current product, and then validates the next one, and so on. How to deal with this kind of processes with a web application ? Is there some framework, design pattern or something else that permits to write this kind of business processes, able to start and hold like that ? A solution could be to split those business processes into smaller ones. For my example, we would have 2 sub-processes : the first one checks all products and flags the problematic ones. Then the user has a screen to decide what to do on flagged products, and validates. At this moment we are sure all products are OK, we can start the second sub-process to perform the others operations.The problem with it is that even if it's pretty simple on this example, it can be really more complicated. Some process have a lot of users interactions like this one, and then could be splitted into 10 subparts. Like I earlier precised, we don't want to modify or rethink business process, to be sure that we lose nothing or introduce new business bugs. Does someone has an experience about it ? Do you know some way to deal with this kind of desktop-to-web developments ?EDIT 15/07/14There was some misunderstanding about this post, surely related to my poor english expression and vocabulary.To summarize the problem : I got a bunch of business workflows described into UML diagrams. They comes from a huge 30-year-old CAMM (production management ERP). The project is to redevelop this application under Java web environment.The main point is that some of those workflows are user-dependent, since, in the middle of the processing, they need a user-interaction. Because web applications are based on a client-server architecture, I don't know how to port them. Reworking/rethinking these workflows is not an option, because it would be too much time-consuming. I need a way to simulate a desktop application on a web app, like Wt, but for Java (i'm not talking about UI but about how to develop workflows ), or to define rules to make those user-dependent workflows web-compatibles. | Desktop to Web - How to deal with user-interactive workflows | web applications;business;java ee;business logic | null |
_softwareengineering.227676 | I came across the idea of using function points as a metric for the velocity of a Scrum team. I saw it in a team and I found two articles mentioning a link between estimates and function points (http://www.ifpug.org/ISMA5-2010/Amol%20Keote-FunctionPointsAndAgile-Hand-in-Hand.pdf and http://www.cosmicon.com/portal/public/FromStoryPointsToCOSMIC.pdf).I am not sure how this can work, because if I understand it correctly, function points measure the value of a feature (e.g. from the users perspective) whereas the velocity measures the effort of finished features. And in my view there's no direct connection between these two. To put it another way: If you have (let's say) a stable Scrum Team which works 2 week Sprints, the number of functions points they deliver per Sprint should vary (possible wildly), which would render a velocity based on function points quite meaningless (e.g. for planning purposes)...Am I missing something here? | Using function points as a metric for the velocity of a Scrum team? | agile;estimation;function point | null |
_webapps.20245 | Is it possible for an administrator of an open group page on Facebook to see if a non-member has been regularly clicking on the page and reading postings on the respective page? | Can the administrator of an open group page on Facebook tell who views page? | facebook;facebook pages;statistics | No, I don't think so. I am an admin of an open, though small, group page on Facebook and I can't see that information. |
_codereview.154642 | I wrote an algorithm to separate a DAG into disjoint sets of vertices. I was hoping to have some comments on algorithmic complexity and efficiency of the Python code. Notably, I don't like the adding and removing of components from the components list.g = {1: [3, 4], 2: [5], 3:[7], 4:[], 5:[], 6:[1], 7:[]}vertices = set(g)components = []while vertices: stack = list((vertices.pop(),)) comp = set() while stack: vert = stack.pop() comp.add(vert) if vert in vertices: vertices.remove(vert) for e in g[vert]: if e in vertices: stack.append(e) else: for component in components: if e in component: component.update(comp) comp = component components.remove(comp) components.append(comp)print([c for c in components])>>> [{2, 5}, {1, 3, 4, 6, 7}] | Split DAG into disjoint sets | python;algorithm;graph;complexity | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.