id
stringlengths
5
27
question
stringlengths
19
69.9k
title
stringlengths
1
150
tags
stringlengths
1
118
accepted_answer
stringlengths
4
29.9k
_webmaster.91602
While exporting magento database from xampp (using phpmyadmin).I am getting error .sql file. and also getting a warning message during export start.Like thisplease help to export magento database.Magento version : Magento ver. 1.9.2.4
Unable to export magento database using xampp phpmyadmin
phpmyadmin
Export from command line if you have having issues with exporting from phpMyAdmin.backup/export: # mysqldump -u root -p[root_password] [database_name] > dumpfilename.sqlrestore: # mysql -u root -p[root_password] [database_name] < dumpfilename.sqlSimilar question on StackOverflow
_datascience.5267
I took on a project to predict the outcome of soccer matches but it turned out to be a very challenging task.I tried out different models but I only got 50-54% accuracy on my test dataset. Some of the models were created in sucha way that a certain model would predict if a team will win, draw, or loose a match. That same model would also predict ifthe opponent of that team will win, draw, or loose the match. Each model predicting with an accuracy of about 50% on each team distinctively. The second set of models I tried, takes the combination of data from both teams and predicts which class the match belongs to (home win, away win, draw). In the system,only 10 matches are given everyday to be predicted. Meaning, if I predict the 10 matches using the second model, I have a chance of predicting 5 correctly. In this project, I only need to predict 3 matches correctly out of the 10 matches given in a day. Is there a systemof knowing the 3 matches which my models have the best chance of predicting correctly? I only need to get 3 correct, I usuallyget 5 correctly but I don't know how to select my 3 best matches. Note: The first type of models use about 50 features for prediction while the second uses 101. I've tried ensembles, they still give me ~50% accuracy. I'm still about to setup a system that selects matches where the prediction for the home team does not contradict the prediction for the away team using the first type of model.
Predicting Soccer: guessing which matches a model will predict correcly
machine learning;predictive modeling
null
_unix.241397
I tried to install Debian 8 (Jessie) with the official DVD 1 from my Card Reader (SDHC UHS-I Card 32GB). Now that does not work, because I am unable to mount it (no signal at all).Now I want to know if there is a way to install it from another HDD partition. I already made it FAT32 and put the files there, but the installer asks for a CD/DVD. Is there another installer that does take the files from the internal partition?Also how do I remove the already started installation? I'm a bit straggled and can't find info about my problem.-#### edit ####I started out formatting my SDHC card to Fat32, putting the whole installer disk on it, making it bootable (does not boot). So I found the setup.exe on the DVD which lead me through the installation process. After rebooting, the installation progress starts and it tells me to either run an automatic search for a CDROM input or manually enter it -> nothing foundSo I randomly guess around with tty3, 4 until I give up and run the shell.With ls dev there is a list of possible drives. rtc0 looks nice, because my cardreader is an Realtek RTS5209. When I try to mount it, it says it is empty.Now with lspci -v I found nothing usable for me.So I made a new partition in FAT32 style, put the contents of the DVD there and mounted it usingmount -t vfat /dev/sda5/ /media/Works like a charm, except that the installer does still ask for a CD / DVD source.When I try to mount sr0 again, it says something about must be blocked device.
Installing Debian 8 (Jessie) from HDD Partition
debian;partition;system installation;hard disk;sd card
null
_softwareengineering.246785
At the place I work we are using a SafeReader class that wraps an IDataReader. One of the 'features' is that if the field you are trying to access wasn't in the query then it just returns a default value.So I am working with some code that is already in place, but apparently never fully worked as it accesses fields that aren't returned from the stored proc it's calling but it didn't throw any exceptions since the SafeReader kindly returned default values.I personally don't like this because it means that when there are mistakes in the code (someone forgets to include a field in the query, or perhaps a misspelling) then it's harder to catch.My question is whether this violates any general 'best practices' of development or object oriented programming ideals? Or does this seem perfectly reasonable?
Is it a good idea to return a default value if a field in a query cannot be found?
c#;object oriented;object oriented design
null
_codereview.48258
Lately, I've been, I've been losing sleepDreaming about the things that we could beBut baby, I've been, I've been praying hard,Said, no more counting dollarsWe'll be counting stars, yeah we'll be counting stars(One Republic - Counting Stars)The 2nd Monitor is known to be a quite star-happy chat room, but exactly how many stars is there? And who are the most starred users? I decided to write a script to find out.I chose to write this in Python because:I've never used Python before@200_success used it and it didn't look that hardI found Beautiful Soup which seemed powerful and easy to useThe script performs a number of HTTP requests to the list of starred messages, keeps track of the numbers in a dict and also saves the pure HTML data to files (to make it easier to perform other calculations on the data in the future, and I had the opportunity to learn file I/O in Python).To be safe, I included a little delay between some of the requests (Don't want to risk getting blocked by the system)Unfortunately there's no way to see which user starred the most messages, but we all know who that is anyway...The code:from time import sleepfrom bs4 import BeautifulSoupfrom urllib import requestfrom collections import OrderedDictimport operatorroom = 8595 # The 2nd Monitor (Code Review)url = 'http://chat.stackexchange.com/rooms/info/{0}/the-2nd-monitor/?tab=stars&page={1}'pages = 125def write_files(filename, content): with open(filename, 'w', encoding = 'utf-8') as f: f.write(content)def fetch_soup(room, page): resource = request.urlopen(url.format(room, page)) content = resource.read().decode('utf-8') mysoup = BeautifulSoup(content) return mysoupallstars = {}def add_stars(message): message_soup = BeautifulSoup(str(message)) stars = message_soup.select('.times').pop().string who = message_soup.select(.username a).pop().string # If there is only one star, the `.times` span item does not contain anything if stars == None: stars = 1 if who in allstars: allstars[who] += int(stars) else: allstars[who] = int(stars)for page in range(1, pages): print(Fetching page {0}.format(page)) soup = fetch_soup(room, page) all_messages = soup.find_all(attrs={'class': 'monologue'}) for message in all_messages: add_stars(message) write_files({0}-page-{1}.format(room, page), soup.prettify()) if page % 5 == 0: sleep(3)# Create a sorted list from the dict with items sorted by value (number of stars)sorted_stars = sorted(allstars.items(), key=lambda x:x[1])for user in sorted_stars: print(user)The results, you ask? Well, here they are: (Spoiler warning!) (I'm only showing those who have \$> 50\$ stars here, to keep the list shorter) ('apieceoffruit', 73) ('ChrisW', 85) ('Edward', 86) ('Yuushi', 93) ('Marc-Andre', 98) ('nhgrif', 112) ('amon', 119) ('James Khoury', 126) ('Nobody', 148) ('Jerry Coffin', 150) ('BenVlodgi', 160) ('Donald.McLean', 174) ('konijn', 184) ('200_success', 209) ('Vogel612', 220) ('kleinfreund', 229) ('Corbin', 233) ('Morwenn', 253) ('skiwi', 407) ('lol.upvote', 416) ('syb0rg', 475) ('Malachi', 534) ('retailcoder', 749) (Mat's Mug, 931) ('Simon Andr Forsberg', 1079) ('Jamal', 1170) ('The Mug with many names', 2096) (Mat's Mug, retailcoder and lol.upvote is the same user) ('rolfl', 2115)It feels strange to do .pop() to fetch data from the select soup, is there another approach available here? However, as this is the first time I'm using Python, any comments are welcome.
We'll be counting stars
python;python 3.x;stackexchange;web scraping;beautifulsoup
That's a beautiful excuse for writing code, and the final product is quite nice as well. First of all, congrats to your Java-ridden mind for not forcing classes into Python where they aren't needed. You import but do not use OrderedDict and operator. Remove unused imports. It is customary to write your code in a way that allows it to be used as either a module, or a script. For this, the if __name__ == '__main__' trick is used:if __name__ == '__main__': # executed only if used as a script You declare a few variables like room, url, and pages up front. This hinders code reuse:The room variable should not be declared up front as a global variable, but in your main section. From there, it can be passed down through all functions.The url specifically but unnecessarily mentions the-2nd-monitor. This isn't harmful, but unnecessary as only the ID is relevant. Furthermore, url is an awfully short name for such a large scope. Something like star_url_pattern would be better except that global constants should be named all-uppercase:STAR_URL_PATTERN = 'http://chat.stackexchange.com/rooms/info/{0}/?tab=stars&page={1}'Reserve plural names for collections. pages should rather be page_count. But wait why are we hardcoding this rather than fetching it from the page itself? Just follow the rel=next links until you reach the end. That last idea could be implemented with a generator function. A Python generator function is similar to a simple iterator. It can yield elements, or return when exhausted. We could build such a generator function that yields a beautiful soup object for each page, and takes care of fetching the next one. As a sketch:from urllib.parse import urljoindef walk_pages(start_url): current_page = start_url while True: content = ... # fetch the current_page soup = BeautifulSoup(content) yield soup # find the next page next_link = soup.find('a', {'rel': 'next'}) if next_link is None: return # urljoin takes care of resolving the relative URL current_page = urljoin(current_page, next_link.['href']) Please don't use urllib.request. That library has a horrible interface and is more or less broken by design. You might notice that the .read() method returns raw bytes, rather than using the charset from the Content-Type header to automatically decode the content. This is useful when handling binary data, but a HTML page is text. Instead of hardcoding the encoding utf-8 (which isn't even the default encoding for HTML), we could use a better library like requests. Then:import requestsresponse = requests.get(current_page)response.raise_for_status() # throw an error (only for 4xx or 5xx responses)content = response.text # transparently decodes the content Your allstars variable should not only be named something like all_stars (notice the separation of words via an underscore), but also not be a global variable. Consider passing it in as a parameter to add_stars, or wrapping this dictionary in an object where add_stars would be a method. I don't quite understand why you write each page to a file. I suspect this was intended as a debugging help, but it doesn't add any value to a user of that script. Instead of cluttering the current working directory, make this behavior optional. Do not compare to None via the == operator this is for general comparison. To test for identity, use the is operator: if stars is None. Sometimes, it is preferable to rely on the boolean overload of an object. For example, arrays are considered falsey if they are empty.Talking is easy,coding is hard.Is this refactoringequally bad?import timefrom bs4 import BeautifulSoupimport requestsfrom urllib.parse import urljoinSTAR_URL_TEMPLATE = 'http://chat.{0}/rooms/info/{1}/?tab=stars'def star_pages(start_url): current_page = start_url while True: print(GET {}.format(current_page)) response = requests.get(current_page) response.raise_for_status() soup = BeautifulSoup(response.text) yield soup # find the next page next_link = soup.find('a', {'rel': 'next'}) if next_link is None: return # urljoin takes care of resolving the relative URL current_page = urljoin(current_page, next_link['href'])def star_count(room_id, site='stackexchange.com'): stars = {} for page in star_pages(STAR_URL_TEMPLATE.format(site, room_id)): for message in page.find_all(attrs={'class': 'monologue'}): author = message.find(attrs={'class': 'username'}).string star_count = message.find(attrs={'class': 'times'}).string if star_count is None: star_count = 1 if author not in stars: stars[author] = 0 stars[author] += int(star_count) # be nice to the server, and wait after each page time.sleep(1) return starsif __name__ == '__main__': the_2nd_monitor_id = 8595 stars = star_count(the_2nd_monitor_id) # print out the stars in descending order for author, count in sorted(stars.items(), key=lambda pair: pair[1], reverse=True): print({}: {}.format(author, count))
_unix.122072
I downloaded ADT bundle from android developer site. Bundle name is :- adt-bundle-linux-x86_64-2014031.zipIt contains eclipse, and sdk folder.In eclipse folder, there is one eclipse executable file. I try to open this using wine1.7,Wine Windows Program Loaderbut it shows The Z:\home\devsda\Downloads\adt-bundle-linux-x86_64-20140321\eclipse\eclipse executable launcher was unable to locate its home directoryPlease help me to install ADT bundle in Ubuntu 12.04, ,so that I will start my project.
ADT bundle not installed in ubuntu 12.04
ubuntu;java;android;wine;eclipse
null
_softwareengineering.132764
I recently saw a question on SO about solving the scramble/boggle game, where the letters are in a 4x4 grid and you have to find as many words as possible. I looked at some of the solutions, tried it myself, and would now like to move onto solving a scrabble game. The boggle solving code is rather simple; store the board state in a matrix and iterate over every move from every position and checking if words exist with the current letter chain. With scrabble, the idea is similar, but I'm still having trouble figuring it out. My currently thinking of:Storing the board in 2 dimensional array.Iterating over each position and skipping if the position is empty.Creating some sort of regex pattern for the letters on the rack and the letter at the position...I'm still really iffy on what to do at step 3 because I know the tile at the position could be the beginning end, or some point in the middle of a word. And then there's the matter of making sure that if a word does fit that it also makes words with other tiles it touches..I'm not asking for code samples, just the thought process from more experienced programmers. To clarify, my goal is:Given the current state of a board and a person's tiles, calculate the legal moves and the points for that move.For anyone following this and waiting for an answer, I found this: http://www.chaddington.com/portfolio/project.html#scrabbleI might look through what he wrote, but I do want to try to figure it out myself first.
Solving Scrabble board?
methodology
I believe you've forgotten the question itself. What is your intent?Given a Scrabble board with already filled tiles, find all the words available?Or let the users play Scrabble by adding tiles and check the score with every newly added tile?If it's the first point, then you may want to:Transform your board into a set of 30 uni-dimensional arrays: one containing rows, another - the columns.For every row, walk through the tiles in the row, surrounding the row by whitespace (empty tiles) and then, replacing consecutive whitespace (empty tiles). For example, stackmeta would become stackmeta.Split those into words. stackmeta would be (stack, meta).Check each word against a dictionary.If it's the second point, then you don't have to iterate over each position (point 2 in your list). You simply search for the words from a given position Ca, b :Horizontally, starting from Ca, 1 and walking to the right until Ca, 15,Vertically, starting from C1, b and walking to the bottom until C15, b.To simplify, you can create two uni-dimensional arrays as:A(a) Ca, n, 1 n 15A(b) Cn, b, 1 n 15Then you'll have to create a single method which will determine existent words given:An uni-dimensional array (A or A),A one-dimension position of the current tile in the array.How? I would start by isolating the word itself, i.e. find the previous and the next whitespace (i.e. empty tile), if any. Then a formed word must be checked against a dictionary. Then you count the score, taking in account the colors of tiles and the tile characters.Example (using a syntax of an imaginary language):var A = stack overflow.ToArray(); // Given the one-dimension array...var b = 4; // ... and the position of the current tile...var leftEdge = A.Take(b).FindLast(' '); // Find the left empty tile,var rightEdge = A.Skip(b).FindFirst(' '); // Then the right empty tile,var word = A.Subset(leftEdge + 1, b + rightEdge - 1); // Then extract the word itself.Assert.AreEquals(stack, word); // Found a good one?bool isValidWord = word.IsInDictionary(en-US); // Search the word in the dictionary.Assert.IsTrue(isValidWord); // stack is a valid word.
_softwareengineering.306936
Promises is a fairly new pattern for me, so I'm still building my intuition for them.I recently came across a case where some code in an adapter-like bit of code was once synchronous, and then became asynchronous, so promises were introduced.Consider:function runCalculation() { var params = this.getParams(); this.callLibraryCalculation(params);}Here, getParams collects values from various places and puts them in one object that can be used by callLibraryCalculation, which wraps, as you would expect, a call from an external source. All this is obviously simplified for the purpose of the question.So this all worked, until a new use case required getParams to retrieve some of it's values from an external API, introducing asynchronous behavior. So that function was altered to handle async, using and returning a promise. Which means consuming it has changed.function runCalculation() { return this.getParams().then(function(params) { this.callLibraryCalculation(params); });}I choose to return the promise here because the functions that call runCalculation have dependent logic that needs to be .then()-ed. but my question is about the callers of runCalculation. They are now producing their own promises as a result of consuming the one returned here. I can currently let most of those promises escape into the ether, because the callers represent the end of execution. But I notice that in the case where it is not end of execution, this passing of promises begins to invade a great deal of code, bubbling from caller to caller.My inclination is to always return a promise from a function that must use one to order it's logic.Is that inclination good intuition? Should I be worried that Promises, once introduced, start to take over my code?Or to ask in a more answerable question: Are there considerations I may have missed that speak for or against such a practice?(Also still grokking the Programmers QnA, so kindly inform if this question could be moved or improved)
Should I be returning promises from any function that uses them?
javascript;promises
My inclination is to always return a promise from a function that must use one to order it's logic.If you have a function with an async operation and you're using promises and there's ever ANY reason for the caller of the function to want to know when the async operation is done or what its final value is, then by all means just return the promise you already have internally.This gives the caller more flexibility. If the caller chooses to not use the returned promise, that's no problem. At least it's there if the caller wants to use it.Should I be worried that Promises, once introduced, start to take over my code?I'm not sure what you mean by take over your code. If you want to give a caller access to async completion, then return a promise. If you don't want to give a caller access to the async completion, then don't return a promise. It's no more complex than that.Any async operation in a function makes the containing function async. It's contagious in that regard. And, promises are the best way to deliver async results and coordinate multiple async operations. So, all code that uses async operations should use promises. This isn't taking over your code - it's the intelligent way to design your async code. If it seems unnatural to you now, then you just need more experience and practice doing it and it will start to become natural and easy. At that point, it won't feel like anything took over your code, but rather that you're using the right tools for the job.
_unix.322939
I compiled the 4.8.7 linux kernel in Arch using the ABS where I received the warning No modules were added to the image. This is probably not what you want.I noticed that the extramodules folder created in /lib/modules/kernel_name has nothing besides a version file whereas the kernel installed through the linux pacakge has modules inside it's folder. My pacman output is:[2016-11-13 05:51] [PACMAN] Running 'pacman -U linux-zouti-headers-4.8.7-1-x86_64.pkg.tar.xz'[2016-11-13 05:51] [ALPM] transaction started[2016-11-13 05:51] [ALPM] installed linux-zouti-headers (4.8.7-1) [2016-11-13 05:51] [ALPM] transaction completed[2016-11-13 05:51] [ALPM] running '70-dkms-install.hook'...[2016-11-13 05:51] [ALPM-SCRIPTLET] ==> No kernel 4.8.7-1-zouti modules. You must install them to use DKMS![2016-11-13 05:52] [PACMAN] Running 'pacman -U linux-zouti-4.8.7-1-x86_64.pkg.tar.xz'[2016-11-13 05:52] [ALPM] transaction started[2016-11-13 05:52] [ALPM] installed linux-zouti (4.8.7-1)[2016-11-13 05:52] [ALPM-SCRIPTLET] >>> Updating module dependencies. Please wait ...[2016-11-13 05:52] [ALPM-SCRIPTLET] >>> Generating initial ramdisk, using mkinitcpio. Please wait...[2016-11-13 05:52] [ALPM-SCRIPTLET] ==> Building image from preset: /etc/mkinitcpio.d/linux-zouti.preset: 'default'[2016-11-13 05:52] [ALPM-SCRIPTLET] -> -k /boot/vmlinuz-linux-zouti -c /etc/mkinitcpio.conf -g /boot/initramfs-linux-zouti.img[2016-11-13 05:52] [ALPM-SCRIPTLET] ==> Starting build: 4.8.7-1-zouti[2016-11-13 05:52] [ALPM-SCRIPTLET] -> Running build hook: [base][2016-11-13 05:52] [ALPM-SCRIPTLET] -> Running build hook: [udev][2016-11-13 05:52] [ALPM-SCRIPTLET] -> Running build hook: [autodetect][2016-11-13 05:52] [ALPM-SCRIPTLET] -> Running build hook: [modconf][2016-11-13 05:52] [ALPM-SCRIPTLET] -> Running build hook: [block][2016-11-13 05:52] [ALPM-SCRIPTLET] -> Running build hook: [filesystems][2016-11-13 05:52] [ALPM-SCRIPTLET] -> Running build hook: [keyboard][2016-11-13 05:52] [ALPM-SCRIPTLET] -> Running build hook: [fsck][2016-11-13 05:52] [ALPM-SCRIPTLET] ==> WARNING: No modules were added to the image. This is probably not what you want.[2016-11-13 05:52] [ALPM-SCRIPTLET] ==> Creating gzip-compressed initcpio image: /boot/initramfs-linux-zouti.img[2016-11-13 05:52] [ALPM-SCRIPTLET] ==> Image generation successful[2016-11-13 05:52] [ALPM] transaction completed[2016-11-13 05:52] [ALPM] running '70-dkms-install.hook'...[2016-11-13 05:52] [ALPM-SCRIPTLET] ==> dkms install vboxhost/5.1.8_OSE -k 4.8.7-1-zoutiThe modules in the linux package kernel's extramodules folder are:bbswitch.ko.gznvidia-drm.ko.gznvidia.ko.gznvidia-modeset.ko.gznvidia-uvm.ko.gz
How do I solve the error No modules were added to the image. This is probably not what you want. when installing kernel packages in Arch Linux?
arch linux;kernel;kernel modules
null
_unix.180654
I have a large CSV file and want to empty certain columns if they were seen before.So I have (to illustrate my problem):Category | Subcategory---------+------------foo | barfoo | barfoo | foobarfoo | foobarAnd I want: Category | Subcategory---------+------------foo | bar | | foobar |The whole CSV is sorted (with sort --strong -k 1,2), so I just need a way to do my task with one column and can later use the same method with the other column.Basically: delete every occurence of foo except the first.It is similar to this question, but I don't want to remove the complete line ..I'm not sure how to do this, since I'm not that into awk.Can anyone help me?
Empty columns which were seen before
awk;macintosh;csv
null
_unix.320747
I compiled gnupg-2.1.15 on CentOS6.5Once compilation is done it's working fine on same host.But if I move binaries and libraries to remote host and try to use gpg it's giving below error.gpg: problem with the agent: End of filegpg: error creating passphrase: Operation cancelledgpg: symmetric encryption of 'file.txt' failed: Operation cancelledstrace gpg -c file.txt (output truncated):write(5, GETINFO cmd_has_option GET_PASSP..., 44) = 44write(5, \n, 1) = 1read(5, OK, 1002) = 2read(5, \n, 1000) = 1write(5, GET_PASSPHRASE --data --repeat=1..., 77) = 77write(5, \n, 1) = 1read(5, INQUIRE PINENTRY_LAUNCHED 625\n, 1002) = 30write(5, END, 3) = 3write(5, \n, 1) = 1INQUIRE PINENTRY_LAUNCHED 631\n, 1002) = 30write(5, END, 3) = 3write(5, \n, 1) = 1, 1002) = 0write(2, gpg: problem with the agent: End..., 40gpg: problem with the agent: End of file) = 40write(2, \n, 1) = 1close(3) = 0write(2, gpg: error creating passphrase: ..., 51gpg: error creating passphrase: Operation cancelled) = 51write(2, \n, 1) = 1write(2, gpg: symmetric encryption of 'no..., 67gpg: symmetric encryption of 'novas.rc' failed: Operation cancelled) = 67write(2, \n, 1) = 1open(/remote/us01home34/ids_cm/.gnupg/random_seed, O_WRONLY|O_CREAT, 0600) = 3fcntl(3, F_SETLK, {type=F_WRLCK, whence=SEEK_SET, start=0, len=0}) = 0ftruncate(3, 0) = 0write(3, q\315\352$}\t\205\36\2137\373+X\210\320o,yZ)\Y\252\325H\342/\231\21\252\0302..., 600) = 600close(3) = 0munmap(0x7f39d9bb7000, 32768) = 0exit_group(2) = ?Entire output of strace:% strace gpg2 -c gui_command.logexecve( gnupg-2.1.15/bin/gpg2, [gpg2, -c, gui_command.log], [/* 43 vars */]) = 0brk(0) = 0xece000mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f495451d000access(/etc/ld.so.preload, R_OK) = -1 ENOENT (No such file or directory)open( gnupg-2.1.15/deps/lib/tls/x86_64/libz.so.1, O_RDONLY) = -1 ENOENT (No such file or directory)stat( gnupg-2.1.15/deps/lib/tls/x86_64, 0x7fff4f505e10) = -1 ENOENT (No such file or directory)open( gnupg-2.1.15/deps/lib/tls/libz.so.1, O_RDONLY) = -1 ENOENT (No such file or directory)stat( gnupg-2.1.15/deps/lib/tls, 0x7fff4f505e10) = -1 ENOENT (No such file or directory)open( gnupg-2.1.15/deps/lib/x86_64/libz.so.1, O_RDONLY) = -1 ENOENT (No such file or directory)stat( gnupg-2.1.15/deps/lib/x86_64, 0x7fff4f505e10) = -1 ENOENT (No such file or directory)open( gnupg-2.1.15/deps/lib/libz.so.1, O_RDONLY) = -1 ENOENT (No such file or directory)stat( gnupg-2.1.15/deps/lib, {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0open(/usr/local/lib/tls/x86_64/libz.so.1, O_RDONLY) = -1 ENOENT (No such file or directory)stat(/usr/local/lib/tls/x86_64, 0x7fff4f505e10) = -1 ENOENT (No such file or directory)open(/usr/local/lib/tls/libz.so.1, O_RDONLY) = -1 ENOENT (No such file or directory)stat(/usr/local/lib/tls, 0x7fff4f505e10) = -1 ENOENT (No such file or directory)open(/usr/local/lib/x86_64/libz.so.1, O_RDONLY) = -1 ENOENT (No such file or directory)stat(/usr/local/lib/x86_64, 0x7fff4f505e10) = -1 ENOENT (No such file or directory)open(/usr/local/lib/libz.so.1, O_RDONLY) = -1 ENOENT (No such file or directory)stat(/usr/local/lib, {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0open(/etc/ld.so.cache, O_RDONLY) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=404457, ...}) = 0mmap(NULL, 404457, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7f49544ba000close(3) = 0open(/lib64/libz.so.1, O_RDONLY) = 3read(3, \177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0 !\0\0\0\0\0\0..., 832) = 832fstat(3, {st_mode=S_IFREG|0755, st_size=88600, ...}) = 0mmap(NULL, 2183696, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f49540e9000mprotect(0x7f49540fe000, 2093056, PROT_NONE) = 0mmap(0x7f49542fd000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x14000) = 0x7f49542fd000close(3) = 0open( gnupg-2.1.15/deps/lib/libbz2.so.1, O_RDONLY) = -1 ENOENT (No such file or directory)open(/usr/local/lib/libbz2.so.1, O_RDONLY) = -1 ENOENT (No such file or directory)open(/lib64/libbz2.so.1, O_RDONLY) = 3read(3, \177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0000\26\0\0\0\0\0\0..., 832) = 832fstat(3, {st_mode=S_IFREG|0755, st_size=67592, ...}) = 0mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f49544b9000mmap(NULL, 2162768, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f4953ed8000mprotect(0x7f4953ee8000, 2093056, PROT_NONE) = 0mmap(0x7f49540e7000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0xf000) = 0x7f49540e7000close(3) = 0open( gnupg-2.1.15/deps/lib/libgcrypt.so.20, O_RDONLY) = 3read(3, \177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\0\257\0\0\0\0\0\0..., 832) = 832fstat(3, {st_mode=S_IFREG|0755, st_size=3456395, ...}) = 0mmap(NULL, 3061312, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f4953bec000mprotect(0x7f4953cd1000, 2093056, PROT_NONE) = 0mmap(0x7f4953ed0000, 32768, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0xe4000) = 0x7f4953ed0000close(3) = 0open( gnupg-2.1.15/deps/lib/libgpg-error.so.0, O_RDONLY) = 3read(3, \177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\360&\0\0\0\0\0\0..., 832) = 832fstat(3, {st_mode=S_IFREG|0755, st_size=282533, ...}) = 0mmap(NULL, 2167992, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f49539da000mprotect(0x7f49539eb000, 2097152, PROT_NONE) = 0mmap(0x7f4953beb000, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x11000) = 0x7f4953beb000close(3) = 0open( gnupg-2.1.15/deps/lib/libreadline.so.6, O_RDONLY) = -1 ENOENT (No such file or directory)open(/usr/local/lib/libreadline.so.6, O_RDONLY) = -1 ENOENT (No such file or directory)open(/lib64/libreadline.so.6, O_RDONLY) = 3read(3, \177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0PE\1\0\0\0\0\0..., 832) = 832fstat(3, {st_mode=S_IFREG|0755, st_size=269592, ...}) = 0mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f49544b8000mmap(NULL, 2370056, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f4953797000mprotect(0x7f49537d1000, 2097152, PROT_NONE) = 0mmap(0x7f49539d1000, 32768, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x3a000) = 0x7f49539d1000mmap(0x7f49539d9000, 2568, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7f49539d9000close(3) = 0open( gnupg-2.1.15/deps/lib/libassuan.so.0, O_RDONLY) = 3read(3, \177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\3204\0\0\0\0\0\0..., 832) = 832fstat(3, {st_mode=S_IFREG|0755, st_size=416569, ...}) = 0mmap(NULL, 2166448, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f4953586000mprotect(0x7f4953597000, 2093056, PROT_NONE) = 0mmap(0x7f4953796000, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x10000) = 0x7f4953796000close(3) = 0open( gnupg-2.1.15/deps/lib/libc.so.6, O_RDONLY) = -1 ENOENT (No such file or directory)open(/usr/local/lib/libc.so.6, O_RDONLY) = -1 ENOENT (No such file or directory)open(/lib64/libc.so.6, O_RDONLY) = 3read(3, \177ELF\2\1\1\3\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0p\356\1\0\0\0\0\0..., 832) = 832fstat(3, {st_mode=S_IFREG|0755, st_size=1921176, ...}) = 0mmap(NULL, 3750152, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f49531f2000mprotect(0x7f495337c000, 2097152, PROT_NONE) = 0mmap(0x7f495357c000, 20480, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x18a000) = 0x7f495357c000mmap(0x7f4953581000, 18696, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7f4953581000close(3) = 0open( gnupg-2.1.15/deps/lib/libtinfo.so.5, O_RDONLY) = -1 ENOENT (No such file or directory)open(/usr/local/lib/libtinfo.so.5, O_RDONLY) = -1 ENOENT (No such file or directory)open(/lib64/libtinfo.so.5, O_RDONLY) = 3read(3, \177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0@\310\0\0\0\0\0\0..., 832) = 832fstat(3, {st_mode=S_IFREG|0755, st_size=135896, ...}) = 0mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f49544b7000mmap(NULL, 2232320, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f4952fd1000mprotect(0x7f4952fee000, 2097152, PROT_NONE) = 0mmap(0x7f49531ee000, 16384, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1d000) = 0x7f49531ee000close(3) = 0mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f49544b6000mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f49544b5000mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f49544b4000arch_prctl(ARCH_SET_FS, 0x7f49544b5700) = 0mprotect(0x7f495357c000, 16384, PROT_READ) = 0mprotect(0x7f49542fd000, 4096, PROT_READ) = 0mprotect(0x7f495451e000, 4096, PROT_READ) = 0munmap(0x7f49544ba000, 404457) = 0brk(0) = 0xece000brk(0xeef000) = 0xeef000fstat(0, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 0), ...}) = 0fstat(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 0), ...}) = 0fstat(2, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 0), ...}) = 0open(/usr/lib/locale/locale-archive, O_RDONLY) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=99158576, ...}) = 0mmap(NULL, 99158576, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7f494d140000close(3) = 0access(/etc/gcrypt/fips_enabled, F_OK) = -1 ENOENT (No such file or directory)open(/proc/sys/crypto/fips_enabled, O_RDONLY) = 3fstat(3, {st_mode=S_IFREG|0444, st_size=0, ...}) = 0mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f495451c000read(3, 0\n, 1024) = 2close(3) = 0munmap(0x7f495451c000, 4096) = 0open(/etc/gcrypt/hwf.deny, O_RDONLY) = -1 ENOENT (No such file or directory)getrlimit(RLIMIT_CORE, {rlim_cur=0, rlim_max=RLIM_INFINITY}) = 0setrlimit(RLIMIT_CORE, {rlim_cur=0, rlim_max=RLIM_INFINITY}) = 0rt_sigaction(SIGINT, NULL, {SIG_DFL, [], 0}, 8) = 0rt_sigaction(SIGINT, {0x495c80, [], SA_RESTORER, 0x7f49532246a0}, NULL, 8) = 0rt_sigaction(SIGHUP, NULL, {SIG_DFL, [], 0}, 8) = 0rt_sigaction(SIGHUP, {0x495c80, [], SA_RESTORER, 0x7f49532246a0}, NULL, 8) = 0rt_sigaction(SIGTERM, NULL, {SIG_DFL, [], 0}, 8) = 0rt_sigaction(SIGTERM, {0x495c80, [], SA_RESTORER, 0x7f49532246a0}, NULL, 8) = 0rt_sigaction(SIGQUIT, NULL, {SIG_DFL, [], 0}, 8) = 0rt_sigaction(SIGQUIT, {0x495c80, [], SA_RESTORER, 0x7f49532246a0}, NULL, 8) = 0rt_sigaction(SIGSEGV, NULL, {SIG_DFL, [], 0}, 8) = 0rt_sigaction(SIGSEGV, {0x495c80, [], SA_RESTORER, 0x7f49532246a0}, NULL, 8) = 0rt_sigaction(SIGUSR1, {0x495a80, [], SA_RESTORER, 0x7f49532246a0}, NULL, 8) = 0rt_sigaction(SIGPIPE, {SIG_IGN, [], SA_RESTORER, 0x7f49532246a0}, NULL, 8) = 0mmap(NULL, 32768, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f4954515000getuid() = 32382mlock(0x7f4954515000, 32768) = 0geteuid() = 32382access( /home/venkatesh/.gnupg/gpg.conf-2.1.15, R_OK) = -1 ENOENT (No such file or directory)access( /home/venkatesh/.gnupg/gpg.conf-2.1, R_OK) = -1 ENOENT (No such file or directory)access( /home/venkatesh/.gnupg/gpg.conf-2, R_OK) = -1 ENOENT (No such file or directory)access( /home/venkatesh/.gnupg/gpg.conf, R_OK) = 0access( /home/venkatesh/.gnupg/options, R_OK) = -1 ENOENT (No such file or directory)stat( /home/venkatesh/.gnupg, {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0stat( /home/venkatesh, {st_mode=S_IFDIR|0755, st_size=118784, ...}) = 0getuid() = 32382open(/usr/share/locale/locale.alias, O_RDONLY) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=2512, ...}) = 0mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f4954514000read(3, # Locale name alias data base.\n#..., 4096) = 2512read(3, , 4096) = 0close(3) = 0munmap(0x7f4954514000, 4096) = 0open( gnupg-2.1.15/share/locale/en_US.UTF-8/LC_MESSAGES/gnupg2.mo, O_RDONLY) = -1 ENOENT (No such file or directory)open( gnupg-2.1.15/share/locale/en_US.utf8/LC_MESSAGES/gnupg2.mo, O_RDONLY) = -1 ENOENT (No such file or directory)open( gnupg-2.1.15/share/locale/en_US/LC_MESSAGES/gnupg2.mo, O_RDONLY) = -1 ENOENT (No such file or directory)open( gnupg-2.1.15/share/locale/en.UTF-8/LC_MESSAGES/gnupg2.mo, O_RDONLY) = -1 ENOENT (No such file or directory)open( gnupg-2.1.15/share/locale/en.utf8/LC_MESSAGES/gnupg2.mo, O_RDONLY) = -1 ENOENT (No such file or directory)open( gnupg-2.1.15/share/locale/en/LC_MESSAGES/gnupg2.mo, O_RDONLY) = -1 ENOENT (No such file or directory)write(2, gpg: WARNING: unsafe permissions..., 77gpg: WARNING: unsafe permissions on homedir ' /home/venkatesh/.gnupg) = 77write(2, '\n, 2') = 2open( /home/venkatesh/.gnupg/gpg.conf, O_RDONLY) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=10, ...}) = 0mmap(NULL, 32768, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f495450d000read(3, use-agent\n, 32768) = 10read(3, , 32768) = 0close(3) = 0munmap(0x7f495450d000, 32768) = 0access( /home/venkatesh/.gnupg/random_seed, F_OK) = 0open( /home/venkatesh/.gnupg/pubring.gpg, O_RDONLY) = -1 ENOENT (No such file or directory)open( /home/venkatesh/.gnupg/pubring.kbx, O_RDONLY) = 3fstat(3, {st_mode=S_IFREG|0600, st_size=32, ...}) = 0mmap(NULL, 32768, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f495450d000read(3, \0\0\0 \1\1\0\2KBXf\0\0\0\0X\33\3\313X\33\3\313\0\0\0\0\0\0\0\0, 32768) = 32close(3) = 0munmap(0x7f495450d000, 32768) = 0access( /home/venkatesh/.gnupg/pubring.kbx, F_OK) = 0open(gui_command.log, O_RDONLY) = 3access(/dev/random, R_OK) = 0access(/dev/urandom, R_OK) = 0getpid() = 8080open( /home/venkatesh/.gnupg/random_seed, O_RDONLY) = 4fcntl(4, F_SETLK, {type=F_RDLCK, whence=SEEK_SET, start=0, len=0}) = 0fstat(4, {st_mode=S_IFREG|0600, st_size=600, ...}) = 0read(4, Q\344\263&\334gG h)\334\347\31\352\325G\323\206L\362&\305G|\31\17%e\20\217-k..., 600) = 600close(4) = 0times({tms_utime=0, tms_stime=1, tms_cutime=0, tms_cstime=0}) = 967382149open(/dev/urandom, O_RDONLY) = 4fcntl(4, F_GETFD) = 0fcntl(4, F_SETFD, FD_CLOEXEC) = 0select(5, [4], NULL, NULL, {0, 100000}) = 1 (in [4], left {0, 99994})read(4, \26\221n*\275\257\20\313\\J\242\221\2410\274X, 16) = 16getrusage(RUSAGE_SELF, {ru_utime={0, 999}, ru_stime={0, 12998}, ...}) = 0times({tms_utime=0, tms_stime=1, tms_cutime=0, tms_cstime=0}) = 967382149open( gnupg-2.1.15/deps/share/locale/en_US.UTF-8/LC_MESSAGES/libgpg-error.mo, O_RDONLY) = -1 ENOENT (No such file or directory)open( gnupg-2.1.15/deps/share/locale/en_US.utf8/LC_MESSAGES/libgpg-error.mo, O_RDONLY) = -1 ENOENT (No such file or directory)open( gnupg-2.1.15/deps/share/locale/en_US/LC_MESSAGES/libgpg-error.mo, O_RDONLY) = -1 ENOENT (No such file or directory)open( gnupg-2.1.15/deps/share/locale/en.UTF-8/LC_MESSAGES/libgpg-error.mo, O_RDONLY) = -1 ENOENT (No such file or directory)open( gnupg-2.1.15/deps/share/locale/en.utf8/LC_MESSAGES/libgpg-error.mo, O_RDONLY) = -1 ENOENT (No such file or directory)open( gnupg-2.1.15/deps/share/locale/en/LC_MESSAGES/libgpg-error.mo, O_RDONLY) = -1 ENOENT (No such file or directory)getuid() = 32382stat(/run/user/32382, 0x7fff4f5049a0) = -1 ENOENT (No such file or directory)getuid() = 32382stat(/var/run/user/32382, 0x7fff4f5049a0) = -1 ENOENT (No such file or directory)stat( /home/venkatesh/.gnupg/S.gpg-agent, {st_mode=S_IFSOCK|0700, st_size=0, ...}) = 0socket(PF_FILE, SOCK_STREAM, 0) = 5stat( /home/venkatesh/.gnupg/S.gpg-agent, {st_mode=S_IFSOCK|0700, st_size=0, ...}) = 0connect(5, {sa_family=AF_FILE, path= /home/venkatesh/.gnupg/S.gpg-agent}, 46) = -1 ECONNREFUSED (Connection refused)open(/usr/share/locale/en_US.UTF-8/LC_MESSAGES/libc.mo, O_RDONLY) = -1 ENOENT (No such file or directory)open(/usr/share/locale/en_US.utf8/LC_MESSAGES/libc.mo, O_RDONLY) = -1 ENOENT (No such file or directory)open(/usr/share/locale/en_US/LC_MESSAGES/libc.mo, O_RDONLY) = -1 ENOENT (No such file or directory)open(/usr/share/locale/en.UTF-8/LC_MESSAGES/libc.mo, O_RDONLY) = -1 ENOENT (No such file or directory)open(/usr/share/locale/en.utf8/LC_MESSAGES/libc.mo, O_RDONLY) = -1 ENOENT (No such file or directory)open(/usr/share/locale/en/LC_MESSAGES/libc.mo, O_RDONLY) = -1 ENOENT (No such file or directory)close(5) = 0uname({sys=Linux, node=us02vlgapps-rh6, ...}) = 0open( /home/venkatesh/.gnupg/.#lk0x0000000000ee08f0.us02vlgapps-rh6.8080, O_WRONLY|O_CREAT|O_EXCL, 0644) = 5write(5, 8080\n, 11) = 11write(5, us02vlgapps-rh6, 15) = 15write(5, \n, 1) = 1close(5) = 0stat( /home/venkatesh/.gnupg/.#lk0x0000000000ee08f0.us02vlgapps-rh6.8080, {st_mode=S_IFREG|0644, st_size=27, ...}) = 0link( /home/venkatesh/.gnupg/.#lk0x0000000000ee08f0.us02vlgapps-rh6.8080, /home/venkatesh/.gnupg/.#lk0x0000000000ee08f0.us02vlgapps-rh6.8080x) = 0stat( /home/venkatesh/.gnupg/.#lk0x0000000000ee08f0.us02vlgapps-rh6.8080, {st_mode=S_IFREG|0644, st_size=27, ...}) = 0unlink( /home/venkatesh/.gnupg/.#lk0x0000000000ee08f0.us02vlgapps-rh6.8080x) = 0link( /home/venkatesh/.gnupg/.#lk0x0000000000ee08f0.us02vlgapps-rh6.8080, /home/venkatesh/.gnupg/gnupg_spawn_agent_sentinel.lock) = 0stat( /home/venkatesh/.gnupg/.#lk0x0000000000ee08f0.us02vlgapps-rh6.8080, {st_mode=S_IFREG|0644, st_size=27, ...}) = 0stat( /home/venkatesh/.gnupg/S.gpg-agent, {st_mode=S_IFSOCK|0700, st_size=0, ...}) = 0socket(PF_FILE, SOCK_STREAM, 0) = 5stat( /home/venkatesh/.gnupg/S.gpg-agent, {st_mode=S_IFSOCK|0700, st_size=0, ...}) = 0connect(5, {sa_family=AF_FILE, path= /home/venkatesh/.gnupg/S.gpg-agent}, 46) = -1 ECONNREFUSED (Connection refused)close(5) = 0getuid() = 32382geteuid() = 32382access( gnupg-2.1.15/bin/gpg-agent, X_OK) = 0clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7f49544b59d0) = 8081wait4(8081, NULL, 0, NULL) = 8081--- SIGCHLD (Child exited) @ 0 (0) ---rt_sigprocmask(SIG_BLOCK, [CHLD], [], 8) = 0rt_sigaction(SIGCHLD, NULL, {SIG_DFL, [], 0}, 8) = 0rt_sigprocmask(SIG_SETMASK, [], NULL, 8) = 0nanosleep({1, 0}, 0x7fff4f504aa0) = 0stat( /home/venkatesh/.gnupg/S.gpg-agent, {st_mode=S_IFSOCK|0700, st_size=0, ...}) = 0socket(PF_FILE, SOCK_STREAM, 0) = 5stat( /home/venkatesh/.gnupg/S.gpg-agent, {st_mode=S_IFSOCK|0700, st_size=0, ...}) = 0connect(5, {sa_family=AF_FILE, path= /home/venkatesh/.gnupg/S.gpg-agent}, 46) = 0read(5, OK Pleased to meet you, process ..., 1002) = 36read(5, \n, 966) = 1unlink( /home/venkatesh/.gnupg/gnupg_spawn_agent_sentinel.lock) = 0unlink( /home/venkatesh/.gnupg/.#lk0x0000000000ee08f0.us02vlgapps-rh6.8080) = 0write(5, RESET, 5) = 5write(5, \n, 1) = 1read(5, OK, 1002) = 2read(5, \n, 1000) = 1ioctl(0, SNDCTL_TMR_TIMEBASE or TCGETS, {B38400 opost isig icanon echo ...}) = 0readlink(/proc/self/fd/0, /dev/pts/0..., 4095) = 10ioctl(0, SNDCTL_TMR_TIMEBASE or TCGETS, {B38400 opost isig icanon echo ...}) = 0readlink(/proc/self/fd/0, /dev/pts/0, 4095) = 10write(5, OPTION ttyname=/dev/pts/0, 25) = 25write(5, \n, 1) = 1read(5, OK, 1002) = 2read(5, \n, 1000) = 1write(5, OPTION ttytype=xterm, 20) = 20write(5, \n, 1) = 1read(5, OK, 1002) = 2read(5, \n, 1000) = 1write(5, OPTION lc-ctype=en_US.UTF-8, 27) = 27write(5, \n, 1) = 1read(5, OK, 1002) = 2read(5, \n, 1000) = 1write(5, OPTION lc-messages=en_US.UTF-8, 30) = 30write(5, \n, 1) = 1read(5, OK, 1002) = 2read(5, \n, 1000) = 1write(5, GETINFO version, 15) = 15write(5, \n, 1) = 1read(5, D 2.1.15\n, 1002) = 9read(5, OK, 1002) = 2read(5, \n, 1000) = 1write(5, OPTION allow-pinentry-notify, 28) = 28write(5, \n, 1) = 1read(5, OK, 1002) = 2read(5, \n, 1000) = 1write(5, OPTION agent-awareness=2.1.0, 28) = 28write(5, \n, 1) = 1read(5, OK, 1002) = 2read(5, \n, 1000) = 1write(5, AGENT_ID, 8) = 8write(5, \n, 1) = 1read(5, ERR 67109139 Unknown IPC command..., 1002) = 44read(5, \n, 958) = 1write(5, GETINFO s2k_count, 17) = 17write(5, \n, 1) = 1read(5, D 5991424\n, 1002) = 10read(5, OK, 1002) = 2read(5, \n, 1000) = 1write(5, GETINFO cmd_has_option GET_PASSP..., 44) = 44write(5, \n, 1) = 1read(5, OK, 1002) = 2read(5, \n, 1000) = 1write(5, GET_PASSPHRASE --data --repeat=1..., 77) = 77write(5, \n, 1) = 1read(5, INQUIRE PINENTRY_LAUNCHED 8085\n, 1002) = 31write(5, END, 3) = 3write(5, \n, 1) = 1INQUIRE PINENTRY_LAUNCHED 8088\n, 1002) = 31write(5, END, 3) = 3write(5, \n, 1) = 1, 1002) = 0write(2, gpg: problem with the agent: End..., 40gpg: problem with the agent: End of file) = 40write(2, \n, 1) = 1close(3) = 0write(2, gpg: error creating passphrase: ..., 51gpg: error creating passphrase: Operation cancelled) = 51write(2, \n, 1) = 1write(2, gpg: symmetric encryption of 'gu..., 74gpg: symmetric encryption of 'gui_command.log' failed: Operation cancelled) = 74write(2, \n, 1) = 1open( /home/venkatesh/.gnupg/random_seed, O_WRONLY|O_CREAT, 0600) = 3fcntl(3, F_SETLK, {type=F_WRLCK, whence=SEEK_SET, start=0, len=0}) = 0ftruncate(3, 0) = 0write(3, 6R\301:\251d\250\177a*\256\347E\317'\356\307C\331\233\362\354Z\334\3718\34\32&\364\366\334..., 600) = 600close(3) = 0munmap(0x7f4954515000, 32768) = 0exit_group(2) = ?
gpg: error creating passphrase: Operation cancelled
command line;gpg;gpg agent
null
_cs.2433
So, in lectures about Rice's Theorem, reduction is usually used to proved the theorem. Reduction usually consists a construction of $M'$, using a TM $M$ which is in the form $\langle M,w \rangle$ to be simulated first, an input $x$ to be simulated if $M$ accepts. $M'$ accepts if x is accepted. I really want a concrete input about $\langle M,w \rangle$ and $x$. For example:$L = \{ \langle M\rangle \mid L(M) = \{\text{ stackoverflow }\}\}$, that is L contains all Turing machines whose languages contain one string: stackoverflow. $L$ is undecidable.What kind of $\langle M,w \rangle$ to be simulated? Suppose we have input x = stackoverflow or x = this is stackoverflow or any x with stackoverflow in it.What if we first simulate a TM $M$ selected from in the possibilities of all TMs, and this TM accepts only a single character $a$ as its language. So, we simulate this $\langle M,w \rangle$ with $w = a$, and surely it will be accepted. And then input $x$ is also accepted according to the definition of $L$. So, we conclude that $\langle M,w \rangle$ in which language is a single $a$ is reducible to $L$ that accepts all TMs which have stackoverflow?Edit: I've just looked up a brief definition of reduction. A reduction is a transformation from an unknown but easier problem to a harder problem but already known. If the harder problem is solvable, so is the easier one. Otherwise, it's not. Given that definition, I think the correct TM $M$ with its description $\langle M,w \rangle$ in my example should be a TM such that it accepts regular languages. This is the harder problem. If this is solvable, then my trivial $L$ with one string is solvable. But apparently, it's not according to the proof. We can effectively say we reduced from language one string problem to regular language problem and try to solve it. Previously, I thought the other way around: $\langle M,w \rangle$ is reduced to one string problem. Is my thinking correct?
A concrete example about string w and string x used in the proof of Rice's Theorem
computability
A reduction is a transformation from an unknown but easier problem to a harder problem but already known. If the harder problem is solvable, so is the easier one. Otherwise, it's not.Your characterisation of reduction is a bit misleading. You don't start with an easy problem and reduce it to a harder problem (how can you know it's an easy problem if it's unknown? Often you're attempting the reduction to find out whether your problem is easy).A reduction is a computable transformation from one problem to another. It proves that the source problem is no harder (in some sense) than the target problem.Sometimes we do this because we already know the source problem is impossible to solve; this proves that the target problem is impossible too. Since the source problem is no harder than the target problem, and we already know the source is undecidable, the target problem must be undecidable (or the source would in fact be harder). More intuitively, if we can reduce the source to the target and the source is undecidable, then the target must be undecidable or we could use the reduction and the solution to the target in order to solve the source (which we already know can't be done).Other times we find a reduction because we know the target problem is decidable. This shows that the source problem is decidable too.So you can use a reduction argument either to a problem that's already known to be decidable, or from a problem that's already known to be undecidable, depending on what you're trying to prove.So, Rice's Theorum. I don't quite understand the questions you're asking, since I haven't seen the particular statement of the proof that's giving you trouble. Instead, here's my quickie explanation of how to prove Rice's Theorum, which I'm pretty sure is similar.Suppose we have an arbitrary language $L$, consisting of (encodings of) exactly those TMs with some non-trivial semantic property $P$.[1] To prove that there is no algorithm for deciding language $L$, I will reduce the Halting Problem to the decision problem for $L$.So the Halting Problem (or the particular variant of it I will use here) is: given $\langle M, x\rangle$, an encoding of a Turing machine $M$ and an input $x$, does $M$ halt on $x$?My reduction must transform the input to the Halting Problem $\langle M, x \rangle$ into the input for the hypothetical decider for $L$, which I will call $ML$. $L$ is a language of Turing machines, so $ML$'s input looks like $\langle M \rangle$.So my reduction will take $\langle M, x \rangle$ and compute $\langle M' \rangle$. $M'$ is a machine that takes an input $w$ and functions as follows:Simulate $M$ on $x$, ignoring the resultSimulate $MP$ on $w$; accept if it accepts and reject if it rejectsHere $MP$ is a machine that whose encoding is in $L$ i.e. it has the property $P$. Since we're considering a non-trivial property $P$, such an $MP$ is guaranteed to exist.Note that $x$ is part of the machine $M'$ the reduction has produced, while $w$ is the input to that machine whenever it is run. $x$ and $w$ are completely unrelated. We are assuming we've been given a particular $x$ as part of the input to the Halting Problem, but since we haven't proposed running $M'$, there is no specific $w$ at the moment.Now, if $M$ halts on input $x$, then $M'$ always gets to stage 2 and thus accepts/rejects exactly the same strings as $MP$. Since the property $P$ is semantic, it doesn't depend on the particular TM, only on the language it accepts, so in this case $M'$ also has property $P$. If $M$ doesn't halt on input $x$, then $M'$ never gets to an accept state regardless of input, so its language is the empty language.So now we don't want to run $M'$ on anything, since it might not even halt, but we could run our hypothetical $ML$ on it to check whether it's in $L$. This will almost tell us whether $M$ halts on $x$; the only thing we're missing is that the empty language might happen to have property $P$, in which case $ML$ will always accept $M'$ whether or not $M$ halts on $x$. But we can easily amend $M'$: if $P$ is true of the empty language (which our reduction could check using $ML$ if $ML$ could actually exist), then we use $MN$ instead of $MP$ - some machine that doesn't have property $P$ (which is also guaranteed to exist by the non-triviality of $P$) - and then our $M'$ has property $P$ if-and-only-if $M$ doesn't halt on $x$.So now we've shown that a hypothetical decider for $L$, the language of machines with property $P$, could be used to decide the Halting Problem. Since we already know the Halting Problem can't be decided, $ML$ can't exist. Since the only thing I assumed about $P$ was that it was a semantic and non-trivial property, the proof holds for any semantic and non-trivial property.I cheated a little in my reduction, since I had to use $ML$ to work out whether the empty language has property $P$, which means the reduction is only computable if $ML$ exists. This breaks my earlier definition of a reduction as a computable transformation from one problem to another, but the proof by contradiction is still perfectly valid; proving a language undecidable by reduction from an undecidable language is really just a special case of a proof by contradiction anyway.[1] A property of a TM is semantic if all TMs that accept the same language share the property, i.e. the property doesn't depend on the particular implementation of the TM but only on the language it accepts. A property is non-trivial if there is at least one TM that has the property and at least one TM that doesn't have the property.
_cs.21359
Is this true? If I change all final states of a given Deterministic Finite Automata to non final states and all non final states to final states then does this new automata represent the complement of the language that was accepted by the original automata?What if we talk about a Non deterministic finite automata instead of a DFA?
Can reversing the final and non-final states of a DFA produce the complement of the original language?
formal languages;automata;finite automata
In DFAs, the path taken in the automaton are deterministic and reach one specific state, so all the strings in the language reach one accepted state and all the other strings on this alphabet reach non-accepting states. Switching the accepting and non-accepting path is equivalent to saying accept every string that doesn't reach an accepting state in the original automaton, don't accept any string that reach an accepting state in the original automaton, in short, Not in the language L of the original automaton, which is the complement of L.In NFAs, it is quite easy to find contradiction to show that this statement is incorrect.Consider the following 2-state NFA with the alphabet {a, b}:state 1 (starting state, accepting state): input a -> go to state 1 input b -> go to state 2state 2: input a -> go to state 1 and 2 input b -> go to state 2The string aaba is accepted by this automaton. If we switch the accepting states, this string is still accepted by the automaton, and thus the two languages can't be the complement of each other.
_unix.118495
So... the pkg_* tools are deprecated, EOL scheduled for September 2014. Time to convert to pkgng. They have provided the pkg2ng tool provided for that. But when I run it, it throws tons of error messages. I don't know if I can ignore them or if that will introduce subtle errors.# pkg2ngConverting packages from /var/db/pkgConverting libsigsegv-2.10...pkg: fopen(/usr/ports/Keywords/display.yaml): No such file or directorypkg: unknown keyword display, ignoring @displayInstalling libsigsegv-2.10... doneConverting m4-1.4.17,1...pkg: fopen(/usr/ports/Keywords/mtree.yaml): No such file or directorypkg: unknown keyword mtree, ignoring @mtreeInstalling m4-1.4.17,1... doneConverting libiconv-1.14_2...pkg: fopen(/usr/ports/Keywords/mtree.yaml): No such file or directorypkg: unknown keyword mtree, ignoring @mtreeInstalling libiconv-1.14_2... doneConverting tdb-1.2.12,1...pkg: fopen(/usr/ports/Keywords/conflicts.yaml): No such file or directorypkg: unknown keyword conflicts, ignoring @conflictsInstalling tdb-1.2.12,1... done(and so on)Google doesn't give me much, only numerous repetitions of the thread that this post stems from: http://lists.freebsd.org/pipermail/freebsd-pkg/2013-June/000052.htmlI find that pretty weird, it looks as if there were only 2 or 3 people on the planet having this problem, one of whom would be me.So...Anyone had this problem, too?Can the error messages be ignored? (But why are they printed, then? Remember, this is the package database, which is pretty central to the system.)What can I do to rectify the situation.
pkg2ng throwing tons of errors about unknown keywords
freebsd;package management
From the FreeBSD manual regarding pkgng:The package database conversion may emit errors as the contents are converted to the new version. Generally, these errors can be safely ignored. However, a list of third-party software that was not successfully converted will be listed after pkg2ng has finished and these applications must be manually reinstalled.These errors are related to display, mtree, conflicts keywords handling: nothing to worry about as these are either obsolete or exotic cases. As stated in the doc, the installed package which did failed to convert would be listed.The bottom line here is that the new pkg info give you all the packages you had.
_cs.29833
I have three functions with values given as $$\begin{align*} P(0) &= 0 \quad & P(i+1) &= 5M(i)\\ M(0) &= 1 \quad & M(i+1) &= R(i) + 2P(i)\\ R(0) &= 3 \quad & R(i+1) &= R(i) + 3P(i)\,.\end{align*}$$If it was a linear recurrence with one function I could solve it using matrices. But here I cannot bring it to a single relationship. Each one is interrelated with the others. How do I approach this problem?
How do I solve interdependent recurrence relations?
proof techniques;recurrence relation
Eliminate one recurrence at a time, by plugging in.For instance, you can use the equation $P(i)=5 M(i-1)$ to eliminate every instance of $P(\cdot)$ in each of the other recurrences. Plugging in, we get$$M(i) = R(i-1) + 10 M(i-2)$$$$R(i) = R(i-1) + 15 M(i-2).$$Now you have two inter-related recurrence relations, instead of three; you've eliminated one.Do it one more time, say to remove each instance of $M(\cdot)$. You get something like$$R(i) = R(i-1) + 15 R(i-3) + 150 M(i-4).$$Do it again, to remove the $M(\cdot)$:$$R(i) = R(i-1) + 15 R(i-3) + 150 R(i-5) + 1500 M(i-7).$$Keep doing this, and you'll get a summation, say something like:$$R(i) = R(i-1) + 15 R(i-3) + 150 R(i-5) + \cdots + 15 \times 10^{(i-3)/2} \times M(0)$$(if $i$ is odd.)Now you're down to a single recurrence relation. Solve it. Then, use the equations above to derive the solutions for $P(\cdot)$ and $M(\cdot)$.
_unix.322781
systemd appears to split very long log lines in multiple log messages:$ journalctl -u myunitNov 12 08:00:18 ovh7 uwsgi[32441]: SHORT LINENov 12 08:00:18 ovh7 uwsgi[32441]: START of VERY VERY LONG LINE ON STDOUTNov 12 08:00:18 ovh7 uwsgi[32441]: CONTINUE VERY VERY LONG LINENov 12 08:00:18 ovh7 uwsgi[32441]: SHORT LINENow, I do not really mind but I need to join the separate log messages to get back the original stdout from my process. I thought I could merely comb through the logs for the pid and join the MESSAGE strings using the journalctl json output:def main(): import optparse, json, sys parser = optparse.OptionParser() parser.add_option('--pid') parser.add_option('-f', '--file') options, args = parser.parse_args() with open(options.file, 'r') as f: for line in f: d = json.loads(line) if d['_PID'] == options.pid: sys.stdout.write(d['MESSAGE'].encode(utf-8))Sadly, the above does not work because systemd also appears to trim the trailing \n from stdout. It generates this:SHORT LINE START of VERY VERY LONG LINE ON STDOUT CONTINUE VERY VERY LONG LINE SHORT LINENow, I can try to add an extra \n for each MESSAGE but this generates this:SHORT LINESTART of VERY VERY LONG LINE ON STDOUTCONTINUE VERY VERY LONG LINESHORT LINENone of the two above results are very helpful. I need this:SHORT LINESTART of VERY VERY LONG LINE ON STDOUT CONTINUE VERY VERY LONG LINESHORT LINEAnd I see nothing in the output of journalctl that would allow me to infer that two consecutive messages are coming from the same line in the original stdout output. Any idea that would allow me to reconstruct this data correctly without having to generate a separate log file for my program's stdout ?
systemd stdout logging for long lines
systemd;systemd journald
null
_cs.73742
Referring to this reference...I'm trying to work out the details of an integer arithmetic implementation of the CORDIC iteration. The CORDIC pseudo-rotations can be summarized as$$\left(\begin{array}{l}x_{n+1} \\y_{n+1} \\z_{n+1}\end{array} \right) = \left(\begin{array}{l}x_n - d_n2^{-n} y_n \\x_n + d_n2^{-n} y_n \\z_n - d_n \omega_n\end{array}\right)$$Where$$\omega_n = \arctan \;2^{-n}$$and$$d_n = \left\{\begin{array}{rl}1 & z_n \geq 0 \\-1 & \text{otherwise}\end{array}\right.$$After $k$ iterations the result should be multiplied by the scale factor, name it $K$. However if we find a sequence $\left\{ \alpha_n \right\}_{n \in \mathbb{N}}$ such that$$\prod_{j=0}^{+\infty} (1 + \alpha_n2^{-n}) = K$$We can achieve the same result of the iteration above by performing$$\left(\begin{array}{l}x_{n+1} \\y_{n+1} \\z_{n+1}\end{array} \right) = \left(\begin{array}{l}(x_n - d_n2^{-n} y_n)(1+\alpha_n2^{-n}) \\(x_n + d_n2^{-n} y_n)(1+\alpha_n2^{-n}) \\z_n - d_n \omega_n\end{array}\right).$$However I was trying to work out the bitwidth per variable necessary, in order to do that I've tried to convert each computation into a fixed point one.$$\left(\begin{array}{l}x_{n+1} \\y_{n+1} \\z_{n+1}\end{array} \right) = \left(\begin{array}{l}(x_n - d_n2^{-n} y_n)(1+\alpha_n2^{-n}) \\(x_n + d_n2^{-n} y_n)(1+\alpha_n2^{-n}) \\z_n - d_n \omega_n\end{array}\right) \Rightarrow \left(\begin{array}{l}2^{2n}x_{n+1} \\2^{2n}y_{n+1} \\2^{2n}z_{n+1}\end{array} \right) = \left(\begin{array}{l}(2^n x_n - d_n y_n)(2^{n}+\alpha_n) \\(2^n x_n + d_n y_n)(2^{n}+\alpha_n) \\(2^{2n}z_n) - d_n (2^{2n} \omega_n)\end{array}\right)$$Given that a shift of $n$ positions should be repeated for $n = 0 \ldots k$ I would have a total size of$$\sum_{n=0}^{k}2n = k(k+1)$$So If I wanted to implement CORDIC to compute $k$ bits I would need variables with size of $\Theta(k^2)$ is this correct?
Implementing cordic in integer arithmetic
computer architecture;arithmetic
null
_softwareengineering.237333
I'm just wondering if you have an application where you define a class that defines some user configurable settings (from an xml file, or a GUI), should you design it so that it follows SOLID as much as possible like the rest of the application? More specifically, how do you change the available settings without violating the Open Closed Principle?Because I'm having trouble picturing this. I can see the addition of settings you can extend the class, but with the removal of settings, or change of a setting there would be no way to modify the configuration class so that it follows SOLID. Or is it possible somehow?I can also imagine trickle down effect from those settings changes, that require classes that depend on them to be modified as well.
Should classes that define settings and application configuration follow SOLID?
c#;.net
null
_codereview.113986
This is my first attempt at writing a template class. I am implementing Andrew's Monotone Chain algorithm, as described here to calculate a 2D Convex Hull. Since this is my first try at templates, I would like a review of my code to make sure I get started on the right track.ConvexHull2d.h// ConvexHull2D// Template class to calculate a 2D convex hull from a set of 2d points// Uses Andrew's Monotone Chain Algorithm// Algorithm based on code found at this web site:// https://en.m.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain//#pragma once#include <vector>#include <algorithm>namespace ConvexHull{ template <typename T> struct Point { T x, y; bool operator <(Point<T> const &p) const { return x < p.x || (x == p.x && y < p.y); } Point() : x(0), y(0) { } Point(T const tx, T const ty) : x(tx), y(ty) { } }; typedef Point<int> PointInt; typedef Point<double> PointDouble; typedef std::vector<PointInt> PointIntArray; typedef std::vector<PointDouble> PointDoubleArray; template <typename T> T cross(Point<T> const &o, Point<T> const &a, Point<T> const &b) { return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x); } template <typename T> class ConvexHull2d { public: ConvexHull2d(); ConvexHull2d(std::vector<Point<T>> const &in); ~ConvexHull2d(); void InitHull(std::vector<Point<T>> const &in); std::vector<Point<T>> GetHullPoints() const; private: std::vector<Point<T>> m_inPoints; std::vector<Point<T>> m_hullPoints; void SetHullPoints(std::vector<Point<T>> const &in); }; template <typename T> ConvexHull2d<T>::ConvexHull2d() : m_inPoints(), m_hullPoints() { } template <typename T> ConvexHull2d<T>::ConvexHull2d(std::vector<Point<T>> const &in) { InitHull(in); } template <typename T> ConvexHull2d<T>::~ConvexHull2d() { } template <typename T> void ConvexHull2d<T>::InitHull(std::vector<Point<T>> const &in) { m_inPoints = in; sort(m_inPoints.begin(), m_inPoints.end()); SetHullPoints(m_inPoints); } template <typename T> void ConvexHull2d<T>::SetHullPoints(std::vector<Point<T>> const &in) { m_hullPoints.clear(); int n = static_cast<int>(in.size()); //Total point count if (n < 3) return; int k = 0; m_hullPoints.resize(2 * n); // Build lower hull for (int i = 0; i < n; i++) { while (k >= 2 && cross(m_hullPoints[k - 2], m_hullPoints[k - 1], in[i]) <= 0) k--; m_hullPoints[k++] = in[i]; } // Build upper hull for (int i = n - 2, t = k + 1; i >= 0; i--) { while (k >= t && cross(m_hullPoints[k - 2], m_hullPoints[k - 1], in[i]) <= 0) k--; m_hullPoints[k++] = in[i]; } m_hullPoints.resize(k-1); // This removes the last point added since it is the same as first point } template <typename T> std::vector<Point<T>> ConvexHull2d<T>::GetHullPoints() const { return m_hullPoints; }}Here is a program to test the class. It generates random integer and double points then calculates the convex hull.main.cpp#include ConvexHull2d.h#include <iostream>#include <vector>#include <random>#include <ctime>double randomNumber(double mn, double mx);int randomNumber(int mn, int mx);using namespace ConvexHull;int main(){ size_t const count = 100; int const minInt = -10; int const maxInt = 10; double const minDouble = -10.0; double const maxDouble = 10.0; std::srand(static_cast<unsigned int>(std::time(0))); PointIntArray intPoints; for (size_t i = 0; i < count; ++i) { int dx = randomNumber(minInt, maxInt); int dy = randomNumber(minInt, maxInt); intPoints.push_back(PointInt(dx, dy)); } ConvexHull2d<int> intHull(intPoints); PointIntArray intHullPoints = intHull.GetHullPoints(); PointDoubleArray doublePoints; for (size_t i = 0; i < count; ++i) { double dx = randomNumber(minDouble, maxDouble); double dy = randomNumber(minDouble, maxDouble); doublePoints.push_back(PointDouble(dx, dy)); } ConvexHull2d<double> doubleHull; doubleHull.InitHull(doublePoints); PointDoubleArray doubleHullPoints = doubleHull.GetHullPoints(); std::cout << Random doubles\n; for (size_t i = 0; i < doublePoints.size(); ++i) std::cout << doublePoints[i].x << , << doublePoints[i].y << std::endl; std::cout << \nDouble Convex Hull points\n; for (size_t i = 0; i < doubleHullPoints.size(); ++i) std::cout << doubleHullPoints[i].x << , << doubleHullPoints[i].y << std::endl; std::cout << \nRandom integers\n; for (size_t i = 0; i < intPoints.size(); ++i) std::cout << intPoints[i].x << , << intPoints[i].y << std::endl; std::cout << \nInteger Convex Hull points\n; for (size_t i = 0; i < intHullPoints.size(); ++i) std::cout << intHullPoints[i].x << , << intHullPoints[i].y << std::endl; return 0;}double randomNumber(double mn, double mx){ return mn + (static_cast<double>(std::rand()) / RAND_MAX) * (mx - mn);}int randomNumber(int mn, int mx){ return mn + (static_cast<int>(std::rand()) % (mx - mn));}I am mainly interested in a review of my class, but any comments on the test program are welcome, as well.
Template class for Andrew's Monotone Chain Algorithm Convex Hull
c++;computational geometry
SPOILER ALERT: you don't want a class at all; you want a function.But first, the style nitpicks! :)namespace ConvexHull{ void foo(); ...}You'll find that a significant fraction of C++ programmers today collapse their namespaces like this:namespace ConvexHull {void foo();...} // namespace ConvexHullIt's a little bit weird to have an opening curly brace without indenting the following lines; but it's equally weird to have a (non-member) function definition that doesn't begin in column 1, and having to indent all your code past column 1 is much more painful to read and write. The benefits of collapsed style really start to show themselves withnamespace ConvexHull {namespace detail {...} // namespace detail} // namespace ConvexHullor, as some would write it,namespace ConvexHull { namespace detail {...} // namespace ConvexHull::detailC++17 will probably support opening a multi-level namespace with namespace ConvexHull::detail { } directly.Another inconsistent style preference that you'll see modern C++ programmers have moved toward is the placement of ampersands: const Foo& x instead of const Foo &x. The former is just easier to read, especially when you've got things like T&& t (versus T &&t). And yes, C++ programmers tend to agree with C programmers that it's correct to write const int *p, not const int* p. Weird, yes, but it's all about readability.It's strange that you spell the name of the class ConvexHull2d, but you don't spell the name of the helper class Point2d (it's just Point). What would you do if I wanted a ConvexHull3d?You define typedefs for PointInt, PointDouble, PointIntArray, and PointDoubleArray, but then never use them. This is terribly bad style and you should get out of this habit.Why would the user ever want to use PointInt, when Point<int> is only two characters longer, and makes it much more clear what's going on?PointIntArray is not an array (neither a C-style array nor a std::array), so that's not even a good name for it.void InitHull(std::vector<Point<T>> const &in);What's up with this member function? It seems like this method is provided only so that you can shove a new set of points into an existing ConvexHull2d object. But it doesn't really make sense to have a ConvexHull2d without a point-set; in fact you already provide a constructorConvexHull2d(std::vector<Point<T>> const &in);(which by the way should be explicit). So if I'm ever tempted to writeConvexHull2d empty;empty.InitHull(somevector);what I really should write isConvexHull2d empty(somevector);And if I'm tempted to writeConvexHull2d empty;if (somecondition) { empty.InitHull(somevector);} else { empty.InitHull(someothervector);}then what I should write isConvexHull2d empty;if (somecondition) { empty = ConvexHull2d(somevector);} else { empty = ConvexHull2d(someothervector);}There's no reason for the InitHull named method to exist. Use constructors and assignment operators for their designed purpose.Relying on ADL to find std::sort is the bad kind of weird, and I'd say you shouldn't do it.Your internal helpers InitHull and SetHullPoints aren't sufficiently differentiated to warrant two different entry points. Fortunately, we've just shown that InitHull is completely unnecessary. I'd argue that SetHullPoints is also unnecessary and should be inlined right into the constructor. That is:template <typename T>struct ConvexHull2d { ConvexHull2d() = default; explicit ConvexHull2d(const std::vector<Point<T>>& in) : m_inPoints(in) { std::sort(m_inPoints.begin(), m_inPoints.end()); int n = in.size(); if (n < 3) return; int k = 0; m_hullPoints.resize(2 * n); for (int i = 0; i < n; i++) { while (k >= 2 && cross(m_hullPoints[k - 2], m_hullPoints[k - 1], in[i]) <= 0) { k--; } m_hullPoints[k++] = in[i]; } for (int i = n - 2, t = k + 1; i >= 0; i--) { while (k >= t && cross(m_hullPoints[k - 2], m_hullPoints[k - 1], in[i]) <= 0) { k--; } m_hullPoints[k++] = in[i]; } m_hullPoints.resize(k-1); } std::vector<Point<T>> GetHullPoints() const { return m_hullPoints; }private: std::vector<Point<T>> m_inPoints; std::vector<Point<T>> m_hullPoints;}; Notice that I'm adhering to the Rule of Zero: the compiler-generated destructor is good enough for me, so I don't need to write it out explicitly. Similarly, I don't need to write out the body of the default constructor; I can just =default it. And I don't need to write a member-initializer for m_hullPoints; I can rely on the compiler to default-initialize that vector to the empty state.I do, however, provide a default constructor, because without a default constructor you can't do some really useful things such as call std::vector<ConvexHull2d>::resize().Depending on how this class is going to be used in practice, you might prefer:to take in by value instead of by const-reference, and move it into m_inPointsto remove the member m_inPoints altogether, since it's never exposed to the userto have GetHullPoints() return a const-reference to m_hullPoints, instead of always returning a copy of m_hullPoints (for example if the caller just wants to iterate over it, not store or modify it)It's a little strange to write cross(o, a, b) instead of cross(a - o, b - o) with a suitably overloaded operator-(Point, Point). However, I could totally believe that cross(o, a, b) turns out to be faster for some reason, so maybe that strangeness is on purpose.Are you planning to add any more members to the ConvexHull2d class? Because if not, I would strongly consider getting rid of the class altogether! Don't you just want a plain old function?template<class Pt>std::vector<Pt> GetHullPoints(std::vector<Pt> in){ auto lex_less = [](const Pt& a, const Pt& b) { return std::tie(a.x, a.y) < std::tie(b.x, b.y); }; std::sort(in.begin(), in.end(), lex_less); ... return hullPoints;}Not every abstraction in C++ requires a class in fact, precious few do. If all you're doing here is transforming one pointset into a slightly sparser pointset, then that sounds like an excellent job for a function.Also notice that by getting rid of the need to store the data long-term, I've been able to generalize my algorithm. Now instead of taking Point<T> for any T, it can actually operate on any type Pt at all, as long as a variable of type Pt has a member .x and a member .y. This means that in my header that defines the GetHullPoints function, I don't need to define class Point at all; it's no longer part of my interface. Let the user worry about choosing the best representation for 2D points; all I care about is my algorithm for computing convex hulls!For more about generalizing algorithms and separating the algorithm from the representation of the data type, I weakly recommend Alexander Stepanov's lectures. They're a bit long and digression-laden, but there's some good stuff in there.So we started with let's remove 2 spaces of indentation from every line in the file, passed through let's remove two helper methods by inlining them, and finished up with let's remove the entire class, along with all of Point! This is a common pattern in modern C++ programming and actually in all programming. Eliminate all inessential complexity, and you'll find that what is left is the essence of the problem you're trying to solve. :)
_hardwarecs.2480
I am currently looking at buying a HP Zbook Studio with an Intel Core i7-6820HQ, and I am looking at buying RAM separately. The best option on the HP website is 32 GB 2133 DDR4 SDRAM (2 DIMM) (probably CL15). Let's assume that price is irrelevant. I was looking at this option: Vengeance Series 32GB (2x16GB) DDR4 SODIMM 2666MHz CL18 .My questions are:Is this memory compatible with the ZBook?Will this memory run at 2666MHz or will the computer/cpu limits its use at 2133Mhz?What will bring me more performances: the 2666Mhz CL18 or the 2133Mhz CL15?How big the performance difference will be?What will be the impact of 2666Mhz CL18 compared to the 2133Mhz CL15 in terms of energy consumption?
DDR4 memory for HP ZBook Studio
laptop;memory;performance
null
_scicomp.7780
I want to numerically solve the non-linear diffusion equation:$$\frac{\partial}{\partial t} T(x,t)= \frac{\partial}{\partial x}\left(T^{5/2} \frac{\partial T}{\partial x} \right)$$I want to use finite difference approach to solve it via Crank-Nicolson method. But I don't understand how to treat the non-linear coefficient when applying the numerical method.
Numerical solution of non-linear diffusion equation via finite-difference with the Crank-Nicolson method
finite difference;parabolic pde;nonlinear equations;diffusion
null
_unix.81959
I want to use aufs to combine a few disks.I am able to mount the aufs file system using the mount command from the command line.However, when trying to mount the same through an fstab entry, it fails. Google tells me that fstab does not mount file systems in the specified order, creating this problem. I also found recommendations to add the mount command in rc.local so the aufs is mounted after fstab.I am using archlinux which uses systemd, so how can I run the mount command at boot in systemd?
How to mount aufs file system on boot in archlinux?
linux;arch linux;systemd;fstab
Systemd has native support for mounts (man systemd.mount). In fact systemd reads /etc/fstab, uses it to generate mount units, and mount the filesystems itself.Rather than relying on fstab, it's also possible to create mount units by hand. This is how system mounts like /dev, /sys, /proc, etc are handled (/usr/lib/systemd/system/*.mount). This method allows you to use systemd dependencies to ensure things get mounted in the right order.systemd mount unit files must be named after the mount point they control (man systemd.unit). As an example, I created a unit file to mount my USB backup drive to /mnt/backup. Following the naming convention, I've created /etc/systemd/system/mnt-backup.mount, with the following contents:[Unit]Description = USB backup disk[Mount]What = LABEL=david-usb-backupWhere = /mnt/backupType = ext4[Install]WantedBy = multi-user.targetI then run systemctl daemon-reload for systemd to load the unit. I can run systemctl start mnt-backup.mount to mount the disk, and/or systemctl enable mnt-backup.mount to have it started at boot.For dependencies add Requires = some-other-mnt-point.mount under the [Unit] section. Optionally, you may use BindTo rather than Requires; this will cause it to get unmounted if one of the dependencies disappears. However Requires does not affect the order in which the disks are mounted. So to make sure that the disks are mounted before aufs, use After. Edit: To expand on the use of Requires and After, the unit section might look like:[Unit]Description = USB backup diskRequires = mnt-data01.mountRequires = mnt-data02.mountRequires = mnt-data03.mountAfter = mnt-data01.mountAfter = mnt-data02.mountAfter = mnt-data03.mount
_unix.363844
IP forward is not working on my Ubuntu machine.Setup:Ubuntu machine: Ubuntu 12.04.5 LTSKernel: 3.13.0-95-genericOne ethernet interface for LAN: eth0One wlan interface for WAN: wlan0Steps followed to enable IP forwarding:Enable wlan0 and connect to WANEnable eth0 and assing static IPip link set dev eth0 upip addr add 192.168.0.1/24 dev eth0Enable IP forwardingecho 1 > /proc/sys/net/ipv4/ip_forwardAdd forward chain rules for both eth0 and wlan0iptables -A FORWARD -i eth0 -j ACCEPTiptables -A FORWARD -o eth0 -j ACCEPTiptables -A FORWARD -i wlan0 -j ACCEPTiptables -A FORWARD -o wlan0 -j ACCEPTEnable MASQUERADE on wlan0iptables -t nat -A POSTROUTING -o wlan0 -j MASQUERADETest:I tried ping from eth0 to wlan0, but arp itself is failing.Observations:IP table rules shows that all data is going on OUTPUT chain rather than FORWARD.root@ubuntu:~# iptables -nvL -t filterChain INPUT (policy ACCEPT 55 packets, 6019 bytes) pkts bytes target prot opt in out source destinationChain FORWARD (policy ACCEPT 0 packets, 0 bytes) pkts bytes target prot opt in out source destination 0 0 ACCEPT all -- eth0 * 0.0.0.0/0 0.0.0.0/0 0 0 ACCEPT all -- * eth0 0.0.0.0/0 0.0.0.0/0 0 0 ACCEPT all -- wlan0 * 0.0.0.0/0 0.0.0.0/0 0 0 ACCEPT all -- * wlan0 0.0.0.0/0 0.0.0.0/0Chain OUTPUT (policy ACCEPT 6 packets, 588 bytes) pkts bytes target prot opt in out source destinationSome extra informationAll executed all commands with root permissions, there are no error in commandsI am pinging from eth0(LAN) to wlan0(WAN) on same host. Even though it is not meaning full ping, it should workI see arp request on eth0 but not on wlan0 interfaceCould someone help me resolve this issue?
IP forward is not working on Ubuntu
ubuntu;networking;ip;routing
null
_webapps.74362
Because I extensively use the new Inbox by Gmail, and it's feature to bundle certain emails in my inbox once a day/week, but I also still use the standard Gmail, I like to see what's really in my useable inbox (that's not in one of these bundles) by this search:has:nouserlabels in:inboxIs there any way to get a link to this simple search as an option in my label list on the left, or even to replace the Inbox option with this one?
Add an artificial label in the Gmail label list?
gmail;gmail filters;gmail labels;gmail search;inbox by gmail
Yes, there is a way. Enable the Quick links Lab, and add to it the URL of your Gmail search.To add the Quick links lab, do the followingGo to Settings (cog wheel) > SettingsClick on the Labs tabSearch for Quick linksClick the related Enable radio buttonClick on the Save changes button.Once the Quick links is enabled it will be available in the left panel. If you have Chat or Hangouts enable, you should click the ... button to display the side panel gadgets.The Quick Links has ha button +/- to expand/collapse it.To add a link, If the Quick links gadget is collapsed, click the + button to expand itClick the Add quick link link.A popup will be displayed. Add the URL to your Gmail searchClick the OK button.
_webapps.45833
In Facebook chat, if someone is in my top list, like, i always see when he is online, does he see me too?like, if there are 2 people, X and Y which doesnt in any specific list.X sees Y on the top list in chat,does Y necessarily see X too in the top list?Thanks.
In Facebook chat, if someone is in my top list, like, i always see when he is online, does he see me too?
facebook;facebook chat
null
_softwareengineering.279269
I'm trying to unit test a small program I wrote.My problem is that I can't see an easy way to unit test my top level class (Matcher) that exposes a single public method (MatchAll).I do have tests for my inner classes, but they are largely trivial.Let me present a problem and a sketch of my solution:Problem: Given list of people, list of their preferred teams and rankings for each team, find a match that both maximizes team rank and takes candidate preferences into consideration.My solution: Candidate - Holds a list of preferred teams and a rank score for each respective team Team - Holds list of accepted candidates. As long as the team has room, it accepts any candidate.Once it fills up, it only accepts candidates that improve its score. It also purges the candidate with lowest score.Team exposes the following methods:IsBetterMatch Add PurgeWeakestMatcher - Contains the list of candidates and list of teams and implements the core logic of assigning candidates to a team.My matching logic is as follows (Pseudocode):function Matchall() while candidates != empty c <- candidates.getFirst() for each t in c.teams betterMatch = t.IsBetterMatch(c) if betterMatch weakest = t.purgeWeakest() t.Add(c) candidates.add(weakest)Assuming team methods are thoroughly tested, how would you suggest to test this function?The tests that I can think of for this function are very complex both to formulate and to setup. For example:When two candidates have same rank and want the same team and the team has room for only one, the first one should be assigned to the team. Second one should be assigned to another team down his preference list.It seems to me that they fall more under the integration tests category, which is why I'm confused. It's my understanding that the unit tests should be short and simple to write
How to unit test a top level method
unit testing
null
_unix.223556
I have a rather large directory, and I like to search the files for occurrence of specific strings. I have a list of about 30 strings, and my directory is 1.3G. I tried adding all the strings to a file called stringsThen I used grep -r -f strings . > grepresultsBut it takes a loooooong time. And I would not complain except I took a peek into the grepresults file, and the content does not seem to match any of my strings. I am doing something wrong. What should I do to see the result of my command immediately, and verify that it is what I want. Then I have no issue letting it run. Please let me know, and I'll post a sample of what it sends currently. I issued grep -rFf foo -o and seems to get a whole bunch of irrelevant content. I do not know how to use stdout. Could you provide more detailed instructions please?
How to check for specific strings in files of a large directory
ubuntu;grep
(Extracted answer from edit)I got the result of the search by letting it run overnight. The command I used was:@ubuntu:~/WORKING_DIRECTORY/LC_ALL=C fgrep -rFf bar > ~/myfileMoving the results file, called myfile in the above command, definitely helped.I also sorted the strings in the file. It was originally called strings, and I learned from one of the comments in this thread to change it to another name. So in the above command it is called bar. Using LC_ALL=C and fgrep instead of grep helped immensely. All the suggestions contributed to the answer.
_vi.6631
I have this\(\w[^\w\u370-\u3ff\u1f00-\u1fff]*\)\([\u370-\u3ff\u1f00-\u1fff][^\w]*[\u370-\u3ff\u1f00-\u1fff]\)\([^\w]*\w\),which I need to improve, but it is getting uncomfortably complicated; is it possible to define shorthands for expressions that are reused, such as \u370-\u3ff\u1f00-\u1fff? or is there some other way to make this easier to work with?
Can one define shorthands for unicode ranges?
regular expression
You can define a variable holding your pattern like this::let g:pat='...'(Note the use of single quotation marks, to prevent side-effects).Then you can search for that variable like this::%s/<C-R>=g:pat<cr>/replacement_part/g This is described at :h c_CTRL-R_=or possibly easier::exe '%s/'.g:pat.'/replacement/g' (you could also wrap this in a printf() call)
_codereview.73619
Let's say that I want to query some API which will respond with array of random numbers:[4, ..., 17, ..., 25]To keep things simple enough, let's say that array has always 10 elements. For every element in that array, I need to emit via socket to all clients just ONE number every M seconds till end of array. When the end of the array is reached, fetch again.The API that I want data from is found here (it's about true random numbers generator) and I choose some abstraction for fetching data(node package: node-random available here).Sadly I can't find an abstraction (package) which support JSON API from the random.org. All of them just supports something that random.org calls Old API for automated clients (which only support HTML and text/plain responses), there is actually a new version of the API called API for automated clients which supports JSON response. So it would be faster or nothing at all to parse raw JSON instead text/plain response.config.jsexports.fetch_options = { minimum : 0, maximum : 40, number : 10, columns : 1, base : 10, random : new};Just some boilerplate instruction for node-random package, where I want to fetch 10 decimals number between [0, 40]. That is all. I used just exports here instead of module.exports because in the future I expect to change this file to support all application configs, like:exports.mongodb_conn_url = ...;so fetch_options and config about database should be logically divided.Main logic (server.js)var http = require('http'), config = require('./config'), evx = require('events'), events = new evx.EventEmitter(), io = require('socket.io'), randGenerator = require(node-random), _ = require(underscore), fetch = true;// Create dummy servervar server = http.createServer(function(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Socket server');});io = io.listen(server);server.listen(8081);// Try to hit API whenever you can (if needed)setInterval(function() { if(fetch) { console.log(Fetching new data...); events.emit('fetch_data'); fetch = false; }}, 0);// Fetching dataevents.on('fetch_data', function() { randGenerator.integers(config.fetch_options, function(err, data) { console.log(Fetched data = , data); events.emit('new_data', data); });});// Passing data to the client via socketevents.on('new_data', function(data) { /* Emit via socket to all clients just ONE number every M seconds, where M is: minimum_step = 0.7 additional_step = Random number between [0, 2] rounded to .3 decimals --------------------------------------------------------------------- M = minimum_step + additional_step; */ var step = 0.7 + Math.round( (Math.random() * 2) * 1000) / 1000, delays = _.range(0.7, step * 20, step); function scheduler(index) { setTimeout(function() { io.sockets.emit('new_number', data[index]); if(index == config.fetch_options.number - 1) { fetch = true; } }, delays[index] * 600); } for(var i = 0; i < data.length; i++) { scheduler(i); }});console.log(End of code in serverB...);Now another server which acts as a client of this socket server can connect to this:var client_io = require('socket.io-client');client_io = client_io.connect('http://localhost:8081');client_io.on('new_number', function(number) { io.sockets.emit('new_bid', number); // Emit to its own clients (browsers) console.log(number);});server.listen(8080);I would appreciate the following:I'm aiming for code correctness, best practices and design pattern usage, especially for the part related to emitting events in node. I see massively that developers inherit from EventEmitter before using any emitting. I don't see any advantage of using that practice.Will it be better to implement ReadableStream here? I don't know to much about streams, but it seems here, in some way, i'm creating something that looks a like stream. So instead of mixing that logic with the server - how to implement a subclass of ReadableSteam and then just to require it.
Passing API data chunk per chunk to its socket clients every M seconds
javascript;node.js;socket;client;socket.io
null
_scicomp.21230
I can write a function to find LCM (lowest common multiple) of an array of integers, but I thought it must have been implemented in numpy or scipy and was expecting something like numpy.lcm() to do that. I'm surprised to find there is no such thing. Perhaps I'm searching in a wrong place. So, if you know any other library where this simple function is defined, please oblige.
LCM builtin in Python / Numpy
python;scipy;numpy
Why not define it yourself, as suggest in the Rosetta Code examples here:http://rosettacode.org/wiki/Least_common_multiple#PythonFor example, you could build on this (via this library):import fractionsdef lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0
_scicomp.27487
I am trying to implement in C or C++ a solution for a fft and Ifft when the signal values are not obtained at a constant rate, making it having a desviation between the values and the periodic ones. I do not know how I can change the algorithm of calculating the fft with synchronized signals as in https://wikimedia.org/api/rest_v1/media/math/render/svg/02a7699d274d226871209491c8a05976d6e46cf3 into a uneven spacing values of signal.One of my ideas is using the values to make the completed signal and then catchiing the correct points, but it is a very time consuming solution, and i think that as we have a deviationThe overall objective is to have the fft as described and the ifft values in that points
fft with non uneven spacing between the value of the signal
fourier analysis;fourier transform
null
_unix.339513
INPUT: [user@notebook test]$ cat a.txtmusicmusicsheetsheetmusic[user@notebook test]$ cat a.txt | cat -vte -$^[[1mmusic^[[22m$^[[1mmusicsheet^[[22m$^[[1msheetmusic^[[22m$^[[4m^[[24m$[user@notebook test]$ NEEDED OUTPUT (after removing these interesting characters): [user@notebook test]$ cat a.txt musicmusicsheetsheetmusic[user@notebook test]$ cat a.txt | cat -vte -music$musicsheet$sheetmusic$[user@notebook test]$ Question: How can I remove the interesting/unknown characters: ^[[1m^[[22m^[[4m^[[24mwhat are these characters? could there be more similar? Trying to use tr to remove non-printable characters just makes these interesting chars visible and removes newline, what is both bad: [user@notebook test]$ cat a.txt | tr -cd '[:print:]'[1mmusic[22m[1mmusicsheet[22m[1msheetmusic[22m[4m[24m[user@notebook test]$
How to remove the ^[[1m ^[[22m ^[[4m ^[[24m characters while keeping the newline?
special characters
@Toby Speight's solution is fine. Some extra information:Normally those are the ansi special character used to produce color, special effects, position the cursor, etc in the terminal.for example grep --color=always '[a-z]*music[a-z]*' files > output will produce characters like that.sed -r s/\x1B\[[0-9;]*[a-zA-Z]//gSugestion: check if you have a GREP_COLOR deprecated variable set to --color=always or similar...
_softwareengineering.61984
So, I am primarily a .Net developer who does some stuff in Java, Python and a few others from time to time. I have heard a lot of people praise Vim and Emacs for greatly increasing efficiency once the basics are nailed down. I can definitely see how many of the features could be very useful with sufficient practice, and even believe the learning curve is probably worth the effort. However...it seems that you would really have to be some sort of wizard of macros and hotkeys to be as efficient in Vim or Emacs as the average developer is in Visual Studio, Netbeans, Eclipse, or other platforms. I have been starting to learn to use Vim and think some of its features are awesome (column editing for example), but it seems that many of the tools provided by the heavy weight IDEs simply could not be replaced buy even the most juiced up text editor. A few processes I would be skeptical anyone could ever be more efficient at in Vim include (I know VS best, so I will stick to those):generating dbml files for Linq-to-SQLAutomated testingdesigning UIsCreating/organizing projects and solutionsI know Vim and Emacs can do a lot of the same things very powerfully that VS can (like intellisense, refactoring, etc.) and it may be able to do some or all of the examples that I provided, but is it realistic to say that someone working on these platforms would actually benefit from Vim or Emacs?
Are Vim or Emacs practical for languages like .Net or Java?
ide;vim;emacs
You've got a mix of concepts going on there, which is maybe not surprising since VS combines a lot of rather disparate features together. One quote (from this site) suggests that Emacs isn't a good IDE, Unix is a good IDE. The idea being that in the Linux/Unix world, you rely on multiple specialized tools that play well together rather than one monolithic tool that does it all. Now, I primarily program in C#, and I use VS to do that. I also really love Emacs and use it for basically everything else. Now, as you say, what you can do in Emacs and what is better to do in Emacs are distinct. But in many cases it isn't a 1-to-1 mapping and there are different ways to reach the same goals using a text editor and/or other tools. I originally was going to address each of your points, but the answer always boiled down to yes, you could in some form. Typically you'd rely on either: 1) an outside tool (like a UI designer) to generate code for you, the import it; 2) automation support from inside the editor (like Elisp code in Emacs) to automate repetitive tasks; or 3) you'd adjust to using text-based tools instead of visual ones (like using MSBuild and writing your own project files instead of relying on VS's set up).In the Emacs world, you don't have a tool that does it all, you have lots of tools and the ability to grow more tools as you need them. I don't yet know it well enough to do all that, so I use VS and I'm happy with the tools it gives me. VS is a really powerful, really good IDE. Now if I was doing Java, I'd have to debate which tool I'd use because I don't know Eclipse or IntelliJ very well. For any other language, Emacs pretty much wins because it's going to do a lot more for me than any other text editor or half-done IDE that those languages might use. (Except maybe Smalltalk, but that's a unique case.)
_unix.353234
I have a requirement to generate a file from a table. I am using sed for streaming the data. I want to use a text qualifier if there is any white space in the table column. Sample inputUnites State | California | UNIX | ABC DEExpected outputUnites State | California | UNIX | ABC DE
Add double quote if there is white space between words in column
text processing;sed
null
_softwareengineering.202681
I'm supposed to implement a relatively complex form that looks like follows, but has at least four more pages requiring the user to fill in all necessary information for the tracks:http://www.mediafire.com/convkey/b441/1hnp8lxbu49ar2ufg.jpgThis data will need to be sent to the server, which is implemented using Dropwizard. I'm looking for best practices on how to upload and send such a complex form with potentially dozens of songs to the server.The simplest available solution I have seen is a simple multipart/form-data request with the following form schema (Source):Client<html><body><h1>File Upload with Jersey</h1><form action=rest/file/upload method=post enctype=multipart/form-data> <p> Select a file : <input type=file name=file size=45 /> </p> <input type=submit value=Upload It /></form></body></html>Server@POST@Path(/upload)@Consumes(MediaType.MULTIPART_FORM_DATA)public Response uploadTrack(final FormDataMultiPart multiPart) { List<FormDataBodyPart> artists = multiPart.getFields(artist); StringBuffer output = new StringBuffer(); for (FormDataBodyPart artist : artists) output.append(artist.getValueAs(String.class)); List<FormDataBodyPart> tracks = multiPart.getFields(track); for (FormDataBodyPart track : tracks) writeToFile(track.getValueAs(InputStream.class), Foo); return Response.status(200).entity(output.toString()).build();}Then I have also read about file uploads via Ajax or Formdata (Mozilla HttpRequest) which allows for Posts in the formats application/x-www-form-urlencoded, multipart/form-data, or text/plain. I don't know which approach, if any, is best.An ideal solution would be to utilize Jackson to convert a json string into my data objects, but I don't get the impression that this is possible with binary data.
How to Implement Complex Form Data?
java;html5;webforms;upload
null
_unix.168446
I usually go to stackexchange when I face programming terminal and I spend most of time trying to append four spaces before my pasted programming code.Is there any faster way to do it from a terminal?What would you do?
How can I add four spaces before each lines of programs code in terminal
bash;text processing
Simply use sed,sed 's/^/ /' fileThis appends four spaces before each line. Add an inline edit option -i to save the changes to the specified file.sed -i 's/^/ /' fileThrough awk,awk '{sub(/^/, , $0)}1' fileORawk '{print $0}' file
_unix.34870
I was wondering if there is a way to grep through systems to find old updates that have stalled or failed. I am using RHEL 6.
Finding Stalled or Failed Updates on System
rhel;upgrade;puppet
That depends on how you install a package or update.If you are a RedHat Satellite customer there is a log in /var/log/rhsm called rhsm.log but it will still use a facility to install typically yumyum There is a yum.log in /var/log/rpm does not maintain logs, however you can run rpm -qa --last to see the list of packages that were installed and when but does not list failures.The only way to see the failures would be at the command line.You might be able to ascertain issues by looking at history but that is subjective and time consuming. You would have to search history and match up the installations or updates to installed packages. That also does not cover if something was installed or updated via other methods that were not run at a command line.Puppet has a framework that it uses to perform package installations. It has a list of around 33 different providers for all OS's. It will search for the ability to install in a descending fashion typically defaulting to yum and falling back to rpm.Because the typical syntax for puppet package installations is package { ssh; ensure => present }The puppet framework determines after that based on your repository preferences and costs associated with installation media which to use then what to use to install it.And you always have the typical fallback /var/log/messages you will sometimes see errors in there depending on what the failure was related to.Also if the package was going to add a module or anything that dmesg would recognize and was backed out you might see info in dmesgAs far as unfinished, you would have to check ps for that. Or available tty's and pty's
_webmaster.96072
It is kinda wired, but I can not find product or category (product list) as a dimension in my custom reports. Nor can I find any other word that fits to these dimensions.How can I add product (name) or category (product list name) to my custom reports?Note: When I am in Conversions -> eCommerce -> Product Performance and click on Customize, then I see these dimensions in this customized report. But I need them in a new report/other report as well.Note 2: When I start a new custom report, I can use Product as dimension. But as soon as I do this and create a new tab in this report, I can not use Product List Category. Why does Google Analytics delimit my selection when I am in a new tab (same report)?
How can I add 'product' or 'category' as dimension to Google Analytics custom reports?
google analytics;reporting
Each custom report is based on the same data - the tabs are meant to merely display the data in a different way.To use different data, you need to create a new report. You will not be able to do it in a new tab.Edit:This link lists how different dimensions and metrics work together and exclude each other, which is helpful in making your reports work.
_codereview.6191
I used to use static or singleton for my DAL class. However, I read some articles saying that singleton is evil and should be avoided. Therefore I try to rewrite my code like this:public class CustomerBLL{ private CustomerHelper helper = new CustomerHelper(); private CustomerDAL dal = new CustomerDAL(); public void Method1(string param) { dal.Method1(param); } public void Method2(string param) { dal.Method2(param); } public void MethodA(int param) { helper.MethodA(param); }}How do I improve this code? It just doesn't look right.
How can I improve this code without using static or singleton?
c#;singleton;static
I believe that some generalizations are to be made lightly. i.e. stating that Singletons are evil in general is not accurate, as there are some cases where Singleton is a proper (and maybe the only) solution. And yes I do believe that it is one of the overly abused patterns out there. Having gotten that out of the way, I move to answer your question.From the code sample you submitted, it is very clear that your CustomerBLL has no business logic and merely acts as a Faade on top of the data access and other helper classes. Facades should be stateless by nature.Having said that, I will offer two choices based on testability and decoupling requirements.If you want to make you CustomerBLL testable and decouple it from the CustomerHelper and CustomerDAL concretions and substitute them with abstractions, then one good design enhancement would be to inject the CustomerHelper and CustomerDAL dependencies into the CustomerBLL class, which allows you to mock and stub the data access and helper classes and focus on testing other code modules that consume the CustomerBLL class. You acheive that through extraxcting interfaces of course.Here is an example of how the code would look if we inject the dependencies through a constructor, note that your CustomerBLL Faade will be an instance class i.e. no static methods will be exposed.public class CustomerBLL{ private readonly ICustomerHelper _helper; private readonly ICustomerDAL _dal; // default constructor initializes the concrete dependencies public CustomerBLL() :this(new CustomerHelper(), new CustomerDAL()) {} // constructor to inject stubbed dependencies for testing purposes public CustomerBLL(ICustomerHelper customerHelper, ICustomerDAL customerDal) { _helper = customerHelper; _dal = customerDal; } public void Method1(string param) { _dal.Method1(param); } public void Method2(string param) { _dal.Method2(param); } public void MethodA(int param) { _helper.MethodA(param); }}public interface ICustomerDAL{ void Method1(string s); void Method2(string s);}public interface ICustomerHelper{ void MethodA(int i);}internal class CustomerDAL : ICustomerDAL{ public void Method1(string s) { } public void Method2(string s) { }}internal class CustomerHelper : ICustomerHelper{ public void MethodA(int i) { }}If on the other hand, testability is not a concern at all, then you can proceed by consuming the CustomerBLL as a Faade in a procedural way through static methods (although I much prefer the testability approach, but its not every ones cup of tea). Here you notice I removed the private fields that hold references to the Helper and DAL classes, because we want to promote that the CustomerBLL Faade is stateless.public class CustomerFacade{ public static void Method1(string param) { new CustomerDAL().Method1(param); } public static void Method2(string param) { new CustomerDAL().Method2(param); } public static void MethodA(int param) { new CustomerHelper().MethodA(param); }}I have seen and used both approaches, in my humble opinion they both are valid depending on the usage scenario. In general I am in favor of testable design and decoupled modules and thats why I proposed the first approach.
_softwareengineering.107382
As a electronic customer, I sometimes have to go to manufacturer's websites to find information about products, drivers/firmware update, etc. More ore less, most of these websites, IMO, are bad. They're slow, not user-friendly (some time, really ugly), and take me lots of time to do what I need to. For example, in Sony's website, I must find Vaio laptops in a list of dozens (may be hundreds) products, then find my specific model in a list of hundreds model. Fail! I also see that on several websites, they may be slightly better, but still not good (HP, Dell, Lenovo (somewhat better), ...)Well, they may be have a large back-end system there, but that does not mean they can make the frond-end faster and more user-friendly. Is there an obvious reason that large corporation's website are that bad?
Why most of large corporations websites are bad?
design;performance;websites;company
null
_codereview.127418
From LeetCode medium 3. Longest Substring Without Repeating Characters:Given a string, find the length of the longest substring without repeating characters.Examples:Given abcabcbb, the answer is abc, which the length is 3.Given bbbbb, the answer is b, with the length of 1.Given pwwkew, the answer is wke, with the length of 3. Note that the answer must be a substring, pwke is a subsequence and not a substring.Here is my solution, but the online judge told me Time Limit Exceeded. Is there a better solution to this problem?private extension String{ subscript (index:Int) -> Character { return (self[self.startIndex.advancedBy(index)]) }}class Solution{ func lengthOfLongestSubstring(s: String) -> Int { var str:String = var longest:Int = Int.min if s.isEmpty { return 0 } for i in 0...s.characters.count-1 { if !str.characters.contains(s[i]) { str += String(s[i]) } else { longest = max(longest, str.characters.count) str = } } return longest }}
Swift solution to Leetcode Longest Substring Without Repeating Characters
strings;programming challenge;time limit exceeded;swift
null
_softwareengineering.340469
We are designing a RESTful API that is mainly intended to meet the needs of a single client. Because of its very particular circumstances, this client has to make as few requests as possible. The API handles i18n through an Accept-Language header in the requests. This works for all things that the client needs to do except for one feature, in which client needs to store the responses of a request to a single endpoint in all available locales. Can we somehow design the API in a way that allows the client to grab all this information with a single request and without breaking a consistent, well-structured RESTful API design?Options we have considered so far:Allowing the inclusion of multiple locales in the Accept-Language header and adding localized versions for all requested locales in the response, each one identified by its ISO 639-1 language code as the key. Creating something like an ?all_languages=true parameter to that endpoint and returning localized versions for all available locales in the response if that parameter is present.(If none of the above works for us) making multiple requests to grab all localized versions from client.Which one is the best alternative?
RESTful API and i18n: how to design the response?
rest;api;api design;http
You've described two effective ways of asking for multiple languages. Either should work fine. I would choose the explicit language request parameter for my own code. TL;DR BackstoryThere is an Accept-Language header. Note, Accept not Accepted. It's a standard part of HTTP content negotiation. The response usually sets a Content-Language header back. Accept-Language is the opening bid, offering a set of options; Content-Language is the resolution, stating what language was chosen. Most Content-Language answers return a single language, but there is an option to provide a comma-separated list of response languages. Usually that would be mixed-content, but there's no reason it could not signal multiple disjoint alternatives. If you wanted the client to request all available languages, there is already a wildcard request option, *. So there is already an HTTP header mechanism you can use. However, beware that you'd be piggybacking a negotiation process that more often presents an array of possible options, and gets back a single option. You'd be shifting the sense to here is a list of options, give me all of them! If you're okay with that, you've got a solution.There is, however, considerable debate as to the suitability of signaling REST API parameters in HTTP headers. It's a bit like entering a restaurant and blurting out your detailed order to the host or matre d' rather than waiting for the waiter or waitress to appear. It can work, and may work well e.g. if the order directed at the host relates to drinks or appetizers--things the host can quickly see to, or quickly communicate to your server. But it can also be seen as a breach of protocol, addressed at the wrong level/layer or to the wrong player.A second alternative would be an explicit request parameter. You suggest ?all_languages=true. That seems overly specific. Something like lang=en,fr,es (allow multiple listed languages) or lang=* or lang=all (specify every available language) seems more general. This could be expressed either in the URL or request body. Either way, your multi-lingual response can be easily encoded into returned JSON payload:[ { lang: en, content: As Gregor Samsa awoke one morning... }, { lang: de, content: Als Gregor Samsa eines Morgens... }, ...]In the end, either of these approaches should work well for you. Either could be viewed as a consistent, well-structured RESTful API design. The determination as to which is better rests mostly on your attitude toward the appropriateness of piggybacking (and slightly altering the typical sense of) HTTP content negotiation headers. My own preference is to not intermix headers and other parameters as equal parts of an API request. The explicit lang or language parameter seems cleaner to me. But since the HTTP verb (e.g. GET, PUT, POST, PATCH, ...) is part of the header, and also critical to / intermixed with the interpretation of the request, I admit the envelope vs. contents distinction is a bit artificial and fuzzy. As with most design decisions, genuine experts answer it differently, and YMMV.
_codereview.35248
I'm kind of new to C++ and was just wondering if anyone could give me tips on how I could make my code more efficient (I added some comments to the code to help you understand it better).Is it a good idea to use switch cases? Is there a way I can use more functions/arrays/pointers?Source codeHere is some of the code:case 1: //Asks for number to place bet on cout << endl << Please choose a number to place your bet on: ; cin >> betNumber; //Checks if number is valid (between 1 and 36) while (betNumber < 1 || betNumber > 36) { cout << endl << You must choose a valid number between 1 and 36, inclusive! << endl; cout << Please choose a number to place your bet on: ; cin >> betNumber; } //Asks for amount to bet on that number cout << endl << How much would you like to bet on the number << betNumber << ? $; cin >> betAmount; //Checks if minimum amount is $1 and if the player has enough money in their account while (betAmount < 1 || betAmount > bankAccount) { cout << endl << You have $ << bankAccount << in your bank account: $; cin >> betAmount; } //Seeds random number to the generator srand(time(0)); //Generates a random number randomNumber = 1 + (rand() % 36); cout << endl << The ball landed on the number << randomNumber << .; //Checks if player won or lost their bet if (betNumber == randomNumber) { bankAccount = win(betAmount, betOdds, bankAccount); cout << endl << Congratulations, you won! You now have $ << bankAccount << in your account. << endl; } else { bankAccount = lose(betAmount, bankAccount); cout << endl << Bad luck, you lost! You now have $ << bankAccount << in your account. << endl; } break;
Roulette game in C++
c++;beginner;random;game
Since there aren't any loops in your code that aren't waiting for the user to provide some input, it's probably way premature to talk about efficiency. Is your code measurably slow? Does it leave you hanging? If not, unless you have an unusual need, save questions on efficiency for later.So let's talk about some more important things: readability and maintainability. Here are some tips on ways to improve the readability and maintainability of your code. These aren't hard rules that you should never break (especially the one on comments); they are guidelines on ways to make your life easier that you should learn to bend when the guideline makes things awkward instead.I hope this helps, even though it may be a lot to take in all at once. Feel free to ask follow-up questions and get other opinions.Avoid RedundancyRedundancy can show up in many forms. One example of it is in your declaration of arrays, using code like int betType[11] = {35, 17, 8, 11, 5, 2, 1, 1, 2, 1, 1};. Unless there's something very special about the number 11, there's no reason to call it out. Instead just say int betType[] = {35, 17, 8, 11, 5, 2, 1, 1, 2, 1, 1}; which will automatically determine the size of the array for you.When you later check your bounds with while (betChoice < 1 || betChoice > 11) {, you can instead use a calculated size (_countof(betType) or sizeof(betType)/sizeof(betType[0])), or even use a std::vector<int> instead of an int[], and check against the vector's size().This will help you avoid magic numbers that don't mean much later. After all, if someone asks you what's special about 11, would you think it's the number of available bet types? But if they asked what betTypes.size() meant, it would be easy to answer.Another way redundancy shows up is in large blocks of repeating code. For instance, case 1 and case 2 have almost the same code. In fact I had to read it a couple times to find the part that was different. Sometimes this can be best handled by refactoring similar parts of code into functions, and passing parameters to them that control how they differ. Sometimes it's better just to extract the parts that are identical into simpler functions, and use them. I'll touch on this more below, but I certainly don't have the answer.Avoid ObfuscationIn the code commented Displays a large dollar sign, there are a lot of casts from int to char so that cout prints the value as a character. But the characters in question are not that unusual. Just use the actual character you want to show, for example replacing cout << endl << << (char)36 << (char)36 << (char)36 << (char)36 << (char)36;withcout << endl << $$$$$This will not only be easier to type or update, it will be easier to read.Avoid CommentsThis recommendation is somewhat controversial, but it begins to target your question about functions. Instead of commenting what a line of code does, comment how a block of code does something unusual. When you're first starting out, everything seems unusual, but eventually you will see patterns and only need to comment on things that are not common patterns.But then, instead of commenting what a block of code does, give it a name instead by putting it in a function. For example, you have several cases where you ask how much the user wants to bet on a number, then loop until they enter a valid number. You could extract this loop into a helper function like this:int getBetAmount(int bankAccount){ int betAmount; cin >> betAmount; while (betAmount < 1 || betAmount > bankAccount) { cout << endl << You have $ << bankAccount << in your bank account: $; cin >> betAmount; } return betAmount;}int _tmain() { : : : case 1: : : : cout << endl << How much would you like to bet on the number << betNumber << ? $; betAmount = getBetAmount(bankAccount); : : : : : : case 2: : : : cout << endl << How much would you like to bet on the numbers << betNumber << and << betNumber + 3 << ? $; betAmount = getBetAmount(bankAccount); : : :}Find some other code that doesn't change much and extract that into functions as well. For example, the code commented Checks if player won or lost their bet, I see creating a function you'd call like this:case 1: : : : bankAccout = awardWinnings(betNumber == randomNumber, betAmount, betOdds, bankAccount); break;case 2: : : : bankAccount = awardWinnings(betNumber == randomNumber || betNumber + 3 == randomNumber, betAmount, betOdds, bankAccount); break;After you make these changes, ideally the parts that are different will start to stand out, and the parts that are the same will have good names that tell you what they do even if they don't have a comment. And then you can more easily avoid incorrect comments like case 2's Check if number is valid (between 1 and 36) that actually checks for 33.You can also avoid comments by naming constants. Instead of starting with int bankAccount = 500 and then 500 lines later referencing 500 to figure out your overall winnings, perhaps declare const int StartingBankAccount = 500; and use the name instead of the number in both places. If you decide to change the initial account wealth, this also helps ensure your ending summary remains correct.Avoid Bad DiceWhile this is a toy program, and a person is unlikely to play long enough for it to matter, rand() % max is a flawed approach to generating random numbers. It's flawed in ways too subtle for me to explain (I understand it, but not well enough to explain it). However Stephan T. Lavavej knows it much better and explains it in a video called rand() Considered Harmful; watch it and use the approach he recommends if you want a more uniformly distributed random number.
_unix.80429
There are 5 huge files ( file1, file2, .. file5) about 10G each and extremely low free space left on the disk and I need to concatenate all this files into one.There is no need to keep original files, only the final one.Usual concatenation is going with cat in sequence for files file2 .. file5: cat file2 >> file1 ; rm file2Unfortunately this way requires a at least 10G free space I don't have.Is there a way to concatenate files without actual copying it but tell filesystem somehow that file1 doesn't end at original file1 end and continues at file2 start?ps. filesystem is ext4 if that matters.
Append huge files to each other without copying them
filesystems;files
AFAIK it is (unfortunately) not possible to truncate a file from the beginning (this may be true for the standard tools but for the syscall level see here). But with adding some complexity you can use the normal truncation (together with sparse files): You can write to the end of the target file without having written all the data in between.Let's assume first both files are exactly 5GiB (5120 MiB) and that you want to move 100 MiB at a time. You execute a loop which consists ofcopying one block from the end of the source file to the end of the target file (increasing the consumed disk space)truncating the source file by one block (freeing disk space)for((i=5119;i>=0;i--)); do dd if=sourcefile of=targetfile bs=1M skip=$i seek=$i count=1 dd if=/dev/zero of=sourcefile bs=1M count=0 seek=$idoneBut give it a try with smaller test files first, please...Probably the files are neither the same size nor multiples of the block size. In that case the calculation of the offsets becomes more complicated. seek_bytes and skip_bytes should be used then.If this is the way you want to go but need help for the details then ask again.WarningDepending on the dd block size the resulting file will be a fragmentation nightmare.
_unix.46143
I am specifying path to my command in the file /etc/profile:export PATH=$PATH:/usr/app/cpn/binMy command is located in:$ which ydisplay /usr/app/cpn/bin/ydisplaySo, when I performing echo $PATH output is looks like:$ echo $PATH...:/usr/app/cpn/binAnd everything is OK, but when I am trying to launch my command via SSH I am getting error:$ ssh 127.0.0.1 ydisplay$ bash: ydisplay: command not foundBut the my path is still present:$ ssh 127.0.0.1 echo $PATH...:/usr/app/cpn/binPlease explain me why Bash unable to find ydisplay during SSH session and how to properly configurate SSH to avoid this issue.More over, if I specifying $PATH in local file .bashrc in the current user all works correctly. But I want to modify only one file instead specifying a lot of files for each user. This is why I am asking.
Why Bash unable to find command even if $PATH is specified properly?
linux;bash;shell;ssh;path
tl;drRunning ssh 127.0.0.1 ydisplay sources ~/.bashrc rather than /etc/profile. Change your path in ~/.bashrc instead.detailsThe only time /etc/profile is read is when your shell is a login shell.From the Bash Reference Manual:When bash is invoked as a login shell, ... it first reads and executes commands from the file /etc/profileBut when you run ssh 127.0.0.1 ydisplay, bash is not started as a login shell. Yet it does read a different startup file. The Bash Reference Manual says:when ... executed by ... sshd. ... it reads and executes commands from ~/.bashrcSo you should put your PATH settings in ~/.bashrc.On most systems, ~/.bash_profile sources ~/.bashrc, so you can put your settings only in ~/.bashrc rather than putting them in both files.There's no standard way to change the setting for all users, but most systems have a /etc/bashrc, /etc/bash.bashrc, or similar.Failing that, set up pam_env and put the PATH setting in /etc/environment.See also:What's the conf file reading between login and non-login shell?Is there a .bashrc equivalent file read by all shells?
_softwareengineering.94957
So, I'm developing some database-driven RESTful Java web services, using Hibernate and MySQL. For testing purposes, I'm using the H2 in-memory database. H2 is nice and fast, so this has worked out really well. The only problem is that populating the DB tables prior to my tests is sort of tedious. I basically create and persist a bunch of objects by hand. I'm wondering if maybe I'm going down the wrong road.Please tell me, what are the best practices for doing what I'm trying to do? Any tools that could help me? Any general strategies or tips?
What are some best practices for populating and using a test database?
java;database;unit testing;orm;tests
I'm going to assume you've designed your API so you can DI your DB details, if not then we can help you through that.In terms of terminology, you're wanting to use a Fake Test Double. In this particular case, I'd recommend using the same in-memory DB (H2), but use DBUnit to work with JUnit in order to create your tables, populate them before each test, truncate the data after each test and then finally teardown the tables once your TestSuite is finished.There are other solutions such as Grails and Spring Roo which create some test data for you, but DBUnit will work a treat for you now.
_codereview.90597
I have this query:def floodhazard_tbl(request): if request.method == GET: # create a list to_json = [] # this code is results a messy JSON data that need underscore.js to manipulate # in order for us to use datatables getgeom1 = FloodHazard.objects.get(id=3).geom response_high = list(PolyStructures.objects.filter(geom__within=getgeom1).values( 'brgy_locat', 'municipali').annotate(counthigh=Count('brgy_locat'))) to_json.append(response_high) getgeom2 = FloodHazard.objects.get(id=2).geom response_medium = list(PolyStructures.objects.filter(geom__within=getgeom2).values( 'brgy_locat', 'municipali').annotate(countmedium=Count('brgy_locat'))) to_json.append(response_medium) getgeom3 = FloodHazard.objects.get(id=1).geom response_low = list(PolyStructures.objects.filter(geom__within=getgeom3).values( 'brgy_locat', 'municipali').annotate(countlow=Count('brgy_locat'))) to_json.append(response_low) return StreamingHttpResponse(list(json.dumps(to_json)), content_type='application/json')Although it works, the respond is very slow and I wonder why.Here's my model:class PolyStructures(models.Model): bldg_name = models.CharField(max_length=100) block_name = models.CharField(max_length=75) bldg_type = models.CharField(max_length=50) brgy_locat = models.CharField(max_length=50) municipali = models.CharField(max_length=50) province = models.CharField(max_length=50) geom = models.MultiPolygonField(srid=32651, null=True, blank=True) objects = models.GeoManager() def __unicode__(self): return self.bldg_nameclass FloodHazard(models.Model): hazard = models.CharField(max_length=6) date_field = models.DateTimeField(null=True, blank=True) geom = models.MultiPolygonField(srid=32651, null=True, blank=True) objects = models.GeoManager() def __unicode__(self): return self.hazardHere's my JS function for displaying the result in my template:function e() { $.ajax({ url: tbl/, dataType: json, beforeSend: function () { $(#info_tbl).show().text(Getting data from server...Please wait.).addClass(getme) }, success: function (e) { function t(e) { return _.reduce(e, function (e, t) { return e + parseFloat(t || 0) }, 0) } $(#info_tbl).text(Successfully Loaded!).fadeOut(1e3).removeClass(getme), $(#myErrorWrapper).hide(), $(#table_wrapper).show(); var a = _.chain(e).flatten().groupBy(brgy_locat, municipali).map(function (e, r) { return { municipality: _(e).chain().pluck(municipali).first(), brgy: r, low: t(_(e).chain().pluck(countlow).value()), medium: t(_(e).chain().pluck(countmedium).value()), high: t(_(e).chain().pluck(counthigh).value()) } }).value(); r.fnClearTable(); for (var o = 0; o < a.length; o++) r.fnAddData([a[o].municipality, a[o].brgy, a[o].low || 0, a[o].medium || 0, a[o].high || 0]) }, error: function () { e(), $(#myErrorWrapper).show() } }) }BTW, I'm using underscore.js and datatables plug-in. The shapefile that I loaded in the PostgreSQL database has a size of 18mb and take up 3 rows in my table but before it was 28K+ rows, my co-worker dissolved it and make it in 3 (Low, Medium, High) rows.I am using django-debug-toolbar to measure the query time.Is there any way to make it fast? Or is it because of the shapefile size? or my query?
Returning JSON from GeoDjango QuerySet and Display using jQuery/AJAX
python;jquery;json;django;underscore.js
null
_unix.150853
How to change icon theme in i3? If this matters, I'm working on Arch Linux. I googled, but I can only find info about GTK theme, not icons.
How to set GTK icon theme in i3?
gtk;icons;i3
I can think of at least 2 options you can choose from:Change ~/.gtkrc-2.0 and ~/.config/gtk-3.0/settings.ini directly (the former for icons in GTK2 applications, the latter for GTK3 applications) - the setting you're looking for is gtk-icon-theme-name in both cases. For GTK2, you can just add a line likegtk-icon-theme-name=Faenza-Ambiance` to the file, for GTK3 the line needs to be inside a [Settings] section like[Settings] gtk-icon-theme-name=Faenza-AmbianceYou can find the name of the theme by looking at the Name property inside its index.theme file.Use LXAppearence to change the GTK2/3 icons (and themes, fonts, etc.). LXAppearance is part of the LXDE desktop environment, but as you can see on the package page, its dependencies are only dbus-glib and gtk2.I prefer using LXAppearance because it gives access to all important theme-related settings but is still very lightweight.
_unix.27527
I'm using the javax.print API to print a Jasper Report on Debian Linux. For some reason the saved lpoptions (CUPS settings) always override settings chosen on the Java Print dialog. At this point the only way I am getting around this problem is to delete the .lpoptions file in the user's directory.This doesn't appear like something I can control with Java so is there a way to keep the Unix CUPS settings from overriding the print settings?
Any way for Unix to ignore lpoptions and let Java do it's job?
linux;debian;printing;java;cups
null
_webapps.12175
Like on chrome OS (which I've never used btw) it's meant to be all about the cloud, how would you transport files between different web apps.Eg I draw a flowchart in Creately, on a normal desktop I'd have to download it as an image file, and then upload it to Google docs so I could embed the image on a word document.But on a cloud based OS, how can you download it to the local computer, which you're not meant to be able to do as that defeats the point of the cloud a bit?Why hasn't anyone come up with a common protocol to enable webapp <> webapp communication?
How can I move files from service to service?
communication
null
_unix.56040
Somehow I'm not able to read the trailing \n sign into the REPLY variable. Under any circumstances I want to avoid a blank line that results from the \n being echoed by read but echo one in case of another character. Given:declare -l REPLYread >&2 -r -N 1 -p Acknowledged? (y): REPLYif [[ $REPLY != $'\n' ]]; then echo >&2fiFor me a possible workaround is it to make read to suppress (-s) echoing the input. But ideally the user should see the single character he input after the prompt.Also IFS= read -d'' doesn't get me the \n character into the variable.Any ideas?
How to read '\n' into variable with Bash's built-in command?
bash;readline;newlines
null
_cogsci.5463
I am referring specifically to a very recent paper by Max Tegmark.In this paper he proposes 3 more criteria (independence, dynamics, and utility principle) in addition to Tononi's original criteria (information and integration).I have seen the paper being discussed in Hacker News, reddit's r/neurophilosophy, and lesswrong, but I think they are mostly light jabs on the actual content of Tegmark's proposal.
Is it truly necessary to upgrade Tononi's criteria of consciousness in the Integrated Information theory?
consciousness;neural network
null
_cs.77465
Looking at this video starting at 1:45, the author claims to be using a second-order approximation for a Markov text generation. He has one letter which he outputs followed by another letter which tells him which state to go to - so in other words, he might first pick AC, so he outputs A and then goes to state C, where he picks CB, so he outputs C and goes to state B, etc. So he has a uni-gram output followed by a uni-gram transition piece of information.But from my understanding, a second-order approximation would be like this, with a bigram followed by a unigram as the transition state.This is the same character-level order-2 n-gram analysis of the (very brief) text condescendences as above, but this time keeping track of all characters that follow each n-gram:co non dnd e, ede s, nes c, (end of text)sc ece n, sen d, cnc eThe table above doesnt just give us some interesting statistical data. It also allows us to reconstruct the underlying textor, at least, generate a text that is statistically similar to the original text. Heres how well do it: (1) start with the initial n-gram (co)those are the first two characters of our output. (2) Now, look at the last n characters of output, where n is the order of the n-grams in our table, and find those characters in the n-grams column. (3) Choose randomly among the possibilities in the corresponding next column, and append that letter to the output. (Sometimes, as with co, theres only one possibility). (4) If you chose end of text, then the algorithm is over. Otherwise, repeat the process starting with (2).I'm extremely confused because both these sources consider themselves to be of order 2 in approximation, but it seems to me that the second source is of a higher order than the first. Is this true, or am I just completely misunderstanding what's happening?
Second-order Markov text generation?
information theory;markov chains;computational linguistics
null
_unix.281651
I am using a Raspberry Pi 2 model with Debian as the OS.I tried a simple java swing program that opens a JFrame on it, and it worked fine.Later, I wanted to use my Pi headlessly i.e. without connecting Display, keyboard and mouse. So I connected to it using the Ethernet port. I installed the tight VNC server on the Pi and the VNC viewer client on my desktop PC.I was able to view and operate the Pi's desktop from my PC, but when I tried to run the same Java swing program, it exited giving out Java Headless exception and sometimes an authentication error. After searching on the Internet I tried some export DISPLAY commands, but no use.I understand that I need to set some parameters, either relating to the JRE or the operating system.Below is the stackpi@raspberrypi:~/prog $ sudo java HelloSwingClient is not authorized to connect to ServerException in thread main java.awt.AWTError: Can't connect to X11 window server using ':1.0' as the value of the DISPLAY variable.at sun.awt.X11GraphicsEnvironment.initDisplay(Native Method)at sun.awt.X11GraphicsEnvironment.access$200(X11GraphicsEnvironment.java:65)at sun.awt.X11GraphicsEnvironment$1.run(X11GraphicsEnvironment.java:115)at java.security.AccessController.doPrivileged(Native Method)at sun.awt.X11GraphicsEnvironment.(X11GraphicsEnvironment.java:74)at java.lang.Class.forName0(Native Method)at java.lang.Class.forName(Class.java:259)at java.awt.GraphicsEnvironment.createGE(GraphicsEnvironment.java:102)at java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment(GraphicsEnvironment.java:81)at java.awt.Window.initGC(Window.java:475)at java.awt.Window.init(Window.java:495)at java.awt.Window.(Window.java:537)at java.awt.Frame.(Frame.java:420)at javax.swing.JFrame.(JFrame.java:225)at HelloSwing.main(HelloSwing.java:6)
Not Able to run simple Java Swing Program on Raspbian on Raspberry Pi 2 Headless connected using tight VNC
java;vnc
null
_softwareengineering.103588
When constructing prototypes, should we also create appropriate unit tests as if we were writing production code? Would it make a difference if we knew in advance that the code was or wasn't going to be re-used for the final solution?
Should Unit Testing be used in Prototypes?
unit testing;prototyping
Even in a prototype, it's good to know what each part is supposed to do. When you write a prototype, you still want to understand what's wrong with your code when something doesn't work as expected. Unit tests are the best solution to figure it out.Furthermore, unit tests are a great way to clarify your mind about what each part of your prototype is supposed to do and most of the time, it can serve as base code to write the tests when you write the production version.But... It really depends of the size of your project and of its complexity. For a small project it might be easier to go ahead and make things works.
_unix.360640
a long time ago, i wrote a udev rule for adb with my phone (device) by setting a group. Everything was OK until some things changed recently:device rom udev packet adb packet now i get under user:$ adb shell* daemon not running. starting it now on port 5037 ** daemon started successfully *error: insufficient permissions for device: verify udev rules.See [http://developer.android.com/tools/device.html] for more information.$ adb devices -lList of devices attached xxxxxxx no permissions (verify udev rules); see [http://developer.android.com/tools/device.html] usb:2-1$ lsusb// here we have the mentioned deviceBus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub// udev rules newly added after i received an error (did'd change anything - still error i can open adb only using root) SUBSYSTEM==usb, ATTR{idVendor}==1d6b, MODE=0666, GROUP=adbusersSUBSYSTEM==usb, ATTR{idVendor}==04e8, ATTR{idProduct}==6860, MODE=0666, GROUP=adbusers// this rule was added very long time ago was working perfect till now SUBSYSTEM==usb, ATTR{idVendor}==18d1, ATTR{idProduct}==4ee7, MODE=0666, GROUP=adbuserslisted now as Bus 002 Device 007: ID 18d1:4ee7 Google Inc. // user is in adbuser group PS. i did check a permission on device and I get: $ ls -l /dev/bus/usb/002/001 crw-rw-r-- 1 root root 189, 128 kwi 22 13:26 /dev/bus/usb/002/001udev rules are not applied ? ps2. 1) enabled udev deug 2) modified rules + added symlinks to track changes by udev SUBSYSTEM==usb, ATTR{idVendor}==1d6b, MODE=0666, GROUP=adbusers, SYMLINK+=android%nSUBSYSTEM==usb, ATTR{idVendor}==04e8, ATTR{idProduct}==6860, MODE=0666, GROUP=adbusers, SYMLINK+=x-android%nSUBSYSTEM==usb, ATTR{idVendor}==18d1, ATTR{idProduct}==4ee7, MODE=0666, GROUP=adbusers, SYMLINK+=s-android%nafter device plug Apr 22 18:50:04 et27 systemd-udevd[304]: seq 2437 queued, 'add' 'usb'Apr 22 18:50:04 et27 systemd-udevd[304]: Validate module indexApr 22 18:50:04 et27 systemd-udevd[304]: Check if link configuration needs reloading.Apr 22 18:50:04 et27 systemd-udevd[304]: seq 2437 forked new worker [1143]Apr 22 18:50:04 et27 systemd-udevd[1143]: seq 2437 runningApr 22 18:50:04 et27 systemd-udevd[1143]: IMPORT builtin 'usb_id' /lib/udev/rules.d/50-udev-default.rules:13Apr 22 18:50:04 et27 systemd-udevd[304]: seq 2438 queued, 'add' 'usb'Apr 22 18:50:04 et27 systemd-udevd[1143]: IMPORT builtin 'hwdb' /lib/udev/rules.d/50-udev-default.rules:13Apr 22 18:50:04 et27 systemd-udevd[1143]: MODE 0664 /lib/udev/rules.d/50-udev-default.rules:41Apr 22 18:50:04 et27 systemd-udevd[1143]: GROUP 1008 /etc/udev/rules.d/51-android.rules:4Apr 22 18:50:04 et27 systemd-udevd[1143]: MODE 0666 /etc/udev/rules.d/51-android.rules:4Apr 22 18:50:04 et27 systemd-udevd[1143]: LINK 's-android1' /etc/udev/rules.d/51-android.rules:4Apr 22 18:50:04 et27 systemd-udevd[1143]: RUN '/usr/lib/virtualbox/VBoxCreateUSBNode.sh $major $minor $attr{bDeviceClass}' /etc/udev/rules.d/60-vboxdrv.rules:5Apr 22 18:50:04 et27 systemd-udevd[1143]: PROGRAM 'mtp-probe /sys/devices/pci0000:00/0000:00:1c.1/0000:03:00.0/usb2/2-1 2 5' /lib/udev/rules.d/69-libmtp.rules:2283Apr 22 18:50:04 et27 systemd-udevd[1144]: starting 'mtp-probe /sys/devices/pci0000:00/0000:00:1c.1/0000:03:00.0/usb2/2-1 2 5'Apr 22 18:50:04 et27 systemd-udevd[1144]: failed to execute '/lib/udev/mtp-probe' 'mtp-probe /sys/devices/pci0000:00/0000:00:1c.1/0000:03:00.0/usb2/2-1 2 5': No such file or directoryApr 22 18:50:04 et27 systemd-udevd[1143]: Process 'mtp-probe /sys/devices/pci0000:00/0000:00:1c.1/0000:03:00.0/usb2/2-1 2 5' failed with exit code 2.Apr 22 18:50:04 et27 systemd-udevd[1143]: handling device node '/dev/bus/usb/002/005', devnum=c189:132, mode=0666, uid=0, gid=1008Apr 22 18:50:04 et27 systemd-udevd[1143]: set permissions /dev/bus/usb/002/005, 020666, uid=0, gid=1008Apr 22 18:50:04 et27 systemd-udevd[1143]: creating symlink '/dev/char/189:132' to '../bus/usb/002/005'Apr 22 18:50:04 et27 systemd-udevd[1143]: creating link '/dev/s-android1' to '/dev/bus/usb/002/005'Apr 22 18:50:04 et27 systemd-udevd[1143]: creating symlink '/dev/s-android1' to 'bus/usb/002/005'Apr 22 18:50:04 et27 systemd-udevd[1143]: created db file '/run/udev/data/c189:132' for '/devices/pci0000:00/0000:00:1c.1/0000:03:00.0/usb2/2-1'Apr 22 18:50:04 et27 systemd-udevd[1145]: starting '/usr/lib/virtualbox/VBoxCreateUSBNode.sh 189 132 00'Apr 22 18:50:04 et27 systemd-udevd[1143]: Process '/usr/lib/virtualbox/VBoxCreateUSBNode.sh 189 132 00' succeeded.Apr 22 18:50:04 et27 systemd-udevd[1143]: passed device to netlink monitor 0x562b37096e00Apr 22 18:50:04 et27 systemd-udevd[1143]: seq 2437 processedApr 22 18:50:04 et27 systemd-udevd[304]: passed 308 byte device to netlink monitor 0x562b37076610Apr 22 18:50:04 et27 systemd-udevd[1143]: seq 2438 runningApr 22 18:50:04 et27 systemd-udevd[1143]: IMPORT builtin 'hwdb' /lib/udev/rules.d/50-udev-default.rules:15Apr 22 18:50:04 et27 systemd-udevd[1143]: IMPORT builtin 'usb_id' /lib/udev/rules.d/60-libgphoto2-6.rules:9Apr 22 18:50:04 et27 systemd-udevd[1143]: unable to access usb_interface device of '/sys/devices/pci0000:00/0000:00:1c.1/0000:03:00.0/usb2/2-1/2-1:1.0'Apr 22 18:50:04 et27 systemd-udevd[1143]: IMPORT builtin 'usb_id' returned non-zeroApr 22 18:50:04 et27 systemd-udevd[1143]: RUN 'kmod load $env{MODALIAS}' /lib/udev/rules.d/80-drivers.rules:5Apr 22 18:50:04 et27 systemd-udevd[1143]: created db file '/run/udev/data/+usb:2-1:1.0' for '/devices/pci0000:00/0000:00:1c.1/0000:03:00.0/usb2/2-1/2-1:1.0'Apr 22 18:50:04 et27 systemd-udevd[1143]: Execute 'load' 'usb:v18D1p4EE7d0232dc00dsc00dp00icFFisc42ip01in00'Apr 22 18:50:04 et27 systemd-udevd[1143]: No module matches 'usb:v18D1p4EE7d0232dc00dsc00dp00icFFisc42ip01in00'Apr 22 18:50:04 et27 systemd-udevd[1143]: passed device to netlink monitor 0x562b37096e00Apr 22 18:50:04 et27 systemd-udevd[1143]: seq 2438 processedApr 22 18:50:04 et27 systemd-udevd[304]: cleanup idle workersApr 22 18:50:04 et27 systemd-udevd[1143]: Unload module indexApr 22 18:50:04 et27 systemd-udevd[1143]: Unloaded link configuration context.Apr 22 18:50:04 et27 systemd-udevd[304]: worker [1143] exitedThe group is not applied on device I get $ ls -al /dev/android1lrwxrwxrwx 1 root root 15 kwi 22 18:42 /dev/android1 -> bus/usb/001/001$ ls -al /dev/s-android1lrwxrwxrwx 1 root root 15 kwi 22 18:50 /dev/s-android1 -> bus/usb/002/005could be an issue on string instead numeric group values ? or GROUP= instead GROUP:= ? if so why udev not yields on this ? notation no as symlink works with old notation so ...string instead numeric no as its resolved proper in logs to -> 1008ok permission is set as expected - as symlinks not showing permissions $ ls -al /dev/bus/usb/002/001 crw-rw-rw- 1 root adbusers 189, 128 kwi 22 19:04 /dev/bus/usb/002/001but still I get insufficient
how to debug adb insufficient permission case
usb;udev;adb
null
_softwareengineering.69308
I know, and use, two version control systems: Subversion and git. Subversion, as of now, gets used for personal projects where I am the only developer and git gets used for open source projects and projects where I believe others will also work on the project. This is mostly because of git's amazing forking and merging capabilities, where everyone may work on their own branch; very handy.Now, I use Subversion for personal projects, as I think git makes little sense there. It seems to be a little bit of overkill. It is OK for me if it is centralized (on my home server, usually) when I am the only developer; I take regular backups anyway. I don't need the ability to make my own branch, the main branch is my branch. Yes, SVN has simple support for branching, but much more powerful support for it makes no sense, I think. Merging can be a pain with it, or at least from my little experience.Is there any good reason for me to use git on personal projects, or is it just simply overkill?
git for personal (one-man) projects. Overkill?
tools;version control;git;svn
It's not overkill. The main reason why I started using Git and Mercurial over Subversion for personal projects is that initiating a repository is so much more easier.Wanna start a new project?> git initBAM! No need to set up a repository server nor check in a folder structure to support branching and tags into a subversion repository.Sharing your project later is just a matter of: git push (other than having a remote repository). Try to do that quickly with subversion!
_softwareengineering.68233
Now that I am using namespaces in my php files which match the file's path, I have to append a namespace to pretty much every class instantiation. The namespaces definitely help my autoloader find files, but the code is becomming harder to read/write. aren't namespaces supposed to simplify my code? why is it making things more complicated? Am I using it wrong? Not sure I see how using a namespace is much better than having super long class names...example:file: /root_path/init.php<?php namespace root_path; $foo = new \sub_path\bar();?>file: /root_path/sub_path/bar.php<?php namespace root_path\sub_path; class bar { }?>
Namespaces just seem to be making things more complicated. Am I missing something?
php;namespace
It looks like you're using it right, but you might not have a need for it.Namespacing allows you to use function and symbol names without worrying about whether a third-party library declares the same thing (which would cause a fatal error in PHP). You can take comfort in knowing that, because you've namespaced everything, there's no chance for collision.But if you're in a position where you're going to know and account for all possible symbols, you're not going to get a whole lot of value from namespaces. Edit: And as G3D mentions in the comments, your specific use case is covered by PEAR's naming conventions.However, relying on prefixes might not work as you'd expect if you start introducing a lot of unknowns. This comes up in Drupal: let's say you've created a module that's named views. Well, Drupal provides a hook system, so you can do things like implement the function hook_foo() by replacing hook with your module's name.So now you have an implementation of a hook named views_foo(). That's all well and fine as long as you didn't need an internal function named views_foo().But let's say there's a new module that extends your module and names itself views_awesome. If views_awesome wants to implement hook_foo(), it'd create a new function named views_awesome_foo(). Ah, but I didn't tell you about another hook already defined:hook_awesome_foo(). So, without namespacing, you have a collision: views_awesome_foo() can refer to view_awesome's implementation of hook_foo or views's implementation of hook_awesome_foo().In this scenario, namespacing is really helpful. Instead of prefixing hook implementations, you can do:\views\hook_foo()\views_awesome\hook_foo()and avoid any ambiguity.
_softwareengineering.350033
This is my situation: Models can contain properties which can be models themselves. Each property can have custom behavior, this behavior must be selected through its name (for example: Versionable, Authorizable or something else). Developers must have the ability to add their own behaviors to the list with available behaviors.Each behavior is implemented in a class, but here is the catch: A model can implement zero or more behaviors. How to be sure that behaviors are being executed in the right manner (e.g. sequence) without breaking up things from other behaviors. I first would suggest that there would be list of supported behaviours, but since a programmer does not know for sure which other behaviors are possible, this does not seem to be a good option.
Adding behaviors to models without interference
modeling;aspect oriented;behavior
null
_unix.52814
This is probably very simple, but I can't figure it out. I have a directory structure like this (dir2 is inside dir1):/dir1 /dir2 | --- file1 | --- file2What is the best way to 'flatten' this director structure in such a way to get file1 and file2 in dir1 not dir2.
Flattening a nested directory
files;directory;rename;cp;recursive
null
_softwareengineering.59515
I just wondered if anyone had any tricks or programs they used when comparing two of the same file but different versions?I appear to have foolishly made a modification at some point today (Went a few hours without running any tests) and it has stopped the whole project working - without throwing up any errors so it must be subtle whatever I have done.I just thought that there must be a program out there that might highlight differences etc.Otherwise, a step by step search might be in order!
Comparing multiple revisions of the same C File
c;gui
Are you familiar with diff tools? Tools such as KDiff, WinDiff, BeyondCompare... they will all compare files and highlight differences. What IDE are you using? Some IDEs (such as Eclipse) have integrated diff tools. Some version control tools also have built-in diff tools (MKS comes to mind). For quick-and-dirty compares, I use Notepad++ which has a comparison plugin. It's a great and free general purpose text editor and the compare can be done on two buffers, you don't even have to load files so it's as simple as copying and pasting two versions of the file in question!
_unix.160031
I want move (not copy with scp) my file from the server to the local repository and finally delete it on the server after transfer. I use next command from the repository, where I want have the file:rsync -rvt --delete-after user@host:/path . I really copy the files by this way. Anyway, the files on the server are not deleted.... It is necessary to do: rm -r filenameCan somebody improve my linux statement and show me, how I can transfer and remove file from the original place in one move. PSAccording to the answer of @user1008764 I want add here additional useful link to the another discussion (how to delete not only the file, but also the directory):https://superuser.com/questions/676671/rsync-does-not-delete-source-directories
File tranfer from the server
files;rsync
try --remove-source-files instead of --delete-after.have a look at serverfault.com/questions/363922/how-to-move-files-with-scp
_scicomp.20759
I want to build a new desktop PC for MD simulations of relatively simple protein/carbohydrate systems using mainly GROMACS and Amber force field. No ab initio or QM-MM simulations are intended for now. For instance, I have been working with a protein of approximately 1500 atoms in the presence of small carbohydrates (<100 atoms). For the protein alone, my home PC (i5-4570 CPU 3.20GHz, not GPU-accelerated) does approximately 5 ns/day, so I want something considerably faster than that.Which hardware should I choose? Could you suggest low (800 US dollars) to high (2000 US dollars) price configurations with good power considering the current technology available? I am not sure if I need a GPU-accelerated machine, so I am open for different configurations.
Good desktop PC for molecular dynamics simulations
simulation
null
_cstheory.3592
Let $\Pi$ be NP-complete problem.Can we partition set of instances of $\Pi$ into finite number of subsets (subproblems) each of which is polynomially solvable (and not necessarily polynomially recognizable)? For example, $\Pi$ is NP-complete for graphs with maximal degree $\Delta=3$, but polynomially solvable for cubic and graphs with $\Delta=2$?I have obtained two answers on my question: trivially yes (by Peter Shor and mikero) and no, unless $P=NP$ (by Sadeq Dousti and Antonio E. Porreca). I'm curious why such easy question gets such contradicting answers (not taking into account the reason that I have formulated it ambiguously). So the question is: how to formulate two questions such that for each of them corresponding answers would hold.The last edition of this question has been answered in full by Peter Shor on Math.SE here.Here is the answer:There are two different possible questions here. When you ask for the solution of an NP-complete problem, you can either (a) require the computer to give you a witness in the yes cases or (b) just require the computer to give you the answer.
Can we partition NP-complete problem into finite number of polynomially solvable problems?
cc.complexity theory
Let $\Pi = \{\Pi_1, \ldots, \Pi_n\}$ be the finite partition of problem $\Pi$. Let $M_1, \ldots, M_n$ be the poly-time machines which decide the corresponding partition.Since the partition is finite, we can construct a poly-time machine $M$ which incorporates the code of $M_1, \ldots, M_n$. On input $x \in \Pi_i$, $M$ determines the corresponding partition $\Pi_i$, and calls the respective machine $M_i$ to decide it.This shows that $\Pi$ can be decided in poly-time, which is impossible unless $P = NP$.Edit: The above approach is incorrect in that $M$ may not be able to determine the correct partition. The right approach is given by Antonio in a comment bellow. It does not need to recognize the partition; instead, it just runs all $M_i$'s on $x$ an accepts if and only if at least one of them accepts.
_unix.35618
In a larger script to post-process some simulation data I had the following line:parallel bnzip2 -- *.bz2Which, if I understand parallel correctly (and I may not), should run n-core threads of the program over all files with the listed extension. You may notice that I misspelled the command bunzip2. I would expect a warning or error message here, but it fails silently. Is this intended? How do I not get bit by this in the future?Update:It is possible that I have a different parallel installed than I think I do:> parallel --version`parallel: invalid option -- '-'parallel [OPTIONS] command -- arguments for each argument, run command with argument, in parallelparallel [OPTIONS] -- commands run specified commands in parallelA man page of parallel on my system gives: parallel(1) parallel(1)NAME parallel - run programs in parallel....AUTHOR Tollef Fog HeenWhich seems this is not the GNU version.
Why does (GNU?) parallel fail silently, and how do I fix it?
gnu parallel;moreutils parallel
You have been hit by the confusion with Tollef's parallel from moreutils. See https://www.gnu.org/software/parallel/history.htmlYou can install GNU Parallel simply by:wget http://git.savannah.gnu.org/cgit/parallel.git/plain/src/parallelchmod 755 parallelcp parallel semWatch the intro videos for GNU Parallel to learn more:https://www.youtube.com/playlist?list=PL284C9FF2488BC6D1
_unix.316366
I've added Spotify launcher to Gnome Shell Dash so it's now a favorite app.How do I add next / prev / play-pause / stop commands to Spotify context menu ?For those who still find this unclear, the goal here is to have something like this:
Spotify controls (next, previous etc) via context menu in gnome favorites
gnome;gnome shell;.desktop
null
_codereview.140807
The code below is an attempt at a solution to an exercise from the book Cracking the Coding Interview. I believe that the worst case time complexity of the code below is \$O(n)\$, where n is the length of each string (they should be the same length since I am checking if there lengths are equal) and the space complexity is \$O(n)\$. Is this correct? In particular does checking the length of each string take \$O(1)\$ time?def is_permutation(first_string, other_string): if len(first_string) != len(other_string): return False count_first = {} count_other = {} for char in first_string: if char in count_first.keys(): count_first[char] += 1 else: count_first[char] = 1 for char in other_string: if char in count_other.keys(): count_other[char] += 1 else: count_other[char] = 1 for char in count_first.keys(): if char not in count_other.keys(): return False elif count_first[char] != count_other[char]: return False return True
Check if one string is a permutation of another using Python
python;strings;python 3.x;complexity
Yes, len(str) should be O(1) in Python. (Good question!) Each of your for loops is O(n), so your whole function is O(n).Your counting loops could be written more compactly asfor char in first_string: count_first[char] = 1 + count_first.get(char, 0)The epilogue could be simplified toreturn count_first == count_otherIt pays to get familiar with the standard Python library, though. Your entire function could be more simply implemented asfrom collections import Counterdef is_permutation(a, b): return len(a) == len(b) and Counter(a) == Counter(b) where len(a) == len(b) is an optional optimization. Writing less code simplifies maintenance and tends to create fewer opportunities for introducing bugs (as in Rev 2 of your question).
_unix.37382
I have a python script which I would like to run in the background. So I do this: $ nohup python script.py &If I am frequently making changes to the script, I need to terminate the process and run the script again.$ kill -9 <pid_of_bg_process>$ nohup python script.py &Is is possible to reload the process without terminating it?
How to reload a background process?
process;background process
Short answer - no.Long answer: You are actually calling a python interpreter. That interpreter loads the script.py and parses it.If you change the script it has to reload the file and start from the beginning, since the interpreter has no way to know which part was changed.Now if your goal is to simply signal python to reload/restart the script, you can wrap it into a shell-script:#!/bin/shLINE=python script.pystop(){ pkill -f $LINE}clean(){ stop exit 0}trap stop 1trap clean 9 15while true do $LINE & waitdoneYou can now start that shell-script (in background, with nohup, if you like).If you send a HUP signal to it, it will restart your python process.If you kill the wrapper process the python script will terminate, too.I did not test my script - but the idea should be clear.
_cogsci.1078
Game theory models something very relevant to psychologists (in particular social psychologists): conflict and cooperation between decision-makers. Unfortunately, classical game theory demands that these decision makers are rational (in a mathematically precise sense). This definition of rationality is challenged empirically (by work like Tversky & Shafir) and on a theoretical level (by complexity results on finding or approximating Nash equilibria: a PPAD-complete problem).Economists and mathematicians (and others) have taken two approaches to overcome this problem. The first is top-down approach of limiting the agent's abilities from an all-powerful rational agent down; this is the bounded rationality approach. The other is the bottom-up approach of evolutionary game theory: start with the simplest agents (that can't even make decisions) and have natural selection, imitation, or another simple dynamic process evolve the population over time. This seems to dove-tail nicely with the biogenic approach to cognition.Are there examples of the tools of evolutionary game theory being used in social psychology or other sub-disciplines of the cognitive sciences? Is there a survey (or book) on EGT's impact on the cognitive sciences?Related questionWhat are good examples of applying dynamical systems in cognitive science?
Evolutionary game theory in the cognitive sciences
reference request;social psychology;mathematical psychology;evolution;game theory
null
_datascience.20327
I have word images as below:Let's say it's a 256x64 image. My aim is to extract the text from the image as 73791096754314441539 which is basically what an OCR does.I am trying to build model which can recognise word from images.When I am saying word it can be any of the follwing:Any dictionary word, non-dictionary worda-z,A-Z, special characters including spaces I have built a model (snippet because of company policies) in tensorflow as below:inputs = tf.placeholder(tf.float32, [common.BATCH_SIZE, common.OUTPUT_SHAPE[1], common.OUTPUT_SHAPE[0], 1])# Here we use sparse_placeholder that will generate a# SparseTensor required by ctc_loss op.targets = tf.sparse_placeholder(tf.int32)# 1d array of size [batch_size]seq_len = tf.placeholder(tf.int32, [common.BATCH_SIZE])model = tf.layers.conv2d(inputs, 64, (3,3),strides=(1, 1), padding='same', name='c1')model = tf.layers.max_pooling2d(model, (3,3), strides=(2,2), padding='same', name='m1')model = tf.layers.conv2d(model, 128,(3,3), strides=(1, 1), padding='same', name='c2')model = tf.layers.max_pooling2d(model, (3,3),strides=(2,2), padding='same', name='m2')model = tf.transpose(model, [3,0,1,2])shape = model.get_shape().as_list()model = tf.reshape(model, [shape[0],-1,shape[2]*shape[3]])cell = tf.nn.rnn_cell.LSTMCell(common.num_hidden, state_is_tuple=True)cell = tf.nn.rnn_cell.DropoutWrapper(cell, input_keep_prob=0.5, output_keep_prob=0.5)stack = tf.nn.rnn_cell.MultiRNNCell([cell]*common.num_layers, state_is_tuple=True)outputs, _ = tf.nn.dynamic_rnn(cell, model, seq_len, dtype=tf.float32,time_major=True)My current approach is to use take input a word image pass it through a CNN extract high level image features, convert the image features to sequential data as below [[a1,b1,c1],[a2,b2,c2],[a3,b3,c3]] -> [[a1,a2,a3],[b1,b2,b3],[c1,c2,c3]] then pass it through a RNN(LSTM or BiLSTM), then use CTC (Connectionist Temporal Loss) to find the loss and train network. I am not getting results as expected, I wanted to know if:There is some other better way to do this taskIf I am converting features to sequence correctlyAny research paper where something like this is done.
How to pass features extracted using CNN into RNN?
neural network;deep learning;tensorflow;rnn;ocr
null
_codereview.151882
I've implemented the K-Means clustering algorithm in Python2, and I wanted to know what remarks you guys could make regarding my code. I've included a small test set with 2D-vectors and 2 classes, but it works with higher dimensions and more classes. Here, it should sort all the elements starting with the same letters in the same classes (except ak, with is quite in between).What I'm interested in:Did I do something unpythonic?Are there unclear or unnecessary parts?What changes could drastically improve the code's performance?from __future__ import print_functionfrom operator import add, subfrom _collections import defaultdictimport random as rdimport mathclass Element: def __init__(self, idf, data, cls='ukn'): self.idf = idf self.data = data self.cls = cls def __str__(self): return '%s: %s -> %s' % (str(self.idf), str(self.data), str(self.cls)) def eucl_dist_to(self, other): diff = map(sub, self.data, other.data) norm2 = math.sqrt(sum([math.pow(coord, 2) for coord in diff])) return norm2def main(): test_data_tuple = [('aa', 1, 7), ('ab', 1, 8), ('ac', 1, 9), ('ba', 2, 1), ('bb', 2, 3), ('ad', 2, 8), ('ae', 2, 9), ('bc', 3, 2), ('bd', 3, 4), ('af', 3, 7), ('be', 4, 2), ('bf', 4, 3), ('ag', 4, 8), ('bg', 5, 1), ('bh', 5, 3), ('ah', 5, 6), ('bi', 6, 2), ('bj', 6, 4), ('ai', 6, 6), ('aj', 6, 7), ('bk', 7, 0), ('bl', 7, 2), ('bm', 7, 3), ('ak', 7, 5)] test_data_elt = list() for t in test_data_tuple: test_data_elt.append(Element(t[0], tuple(t[1:]))) # test_data_elt.sort(key=lambda e: e.idf) results = k_means(test_data_elt, 2, 5)def k_means(elts, nb_classes, nb_steps): k = nb_classes #init centroids = list() cls_content = defaultdict(list) for cls_nb in range(k): cls_name = 'class_'+str(cls_nb) centroids.append(Element(cls_name, rd.choice(elts).data, cls='centroid')) cls_content[cls_name] = list() for itr in range(nb_steps): # assign cls_content.clear() for elt in elts: min_dist = float('inf') for c in centroids: dist = c.eucl_dist_to(elt) if dist < min_dist: min_dist = dist best_class = c.idf cls_content[best_class].append(elt) elt.cls = best_class # adjust for c in centroids: elts_in = list(cls_content[c.idf]) if len(elts_in) == 0: sum_elts_data = 0 else: sum_elts_data = list(elts_in[0].data) for elt in elts_in[1:]: sum_elts_data = map(add, sum_elts_data, elt.data) sum_elts_data[:] = [e / float(len(elts_in)) for e in sum_elts_data] c.data = tuple(sum_elts_data) print('\nIteration %d' % itr) for c in centroids: cls_name = c.idf print('\n'+str(c)) for e in cls_content[cls_name]: print(e) return cls_contentif __name__ == '__main__': main()
K-Means clustering in Python2
python;performance;python 2.7;reinventing the wheel;clustering
null
_codereview.124385
I have written this program to deal 7 cards to one player.#include <iostream>#include <string>#include <cstdlib> //for rand and srand#include <cstdio>#include <vector>using namespace std;string suit[] = {Diamonds, Hearts, Spades, Clubs};string facevalue[] = {Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace};int numberOfCardsDrawn = 0;string drawnCards[52];string drawCard () { string card; int cardvalue = rand()%13; int cardsuit = rand()%4; card += facevalue[cardvalue]; card += of ; card += suit[cardsuit]; return card;}bool isMyCardAlreadyDrawn (string card) { for(int i = 0; i < 52; i++) { if(card.compare(drawnCards[i]) == 0) { // if this is true, then both strings are the same return true; } } return false; // if the code reaches this point, then the card has not been drawn yet}string getCard () { srand(time(0)); string card = drawCard(); while (isMyCardAlreadyDrawn(card) == true) { // keep drawing until an undrawn card is found card = drawCard(); // draw a new card } drawnCards[numberOfCardsDrawn] = card; numberOfCardsDrawn++; return card;}int main () { cout << Your Cards:\n; vector<string> p0; //player 0's card const int DEAL_CARDS = 7; //number of cards we can deal to each player string choices[] = { a, b,c,d,e,f,g }; for (int i = 0; i < DEAL_CARDS; i++){ string p0_getCard = getCard(); cout << << choices[i] << )<< p0_getCard << ; p0.push_back(p0_getCard); }}However, I will eventually want to have a five-player game (dealing cards to four more vectors), and I feel that extending this code to accomplish that would result in excessive code duplication. How do I go about improving the code to support that?
Distributing cards to players in C++
c++;random;playing cards
null
_webapps.59547
It seems that after cards are archived, they are removed from the boards they were associated with. I'm hoping that's not the case and that various metadata about the cards are tracked. What I want to be able to check is the state of a list (or board) at a specific timestamp in time.
Is there a way to look at a Trello board as a snapshot in time?
trello;trello cards
null
_cs.55013
I want to know the difference between these three languages and it would be great if you would give some examples as well, thank you.:)
What is the difference between formal language, regular language and regular expression?
formal languages;terminology;regular languages
An alphabet $\Sigma$ is a finite collection of symbols. For example, $\Sigma = \{0,1\}$.A word over an alphabet $\Sigma$ is a finite sequence of letters from $\Sigma$. For example, $0$, $01$ and $1110$ are all words over $\{0,1\}$. The empty word (that is, the empty sequence) is also allowed, and denoted $\epsilon$ (or sometimes $\lambda$).The collection of all words over $\Sigma$ is denoted $\Sigma^*$.A formal language over an alphabet $\Sigma$ is a set of words over $\Sigma$. Equivalently, a formal language over $\Sigma$ is a subset of $\Sigma^*$.A regular language over $\Sigma$ is a formal language over $\Sigma$ which is accepted by some DFA.A regular expression over $\Sigma$ has the following syntax:$\epsilon$ is a regular expression.$\sigma$ is a regular expression for all $\sigma \in \Sigma$.If $r_1,r_2$ are regular expressions then so are $(r_1)^*$, $(r_1+r_2)$ and $(r_1r_2)$.In practice we don't write all the parentheses. Each regular expression denotes some formal language (you will learn this translation in class). It turns out that a formal language is regular if and only if there is some regular expression denoting it.If you have any more questions, I recommend reading a textbook which covers regular languages, for example Hopcroft and Ullman.
_vi.5873
When I define key mappings, I prefer using a modifier key with another key, because modifier key can make you so much fast if you need to press some key mapping multiple times, you only need to hold down the modifier key once and keep pressing the other key. e.g.say if I map ctrl j to cycle through opening windows. I just need to hold down ctrl once and press several time j to get to the window I want. that's just 1 * ctrl + n * j key strokes. But the <leader> key is different. <leader> key is not modifier key. So if map <leader> j to cycle through windows. I need to repeat: press <leader>, press j several times. that's n * <leader> + n * j key strokes.So is there any chance I can make the <leader> key modifier? or if you know some other way I can define my own modifier key?
Can I make key modifier, or is there anyway I can get more custom modifier key?
key bindings
As has been said, this is not directly possible. There exists however plugins that create clever maps to achieve something similar: tinykeymap, tinymode or vim-submode
_computergraphics.1606
I have the following problem:Give a matrix that will transform the point $(x,y,z)$ into the point $(\frac{2}{x+y}, \frac{5y + z}{2x + 2y}, 3)$.I have been reading my book to find a way to solve it without success. I will very much appreciate your feedback about how to solve it.
Transform a point into another point
transformations
null
_cogsci.17369
In the context of a broader question, someone asked:Can the detailed analyses from, say, the Wechsler test, be used to inform decisions significantly better that gut feelings can?While this question might be closed, I thought a more defined question regarding the correlation between self-rated and objective measures of intelligence would be good to have. I feel as if I've read papers that suggest the correlation is modest (e.g., r = .2 or .3). Presumably, Dunning-Kruger and a bunch of self-serving biases operate. But I could not find any authoritative reference off hand. So my questions:What is the correlation between self-rated intelligence and objective measures of intelligence (i.e., full scale IQ scores from well-validated measures)?To what extent does the correlation depend on how the self-ratings are obtained?
What is the correlation between self-rated and objective measures of intelligence?
intelligence;bias
The term you are looking for is self-assessed intelligence (SAI) (sometimes subjectively-assessed intelligence or self-estimated intelligence). The leaders in this field are Tomas Chamorro-Premuzic and Adrian Furnham. From their book Personality and Intellectual Competence (2014):Correlations between SAI and psychometric intelligence have been significant and positive, albeit generally modest (r<.30).So you are spot on. :-) SAI is a subset of self-tests of intelligence, that can range from simple estimates, to full-fledged self-administered IQ tests. As such, correlations can vary a lot. However, SAI is generally considered to be an estimate, rather than a test, and this does not appear to be affected much by methodology. From Paulhus et al (1998):Correlations between single-item self-reports of intelligence and IQ scores are rather low (.20.25) in college samples. The literature suggested that self-reports could be improved by three strategies: (1) aggregation, (2)item weighting, and (3) use of indirect, rather than direct, questions. ... Although results showed some success for both direct and indirect measures, the failure of their validities to exceed .30 impugns their utility as IQ proxies in competitive college samples.On the other hand, the SAI literature reveals significant gender differences in SAI estimates - with males significantly overestimating and females significantly underestimating their intelligence - as well as significant cross-cultural differences in estimates, suggesting that the correlation is more heavily affected by social stereotypes.
_webapps.79622
How can I join an event without having my name listed? Below I can see everyone's name, almost all of which I don't know, except for Facebook User's.Names of attendees for event on public page that I Like.How can I be that guy?
How to anonymously join public events?
facebook;privacy;calendar;anonymous
There is no way to hide your name from the list. Event host can change privacy setting for the event but in that case also your name will be visible to selected audience.What you can do is you can remove yourself from the list.
_codereview.121742
I have been learning AngularJS and have written my first app. It's a Hangman AI which learns words and guesses the solution based on the words it knows.Please look over my code and provide some pointers towards better practices, techniques and overall criticism.Here is a CodePen demo, as the Stack Snippet may have cross-site AJAX issues.var app = angular.module(HangManAI, []);app.controller('HangManController', ['$scope', '$http', function($scope, $http){ $scope.step = 0; $scope.theWords = new Array(); $scope.wordCount = 0; $scope.wordLetters = new Array(); $scope.myGuess = None; $scope.testString = ; $scope.attempts =10; $scope.letterFound = false; $scope.myMouth = G'Day. I am a hangman AI written with AngularJS. I can win a game of hangman against you if I know the words you use. Click New Game to begin.; $scope.error = ; var availableLetters = [A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z]; var knownWords = []; //Functions $scope.startAGame = function(){ $scope.theWords = new Array(); $scope.wordCount = 0; $scope.attempts = 10; $scope.error = ; availableLetters = [A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z]; $scope.myMouth = Alright! First tell me how many words there are and how many letters for each word.; $scope.step = 1; var req = { method: 'GET', url: 'http://www.hott-source.com/hangman/getMemory.php', data: { } } $http(req).then(function(response){ knownWords = response.data; $scope.testString = knownWords; }, function(response){ $scope.error = I could not get my memory. Try reloading the page.; }); } $scope.checkWords = function(){ //Loop through each typed word var i = $scope.theWords.length; var wordKnown = false; var newWords = ; var whatToSay = ; while(i--){ var currentWord = $scope.theWords[i].word; //Check if we know it. if(typeof knownWords[currentWord.length-1] === 'undefined') { } else{ var innerLoop = knownWords[currentWord.length-1].length; while(innerLoop--){ if(knownWords[currentWord.length-1][innerLoop] == currentWord) { wordKnown = true; } } } if(!wordKnown) { if(newWords != ) { newWords += :; whatToSay += , ; } else whatToSay = I didn't know these words; ; newWords += currentWord; whatToSay += currentWord; } $scope.step=5; $scope.error = whatToSay; } //This needs to save to memory var myUrl = 'http://www.hott-source.com/hangman/getMemory.php'; if(newWords != ) myUrl += '?newWords='+newWords; var req = { method: 'GET', url: myUrl, data: { } } $scope.myMouth = ; $http(req).then(function(response){ $scope.myMouth = Do you want to play again?; }, function(response){ $scope.myMouth = I could not get my memory. Try reloading the page.; }); } $scope.nextLetter = function() { if($scope.letterFound) $scope.letterFound = false; else $scope.attempts -=1; if($scope.attempts > 0) chooseALetter(); else { $scope.myMouth = Damn it... please show me the missing letters. Each click will change the letter. Click done when its right; $scope.step = 4; } } $scope.fixLetter = function(letterIndex, wordIndex) { var aWord = this.theWords[wordIndex].word; var aLetter = aWord[letterIndex]; switch(aLetter) { case A: aLetter = B; break; case B: aLetter = C; break; case C: aLetter = D; break; case D: aLetter = E; break; case E: aLetter = F; break; case F: aLetter = G; break; case G: aLetter = H; break; case H: aLetter = I; break; case I: aLetter = J; break; case J: aLetter = K; break; case K: aLetter = L; break; case L: aLetter = M; break; case M: aLetter = N; break; case N: aLetter = O; break; case O: aLetter = P; break; case P: aLetter = Q; break; case Q: aLetter = R; break; case R: aLetter = S; break; case S: aLetter = T; break; case T: aLetter = U; break; case U: aLetter = V; break; case V: aLetter = W; break; case W: aLetter = X; break; case X: aLetter = Y; break; case Y: aLetter = Z; break; case Z: aLetter = A; break; default: aLetter = A; } aWord = aWord.replaceAt(letterIndex, aLetter); this.theWords[wordIndex].word = aWord; } $scope.foundLetter = function(letterIndex, wordIndex) { $scope.letterFound = true; var aWord = this.theWords[wordIndex].word; aWord = aWord.replaceAt(letterIndex, this.myGuess); this.theWords[wordIndex].word = aWord; var hasNotFinished = false; for(var i = 0; i<this.wordCount; i++) { var theWord = this.theWords[i].word; var j = theWord.length; while(j--){ if(theWord[j] == _) { hasNotFinished = true; break; } } if(hasNotFinished) break; } //Make some way to reverse if(!hasNotFinished) { $scope.myMouth = YAY!, I GOT IT; $scope.checkWords(); } } $scope.createTempWords = function(){ //If the word array is bigger than the number of words we want, slice it. if(this.theWords.length > this.wordCount) this.theWords = this.theWords.slice(0, -1); else { //Otherwise push in another word. for(var i = this.theWords.length; i<this.wordCount; i++) { this.theWords.push({id:i, word: _, letters:1}); } } } //Increase or decrease the size of the words $scope.wordSize = function(num){ if(this.theWords[num].word.length > this.theWords[num].letters) this.theWords[num].word = this.theWords[num].word.substr(0, this.theWords[num].letters); else { //Otherwise push in another word. for(var i = this.theWords[num].word.length; i<this.theWords[num].letters; i++) { this.theWords[num].word += _; } } } //Player has finished inputting their words. $scope.readyToPlay = function(){ if($scope.theWords.length < 1) $scope.myMouth = You need to enter some words first.; else{ $scope.instructions = Click the button which matches the letter location, or click no!; $scope.step = 2; chooseALetter(); } } //Enables me to delete an element from an array based on value. Array.prototype.deleteElem = function(val) { var index = this.indexOf(val); if (index >= 0) this.splice(index, 1); return this; } //Enables me to replace a character at a set index of a string String.prototype.replaceAt=function(index, character) { return this.substr(0, index) + character + this.substr(index+character.length); } //Choose the most likely letter out of all known words with the lengths equal to the words in the phrase. function chooseALetter() { var letterCount = []; for(var i=0;i<availableLetters.length;i++){ letterCount[i] = 0; } //Loop through each secret word for(var phraseWord_i = 0; phraseWord_i<$scope.theWords.length; phraseWord_i++) { var thisPhraseWord = $scope.theWords[phraseWord_i].word; var phraseWordLength = thisPhraseWord.length; //Loop through all the words of the same length if(typeof knownWords[phraseWordLength-1] === 'undefined') { } else { for(var knownWord_i = 0; knownWord_i<knownWords[phraseWordLength-1].length; knownWord_i++){ var thisKnownWord = knownWords[phraseWordLength-1][knownWord_i]; // var i = thisKnownWord.length; var canUse = true; //Check if this word is allowed to be used while (i--) { //Has this letter been discovered? if(thisPhraseWord[i] != _){ //Does thisKnownWord match that letter if(thisPhraseWord[i] != thisKnownWord[i]){ canUse = false } } } //If this word can use add 1 to all the letterCounts if(canUse){ var i = thisKnownWord.length; while(i--){ letterCount[availableLetters.indexOf(thisKnownWord[i])] += 1; } } } } } //Find the most used letter var maxIndex = 0; var max = letterCount[0]; for (var i = 1; i < letterCount.length; i++) { if (letterCount[i] > max) { maxIndex = i; max = letterCount[i]; } } $scope.myGuess = availableLetters[maxIndex]; $scope.myMouth = Are there any + $scope.myGuess + 's in your phrase?; availableLetters.deleteElem(availableLetters[maxIndex]); }}]);app.filter('isPlural', function(){ return function(input) { if(input > 1 || input == 0) return s; else return ; }});app.filter('dashes', function(){ return function(input) { var result = ; for(var i =0; i<input.length; i++) { result += _ ; } return result; }});.error{ color: red;}.inLineList{ list-style: none; float: left; padding-right: 20px;}p{ clear:left;}<script src=https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js></script><body ng-app=HangManAI> <script src=http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js></script> <div ng-controller='HangManController'> <p>{{myMouth}}</p> <p class='error'>{{error}}</p> <div ng-show='step == 0'> <button ng-click='startAGame()'>New Game</button> </div> <div ng-show='step==1'> <input type='number' ng-model='wordCount' ng-change='createTempWords()' min=0> <p>You want {{wordCount}} word{{wordCount | isPlural}}</p> <ol> <li ng-repeat='aWord in theWords track by $index'><input type='number' ng-model='aWord.letters' ng-change='wordSize($index)' ng-show='!gameOn'><button ng-click='foundLetter($index, $parent.$index)' ng-disabled='!gameOn' ng-repeat='letter in aWord.word track by $index'>{{ letter }}</button> {{aWord.letters}} letter{{aWord.letters | isPlural}}</li> </ol> <button id='startGame' ng-click='readyToPlay()' ng-show='!gameOn'>Start The Game</button> </div> <div ng-show='step==2'> <p>I have {{attempts}} time{{attempts | isPlural}} I can guess wrong</p> <ol> <li class='inLineList' ng-repeat='aWord in theWords track by $index'><button ng-click='foundLetter($index, $parent.$index)' ng-repeat='letter in aWord.word track by $index'>{{ letter }}</button></li> </ol> <p><button ng-show='!letterFound' ng-click='nextLetter()'>No</button><button ng-show='letterFound' ng-click='nextLetter()'>Next Letter</button></p> </div> <div ng-show='step==4 || step==5'> <ol> <li ng-repeat='aWord in theWords track by $index'><button ng-click='fixLetter($index, $parent.$index)' ng-repeat='letter in aWord.word track by $index'>{{ letter }}</button></li> </ol> <p><button ng-show='step==4' ng-click='checkWords()'>Done</button></p> <p><button ng-show='step==5' ng-click='startAGame()'>New Game</button></p> </div> </div> <script src='js/modules/HangManAI.js'></script> <script src='js/controllers/HangManController.js'></script> <script src='js/filters/isPlural.js'></script> <!--<script src='js/services/getMemory.js'></script>--></body></html>
Hangman learning AI
javascript;html;css;angular.js;hangman
null
_webapps.75625
Just today when I click on Contacts in Gmail, it opens a new tab with a new contacts web application. Please tell me how to disable this and get back to the old version of contacts (Gmail).It's funny that I was just trying to help my girlfriend last week, because she can no longer send me email easily because it always wants to send through a Google circle even if we directly enter the email. I was trying to fix it in that New app (that somehow she had a few weeks before me) and it was impossible. They really broke things this time.Also found search doesn't work as well. It can't even find the emails that it brings up as suggestions when composing an email and entering a name.
Disable Google Contacts Preview
gmail;google contacts
In the side menu click More Leave the Contacts preview you will be taken to old Google contacts.
_webmaster.39764
I usually know this stuff, but its a real concern. (I'm tired so i hope this makes sense.)I make a post and then add tags in the Wordpress backend. For example, the title of the post is make big money. In the tag area I'm adding make big money, or tools to make big money, or how does blogging make big money.I'm wondering as these tags that are the ones usually in tag clouds. Are they still OK to use with all the Google updates?All those different tags go to the same post page. So I'm wondering if its considered duplicate content.
Are blog posts with the tags in tag clouds bad for SEO?
seo;tags
null
_cstheory.2123
I wish to know the VC-dimension of a range space $(X,\mathcal{R})$ constructed as follows:$X$ is the cylinder $\{(x,y,z)\in\mathbb{R}^3|x^2+y^2\leq 1\}$The ranges in $\mathcal{R}$ are formed by taking the union of circular disks such that:the plane containing the disk is orthogonal to the z axis (we stack the disks in the z direction)a disk is tangent to the cylinder boundary at the point $(1,0,z)$a disk has diameter $f(z)+1$, where $f(z)$ is bounded (strictly) by $-1<f(z)<1$, and strictly monotonically increasing, strictly monotonically decreasing, or constant.Any set constructed by rotating one of these ranges about the z axis by an arbitrary angle is also a range.Intuitively, imagine taking a set of coins (circular, of course) and sorting them by diameter, either decreasing or increasing. Then drop them carefully into a tube (the main cylinder) in that order, so each rests on the last. Now tip the tube slightly so that they all rest against the side of the cylinder. If our coins had zero thickness and we had one for every real number, this would be our range.I'm mostly interested in the case that $f(z)$ is sigmoid, like the error function or $\tanh$. Specifically, I'm interested in the cylindrical ranges formed by the family of functions $\tanh(\alpha(z-\beta))$, where $\alpha,\beta\in\mathbb{R}$. I know that this range space has at least VC-dim 4 (I can construct a set of four points that it shatters), but I'm interested in putting an upper bound on it and understanding why. I know that:Circular disks in $\mathbb{R}^2$ have VC-dim 3Subsets of the strip $\{-1\leq y\leq 1\}\subset\mathbb{R}^2$ that are bounded above or below by $\tanh(\alpha(z-\beta))$ have at least VC-dim 3, probably equal to 3, because the slope part of the $\tanh$ function acts much like a lineIs there any way to combine these facts to obtain an upper bound on the VC-dimension? Is there anything to say about general $f(z)$ that meet the criteria in (2)?
VC-dimension of Cylinders within a Cylinder
cg.comp geom;vc dimension
null
_codereview.37378
I'm building an http handler at work which has about 6 methods and I'm trying to figure out what design pattern will work the best for my needs:What's done already (Only an example to make this more clear, methods are not real, but the main concept is there):#region interfacespublic interface IDateRange{ DateTime StartDate { get; set; } DateTime EndDate { get; set; }}public interface ISomeMoreParams{ int Param1 { get; set; } int Param2 { get; set; }}public interface IBaseParams{ string UserName { get; set; } string CompanyName { get; set; }}public interface IClassMethod : IBaseParams{ void ExecuteLogic(HttpContext context);}#endregion#region FactoryClasspublic static class ClassMethodFactory{ public static IClassMethod GetInstance(string methodName) { switch(methodName) { case MethodA: return new MethodA(); case MethodB: return new MethodB(); case MethodC: return new MethodC(); } throw new NotImplementedException(string.Format({0} is not implemented, methodName)); }}#endregion#region Class methodspublic class MethodA : IClassMethod, IDateRange{ string UserName { get; set; } string CompanyName { get; set; } DateTime StartDate { get; set; } DateTime EndDate { get; set; } public void ExecuteLogic(HttpContext context) { // Do MethodA }}public class MethodB : IClassMethod, ISomeMoreParams{ string UserName { get; set; } string CompanyName { get; set; } int Param1 { get; set; } int Param2 { get; set; } public void ExecuteLogic(HttpContext context) { // Do MethodB }}public class MethodC : IClassMethod, IDateRange, ISomeMoreParams{ string UserName { get; set; } string CompanyName { get; set; } DateTime StartDate { get; set; } DateTime EndDate { get; set; } int Param1 { get; set; } int Param2 { get; set; } public void ExecuteLogic(HttpContext context) { // Do MethodC }}#endregion#region HttpHandlerpublic IClassMethod method;public void ProcessRequest(HttpContext context){ ProcessParams(); ExecuteLogic();}public ProcessParams(){ var qs = HttpContext.Current.Request.QueryString; method = ClassMethodFactory.GetInstance(qs[action]); if(method is IDateRange) { (method as IDateRange).StartDate = DateTime.Parse(qs[startDate]); (method as IDateRange).EndDate = DateTime.Parse(qs[endDate]); } if(method is ISomeMoreParams { (method as ISomeMoreParams).Param1 = int.Parse(qs[param1]); (method as ISomeMoreParams).Param2 = int.Parse(qs[param2]); } if(method is IBaseParams) { (method as IBaseParams).UserName = qs[UserName]; (method as IBaseParams).CompanyName = qs[CompanyName]; }}public ExecuteLogic(){ method.ExecuteLogic();}#endregionNow, the only part the I have a problem with, is the casting each time I want to see if the class method implements some parameter logic. I wish it would be more organized.My thoughts:1. Create for each parameter interface a parameter resolver class which would look like this:#region Resolverspublic class DateRangeResolver{ public void Resolve(IDateRange dateRangeClass) { var qs = HttpContext.Current.Request.QueryString; dateRangeClass.StartDate = DateTime.Parse(qs[startDate]); dateRangeClass.EndDate = DateTime.Parse(qs[endDate]); }}public class SomeMoreParamsResolver{ public void Resolve(ISomeMoreParams someMoreParamsClass) { var qs = HttpContext.Current.Request.QueryString; someMoreParamsClass.Param1 = int.Parse(qs[param1]); someMoreParamsClass.Param2 = int.Parse(qs[param2]); }}public class BaseParamsResolver{ public void Resolve(IBaseParams baseParamsResolver) { // Do resolve }}#endregionThen I change the code to fit the new approach:#region interfaces// ...public interface IClassMethod : IBaseParams{ void ProcessParams(); void ExecuteLogic();}// ...#endregion#region Class methods// ...public class MethodA : IClassMethod, IDateRange{ // params public void ProcessParams() { new BaseParamsResolver().Resolve(this); new DateRangeResolver().Resolve(this); } public void ExecuteLogic() { // Do MethodA }}public class MethodB : IClassMethod, ISomeMoreParams{ // params public void ProcessParams() { new BaseParamsResolver().Resolve(this); new SomeMoreParams().Resolve(this); } public void ExecuteLogic() { // Do MethodB }}public class MethodC : IClassMethod, IDateRange, ISomeMoreParams{ // params public void ProcessParams() { new BaseParamsResolver().Resolve(this); new DateRangeResolver().Resolve(this); new SomeMoreParams().Resolve(this); } public void ExecuteLogic(HttpContext context) { // Do MethodC }}// ...#endregion#region HttpHandler// ...public void ProcessParams(){ method.ProcessParams();}//...#endregionNow, my problem is that if I don't call the right resolvers on the ProcessParams of each class method, I would get an exception at runtime and not on debug, which means, I need to consider a new approach or change the existing approach to do so.I had another idea, the idea is to add to each parameter interface its own resolver so when a class method implements the param interface it would also need to define the resolver for the interface.This idea, although sounds better, still doesn't enforce the programmer to actually call these resolvers when executing the ProcessParams() function.Now, after this long long explanation... is there a better way?
Best design pattern to approach http handler with multiple methods
c#;object oriented;design patterns
null
_unix.245273
My question is actually pretty much in the title. Is it possible to jail an older 32-bit FreeBSD, such as 6.4 or 8.4 in a 64-bit FreeBSD 10.2?I'll also appreciate pointers and explanations on how to accomplish this and information on what prerequisites my host needs to fulfill.NB: according to this blog article, jailing an older FreeBSD on a current one is possible. But that article makes no mention of 32-bit versus 64-bit.
Can I jail an older 32-bit FreeBSD on a (current) 64-bit FreeBSD?
freebsd;jails
null
_codereview.128286
In my attempt to help improve Using Array to store calculations in VBA, I figured a good way to do it would be to create two dictionaries of values to lookup.So this was my attempt at creating two dictionaries from two sheets and then gathering data from a third sheet into an array and looking up the items in the array based on a condition as to which dictionary to use.My sample is pretty small and the last line of printing was just to see it worked. I actually struggled with this for a little while, so I'm thinking there are some improvements to be made. Also - is this sufficiently made to be scaled up to millions of data points? What about more than one dictionary - should that be refactored? What if there are more criteria needed for the lookup? Option ExplicitPublic Sub ArrayLookupAndPopulate() Dim firstTable As Object Set firstTable = CreateObject(Scripting.Dictionary) Dim secondTable As Object Set secondTable = CreateObject(Scripting.Dictionary) Dim rowNumber As Long Dim myKey As String Dim lookupArray As Variant Dim myIndex As Long For rowNumber = 1 To 10 firstTable.Add CStr(Sheet1.Cells(rowNumber, 1)), Sheet1.Cells(rowNumber, 3) secondTable.Add CStr(Sheet2.Cells(rowNumber, 1)), Sheet2.Cells(rowNumber, 3) Next Dim lastRow As Long lastRow = Sheet3.Cells(Rows.Count, A).End(xlUp).Row Dim lastColumn As Long lastColumn = Sheet3.Cells(1, Columns.Count).End(xlToLeft).Column + 1 ReDim lookupArray(1 To lastRow, 1 To lastColumn) lookupArray = Sheet3.Range(Cells(1, 1), Cells(lastRow, lastColumn)) For myIndex = 1 To 9 myKey = lookupArray(myIndex, 2) If lookupArray(myIndex, 1) = First Then lookupArray(myIndex, 3) = firstTable.Item(myKey) If lookupArray(myIndex, 1) = Second Then lookupArray(myIndex, 3) = secondTable.Item(myKey) Next Sheet3.Range(F1:H9) = lookupArrayEnd SubI don't want to edit the code, but I just realized I don't need to redim.
Creating two dictionaries to lookup values into an array
vba;excel
null
_unix.311651
I use Nginx on Ubuntu 16.04 for using Guacamole as RDP clientless.This is working perfectly on my computer which is in an external LAN. But not working in another external LAN which have proxy (work area).When I go to the app from my browser : http://myserverguaca/guacamole/I can see log-in page and I can log on. But when I try to start the RDP there is a loading, then a message that says:The server take to many to time to be respond.Do you think I have to forward another port ?I have forwarded the port 8080 to 80, RDP use : 3389, but this is in localhost, don't know why I should forward this too and how I can do it.I hope you can help me.There is the configuration of my RDP access (user-mapping.xml)<user-mapping><connection name=rdp><protocol>rdp</protocol><param name=hostname>localhost</param><param name=port>3389</param><param name=server-layout>fr-fr-azerty</param><param name=ignore-cert>true</param></connection></user-mapping>and my config on nginx (sites-enabled/guacamole)server {listen 80;server_name vpsmyserver.net.com;location /guacamole/ {proxy_pass http://localhost:8080/guacamole/;proxy_buffering off;proxy_http_version 1.1;proxy_set_header X_Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header Upgrade $http_upgrade;proxy_set_header Connection $http_connection;access_log off;}}
Nginx for reversing proxy on guacamole but RDP not working on External LAN with proxy
nginx;port forwarding;freerdp;reverse proxy
null
_webmaster.99538
What steps should I proceed to tell Google about my migration from HTTP to HTTPS (there is 301 valid redirect is set), nothing I can see in Google webmaster (they have migration, but it is saying they do not support such migrations). Eventually I just setup ssl cert and set nginx accordingly and after two weeks I see nothing indexed and nothing in search. Is this expected? Also, how bad for SEO subdomain.domain.com? Domain goes to subdomain.domain.com with 301 redirect..Much appreciated!
Migration to HTTPS & subdomains
seo;google analytics;google search console;https;migration
null
_unix.18473
I am using a Palm Tungsten E2 PDA which I sync to a linux machine via jpilot. jpilot is kind of ugly but it works and it is sufficient to look up things on the computer.Now I want to sync the same data to a 'backup' Palm PDA (m150). First tests with jpilot did not work as expected, because it seems that the devices differ too much and jpilot is too dependent on different database file formats (i.e. I guess the devices internally use different database schemas).Syncing to the backup PDA m150 works with j-pilot, when a fresh ~/.jpilot config is used.How can I solve this? Is there is some GUI which supports to sync to multiple devices (and abstracts away device differences)?Since I am using Ubuntu 10.04 I assume that KDE Akonadi is not a solution because it is too alpha.
How to sync multiple Palm PDA devices?
synchronization
null
_cs.1138
For every computable function $f$ does there exist a problem that can be solved at best in $\Theta(f(n))$ time or is there a computable function $f$ such that every problem that can be solved in $O(f(n))$ can also be solved in $o(f(n))$ time?This question popped into my head yesterday. I've been thinking about it for a bit now, but can't figure it out. I don't really know how I'd google for this, so I'm asking here. Here's what I've come up with:My first thought was that the answer is yes: For every computable function $f$ the problem Output $f(n)$ dots (or create a string with $f(n)$ dots or whatever) can obviously not be solved in $o(f(n))$ time. So we only need to show that it can be solved in $O(f(n))$ time. No problem, just take the following pseudo code:x = f(n)for i from 1 to x: output(.)Clearly that algorithm solves the stated problem. And it's runtime is obviously in $\Theta(f(n))$, so problem solved. That was easy, right? Except no, it isn't because you have to consider the cost of the first line. The above algorithm's runtime is only in $\Theta(f(n))$ if the time needed to calculate $f(n)$ is in $O(f(n))$. Clearly that's not true for all functions1.So this approach didn't get me anywhere. I'd be grateful for anyone pointing me in the right direction to figure this out properly.1 Consider for example the function $p(n) = \cases{1 & \text{if $n$ is prime} \\ 2 & \text{otherwise}}$. Clearly $O(p(n)) = O(1)$, but there is no algorithm that calculates $p$ in $O(1)$ time.
For every computable function $f$ does there exist a problem that can be solved at best in $\Theta(f(n))$ time?
complexity theory
By the Gap theorem (using the formulation from here, search for 'gap'), for any computable unbounded function $g : \mathbb{N} \rightarrow \mathbb{N}$, there exists some increasing (in fact, arbitrarily large) computable function $f : \mathbb{N} \rightarrow \mathbb{N}$ such that $DTIME(f(n)) = DTIME(g(f(n))$.This answers your question in that there exists such an $f$ (infinitely many, in fact): for every computable function $g$ such that $g = o(n)$, there exists some increasing function $f$ such that all problems solvable in $O(f(n))$ time are also solvable in $O(g(f(n)) = o(f(n))$ time. Note that $f$ is not necessarily time-constructible - for the time-constructible case, see the answer by @RanG.In the Wikipedia formulation (which requires that $g(x) \geq x$), then $g \circ f$ becomes your example, and $f$ needs to be $\omega(n)$ (so you go the other way around - 'problems solvable in $O(g(f(n))$ are also solvable in $O(g(n))$' is the interesting part).The Wikipedia article does not note that $f$ is increasing and can in fact be arbitrarily large ($f(n) \geq g(n)$ for instance). The article that proves the gap theorem does mention and prove this (see here, for example).
_unix.17870
By default vim aligns lines inside LI tags on the same position as the position of LI tag, but I want the contents of LI to have deeper indentation.Current behaviour:<LI>first linesecond lineI want:<UL> first line second lineIs this possible?
How to change vim auto-indent behavior?
vim;indentation
null
_softwareengineering.76940
What do you think? Is Visual Studio Lightswitch becoming the Oracle APEX for SQL Server in the futrure? Are these two technologies comparable?
Is VS Lightswitch the Oracle APEX from Microsoft?
web development;.net;visual studio;oracle;silverlight
null
_codereview.108887
This code shows a title with an image and subtitle:What improvements can I make in this code and is there a better of doing this?package Components.CustomLabel;import javafx.scene.control.Label;import javafx.scene.image.Image;import javafx.scene.image.ImageView;import javafx.scene.layout.GridPane;/** * * @author Aamir khan */public class LabelWithSubTitle extends GridPane {private final Label title = new Label();private final Label subTitle = new Label();private final ImageView thumb = new ImageView();public LabelWithSubTitle(String titleString, String subString, Image thumb) { setTitle(titleString); setSubTitle(subString); setThumb(thumb); init();}private void setSubTitle(String sub) { subTitle.setText(sub);}private void setThumb(Image img) { thumb.setImage(img);}private void setTitle(String titleString) { title.setText(titleString);}private void init() { add(thumb, 0, 0, 1, 2); add(title, 1, 0); add(subTitle, 1, 1);}}
Label with Subtitle
java;performance;javafx
null
_codereview.116416
I have written command line chess in Python 3.4.3 and the code is included here. The chessboard is printed to standard output as a 2-D array; for now I only have CLI and the output in the command line is as below:['Rb' '0 ' 'Bb' 'Qb' 'Kb' 'Bb' 'Nb' 'Rb']['Pb' 'Pb' 'Pb' 'Pb' '0 ' 'Pb' 'Pb' 'Pb']['0 ' '0 ' 'Nb' '0 ' '0 ' '0 ' '0 ' '0 ']['0 ' '0 ' '0 ' '0 ' 'Pb' '0 ' '0 ' '0 ']['0 ' '0 ' '0 ' '0 ' 'Pw' '0 ' '0 ' '0 ']['0 ' '0 ' '0 ' '0 ' '0 ' 'Qw' '0 ' '0 ']['Pw' 'Pw' 'Pw' 'Pw' '0 ' 'Pw' 'Pw' 'Pw']['Rw' 'Nw' 'Bw' '0 ' 'Kw' 'Bw' 'Nw' 'Rw']Where R:Rook, N:Knight, B:Bishop, Q:Queen, K:King, P:Pawn and the lower case letters denote the corresponding color.Furthermore, I used exceptions for impossible moves. How can I improve the code so that the program will not terminate when a impossible move is attempted? I have yet to implement castling, check and enpassant. There also needs to be a check for checkmate. I would be glad if you can provide some insight on my code.The latest code is here.import numpy as npimport tkinter as tk# PATH OBSTRUCTIONS, CHECK, PROMOTION AND CASTLINGclass ChessBoard: count = 0 # This is the counter to keep track of moves def __init__(self): self.objectboard = self.form_board() def __str__(self): string = '' board = self.draw_board(self.objectboard.T) # Transpose is necessary to make the board as we are accustomed to for i in reversed(range(8)): # It is reversed so that white is at the bottom string += str(board[i]) + '\n' return string def form_board(self): # Forms the board and puts the pieces on the respective positions board = np.zeros((8,8), dtype = object) # Now we should put the pieces on the board WhiteRook1 = Rook(0, 0, 'w', board) WhiteRook2 = Rook(7, 0, 'w', board) WhiteKnight1 = Knight(1, 0, 'w', board) WhiteKnight2 = Knight(6, 0, 'w', board) WhiteBishop1 = Bishop(2, 0, 'w', board) WhiteBishop2 = Bishop(5, 0, 'w', board) WhiteQueen = Queen(3, 0, 'w', board) WhiteKing = King(4, 0, 'w', board) # Now we should put the pawns for i in range(8): exec(WPawn + str(i+1) + = Pawn(i, 1, 'w', board)) # This syntax is for changing variable names # Now put the black pieces BlackRook1 = Rook(0, 7, 'b', board) BlackRook2 = Rook(7, 7, 'b', board) BlackKnight1 = Knight(1, 7, 'b', board) BlackKnight2 = Knight(6, 7, 'b', board) BlackBishop1 = Bishop(2, 7, 'b', board) BlackBishop2 = Bishop(5, 7, 'b', board) BlackQueen = Queen(3, 7, 'b', board) BlackKing = King(4, 7, 'b', board) # Now we should put the pawns for i in range(8): exec(BPawn + str(i+1) + = Pawn(i, 6, 'b', board)) return board def draw_board(self, board): func_sym_col = np.vectorize(self.retrieve_piece) symbolic_board = func_sym_col(board) return symbolic_board def retrieve_piece(self, piece): if isinstance(piece, ChessPiece): return str(piece.symbol+piece.color) else: return '0 ' def rules(self, piece, i, j, m, n): board = self.objectboard #symboard = self.draw_board(board) if ((self.__class__.count % 2) == 0): if (piece.color == 'b'): raise Exception('It is Whites turn to play') else: if (piece.color == 'w'): raise Exception('It is Blacks turn to play') piece_type = piece.symbol # Rules depend on the piece # Implement check check_new_pos = 0 # We should modify this write a loop over other pieces opponent_king = 0 auxboard = [] if ((m - i) >= 0): check1 = 1 else: check1 = 0 if ((n - j) >= 0): check2 = 1 else: check2 = 0 if piece_type == 'K': if (abs(i - m) > 1): raise Exception('This is not a valid move for the King') elif (abs(j - n) > 1) : raise Exception('This is not a valid move for the King') elif check_new_pos: raise Exception('The King cannot move to a threatened square!!!') elif opponent_king: raise Exception('You cannot go too close to the opponent king') elif piece_type == 'Q': if not ((abs((i - m) / (j - n)) == 1) or ((i - m) == 0) or ((j - n) == 0)): raise Exception('The queen cannot move like this') if (i - m) == 0: if check2: auxboard = board[i][j+1:n] else: auxboard = board[i][n+1:j] elif (j - n) == 0: if check1: auxboard = board[i+1:m][j] else: auxboard = board[m+1:i][j] else: if check1 and check2: for ct in range(m - i - 1): auxboard.append(board[i + 1 + ct][j + 1 + ct]) elif check1 and (not check2): for ct in range(m - i - 1): auxboard.append(board[i + 1 + ct][j + 1 - ct]) elif (not check1) and check2: for ct in range(i - m - 1): auxboard.append(board[i + 1 - ct][j +1 + ct]) elif (not check1) and (not check2): for ct in range(i - m - 1): auxboard.append(board[i + 1 - ct][j + 1 - ct]) if not (all(p == 0 for p in auxboard)): raise Exception('The path is obscured') elif piece_type == 'R': if not (((i - m) == 0) or ((j - n) == 0)): raise Exception('The rook cannot move like this') if (i - m) == 0: if check2: auxboard = board[i][j+1:n] else: auxboard = board[i][n+1:j] elif (j - n) == 0: if check1: auxboard = board[i+1:m][j] else: auxboard = board[m+1:i][j] if not (all(p == 0 for p in auxboard)): raise Exception('The path is obscured') elif piece_type == 'B': if not (abs((i - m) / (j - n)) == 1): raise Exception('The bishop cannot move like this') if check1 and check2: for ct in range(m - i - 1): auxboard.append(board[i + 1 + ct][j + 1 + ct]) elif check1 and (not check2): for ct in range(m - i - 1): auxboard.append(board[i + 1 + ct][j + 1 - ct]) elif (not check1) and check2: for ct in range(i - m - 1): auxboard.append(board[i + 1 - ct][j +1 + ct]) elif (not check1) and (not check2): for ct in range(i - m - 1): auxboard.append(board[i + 1 - ct][j + 1 - ct]) print(board[i + 1 - ct][j + 1 - ct]) if not (all(p == 0 for p in auxboard)): raise Exception('The path is obscured') elif piece_type == 'N': # The path may be obscured this time if not (((abs(i - m) == 2) and (abs(j - n) == 1)) or ((abs(i - m) == 1) and (abs(j - n) == 2))): raise Exception('The knight cannot move like this') elif piece_type == 'P': if piece.color == 'w': if piece.count == 0: if not(((n - j) == 2) or ((n - j) == 1) and ((i - m) == 0)): raise Exception('The pawn cannot move like this') elif piece.count != 0: if not((n - j) == 1): raise Exception('The pawn cannot move like this') else: if piece.count == 0: if not(((n - j) == -2) or ((n - j) == -1) and ((i - m) == 0)): raise Exception('The pawn cannot move like this') elif piece.count != 0: if not((n - j) == -1): raise Exception('The pawn cannot move like this') # Implement one cannot move to a square containing same color piece if board[m][n] != 0: # There is a piece in the final position if board[i][j].color == board[m][n].color:# Two pieces are of the same color raise Exception(You cannot go to your own pieces location) elif board[m][n].symbol == 'K':# The opponent king is in the location raise Exception(You cannot eat the KING) if ((piece_type == 'P') or (piece_type == 'K')): piece.count += 1 return 1 def move(self, position): # These two strings are for board coordinates letstr = 'abcdefgh' numstr = '12345678' board = self.objectboard if not (len(position) == 4): raise ValueError('The position string should consist of 4 characters'); # Get the final and initial positions initial_pos = position[:2] final_pos = position[-2:] # First perform the checks if not (str == type(initial_pos) and (str == type(final_pos))): # Check if the arguments are strings raise TypeError('The supplied positions should be strings!') elif not ((initial_pos[0] in letstr) and (initial_pos[1] in numstr)): # Check if they fulfill the condition to be on the board raise ValueError('The initial position values should be between a1 and h8') elif not ((final_pos[0] in letstr) and (final_pos[1] in numstr)): # Check if they fulfill the condition to be on the board raise ValueError('The final position values should be between a1 and h8') elif initial_pos == final_pos: raise ValueError('Final position should be different from the initial position') # Now determine if there is a piece on the initial square i = letstr.index(initial_pos[0]) ; j = numstr.index(initial_pos[1]) # Numerical initial position m = letstr.index(final_pos[0]); n = numstr.index(final_pos[1]) # Numerical final position if not (isinstance(board[i][j], ChessPiece)): raise Exception('There is no chess piece here') piece = board[i][j] if self.rules(piece, i, j, m, n) != 1: raise('This move is not allowed') # Move the piece on the chessboard piece.movepiece(i, j, m, n, board) self.__class__.count += 1 # Increment the counter after each allowed moveclass ChessPiece: # This is the base class, all the other specific pieces inherit this class. def __init__(self, x, y, color): if not ((int == type(x)) and (int == type(y))): raise TypeError(' x and y should be integers!!') elif not ((x in range(8)) and (y in range(8))): raise ValueError('x and y positions should be between 0 and 7 inclusive') elif not ((str == type(color)) and (color in 'wb')): raise ValueError('Color should be w or b') self.pos_x = x self.pos_y = y self.color = color # IMPLEMENT PROMOTION HERE def movepiece(self, i, j, m, n, chessboard): self.pos_x = i self.pos_y = j chessboard[i][j] = 0 # Set the previous position to be zero chessboard[m][n] = selfclass King(ChessPiece): def __init__(self, x, y, color, chessboard): ChessPiece.__init__(self, x, y, color) self.symbol = 'K' self.count = 0 chessboard[self.pos_x][self.pos_y] = selfclass Queen(ChessPiece): def __init__(self, x, y, color, chessboard): ChessPiece.__init__(self, x, y, color) self.symbol = 'Q' chessboard[self.pos_x][self.pos_y] = selfclass Rook(ChessPiece): def __init__(self, x, y, color, chessboard): ChessPiece.__init__(self, x, y, color) self.symbol = 'R' chessboard[self.pos_x][self.pos_y] = selfclass Bishop(ChessPiece): def __init__(self, x, y, color, chessboard): ChessPiece.__init__(self, x, y, color) self.symbol = 'B' chessboard[self.pos_x][self.pos_y] = selfclass Knight(ChessPiece): def __init__(self, x, y, color, chessboard): ChessPiece.__init__(self, x, y, color) self.symbol = 'N' chessboard[self.pos_x][self.pos_y] = selfclass Pawn(ChessPiece): def __init__(self, x, y, color, chessboard): ChessPiece.__init__(self, x, y, color) self.symbol = 'P' self.count = 0 # To keep track if it just started moving chessboard[self.pos_x][self.pos_y] = self# These are auxiliary functions##################################################################### ACTUAL CODE STARTS HEREchessboard = ChessBoard()print(chessboard)chessboard.move('e2e4')print(chessboard)chessboard.move('e7e5')print(chessboard)chessboard.move('d1f3')print(chessboard)chessboard.move('b8c6')print(chessboard)chessboard.move('c1e3')print(chessboard)chessboard.move('f8c5')print(chessboard)chessboard.move('f3f7')# Already mate hereprint(chessboard)chessboard.move('h8h5')print(chessboard)chessboard.move('h1h4')print(chessboard)
Python3 command line chess
python;python 3.x;gui;chess
OO design pointsSplitting responsibilitiesWhy does a Board know how each piece moves? And each piece knows nothing? It makes much more sense to implement a move(self, target_position) for each piece.Multiple instancesclass ChessBoard: count = 0 # This is the counter to keep track of movesCount should be an instance method (self.count) as it currently stands, you can only have one board at a time.Use built-insWriting in Python allows you to avoid explicit indexing and looping, easier code that does the same can be written using built-ins (enumerate, reversed, join ...)def __str__(self): board = self.draw_board(self.objectboard.T) return '\n'.join((map(str, reversed(board)))) + '\n'NamesThis has been said hundreds of times in this site, I will repeat it: long descriptive names are a must for good code. A good rule of thumb is that no name should require a comment next to it to explain it. Just use a more descriptive name in the first place, for example (in the Pawn class):self.count = 0 # To keep track if it just started movingBecomes:self.has_already_moved = 0BooleansA Boolean is either true or false, much clearer than 0 or 1, so I suggest using:self.has_already_moved = FalsePretty printingYour output format is not nice, it is confusing and user un-friendly, I suggest taking full advantage of Python-3 full Unicode compatibility using the Chess Unicode characters and removing the square brackets and quotations marks.Avoid arbitrary outside world modificationsInside each Piece class:chessboard[self.pos_x][self.pos_y] = selfIs very crippling:Reading (for example) WhiteRook1 = Rook(0, 0, 'w', board) gives me no clue that the board is being modifiedWhiteRook1 = Rook(0, 0, 'w', board) will fail if the board has any other name than chessboard, a very fragile way of programming.eval is best avoided for i in range(8): exec(WPawn + str(i+1) + = Pawn(i, 1, 'w', board)) No.Use a list to store the pieces, not a variable for each piece, this coupled with the pieces knowing out to move will simplify your code.Declare static methods staticmethoddef retrieve_piece(self, piece): if isinstance(piece, ChessPiece): return str(piece.symbol+piece.color) else: return '0 'Here retrieve_piece is static in that it does not access the internals of a class, so make this clear and declare it as:@staticmethoddef retrieve_piece(piece): if isinstance(piece, ChessPiece): return str(piece.symbol+piece.color) else: return '0 'Assign booleans directly if ((n - j) >= 0): check2 = 1 else: check2 = 0Becomes just:check2 = n - J >= 0
_codereview.166495
I have this code//TRIGGER MULTIPLE VIEWS, WALL AND FORUMif(isset($_COOKIE[projects-sorting])) { $_SESSION['projectsDisplayMode'] = $_COOKIE[projects-sorting];}if(isSet($_GET['mode'])) { $_SESSION['projectsDisplayMode'] = $_GET['mode'];}if(!isSet($_SESSION['projectsDisplayMode'])) { $_SESSION['projectsDisplayMode'] = wall; //default is wall mode}$mode = $_SESSION['projectsDisplayMode'];setcookie(projects-sorting, $mode, time() + (86400 * 30), /); // 86400 = 1 dayWhich to me looks overly complicated, but it does work.What it does:Checks if a specific cookie exists, if it does, set session variable projectsDisplayMode to whatever that cookie's content is.Check if _GET variable mode exists, if it does, set projectsDisplayMode to whatever that variable is (Would overwrite the last variable set if both exist)Last check if the session variable is set at all, if it's not set it to wall, as that is the default.Now set $mode (A specific page variable) to be processed a bit more to show the page properly.I'm not concerned with the afterwards processing, I just want to see if there is a better way that I can do the first bit that may be faster or more standard, or more pleasant to look at.
Seemingly complicated way of displaying page views
php
You only really need one if. IMO something like this would be easier to read.if(!empty($_GET['mode'])){ $mode = $_GET['mode'];}else{ $mode = !empty($_COOKIE[projects-sorting]) ? $_COOKIE[projects-sorting] : wall; }setcookie(projects-sorting, $mode, time() + (86400 * 30), /);$_SESSION['projectsDisplayMode'] = $mode;At the end of this, $_SESSION['projectsDisplayMode'] and $_COOKIE[projects-sorting] will always be the same value, so I would omit the former. You really shouldn't use session to store intermediate values anyway. You should be setting session to the value of $mode, not vice versa.
_unix.227553
I have a ethernet connection eth0 and a wifi usb connection wlan0 on my raspbian box which both connect to a router with internet.In my etc/network/interfaces file I have a setup that allows me to connect via SSH to my eth0 or wlan0 iface....iface eth0 inet static address 192.168.1.100 netmask 255.255.255.0 gateway 192.168.1.1...iface wlan0 inet static address 192.168.1.200 netmask 255.255.255.0...This config is fine and works as expected.However this setup causes conflict with another software that demands each to have iface to be on its own subnet.When I reconfigure my /etc/network/interfaces file like so...iface eth0 inet static address 192.168.1.100 netmask 255.255.255.0 gateway 192.168.1.1...iface wlan0 inet static address 192.168.2.200 netmask 255.255.255.0...As wlan0 is now apart of another subnet (192.168. 2 .200) I can no longer connect to it through SSH, I also can not reach it via ping 192.168.2.200 from a Windows Machine.When connected to eth0 through SSH, cmd tcpdump returns...23:05:27.296764 IP 192.168.1.5.49846 > 192.168.1.100.ssh: Flags [.], ack 2284256, win 252, length 023:05:27.297540 IP 192.168.1.100.ssh > 192.168.1.5.49846: Flags [P.], seq 2284256:2284544, ack 17665, win 594, length 28823:05:27.298780 IP 192.168.1.5.49846 > 192.168.1.100.ssh: Flags [.], ack 2284544, win 251, length 023:05:27.299201 IP 192.168.1.100.ssh > 192.168.1.5.49846: Flags [P.], seq 2284544:2284832, ack 17665, win 594, length 28823:05:27.300434 IP 192.168.1.5.49846 > 192.168.1.100.ssh: Flags [.], ack 2284832, win 256, length 023:05:27.301316 IP 192.168.1.100.ssh > 192.168.1.5.49846: Flags [P.], seq 2284832:2285120, ack 17665, win 594, length 28823:05:27.302296 IP 192.168.1.100.ssh > 192.168.1.5.49846: Flags [P.], seq 2285120:2285280, ack 17665, win 594, length 16023:05:27.302712 IP 192.168.1.5.49846 > 192.168.1.100.ssh: Flags [.], ack 2285120, win 255, length 023:05:27.303873 IP 192.168.1.5.49846 > 192.168.1.100.ssh: Flags [.], ack 2285280, win 254, length 0...What I have TriedUpdated /etc/network/interfaces and changed netmask to netmask 255.255.0.0Still the problem remains
How to assign two iface to different subnets?
networking;network interface;subnets
null
_softwareengineering.303546
I just wanted to check that I understand the LSP correctly and can solve it. I am taking the classic rectangle/square problem and attempting a solution:class Rectangle{ public $width; public $height; function setWidth($width){ $this->width = $width; } function setHeight($height){ $this->height = $height; }}class Square extends Rectangle{ function setWidth($width){ $this->width = $width; $this->height = $width; } function setHeight($height){ $this->height = $height; $this->width = $height; }}If you had some code like:function changeSize(Rectangle $rect){ $rect->setWidth(10); $rect->setHeight(30); $this->assertEquals(10,$rect->width); $this->assertEquals(30,$rect->height);}Then obviously rectangles and squares are not interchangeable, as square introduces a constraint to the parent class. Therefore, a square should not inherit from rectangles.But surely we can agree that both square and rectangle are four sided shapes? This is my proposed solution, based on this premise:abstract class AFourSidedShape{ public $width; public $height; abstract public function __construct($width,$height); public function scaleUp($percentage){ $this->height = $this->height + (($this->height / 100) * $percentage); $this->width = $this->width + (($this->width / 100) * $percentage); } public function scaleDown($percentage){ $this->height = $this->height - (($this->height / 100) * $percentage); $this->width = $this->width - (($this->width / 100) * $percentage); }}class Rectangle extends AFourSidedShape{ function __construct($width, $height){ $this->width = $width; $this->height = $height; }}class Square extends AFourSidedShape{ function __construct($width, $height){ if($width != $height){ throw new InvalidArgumentException('Sides must be equal'); }else{ $this->width = $width; $this->height = $height; } }}Our client code should be changed to something like:function changeSize(AFourSidedShape $shape){ $origWidth = $shape->width; $origHeight = $shape->height; $shape->scaleUp(10); $this->assertEquals($origWidth + (($origWidth/100) * 10),$shape->width); $this->assertEquals($origHeight + (($origHeight/100) * 10),$shape->height);}My theory is: rectangles and squares really are both foursidedshapes, so there shouldn't be a problem with inheriting from the foursidedshape abstract class. Whilst the square is still adding extra constraints in the constructor (i.e. throwing an error if the sides aren't equal), it shouldn't be a problem since we haven't implemented the constructor in the abstract parent class, and so client code shouldn't make assumptions about what you can/cannot pass into it anyway.My question is: have I understood LSP, and does this new design solve the LSP problem for square/rectangle? When using interfaces as suggested:interface AFourSidedShape{ public function setWidth($width); public function setHeight($height); public function getWidth(); public function getHeight();}class Rectangle implements AFourSidedShape{ private $width; private $height; public function __construct($width,$height){ $this->width = $width; $this->height = $height; } public function setWidth($width){ $this->width = $width; } public function setHeight($height){ $this->height = $height; } //getwidth, getheight}class Square implements AFourSidedShape{ private $width; private $height; public function __construct($sideLength){ $this->width = $sideLength; $this->height = $sideLength; } public function setWidth($width){ $this->width = $width; $this->height = $width; } public function setHeight($height){ $this->height = $height; $this->width = $height; } //getwidth, getheight}
Does this code solve the square/rectangle Liskov Substution Principle example?
design patterns;object oriented design;inheritance;liskov substitution
null
_unix.307300
I'm using tar to archive a bunch of files to LTO-7 tape. Generally each file is about 1-2GB, and there can be several hundred of them in each archive (up to ~1TB per archive).At the moment, I'm archiving using:tar -cvf /dev/nst0 --totals --warning=no-file-changed $OLDEST_DIRThis is getting me about 90MBps from a disk that should be capable of about three times that (and the tape should be capable of 2-3 times that). Looking closely, it seems like I'm CPU-bound since tar is taking 100% of one CPU.This is particularly annoying since I'm trying to verify if the archive is the right size by first doing this tar -cP --warning=no-file-changed $OLDEST_DIR | wc -c... and then comparing the sizes of the archives produced.So, is there any quicker way?
Faster (uncompressed) archiving tool than tar?
backup;tar;archive;large files;tape
null
_softwareengineering.274721
New guy on the team so I figured I'd ask here in public than sound like a complete dweeb and ask elsewhere. Without giving too much or anything away (please ask questions if you want), but should, or is it in any way traditional, to write code that rolls out a directory containing nothing but script files to /opt/bin? Shouldn't bin contain... binaries?I know that most distributions of linux or chock full of scripts in the /bin directory, but was that always the case?
Should a bin directory be full of shell scripts?
linux;directory structure
null
_cs.11229
A bridge (critical edge) in an undirected graph is an edge whose removal increases the number of connected components.I need to determine all critical edges in an undirected graph, in $O(V+E)$ time. From what I found out, I need to use a modified DF search, but all pseudo-code algorithms I found have low[v] and d[v] which I don't understand.Can someone please explain to me the $O(V+E)$ bridge determination algorithm?
Bridge determination in undirected graphs
algorithms;graph theory;graphs;graph traversal
null
_unix.360735
I am trying to start a java SWT application after the system has booted and the user has logged in on a debian based distro (RaspbianOS on a Raspberry Pi). Therefore I have added the line sh <path>/startProgram.sh into the rc.local file. I know that the start-script is getting called because I created a new directory for debug purposes in this script. Apart from that the script looks like this:java -jar /home/pi/Downloads/AlarmClock.jarAnd if I double click it manually it starts the application just fine. However it won't start at boot of the system. My first thought was that the X-server has not yet been initialized at that point but according to this article the rc.local script is the very last init script to run and therefore the x-server should be initialized by then (at least according to my understanding) Does anyone has an idea on how to start the program that will create a GUI after user login?
Start SWT application after system start
raspberry pi;java;startup;raspbian
null