id
stringlengths 5
27
| question
stringlengths 19
69.9k
| title
stringlengths 1
150
| tags
stringlengths 1
118
| accepted_answer
stringlengths 4
29.9k
⌀ |
---|---|---|---|---|
_unix.316424 | I have an array:$ arr=(one two)I want to access it's content through another variable which contains the name of the array:$ arrname=arrI want to access (one two) using the variable arrname. I tried dereferencing it:$ echo ${!arrname}one$ echo ${!arrname[@]}0But it does not work as I expected it to. How can I access the content of the array arr do that? | Dereferencing array | bash;array | null |
_softwareengineering.284634 | Let assume I have two simple model classes: Product and BrandIt is obvious I have a query method in Product class like thisProduct product = Product.findById(123);What if, I want to query products by brand?ArrayList<Product> products = Product.findByBrand(234);// orArrayList<Product> products = Product.findByBrand(new Brand(ABC, 234));Assume 234 is the brand ID in the database.I assume the 2nd way of writing make the method more easy to test as I can mock the Brand class in my unit test, right? | Domain object model: query by id vs object | java;object oriented;unit testing;domain model;mocking | null |
_softwareengineering.92298 | I am working on a script to get data from excel spreadsheets to a database. The data is from surveys conducted by our office where the data comes in with very little formatting. At the moment, the data is manipulated with a lot of copy and paste, then analysed 'by hand' (ie. someone clicks and drags in excel and does pivots and copy pastes into other software).This leads to messy file structures and missing or incorrect/incomprehensible data. enter the need for a database.I have got a solution working which will accept csv files. It will parse the data and insert it correctly as long as each column header is correct. But my superior is pushing me to accept xml files with an xsd schema so I can validate the data.My argument would be that whether or not I use xml, the user will have to save the original file as another file type and I can validate the data within my script based on column headers anyway.The counter argument is that if they decide to include a new data set (ie, new table layout) my script might break. Either way, if the data type is incorrect, the user will have to go back to the file and edit it before any solution will work. So the answer I'm looking for is whether or not I should bother to set up xml functionality.[note, I am using php to script as I am not familiar with vba and I'm on a student placement so I do not have enough time to learn a new language.][ASIDE - am I taking the wring approach to this?] | Should I implement functionality for an xml file+schema? | php;database;scripting;validation | If I were you, I would create the importer to work with the CSV, but include stub functionality for the XML. Release the tool with the CSV functionality and then begin working on the XML.As far as your superior is concerned, I would point out that working with CSV is drastically simpler than working with XML, so you can get a deliverable faster, and then work on the XML portion. This means that the rest of the team can begin using this tool, and then later on if they do decide to change, the XML functionality will be there.As to your final question, sort of. You have an idea for something good, and your superior is trying to provide an augmentation to make that better in their mind. This isn't a bad thing, as you get paid the same, but have more hours of work to do. As a result, I would suggest that you try and massage their idea into yours, and make it an even better idea instead of fighting the change. |
_unix.155928 | I am using Xenomai linux, and I have internet on it, but when I do apt-get update or apt-get install I get bunch of errors like thishttp://security.debian.org/dists/etch/updates/contrib/source/Sources.gz 404 Not Found [IP: 212.211.132.250 80]I understand it has to do with unsupported repositories, but I googled around, but couldn't find what I need to do to fix it for Xenomai.This is my /etc/apt/sources.list: # # deb cdrom:[Debian GNU/Linux 4.0 r3 _Etch_ - Official i386 NETINST Binary-1 20080218-14:15]/ etch contrib main deb http://ftp.nl.debian.org/debian/ etch main deb-src http://ftp.nl.debian.org/debian/ etch main deb http://security.debian.org/ etch/updates main contrib deb-src http://security.debian.org/ etch/updates main contrib | Failed to fetch 404 errors during apt-get commands | xenomai | Take a look at this answer, looks like support for etch ended a while ago. Try using the archive instead of using the Netherlands mirror.deb http://archive.debian.org/debian/ etch main contrib |
_softwareengineering.221009 | I seek your advice on SPA (Single-page application) architecture.I'm building an SPA which edits a model. The models consists of objects which have a relation to one another. The objects (and relations) are stored in a single a collection on the server's database. The user must authenticate on server and sessions are implemented to track user activities.For this SPA I have a choice in thick or thin serve architecture.SPA thin server architectureThe complexity of managing inter object relations (model) is done on the clientFull data set is exchanged between client and server and thereFew interactions between client and serverHeartbeat pattern is implemented to keep session alive after authenticationProcess:User logs in (heartbeat starts)Client fetches all objects from the server database collectionClient constructs a data model from the objects (using the relations) and visualizes the modelUser edits the model and saves the changesOn save the client deconstructs the data modelAll objects are submitted to the server which stores these 1:1 in the database collectionSPA thick server architectureThe complexity of managing inter object relations (model) is done on the serverSmall data packages are exchanged between client and server (after initial load)Many interactions between client and serverFrequent changes omit the need for heartbeat to keep the session alive(though I except the risk of a session will time-out due to prolonged inactivity of the user)Process:User logs inClient fetches all objects from the server database collectionClient visualizes the server side model but does not construct a client side data modelUser edits the visualized model where each change is submitted to the severServers logic determines the changes to the model and updates (1 or more) the collection accordinglyWhich architecture would be favored for my SPA - and why? | SPA thin or thick architecture | design;design patterns;architectural patterns | null |
_unix.258079 | I have the following output as a user running crontab -l:#Ansible: backup-external chaos*/20 * * * * flock --nonblock /home/mu/.cache/backup-external.lock backup-external chaos*/20 * * * * /home/mu/bin/ddc-save-brightnessNeither job is executed. If I run them manually, they seem to work just fine.The Ansible snippet there comes from using Ansible to add this one job for my user.Looking at systemctl status crond.service -l makes it clear that the service itself is running. It seems to fail to load the crontab for my user mu due to SELinux it seems: crond.service - Command Scheduler Loaded: loaded (/usr/lib/systemd/system/crond.service; enabled; vendor preset: enabled) Active: active (running) since Mi 2016-01-27 17:51:08 CET; 1h 43min ago Main PID: 1351 (crond) CGroup: /system.slice/crond.service 1351 /usr/sbin/crond -nJan 27 17:51:09 martin-friese.fritz.box crond[1351]: (mu) Unauthorized SELinux context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 file_context=unconfined_u:object_r:user_cron_spool_t:s0 (/var/spool/cron/mu)Jan 27 17:51:09 martin-friese.fritz.box crond[1351]: (mu) FAILED (loading cron table)Jan 27 17:51:09 martin-friese.fritz.box crond[1351]: (CRON) INFO (running with inotify support)Jan 27 18:01:01 martin-friese.fritz.box CROND[3726]: (root) CMD (run-parts /etc/cron.hourly)Jan 27 18:01:01 martin-friese.fritz.box anacron[3737]: Anacron started on 2016-01-27Jan 27 18:01:01 martin-friese.fritz.box anacron[3737]: Will run job `cron.daily' in 13 min.Jan 27 18:01:01 martin-friese.fritz.box anacron[3737]: Jobs will be executed sequentiallyJan 27 18:01:01 martin-friese.fritz.box run-parts[3741]: (/etc/cron.hourly) starting mcelog.cronJan 27 18:14:01 martin-friese.fritz.box anacron[3737]: Job `cron.daily' startedJan 27 19:01:01 martin-friese.fritz.box CROND[2681]: (root) CMD (run-parts /etc/cron.hourly)This is on Fedora 23 and I did not change the SELinux policy, so it is probably enforcing strictly.What do I have to change in order to get the jobs running again? | User cron jobs are not being executed any more (perhaps SELinux) | fedora;cron;selinux | This was resolved in this bugzilla: https://bugzilla.redhat.com/show_bug.cgi?id=1298192Please make sure you have the latest kernel: 4.3.3-301 |
_webapps.42242 | As in Microsoft Excel, I want to protect certain cells in Google Spreadsheet. This is possible, but asides from the fact that it is quite confusing to me, it doesn't seem possible to protect cells from myself? The write-protection isn't extended to my edits, if I am the author of the spreadsheet. I need to stay in control of it otherwise, but I don't want to sacrifice write protection for this privilege.Did I miss something? Do you have any recommendation of how to work around this? | How to protect table cells in Google Spreadsheets from myself (accidental edits)? | google drive;google spreadsheets | null |
_unix.213047 | When we do a yum install or yum update where does yum stores the downloaded packages in the system. | Where does yum store the temporary packages | yum | null |
_softwareengineering.187380 | I recently heard of an interview question: Given a string and a dictionary. Break the string into meaningful wordsand I remember solving this before with dynamic programming fairly quickly (maybe O(n) time? ) in one of my old algorithm classes but I can not remember the name of the algorithm. Could someone point me in the right direction? | Algorithm Identification [ String & Dictionary ] | algorithms;strings | Your instincts are on the money though as suggested in this Stack Overflow question, tries (prefix trees) are also a valid solution. The process is called Word Segmentation. |
_unix.271164 | I am in a network and a user is sending broadcast messages on udp port 5353. Regardless of what that is and what their purpose is, I decided to block all the traffic, so I ran:sudo iptables -A INPUT -i eth0 -p udp -m state --state NEW -m udp --dport 5353 -j DROPBut I am still getting the traffic (in wireshark), but with different source and destinations (neither the source nor the destination matches my IP). Apparently I need a mechanism to drop the broadcasts, is there any way of doing that using iptables or ufw? | How to block broadcast messages (Apple's mDNS traffic) | iptables;udp;multicast;mdns | UDP cannot have state - try without the state clause.Also, be aware that if you are checking incoming traffic with tcpdump, this listens OUTSIDE the firewall. |
_webmaster.68335 | I am working on a web project that has nearly 100 thousand instant users and there is a webpage that we are using for test cases. There are no links pointing to it from other pages. It shouldn't be indexed by Google or any other search engines.noindex can be used in this situation, I know but I wonder if Google (or any others) indexes this page, if I don't do anything to prevent it. | Is Google indexing pages that has no connection with other pages? | indexing;google index;noindex | null |
_unix.109774 | I'm using Buildroot to generate an embedded Linux with a kernel v. 2.6.39, which in the end starts busybox. Everything works fine when building with Initramfs as rootfs. But Initramfs isn't the best for my needs, so i want to switch to other fs like SquashFS or even better not compressing it at all.Anyways i can't figure out how to tell the kernel it shall boot for instance the SquashFS file. What i do know, is that this is done by some kernel command line parameters. Unfortunately i can't find more about this with different search engines or here. And so it doesn't work. It always ends, as expected, with a kernelpanic.And how is it done if I haven't got it compressed and therefor it just has to be copied from Flash to RAM ? | Change the root filesystem on an embedded system | filesystems;kernel;linux kernel;embedded;buildroot | Make sure you build what ever file system you want directly into the kernel and not as a module. SquashFS is readonly so you can't use that alone. You may be better off booting from initramfs then loading root from an image, but that's your call. |
_webapps.79554 | I am trying to capture and store data into a spreadsheet using google forms. Everything will be stored in google drive.How do I set up forms/ spreadsheet to input the data captured in the form into particular columns of a spreadsheetThe form will be sent out each week and the data will be sent to the specific columns for that weeks informationI was intending on using Boomerang for the repetitive emailing (does anyone have any better solutions?)Help with any of the above will be greatly appreciated. | Google Forms - Survey data storing | gmail;google forms;survey | Your Google Form decides which column to store the data in - you do not control this.And the design you're aiming for (different weeks data in different columns) is likely to cause long term problems. But there is a better approach:In general, the first column in the sheet which it stores data in is labelled Timestamp, and contains the date/time when the data was entered.Each column after that contains data in the order in which the question was added to the forum, ie:Column B gets the answer to the first question you added.Column C gets the answer to the second question you added, etc.These relationships are maintained even if you re-order the questions on the form.You can add helper-columns to the right of the ones filled in the by the form. So you could add week submitted, and use this to calculate the value from the Timestamp column. Then use a pivot table (or similar) to create a summary of the data, with the week submitted as the column value. This will give a view of the data like what you described originally, while still using the Forms data storage approach. |
_codereview.133769 | I have to reverse a string in JavaScript and cannot use the built in reverse() function. It does not seem efficient to have to create two arrays but is there a better way?function reverseString(str) { newarr = str.split(); result = []; x = newarr.length; for (i = x; i > -1; i--) { result.push(newarr[i]); } str = result.join(); return str;}reverseString(hello); | Reverse string in JavaScript without using reverse() | javascript;strings;array | One array to rule them allYou do not need to create two arrays; one is enough. Simply swap slots until you've reached the middle of the array.Declare your variablesIt is better to use the var keyword to define your variables. Otherwise, they are declared on the top-level scope, i.e; they become global, and may be accessed and modified by other functions.Why not use reverse()?You do not say why you cannot use built-in functions. If you happen to have some base code which overrides native functions, then some groaning and roaring is in order.function reverse(str) { var chars = str.split(); var length = chars.length; var half = length / 2; for (var ii = 0; ii < half; ii++) { var temp = chars[ii]; var mirror = length - ii - 1; chars[ii] = chars[mirror]; chars[mirror] = temp; } return chars.join();}console.log(reverse(abcd));console.log(reverse(abcde)); |
_webapps.108934 | I have a problem. People cannot make Check-In in our page https://www.facebook.com/ShishaHouse.ee/ In the setting this function is put ON, but people still cannot Check In here... What is the problem? | I cannot make Check-In into our page | facebook;facebook pages | null |
_unix.216148 | On occasion I get output from a command that includes key value pairs, with possibly more than one pair per line. As a repeatable example, consider the command ip addr show dev eth0:ip addr show dev eth0 | grep -v link/ether2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000 inet 10.0.2.15/24 brd 10.0.2.255 scope global eth0 valid_lft forever preferred_lft forever inet6 fe80::a00:27ff:fe0f:dbb3/64 scope link valid_lft forever preferred_lft foreverFor the purposes of this example I might want to capture the values following mtu, inet, and brd (i.e. 1500, 10.0.2.15/24, and 10.0.2.255 respectively, here). It can be assumed that each keyword will not occur more than once in the input.The only way I can see to handle this would be capture the output of the source command to a temporary variable, and repeatedly parse that until all the keywords have been processed.Is there an easier or better way to pick out these key value pairs, discarding the remainder of the text?Suggested example provision and unordered output:ip addr show dev eth0 | someCommand brd inet mtumtu 1500inet 10.0.2.15/24brd 10.0.2.255 | Matching keyword value pairs from semi-structured input | shell script;text processing | Assuming that key name will appear at most once, here is how you may try. ip addr show dev eth0 | perl -ne 'chomp; foreach $param (qw(mtu inet brd)) { /($param)\s+(\S+)/ && do { print $1 $2\n; }}' |
_webmaster.13305 | I bought a new domain for myself. I got an email account free with the domain. Inorder to access mails through my gmail account I set up auto-forwarding all mails from my domain's webmail. Now the problem is at times it forwards mails instantly but sometimes it doesn't. Can anything be done about it? | Forwarding emails not working | domains;webmail | There are many places where delays could occur in the path between your domain and Google's servers. No, there's not a lot you can do about that. |
_webmaster.25556 | I'm looking for a support system/helpdesk where users are required to pay for every question they have asked. Can anybody recommend me a good one? | PHP paid-for support script? | php;looking for a script | Can't name one off the top of my head but there are quite a few in the 'support' section at hotscripts |
_opensource.5633 | Let's say I wanna create the same class port it to another language, am I allowed to copy anything from the following file?In my case I'm interested in the comments, since microsoft seems to explain things better than I do (since my main language is not english).Am I allowed to copy the comments? the enum? or nothing at all?I'm using Visual Studio Community. On a follow up question, sometimes Visual Studio will let you browse the actual source code (normally for inline functions) in other languages (not in .NET tho), in such case, can I copy anything from there? The file path is C:\Users\MyName\AppData\Local\Temp\MetadataAsSource\2fc4dc8304b74a10ab128418499592c5\a67ebc72e7ad4d8191f243ac221a75d2 File[from metadata] #region Assembly mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089// C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\mscorlib.dll#endregionusing System.Collections.Generic;namespace System.IO{ // // Summary: // Provides static methods for the creation, copying, deletion, moving, and opening // of a single file, and aids in the creation of System.IO.FileStream objects.To // browse the .NET Framework source code for this type, see the Reference Source. [ComVisible(true)] public static class File { } public static void AppendAllLines(string path, IEnumerable<string> contents); public static void Copy(string sourceFileName, string destFileName); enum Something { a = 1, b = 2 }} | Am I allowed to copy/paste code from visual studio generated .NET-Metadata | license file | null |
_unix.277502 | I have an Ubuntu 14.04 LTS, kernel 3.13 in a Intel Xeon + 8Gb box. It has apache 2.4.7 configured in mpm worker with up to 4000 workers. The max bandwidth allowed by the ISP is 100Mbps.If I test this server with apache ab locally: ab -n 10000 -c 1000 http://www.mysite.com/test.pngAnd from another terminal I check apache workers: watch -n0 'ps -eLf | grep apache | wc -l'I can watch worker count growing until reach 1000 threads serving the requests. So far so good.However if I run the same test from an external machine, workers stop growing at around 400 workers. I guess this is related to some bottle neck in the tcp/ip configuration. Searching the web I have found several web pages explaing how to increase some sysctl settings to achieve more simultaneous connections. I have tried this: sysctl -w net.core.somaxconn=50000 sysctl -w net.ipv4.tcp_max_syn_backlog=30000 sysctl -w net.core.netdev_max_backlog=5000However repeating the test with these new settings makes no difference. You cannot see more than 400 workers simultaneously.Where could be the bottle neck? | Why my server cannot serve more than 400 concurrent connections | performance;webserver;apache httpd;tcp ip | null |
_vi.5050 | I use vim's spellchecking feature. Given that I work with many technical terms and LaTeX commands, I tend to add many them to my personal dictionary in ~/.vim/spell/en.utf-8.add.I would like to share this file across multiple machines, so that when I add a word to the file on one machine, it is also added on other machines, and I don't need to add it once on each machine. I tried versioning ~/.vim/spell/en.utf-8.add in git, but this does not seem to work: vim does not pick up the new terms. I suspect that vim also needs the file en.utf-8.add.spl to be edited somehow, but as this file is binary, versioning it will probably lead to conflicts.Does anyone here have a satisfactory solution to have vim spellcheck dictionary additions as part of their config, and synchronising them between all of their machines? | How to share vim spellchecking additions between multiple machines? | spell checking | Vim uses the spl file to do the checks, and the spl file is generated from the add file. We can speculate on whether the spl file is portable across different machines and Vim versions, but it's easier (and safer) to re-generate it as needed. Now, the spl file is re-generated automatically when you add words to your local dictionary from within Vim, but you must run mkspell to re-generate it if you edit the add file directly.With that in mind, you can do something like this: synchronize the add file by whatever means (with git, rsync, NFS, or whatever), and add these commands to your vimrc on all machines:for d in glob('~/.vim/spell/*.add', 1, 1) if filereadable(d) && (!filereadable(d . '.spl') || getftime(d) > getftime(d . '.spl')) exec 'mkspell! ' . fnameescape(d) endifendforThis will re-generate the spl file at Vim startup whenever the corresponding add file is newer than it. |
_softwareengineering.102290 | I've been programming in PHP for a long time, and I've just recently decided to make the switch to Python. Of all the Python web frameworks, I settled on Twisted Web to build the framework of my startup.However (and I know it sounds nitpicky), mod_rewrite was something that I really appreciated about Apache. I want the entire system written in Python, and not just bits and pieces written in PHP and Python: while a PHP frontend could work, I'd avoid it if it was at all possible.Is it possible to build such an application without resorting to ugly urls?Note: I am aware of the fact that Django allows URL rewriting, but it kinda defeats the purpose of using Twisted by itself. | Is there an equivalent of mod_rewrite for Twisted web? | python;frameworks | There's a section of the Twisted Documentation that mentions inspiration from Apache's mod_rewrite and lists some methods, specifically twisted.web.rewrite, to do similar things. |
_cogsci.17948 | In my experience, anorexic peole tend to dislike it not only when they have to eat too much food, but also dislike it when they see others consume too much food in front of them, as well as being concerned and perhaps also displeased when others consume food away from them, even if they do not see such people consuming such food.Can someone please explain to me how this psychological issue works?P.S.: I am looking for an answer here because I know that anorexia is a psychological condition.Thanks. | Anorexia: attitude of anorexic people towards other people's consumption of food | behavior;feeding | null |
_codereview.90213 | I've never serialized a structure to a file before in C++, so I'm looking for critique on my first try at it.My main concerns are:It uses the streams space-delimited behavior. If a vector<char> that contains a space is serialized, it skips the space, which results in an exception. From my tests, it works fine for non-whitespace elements, but I'd like any suggestions on how I could circumvent this problem.Should I be throwing an exception on bad reads? Am I throwing the right exception?Should I be clearing the vector before adding to it while reading?The string formatting for the runtime_errors is ugly. I didn't want to introduce a stringstream just to format the message.#include <fstream>#include <vector>#include <string>#include <stdexcept>template <class T>std::fstream& operator<<(std::fstream& fs, std::vector<T>& v) { //Write size of vector fs << v.size() << ' '; //Write contents for (T& t : v) { fs << t << ' '; } return fs;}template <class T>std::fstream& operator>>(std::fstream& fs, std::vector<T>& v) { v.clear(); unsigned int vSize; fs >> vSize; if (!fs.good()) { throw std::runtime_error( std::string(Problem reading serialized vector size: ).append(std::to_string(vSize)) ); } for (unsigned int i = 0; i < vSize; i++) { T readT; fs >> readT; if (!fs.good()) { unsigned long errPos = fs.tellg(); throw std::runtime_error( std::string(Problem reading serialized vector content at ).append(std::to_string(errPos)) ); } v.push_back(readT); } return fs;} | Serialize/deserialize a vector using insertion/extraction operators | c++;c++11;serialization;vectors | null |
_codereview.148322 | My web application can take URL-encoded strings and return a JSON that contains information, like API calls.My main concerns are with security. I need a cheap and easy (but secure) way to do certain commands. This part is handled by the adminhandle section of the code. My code is currently designed to be able to be deployed on a heroku app, but simply changing:port = int(os.environ.get('PORT', 17995))at line 12 to:port = 80should be fine, allowing you to access this server from http://localhost. Inside the code itself contains a hashed password and a salt. The password I use I generated with the random module (perhaps it is worth noting, since there are more secure RNGs out there).My server is currently operational at here.from twisted.web.server import Sitefrom twisted.web.resource import Resourcefrom twisted.internet import ssl, reactorfrom twisted.python.modules import getModuleimport urllib.parseimport cgiimport jsonimport osimport hashlibadmin_salt = ''realpass = ''port = int(os.environ.get('PORT', 17995))class FormPage(Resource): isLeaf = True def render_GET(self, request): out = {} print(request.uri) x = (request.uri).decode('ascii') x = x[1:] x = todi(x) request.setHeader('Content-Type', 'text/plain; charset=UTF-8') valid = False if 'adminaccess' in x: vlr = adminhandle(x) out.update({'ADMIN':vlr[0]}) if len(vlr) != 1: out.update({'CMDRES':vlr[1]}) if 'key' in x: if x['key'] == 'chess': valid = True out.update({'my_name':'Bob'}) out.update({'success':valid}) return json.dumps(out).encode('UTF-8')## def render_POST(self, request):## x = request.content.read()## print(x)## return xdef todi(st): if len(st) == 0: return '{}' if st[len(st)-1] == '/': st = st[:-1] if len(st) == 0: return '()' if st[0] == '?': st = st[1:] st = urllib.parse.parse_qsl(st) return dict(st)def adminhandle(di): rawupass = (admin_salt+di['adminaccess']).encode('ascii') hashupass = hashlib.sha512(rawupass).hexdigest() result = [False] if hashupass == realpass: #access granted! del result[0] result.append(True) if 'command' in di: if di['command'] == 'listdir': result.append(str(os.listdir(os.getcwd()))) return result#certData = getModule(__name__).filePath.sibling('server.pem').getContent()#certificate = ssl.PrivateCertificate.loadPEM(certData)factory = Site(FormPage())reactor.listenTCP(port, factory)#reactor.listenSSL(443, factory, certificate.options())reactor.run() | Basic web app that returns a JSON of information | python;python 3.x;twisted | The first problem is the function todi. I'm assuming a better name for it would be to_dict. If that is the case it does not make sense, that it sometimes returns the string {}, sometimes () and sometimes an actual dictionary. I think this would be equivalent/better:def to_dict(st): st = st.strip(/?) if not st: return dict() return dict(urllib.parse.parse_qsl(st))This strips of any / or ? from the beginning or end of the string and returns an empty dictionary if the string is empty.Your function adminhandle should take the parameters it needs as parameters, not retrieve them on its own from data. It can also be slightly simplified by using the fact that lists are mutable, so you can just write result[0] = True instead of del result[0]; result.append(True):def adminhandle(adminaccess, command): result = [False, ] if adminaccess is not None: rawupass = (admin_salt+adminaccess).encode('ascii') hashupass = hashlib.sha512(rawupass).hexdigest() if hashupass == realpass: #access granted! result[0] = True if command == 'listdir': result[1] = str(os.listdir(os.getcwd())) return resultx is also a really bad name. At least name it data or something telling the reader what it actually is. data = to_dict(request.uri.decode('ascii')[1:])Your placeholder variable valid is also not necessary. As is writing out.update({'success': valid}). out['success'] = valid is sufficient. I would also use the fact that dictionaries have a dict.get method, that returns None if the key does not exist. out = {'success': False} adminaccess, command = data.get('adminaccess'), data.get('command') out['ADMIN'], out['CMDRES'] = adminhandle(adminaccess, command) if not out['CMDRES']: del out['CMDRES'] if data.get('key') == 'chess': out['my_name'] = 'Bob' out['success'] = True return json.dumps(out).encode('UTF-8') |
_unix.91088 | I have an Open Office Spreadsheet document stored inside a bash variable. I want to do something like the following to feed Open Office via STDIN:echo $openOfficeDoc | oofficeBut it doesn't work.Note: The content of the bash variable must not be written to disk.I'll emphasize that I'm trying to pass to Open Office the actual data of the file.I'm trying to store passwords in an Open Office Spreadsheet file. The passwords are encrypted using GPG. I don't want the passwords to be written to disk for security reasons.The bash variable value is a binary blob of an Open Office Spreadsheet document. It is not ASCII.The bash code I used to create the blob is:data=$(cat Encrypted.gpg | gpg -u Dor -d)While Encrypted.gpg is an encrypted file of an Open Office Spreadsheet.Is it possible to feed Open Office via STDIN? | Is it possible to feed Open Office via STDIN? | bash;pipe;stdin;openoffice | I don't think OpenOffice can be convinced to read from its standard input. But that doesn't matter. Just write the data to a temporary file.You don't want the passwords to be written to disk. That's fine. Write them to a file that isn't stored on disk.Many systems use an in-memory filesystem (tmpfs) for /tmp. Solaris has been doing that for ages; Linux distributions have been slow to come to the mix (Fedora 18 adopted it, Debian and Ubuntu still haven't budged) so it usually requires the system administrator to set it up manually. However, modern Linux distributions mount a tmpfs filesystem somewhere; recent versions of the standard library require it. The standard location for tmpfs is /run, with /run/shm being world-writable (same permissions as /tmp), but some distributions may not have it yet; look at /dev/shm and perhaps other locations. |
_unix.10545 | With this I can check, that there is internet connection. if there is no internet connection (succesfull pings to this 2 places), then it waits 600 sec, then it runs along:ping -W 1 -c 4 www.google.com >& /dev/null && ping -W 1 -c 4 www.yahoo.com >& /dev/null || sleep 600But: how could I rewrite this one line, so that it loops until there is internet connection? | internet connection checker one-liner | linux;shell;networking;ping | while ! ping -W 1 -c 4 www.google.com >& /dev/null || ! ping -W 1 -c 4 www.yahoo.com >& /dev/null; do sleep 600doneThough I'd just test connectivity to an IP address; 8.8.8.8 is Google's public DNS server (it has very high availability). Testing whether DNS works is unreliable anyway because the entry may be in the cache.while ! ping -W 1 -c 1 8.8.8.8 >&/dev/null; do sleep 600; donePing isn't always the best way to check internet connectivity. Many places (especially enterprise networks) block all but web access. You can test whether the web is working by downloading a file from a high-availability server. This tests DNS as well, at least from the HTTP proxy's point of view (which again is often what matters).while ! wget -q -O /dev/null --no-cache http://www.google.com/; do sleep 6000; done |
_unix.377252 | How can I use fail2ban with DDWRT or a router?I love using fail2ban, but there is no info about using fail2ban in a linux base ddwrt / optware / entware and so on. | Fail2Ban with DDWRT or router | linux;router;firmware;fail2ban | null |
_softwareengineering.220065 | This applies to C (and probably to any other similar non-object oriented language). If I have a central data store and potentially concurrent access there are two ways I can see of protecting it.Let's say I have a data store with a few data elements...struct MyStore{ int data1, data2, data3, ...., dataN;} store[M];In this example the data types are the same but let's imagine this applies to something a bit more varied with different types etc... this is just to keep the question simple.To grant other users access to the data within I could do a few things.Could provide critical region functions and rely on the caller to get the protection correct.I could provide a setter and getter function for each data item type in the store and manage the critical regions within the module and protect the user from having to deal with any logic.My trouble with the first method is that the burden is placed on the caller.My trouble with the second, at least in C, is that firstly I end up writing a whole load of boiler plate accessors and secondly more complex stuff like test-and-set or needing to hold a lock on the data whilst doing several operations becomes messy. E.g. for method 2 I needint GetData1(unsigned int index) { int data; ENTER_CR(); data = store[index].data1; LEAVE_CR(); return data;}......int GetDataN(unsigned int index) { int data; ENTER_CR(); data = store[index].dataN; LEAVE_CR(); return data;}And the same for all the setters. And then what if I want to set multiple items atomically? Gets hard!How to get some of the benefits of modularity and encapsulation but still have a flexible interface? | Modularity and encapsulation in C | c;encapsulation | When providing a thread-safe interface (with or with OOP) you need to make sure that your operations are at the level you want to be atomic. If setting or getting a single field is the level of atomic operation you want to support, then option 1 works. (On the other hand, getting and setting int's is atomic anyways)The reality probably is that a simple data object isn't the correct place in a design to provide thread safety, because as you noted you really do not know what the real operations the data is being used for are. You can still encapsulate thread safety, but it needs to be where you are doing something, not just storing something. |
_softwareengineering.240877 | Coming from Java, I've never used a language with dynamic typing. I'm very used to the static-typing way of thinking.My question is, how much does the use of dynamic typing as opposed to static typing influence the overall design of programs written using languages with that kind of typing?Does the kind of typing (static/dynamic) influence the design of programs significantly? Working with a dynamically-typed language, would you structure your application differently than working with a statically-typed language? Or is it merely a language characteristic that affects mainly local implementation details, but doesn't affect overall designs? | How significant is the impact of the type system (static/dynamic) on the overall design of programs? | design;programming languages;dynamic typing;static typing | null |
_codereview.38556 | I was reading about opaque pointers and decided to try it with queues. Please review my code and let me know if there are any errors and how to improve code quality and performance.It uses lines to enqueue and dequeue. All lines have fixed sizes and dequeue/enqueue never share a line. New lines are added only when all lines are full, not counting the dequeue line. The lines are stored in a linked list.queue.h#ifndef QUEUE_H#define QUEUE_H#include <stdlib.h>#include <assert.h>#define QU_SUCCESS 0#define QU_ERROR 1typedef struct Queue Queue;Queue *qu_allocate_custom(size_t lines, size_t capacity);Queue *qu_allocate(void);void qu_free(Queue *queue);int qu_enqueue(Queue *queue, void *content);void *qu_dequeue(Queue *queue);size_t qu_get_count(Queue *queue);void qu_shrink_to_fit(Queue *queue);#endifqueue.c#include queue.h#define QU_DEFAULT_LINES 4#define QU_DEFAULT_LINE_CAPACITY 50//Data structures/*The line has a fixed size. It contains a link to the next and can hold void *.I'm using double pointers because I expect it to act like an array of void *.So, when I do position++ it will move sizeof(void *) and point to the nextstored address. Also the end of the line, if it's not full, can be delimited bysimply doing *position = NULL.*/typedef struct Line Line;struct Line { void **start; void **position; void **end; Line *next;};/*The queue structure just stores meta info and points to lines. The member indexis there because I thought it would make the the other functions simpler sincethey won't have to deal with special cases. They just treat it as if it were a regular line. And that's ok because most functions take the line that comes beforethe one they are operating on as an argument so they don't have to walk throughthe list to find that node in order to update the pointer to the next;The queue stores only elements of sizeof(void *), whatever is received by enqueuewill be sent back by dequeue, so it can store a pointer to anything andalso work with other data types of size up to sizeof(void *).The queue works like this:1 - When it's created, lines of fixed sizes are allocated2 - Dequeue is set to the first position, enqueue to the second3 - Both just walk along the list and never share a Line4 - If dequeue moves to the same line as enqueue, enqueue will go to the next.If the line is not full, one past the last element will contain NULL to indicatethat's the end.5 - If enqueue finishes filling a line, it will check if the next is empty. Ifthat's the case, it will go there. Otherwise dequeue is certainly using the line.So enqueue will try to create a new line.*/struct Queue { Line index; //just a pointer to the first line Line *enqueue; Line *dequeue; size_t count; size_t line_capacity;};//Internal methods//Take the element that comes before, so it doesn't have to walk through the liststatic void free_line_after( Line *previous ){ assert(previous->next != NULL); Line *line = previous->next; previous->next = line->next; free(line);}static void free_all_lines( Line *first ){ void *next; for(Line *ite = first; ite != NULL; ite = next){ next = ite->next; free(ite); }}/*Allocate a line and space for its contents in a single call to malloc since thelines have fixed sizes. There's no point in calling malloc twice here.*/static Line *push_line_after( Line *previous, size_t capacity ){ assert(previous != NULL && capacity > 0); //Allocate space for Line and its contents Line *new_line = malloc(sizeof(Line) + capacity * sizeof(void **)); if(new_line == NULL) return NULL; //Put on the list new_line->next = previous->next; previous->next = new_line; //Set all pointers and add a NULL delimiter so dequeue will be able to recognize //this line has nothing to dequeue new_line->start = (void **)(new_line + 1); new_line->position = new_line->start; new_line->end = new_line->start + capacity; *new_line->position = NULL; return new_line;}static inline Line *next_line( Queue *queue, Line *current ){ return (current->next != NULL) ? current->next : queue->index.next;}//Since it's an opaque pointer, setters/getterssize_t qu_set_capacity(Queue *queue, size_t new_capacity){ if(new_capacity > 0) queue->line_capacity = new_capacity; return queue->line_capacity;}size_t qu_get_count(Queue *queue){ return queue->count;}//Public methods/*Create a new queue with `lines` starting lines, each with `capacity` for pointers*/Queue *qu_allocate_custom( size_t lines, size_t capacity ){ if(lines < 2 || capacity < 1) return NULL; Queue *new_queue = malloc(sizeof(Queue)); if(new_queue == NULL) return NULL; //If the value is garbage, push_line_after will break the list new_queue->index.next = NULL; //Create all starting lines or cancel the operation Line *previous = &new_queue->index; while(lines-- > 0){ previous = push_line_after(previous, capacity); if(previous == NULL){ free_all_lines(new_queue->index.next); free(new_queue); return NULL; } } //Dequeue starts behind so it doesn't have to iterate through the whole list //on the first call new_queue->dequeue = new_queue->index.next; new_queue->enqueue = new_queue->dequeue->next; new_queue->count = 0; new_queue->line_capacity = capacity; return new_queue;}Queue *qu_allocate( void ){ return qu_allocate_custom( QU_DEFAULT_LINES, QU_DEFAULT_LINE_CAPACITY );}void qu_free(Queue *queue){ free_all_lines(queue->index.next); free(queue);}int qu_enqueue( Queue *queue, void *content ){ //First enqueue will check if the current line is full. if(queue->enqueue->end == queue->enqueue->position){ //If it is it will check if the next line if empty and go there if it is Line *next = next_line(queue, queue->enqueue); if(next != queue->dequeue) queue->enqueue = next; //If the next line is not empty, it will try to create a new line else { next = push_line_after(queue->enqueue, queue->line_capacity); if(next == NULL) return QU_ERROR; queue->enqueue = next; } } //Store, update position, update count *queue->enqueue->position++ = content; ++queue->count; return QU_SUCCESS;}/*Dequeue sets position back to zero when it starts working on a line. NULL also delimits the line end when enqueue is moved before the line is full (when dequeuetells it to move).*/void *qu_dequeue( Queue *queue ){ //If this line is empty if(queue->dequeue->end == queue->dequeue->position || *queue->dequeue->position == NULL){ //Check if there's something on the next line Line *next = next_line(queue, queue->dequeue); if(next->start == next->position) return NULL; //Finish here and go there queue->dequeue->position = queue->dequeue->start; queue->dequeue = next; //Move enqueue if it's on this new line if(queue->dequeue == queue->enqueue){ queue->enqueue = next_line(queue, queue->enqueue); //And add a delimiter if it's not full if(queue->dequeue->end != queue->dequeue->position) *queue->dequeue->position = NULL; } //Don't forget to set the position to 0 so it can be processed queue->dequeue->position = queue->dequeue->start; } //There's something to return --queue->count; return *queue->dequeue->position++; }//Since dequeue is always behind enqueue, all lines between enqueue and dequeue//must be empty and thus safe to freevoid qu_shrink_to_fit( Queue *queue ){ //First process all lines after enqueue Line *last = queue->enqueue; while(last->next != NULL){ if(last->next == queue->dequeue) return; free_line_after(last); } //Now process all starting lines behind dequeue last = &queue->index; while(last->next != queue->dequeue) free_line_after(last);}And some code to perform simple tests#include <stdio.h>#include queue.hint main(void){ Queue *queue = qu_allocate(); if(queue == NULL){ return 1; } char *words[] = { Highest Priority, High Priority, Almost High Priority, Regular Priority, Almost Low Priority, Low Priority, Lowest Priority, He who laughs last, laughs best., }; for(char **ite = words; **ite != '\0'; ++ite){ qu_enqueue(queue, *ite); } qu_enqueue(queue, About the middle.); printf(Count is: %zu\n, qu_get_count(queue)); qu_dequeue(queue); qu_dequeue(queue); printf(Count is: %zu after dequeuing 2 elements\n\n, qu_get_count(queue)); for(char **ite = words; **ite != '\0'; ++ite){ qu_enqueue(queue, *ite); } qu_enqueue(queue, Before last.); qu_enqueue(queue, Last.); qu_shrink_to_fit(queue); for(char *location; (location = qu_dequeue(queue)) != NULL;){ puts(location); } for(int i = 0; i < 500; ++i) qu_dequeue(queue); printf(Count is: %zu\n, qu_get_count(queue)); qu_free(queue); return 0;} | Queue implementation in C | c;queue | I did something very similar to this in assembly a looooong long time ago, so I'm going to compare and contrast for the sake of nostalgia. And helping you out, that too.The main difference in our top level designs is that I was storing values as elements of the Line, whereas you are storing void*. The reason I didn't always store void* was that it didn't require any additional memory management for consuming code by default. If I needed to do memory management separately, I could do that by making it a queue of pointers. In your code, you must either store pointers to static data or malloc and mfree each element separately. I see those two possibilities as a hazard in the case that the consumer doesn't yet know whether dynamic allocation is necessary, or worse, if void* to static data and void* to something on the heap have been mixed in the same Queue somehow. The end result will be an error (trying to mfree static data) or memory leaks (not mfreeing heap data). It's especially error prone because if you need to mfree, you have to do it soon after you dequeue it (possibly happening in many functions) or it leaks, so switching between static data and heap will be hazardous.On the other hand, believe me when I say you've avoided the following headaches by storing only void*:Destructors. You can handle disposal of the structure when it's dequeued or instead store that pointer elsewhere and not dispose of it in your consuming code. My ASM version had to be initialized with an optional pointer to a destructor function, yours leaves that up to the consumer.Lots of pointer math internally. It is waaaay simpler to allocate an array of a void* and come up with a pointer to element i than it is to allocate an array of arbitrary sized structures, which may need to have their element size adjusted for alignment, etc. etc.That would be a really tough thing to change, and ultimately a matter of documentation more than quality, so let's move on.The fact that your Queue involves a Line by value that doesn't have an accompanying buffer of elements is somewhat of a misuse of the structure. I can see where it looks like it might be necessary in order to have free_line_after and push_line_after take and/or return a Line*, but you can make those functions and the Queue structure simpler and clearer by eliminating the index from Queue. Instead:struct Queue { Line* enqueue; Line* dequeue; size_t count; size_t line_capacity;}static void free_line( Line** ppLine ) { Line* toFree = *ppLine; assert(toFree !== NULL); *ppLine = toFree->next; free(toFree);}// theoretically could make this return a bool indicating error/no error,// but it's easier to remember that NULL means error.static Line* push_line_before( Line** ppLine, size_t capacity ) { Line* before = *ppLine; Line* new_line = malloc(sizeof(Line) + capacity * sizeof(void **)); if (new_line == NULL) return NULL; new_line->next = before; *ppLine = new_line; /* do initialization the same way you did it... */ return new_line;}static void why_this_way_is_better(Queue* someQueue) { // Queue has no Line-valued member, and yet we can still use the same // functions for a Queue member... free_line( &(someQueue->dequeue) ); push_line_before( &(someQueue->enqueue) ); // ... as the ones for a line member free_line( &(someQueue->dequeue->next) ); push_line_before( &(someQueue->enqueue->next) );}Again, that will change a few things logically throughout your code and header, but it will end up far cleaner and clearer than it started. You've got pointers to pointers in C, an often underestimated advantage over other languages, and so far you're doing great with them. If you can handle using them for pointers to arrays of pointers, you can handle using pointers to members as objects.Other than that, the nature of the task demands a bunch of hairy pointer-chasing and a little bit of pointer math, which is tough to read. Stuff like return *queue->dequeue->position++; takes a second for me to digest fully. If your comments were at all lacking, I would want some of the longer statements to be broken up and have some intermediates made into local variables with names. However, your comments spell out what's going on very clearly, so I don't think that counts against you. |
_codereview.97775 | I have project where I will need to create lots of immutable strings. If I am using std::string, which has huge overhead - about 60-70% against const char *. On a 64-bit machine, the current implementation uses 8 bytes for the class + the const char * size. This is the same size as it would be with plain C.I will also do optimization with union and will put small strings into the pointer itself.I need to know if I am on right track.#include <stdio.h>#include <memory>#include <string.h>class String{public: String(){}; String(const char *s) : _data(__dup(s)){}; String(const String & other) : String( other.c_str() ){}; String(String && other) = default; String & operator=(String other){ std::swap(_data, other._data); return *this; } const char *c_str() const{ return _data.get(); } int cmp(const String & other) const{ if (c_str() == nullptr) return other ? -1 : 0; return strcmp(*this, other); } operator bool() const{ return c_str(); } operator const char *() const{ return c_str(); } bool operator == (const String & other) const{ return cmp(other) == 0; } bool operator != (const String & other) const{ return cmp(other) != 0; } bool operator > (const String & other) const{ return cmp(other) > 0; } bool operator >= (const String & other) const{ return cmp(other) >= 0; } bool operator < (const String & other) const{ return cmp(other) < 0; } bool operator <= (const String & other) const{ return cmp(other) <= 0; }private: static char *__dup(const char *s){ auto size = strlen(s); char *copy = new char[size]; memcpy(copy, s, size); return copy; }private: std::unique_ptr<char[]> _data;};void p(String &s){ printf(%s\n, s ? (const char *) s : [null]);}int main(){ String s1; p(s1); String s2 = { hello }; p(s2); String s3a = s2; p(s3a); String s3 = std::move(s3a); p(s3); s1 = s3; p(s1); s1 = hi; p(s1); String a = aaaa; String b = bbbb; String c = aaaa; printf(%s %s\n, a == c ? Y : N, Y); printf(%s %s\n, a == b ? Y : N, N); printf(%s %s\n, a != b ? Y : N, Y); printf(%s %s\n, a < b ? Y : N, Y); printf(%s %s\n, a > b ? Y : N, N); printf(%s %s\n, a <= b ? Y : N, Y); printf(%s %s\n, a >= b ? Y : N, N); printf(%s %s\n, a <= c ? Y : N, Y); printf(%s %s\n, a >= c ? Y : N, Y); return 0;} | Immutable C++ String class | c++;strings;c++11;immutability | DesignIn modern standard libraries, std::string uses short string optimization, which allows to avoid heap allocations at all for string shorter then ~20 chars (on 64-bit machines). So you really want to measure performance, I am not readily convinced that your string offers performance improvement. Of course, for your specific use pattern it might, but you have to measure.__dup functionThis is the most problematic part of the code.Apparently, you forgot to return value from __dup method (now fixed).You must allocate one char more and fill it with zero. Or copy size+1 characters from the source.Identifiers with leading double underscores or one leading underscore and a capital letter are reserved by the standard. You must not use such an identifier. It is enough that you already have put it into private section.After the corrections, the function could look like this:static char *dup(const char *s){ auto size = strlen(s); char *copy = new char[size + 1]; memcpy(copy, s, size + 1); return copy;}SafetyFunctions do not check for null pointers. This code will cause illegal memory access:String x;String y{x};StyleYou don't need semicolons after the member function definitionsI would recommend not putting methods on a single line even if they have empty bodies.You can use C++ style headers <cstring> and <cstdio> instead of C-style ones.I would recommend to implement an operator<<(std::ostream &, const String &) so you could use your string together with iostreams.For testing, it is better to use a testing framework. Like boost.test, gtest, Catch etc. |
_softwareengineering.232163 | The typical programming designing method that I've come to use goes like this:1. ID the problem and what's required2. Make your program do something simple3. Test it4. Make your program do a little bit more5. Repeat 2 until all the micro problems are solved by the program as a wholeBasically, incremental design. So, all the pieces can be split apart and each micro problem is solved by a micro problem function; does a great job with cohesion and reduces coupling.Then, sometime in the future, the program comes across a problem that is just like the problem it is built on, but requires a little extra. So, I'd say add the functionality to the program, to make up for it. If, when you're adding that functionality, the already established working logic has to be edited to make the new functionality work, it suddenly seems like you're messing with something you shouldn't. So, is there a designing method where every program developed with it can be added onto without compromising working logic?Example:word = yes,no,maybe,sooldCSVSplit(word, ,) -> {yes, no, \maybe, so\}newCSVSplit(word, ,) -> {yes, no, maybe,so};The oldCSVSplit function does what it should, split on ,. Then, sometime in the future, commas inside quotes must be ignored to properly get entries. Adding the functionality to ignore single/double quotes would severely alter the logic, with more ifs and checks and even a stack for keeping track of starting quotes. Is such a scenario avoidable? What method can make such additions painless and less compromising to working logic? | How to design to allow for future logic revision? | design | There's no way to guard against all changes in requirements. No matter how you design your code, there always exists a requirement that'll force you to alter the functionality. Attempting to foresee all the possible changes is futile and ill-adviced - you'll end up with over-generalized and over-abstracted code, paying an up-front cost of increased complexity without knowing for sure it's going to pay off later. Worse, since there's always a change your code isn't protected against, there's no limit to how far you can overengineer your code.The best you can do is code for the current set of requirements and adapt to change. If you keep your design modular, even if new additions require significant amounts of rework, you'll at least be fairly confident you're not inadvertently breaking completely unrelated functionality. Once you get burned by a particular kind of change, then you can make your code resistant to other changes of that same type. (If it happened once, there's a good chance it'll happen again.) |
_codereview.92122 | Here is the code that I wrote to give me sum of prime numbers between n and m:class TestClass { final static int MAX=1000000; final static boolean[] isPrime=isPrime(); public static void main(String args[] ) throws Exception { BufferedReader keyboard= new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(keyboard.readLine()); while(t>0 && t<=100){ String[] tempInt=keyboard.readLine().split( ); int n=Integer.parseInt(tempInt[0]); int m=Integer.parseInt(tempInt[1]); int sum=primeSum(n,m); System.out.println(sum); t--; } }private static int primeSum(int n, int m) { int sum=0; for(int i=n;i<=m;i++){ if(isPrime[i]){ sum=sum+i; } } return sum; } private static boolean[] isPrime(){ int maxFactor= (int)Math.sqrt(MAX); boolean[] isPrime=new boolean[MAX + 1]; int len=isPrime.length; Arrays.fill(isPrime,true); isPrime[0]=false; isPrime[1]=false; for(int i=0;i<=maxFactor;i++){ if(isPrime[i]){ for(int j=i+i;j<len;j+=i){ isPrime[j]=false; } } } return isPrime; }}Input:21 9999910000 99999Output:454396537448660141Now I'm trying to further optimize sieve by just taking odd number what usually in practice. Here is the optimized sieve function that I have written:private static boolean[] isPrime(){ int root=(int) Math.sqrt(MAX)+1; int limit=(MAX-1)/2; boolean[] isPrime=new boolean[limit]; Arrays.fill(isPrime, true); root = root/2 -1; for(int i = 0; i < root ; i++){ if(isPrime[i]){ for( int j = 2*i*(i+3)+3 , p = 2*i+3; j < limit ; j=j+p ){ isPrime[j]=false; } } } return isPrime;}Which I was able to do. I tested the above function till MAX=100. Here is the Ideone link.Test results: truetruetruefalsetruetruefalsetruetruefalsetruefalsefalsetruetruefalsefalsetruefalsetruetruefalsetruefalsefalsetruefalsefalsetruetruefalsefalsetruefalsetruetruefalsefalsetruefalsetruefalsefalsetruefalsefalsefalsetruefalsei.e 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 so on..Now what really bugging me is the indexing I did in primeSum() method for this optimized sieve:private static int primeSum(int n, int m) { int sum; if(n>0 && n<=2){ sum=2; }else sum=0; //System.out.println(sum); for( int i = (n-3)/2; i <= (m-3)/2 ; i++){ if(isPrime[i]){ //System.out.println(i); sum=sum+2*i+3; } } return sum; }But obviously, this indexing of n is failing for n<3, so I have to do this to get this code working:if(n>0 && n<=2){ sum=2; n=n+2; }But then it still fails for the cases when I've to find it between ranges:1 21 12 2So should I again include these cases and deal with it separately like this?private static int primeSumInRange(int n, int m) { int sum; if(m ==1) return 0; if(n<=2){ sum=2; n=n+2; }else sum=0; if(m>2){ for( int i = (n-3)/2; i <= (m-3)/2 ; i++){ if(isPrime[i]){ sum=sum+2*i+3; } } } return sum; }Is my way of doing the indexing i in primeSum() method proper? Or can I improve it? What are the other possible way of indexing here? | Sum of primes between two number from optimized Sieve of Eratosthenes | java;performance;primes;sieve of eratosthenes | What you did is called Sieve of Sundaram and saves half the memory. You can save factor 8 if you use a BitSet (or implement it manually e.g. using a long[]). For small numbers it costs some time, but for big numbers it may be faster when random access is involved (less memory means that more fits in cache). When dealing with really big primes, you want both optimizations.private static boolean[] isPrime(){ int root=(int) Math.sqrt(MAX)+1; int limit=(MAX-1)/2; boolean[] isPrime=new boolean[limit]; Arrays.fill(isPrime, true); root = root/2 -1;You really shouldn't do things like this. The problem is already confusing by the fact that you start with a number but work with an index which is half as big (and rounded down and in your case I guess additionally decremented). It's much better to use one variable for one thing. for(int i = 0; i < root ; i++){ if(isPrime[i]){ for( int j = 2*i*(i+3)+3 , p = 2*i+3; j < limit ; j=j+p ){Is it correct? How do you know that you should iterate exactly up to root? Why 2*i*(i+3)+3? The first value to cross out is usually p*p, which you need to transform to index.I wouldn't use the p = 2*i+3 formula. When compared to p = 2*i+1, you save one bit, bit it gets even more confusing.What about something likeint numberToIndex(int oddNumber) { // Asserts cost nothing unless switched on. assert (oddNumber & 1) == 1; // The right shift is just a faster division by 2 return oddNumber >> 1;}int indexToNumber(int index) { return 2 * index + 1;}? By using these functions, you could make it nearly readable. truetruetruefalsetruetruefalsetruetruefalsetruefalsefalsetruetruefalsefalsetruefalsetruetruefalsetruefalsefalsetruefalsefalsetruetruefalsefalsetruefalsetruetruefalsefalsetruefalsetruefalsefalsetruefalsefalsefalsetruefalseCan you read it? Do you want to read it? Maybe you should write a formatting method and get something like3, 5, 7, -9, 11, 13, -15where the negatives denotes non-primes (or leave them out or whatever debugging output suits you). In any case you should write a test, so that you don't have to look at the output every time you change anything. You can test some probes likeassertTrue(isPrime(127));assertFalse(isPrime(129));and test some small primes in loop (and get the expected value using some trivial method). Finally, you can verify that there are 105_097_565 primes which fits in int.I wouldn't call the array isPrime as isPrime[0] must be false as 0 is no prime. So let's call it isPrimeIndex.Now what really bugging me is the indexing i did in primeSum() method for this optimized sieveSure, the 2 needs a special handling and then you should make sure that m and n are odd. I guess that you code is wrong and I'd try something like this instead:private static int primeSum(int n, int m) { if (m < 2) { return 0; // no primes below 2 } if (n < 2) { n = 2; // no primes below 2 } // Add 2 if in range. int sum = n <= 2 && 2 <= m ? 2 : 0; // Round up to next odd in a very hacky way. n += ~n & 1; // Round down to next odd. m -= ~m & 1; for (int i = numberToIndex(n), p = n; i<=numberToIndex(m); ++i, p+=2) { sum += isPrimeIndex[i] ? p : 0; }}How does my hacky rounding work: If n is odd, then ~n is even and ~n & 1 is 0, so nothing changes. If n is even, then ~n is odd and ~n & 1 is 1, so n gets incremented. You could use something like n += (n % 2) == 0 ? 1 : 0 which is equivalent (but slower) or whatever suits you.So should i again include these cases and deal with it separately ? like thisMy strategy is to handle special cases upfront (here: deal with the two) and normalize everything ASAP (here: ensure that m and n are odd). This tends to make things simple. |
_unix.251584 | The digital clock of GNOME I am referring to is indicated in this screenshot:This is the advanced custom format I would like GNOME's digital clock to have:%l:%M:%S %p %A, %e %B %Yat the moment this format would be:1:05:10 pm Saturday, 26 December 2015if to get this custom format I would need to install an extra extension, I am willing to, please just tell me the name of the extension I would need and how to install it. | How do I adjust the format of GNOME's digital clock to an advanced custom format? | gnome;clock;gnome panel | null |
_unix.73787 | In my process list under Ubuntu (using top/System Monitor) one of the largest memory hogs (200+Mb) was python. I searched a bit for one of my programs to be the cause until I realised this was my Python IDE (Wing), which itself is written in Python.I thought I could change the name of the program by inserting setproctitle from the setproctitle package, but the python version that Wing is using is different from my own. setproctitle needs to be compiled and the python that wing uses is not a full installation (I asked Wing Support but they are unlikely to change that/incorporate setproctitle).setproctitle can only change the name of the running process, so I could not make a script that starts Wing and then change the process name either.After that I tried to write to /proc/PIDNUM/comm, but although that 'file' is 'rw', I am not allowed to write there.I finally found a, not-so-portable, solution for this particular case. But I would like to know if there is a standard way of changing the process name of another (possible a child-) process with a Linux system call. | How can you change the process name of Wing IDE from python to something more descriptive | process;python;system calls | A process can only write to its own /proc/pid/comm. So since it sounds like you can modify the IDE's code, you can just have it write to /proc/self/comm.Another option would be to change the name of its Python executable, and then change all the #! lines, but that may be a PITA.Othermore painfuloptions would be writing some C code and using LD_PRELOAD or ptrace. |
_unix.322562 | How to switch the user and to pass the password along in Groovy script? As I am working in Jenkins Pipeline plugin, wanted to execute some commands with root privilege, but default user is jenkins.Code is:node { sh whoami }Output is:[test_cdpipeline] Running shell script+ whoamijenkins | How to switch the user and to pass the password along in Groovy script? | jenkins | null |
_webmaster.25874 | I don't know if this is the write forum to post this on... If it's not sorry to bother you!I'm going to need to get into a server which can accept ~x users; however, ~2*x users will be trying to get in. So maybe, ~30 spaces on the server are avaliable, with ~60 users trying to get in. In order to get in, you have to keep reloading/refreshing the page.I was wondering, do I increase my chances of getting in if I open multiple browsers, and set them to reload the page every second? i.e. would attempting to get in on multiple browsers (on the same network) increase my chances?Also, are there any ways to increase my chances? For example, are there way to tell the server that my packets are priority or something?By the way, I know some PHP/HTML/CSS/C++ if that makes a difference.Thanks. | Access Populated server | webserver;firefox | null |
_opensource.156 | Is there a way to analyze my code I want to release as opensource to see if it is / or has parts that are already licensed or proprietary? | How can I determine if some code I want to release as opensource is already licensed or proprietary? | licensing;proprietary code | Yes, there are (paid) services such as Black Duck or Open Logic that will audit your code, and report all of the licensed pieces of software found.They will even find snippets in your code which are copy/pasted or too closely resemble snippets found on the internet which are shared with an unfavorable license. |
_unix.180528 | I have text file including text format like this. 012345,[ThinkPadT2/3Gband,Mac],Lenovo,iPhone3G,A1241How do i replace comma inside words only within double quote by pipe(|) operator using sed. I need output like this :012345,[ThinkPadT2/3Gband | Mac],Lenovo,iPhone3G|A1241 | how to replace a character within in a multiple double quoted words within a line using sed? | text processing;sed | null |
_codereview.112583 | I have some questions on how I can improve this add action (method) in controller:I'm using the add action only if post request. Is it correct?This action doesn't have views ($this->autoRender = false;). Is it correct?I set a response .json file to this action but I didn't change on routes to routing .json files (the file will be return when access localhost:8765/users/add). Is it correct?I'm using Enums(handmade) to store messages that will returned to user. Is it correct?I'm using an object to store the fields of message (that will returned to user), that object will be serialized and returned like this:$this->response->body(json_encode($response));Is it correct?Controller code:public function login(){ $this->autoRender = false; $this->response->type('json'); if ($this->request->is('post')) { $user = $this->Auth->identify(); if ($user) { $this->Auth->setUser($user); $response = new ResponseMessage(); $response->code = CodeEnum::LOGIN_GRANTED; $response->name = NameEnum::LOGIN_GRANTED; $response->type = TypeMessageEnum::SUCCESS; $this->response->body(json_encode($response)); }else { $response = new ResponseMessage(); $response->code = CodeEnum::LOGIN_DENIED; $response->name = NameEnum::LOGIN_DENIED; $response->message = MessageEnum::USER_PASS_INCORRECT; $response->type = TypeMessageEnum::ERROR; $this->response->body(json_encode($response)); } }} | CakePHP login action returning json | php;json;authentication;cakephp | If you have another point to improve, please comment or answer, I will change the accepted answerTo put in CakePHP pattern I remove both lines:$this->autoRender = false;$this->response->type('json');and change how I create and return the JSON file change this:$this->response->body(json_encode($response));to this:$this->set('response', $response);$this->set('_serialize', 'response');the result:public function login(){ if ($this->request->is('post')) { $user = $this->Auth->identify(); if ($user) { $this->Auth->setUser($user); $response = new ResponseMessage(); $response->code = CodeEnum::LOGIN_GRANTED; $response->name = NameEnum::LOGIN_GRANTED; $response->type = TypeMessageEnum::SUCCESS; $this->set('response', $response); $this->set('_serialize', 'response'); }else { $response = new ResponseMessage(); $response->code = CodeEnum::LOGIN_DENIED; $response->name = NameEnum::LOGIN_DENIED; $response->message = MessageEnum::USER_PASS_INCORRECT; $response->type = TypeMessageEnum::ERROR; $this->set('response', $response); $this->set('_serialize', 'response'); } }} |
_codereview.75670 | I have XML below which is stored as a String in xmlData variable and I need to pass this String to my URL in client_data variable and then execute the URL:<?xml version=1.0?><ClientDataxmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xsi:schemaLocation=http://www.google.com model.xsd xmlns=http://www.google.com> <client id=100> <clock> <for> <etc>val(tery) = 1</etc> <while><![CDATA[val(tery) < 20]]></while> </for> </clock> </model></ClientData>Below is the URL I am hitting on the browser by URL encoding client_data value manually to get the response back and it works fine through browser -http://localhost:8080/test_tmp?max_time=30&users=1000&client_data=<?xml version=1.0?><ClientDataxmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xsi:schemaLocation=http://www.google.com model.xsd xmlns=http://www.google.com> <client id=100> <clock> <for> <etc>val(tery) = 1</etc> <while><![CDATA[val(tery) < 20]]></while> </for> </clock> </model></ClientData>Now I have started using Apache HttpClient to execute the URL and I have got below code which is working fine -Using Apache HttpClient This code works fine and I am able to get the response back. I am getting JSON response back as a string which is expected.public static void main(String[] args) { for(int i= 1; i<=100; i++) { // this will return xml as a string String xmlData = getXMLData(i); String url = generateURL(xmlData); // do I need to create this everytime for each call? HttpClient httpclient = HttpClientBuilder.create().build(); HttpGet request = new HttpGet(url); StringBuilder response = new StringBuilder(); try { HttpResponse httpResponse = httpclient.execute(request); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); String phrase = statusLine.toString(); if (statusCode == HttpStatus.OK.value()) { BufferedReader rd = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent())); String line = ; while ((line = rd.readLine()) != null) { response.append(line); } } } catch (ClientProtocolException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } // prints response System.out.println(response.toString()); // and then I am serializing json response here to my POJO if it not null }}private static String generateURL(final String clientData) { StringBuilder url = new StringBuilder(); url.append(http://localhost:8080/test_tmp?max_time=30&users=1000&client_data=); url.append(URLEncoder.encode(clientData, UTF-8)); return url.toString();}I am opting for code review to see whether there is any better way to execute the URL efficiently using Apache HttpClient or if there is any way to simplify the above code. | Executing URL using Apache HttpClient | java;optimization;xml;http;url | EfficiencyIn response to// do I need to create this everytime for each call?HttpClient httpclient = HttpClientBuilder.create().build();Then no. The construction doesn't take any parameter, so it's independent from the loop and you can initialize only once before the loop. And although the javadoc for those methods is empty, by the looks of .create().build() I'd say that it's not a cheap instantiation.SimplificationYou can save some lines by using IOUtils to read the content from the response, as explained in this answer.ReadabilityYour function is a bit too long. You can probably divide it into smaller functions. I would start extracting the try/catch block into a readResponse() method.MiscellaneousThisHttpStatus.OK.value()is from Spring. There's nothing wrong with it, but since you're using an Apache library, why don't you use HttpStatus from the Apache library? |
_unix.38685 | Can anyone help me explain this?Just installed a fresh copy of Linux Mint 12 downloaded from their website only a few days ago. They claim that it uses Gnome 3 but gnome-about says it is Gnome 2. | Linux Mint 12 claims to come with Gnome 3 but gnome-about says it is Gnome 2 | gnome;linux mint;gnome3 | null |
_hardwarecs.7857 | so basically I've gotten the chance to build a computer that has a budget of $2,000 to $7,000. But I just don't know anything about computers. See I'm in dire need for an upgrade from my current MacBook Pro, and this is because I work using the 3D Animation program known as Blender. I need a PC that renders animations in Blender extremely fast, both Cycles and Internal. I also want to use this computer for gaming. I won't keep too many games on it, I for the most part want to just run Dolphin Emulator on it and maybe a few other PC games, but I need to know what I need in order to build this computer that would be within my budget. I don't know anything, nothing about CPU, GPU, nothing. I want to get a high quality monitor, 4K or higher, a good keyboard which I can probably choose on my own, and uh yeah that's pretty much it. Here are the specs for my recent MacBook Pro:Processor - 2.3 GHz Intel Core i7Memory - 16 GB 1600 MHz DDR3Graphics - NVIDIA GeForce GT 750M 2048 MB Intel Iris Pro 1536 MBSo my sister got her computer built and i want to follow the same steps she did which was getting all the information and then buying the parts needed, and then going to Fries Electronic so I can get it built. Again, not sure about what all that info is and I don't know if this is possible but I heard that you can have multiple graphic cards in the computer for very good improvement, if anyone can explain to me what I need (but act like you're talking to a 5 year old) then I'd be all set. Anyways, thanks! | I need a really good computer that I can get built for Blender 3D rendering and gaming | graphics cards;gaming;motherboard;monitors | null |
_vi.9308 | The question is somewhat straightforward. To open a vertical split, I use: :vs. When opening a vertical split, I'd like to initialize it with a file directly.If I do :vs myfile.txt this will move the file I am currently working on to the right and open myfile.txt on the left of the split.Rather, I would like the opposite to happen: the file I am working on before the vertical split stays on the left, and myfile.txt opens on the right of the split. | How to change the location of a new vertical split? | split | You should use::botright vsp myFile.txtSee :h botright:Execute {cmd}. If it contains a command that splits a window, it will appear at the bottom and occupy the full width of the Vim window. When the split is vertical the window appears at the far right and occupies the full height of the Vim window.EDIT Credit goes to ingo for this one:You can make botright the default behavior by using the splitright option in your vimrc. In this configuration topleft can be used to open a split on the left. |
_unix.155498 | In each folder I find a hidden file called .DS_store? What is this exactly? | In Mac Os, what is .DS_store? | files;filesystems;osx | null |
_webapps.107252 | What is the easiest way to determine if I am uploading duplicate photos in Google Photos?Is there an option or setting maybe to notify me? | What is the easiest way to determine if I am uploading duplicate photos in Google Photos? | google photos;duplicate | null |
_softwareengineering.255335 | We have a use case where we store table-like data, but we know about the schema of the data only at runtime. In our application, a power user defines a schema and normal user can create records and make relations between those records. The problem that we are having is that when doing complex queries over the related tables (one could say, joins) with filtering and sorting, stuff becomes slow, which is logical. To give an example.Lets say we have an article table with 1M rows and supplier table with 500 rows. Some suppliers have 50K articles. Now lets say I want to get all the articles from that supplier, but sorted by the article name. This query is slow. Which is not strange as it basically creates some sort of temporary table/result, which it needs to sort, but it cannot do it fast as there is no index on a temporary table/result. Our current solution uses Neo4j, but I also tried this on orientdb and in both cases queries are slow, because of the same behavior.Now we have solved this problem for now by creating indexes at runtime based on the schema the user provided, denormalizing articles and suppliers in one index. The problem is that keeping this index up-to-date is very cumbersome. Lets say we want to filter on the articles table on its supplier name. Now the supplier name is in the index, but it has been replicated 50K times in the above example. So if the user changes the name of the supplier, 50K index records need to be updated. Giving us all sorts of performance headaches and timing issues such as what happends if the user in a couple of seconds changes the supplier name twice, we need to queue the operations. Etc etc. So my actual question, is there a clean, non-cumbersome way to automatically denormalize or index out of the box, for a system where the DB schema can change at run-time? | Automatic denormalization for a NoSQL database application | database;data structures;nosql | null |
_codereview.110600 | I'm an 'old school' programmer (C, C++), and I have step-by-step, algorithmic thinking. I'm writing some code in Angular + Django and I know that this code is ugly but I don't have any idea how to refactor it.First of all, I have the models:class Product(models.Model): name = models.CharField(max_length=100) status = models.CharField(max_length=10, choices=STATUSES.items(), default='new')class Ad(models.Model): image = models.ImageField(upload_to=ad) width = models.IntegerField(blank=True) height = models.IntegerField(blank=True) product = models.ForeignKey(Product, null=True, blank=True)class AdStatus(models.Model): status = models.IntegerField(default=1) ad = models.ForeignKey(Ad)Next I have simple classes for serializing:class AdSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Ad fields = [url, id, image, width, height. product]#etc...And every model has its own factory in Angular: .factory('AdStatus',[$resource, function ($resource){ var Resource = $resource( /api/ad_status/:ad_id/, {ad_id: '@id'}, { query: { isArray: true, transformResponse: function (data) { var items = angular.fromJson(data); return items.results; } }, update: { method: PUT, } }, { stripTrailingSlashes: false } ); Resource.prototype.changeStatus = function(status){ this.status = status; this.$update(); }; return Resource; }])/etcThis is the main code://controller isn't badangular.module('controllers.statuses', []).controller('StatusCtr', [$scope, $stateParams, StatusSetter, function($scope, $stateParams, StatusSetter) { $scope.click = function(){ $scope.t = StatusSetter.change($stateParams.id);// this is id of product };}]);But this makes me a little sick:.factory('StatusSetter', [AdStatus, Product, Ad, function(AdStatus, Product, Ad){ var changeStatus = function(id, productStatus, adStatus){ var product = Product.get({product_id: id}); product.$promise.then(function(data) { product.changeStatus(productStatus); var ads = Ad.query(); var ad_status = AdStatus.query(); var tmp = []; ads.$promise.then(function(data){ for (var i = 0; i < ads.length; i++) { if (ads[i].product == product.url){ tmp.push(ads[i]); } } ad_status.$promise.then(function(data){ for (var i = 0; i < ad_status.length; i++){ for (var j = 0; j < tmp.length; j++){ if (ad_status[i].ad == tmp[j].url){ ad_status[i].changeStatus(adStatus); } } } }) }); }); return product; }; return { change: function(id){ return changeStatus(id, new_status, 30); } } }])The main philosophy of this code is:change AdStatuses which points at Ads (which points at Products)Any ideas? Maybe I can separate this 'filtering' to $resource or something. | Ad filtering in Angular factory | javascript;beginner;angular.js;django | null |
_codereview.31664 | I want you to pick my code apart and give me some feedback on how I could make it better or simpler. For a full tree (all nodes with 0 or 2 children) it works deterministically:public class Construct { private TreeNode root; private static class TreeNode { TreeNode left; TreeNode right; int item; public TreeNode(TreeNode left, TreeNode right, int item) { this.left = left; this.right = right; this.item = item; } } public void treeFromPreOrderAndInorder(int[] pre, int[] inorder) { if (pre == null || inorder == null) { throw new IllegalArgumentException(Your tree is not accurate); } if (pre.length != inorder.length) { throw new IllegalArgumentException(Your tree is not accurate); } // should this be overloaded + testing. root = treeFromPreOrderAndInorder(pre, 0, inorder, 0, inorder.length - 1); } /** * Private functions are not overloaded. * Check binary0. */ private TreeNode treeFromPreOrderAndInorder(int[] pre, int pos, int[] inorder, int lb, int hb) { if (lb > hb) return null; // step 1: fetch parent int parent = pre[pos]; // step 2: fetch position int parentPosInorder; for (parentPosInorder = lb; parentPosInorder <= hb; parentPosInorder++) { if (inorder[parentPosInorder] == parent) { break; } } if (parentPosInorder > hb) { throw new IllegalArgumentException(Your tree is not accurate); } // proof in diagram : https://bitbucket.org/ameyapatil/pointstonote/commits/a3137e1e5c9f40f28c53b9c62e27f0e8bf81a000 int numElemsInLeftSubTree = parentPosInorder - lb; /** * Basically absolutely same as construct Balanced BST from sorted array * with this extra junk to be added. */ int leftParentPosPre = pos + 1; // proof in diagram : https://bitbucket.org/ameyapatil/pointstonote/commits/458d044f96226e8df1c47775dbe3c8c5ad9ecce4 int rightParentPosPre = pos + numElemsInLeftSubTree + 1; // step 3: recurse TreeNode node = new TreeNode(null, null, parent); node.left = treeFromPreOrderAndInorder(pre, leftParentPosPre, inorder, lb, parentPosInorder - 1); node.right = treeFromPreOrderAndInorder(pre, rightParentPosPre, inorder, parentPosInorder + 1, hb); return node; } | Construct a tree given pre and inorder or post and inorder | java;algorithm;recursion;tree | null |
_unix.121026 | Following data needs to be sorted respecting the locale sort order:wirdsinwrpchewarberUberpchpeachThere was nor problem by using sort$ sort < datapeachpchepchsinUberberwarwrwirdwhich respects the locale, and $ LC_ALL=C sort < dataUberpeachpchpchesinwarwirdwrberwithout locale.Now I tried to do so with perl, but I'm failed:$ perl -e 'local $/ = undef; print sort <>;' < databerpchewarpchsinUberpeachwrwirdThe result is either the first output of sort, nor the second.Running Ubuntu 12.04 LTS | Sorting with Perl respecting Locale Settings | perl;sort;locale | The problem is local $/ = undef. It causes perl to read entire file in to @ARGV array, meaning it contains only one element, so sort can not sort it (because you are sorting an array with only one element). I expect the output must be the same with your beginning data (I also use Ubuntu 12.04 LTS, perl version 5.14.2:$ perl -le 'local $/ = undef;print ++$i for <>' < cat1$ perl -le 'print ++$i for <>' < cat123456789If you remove local $/ = undef, perl sort will proceduce same output with the shell sort with LC_ALL=C:$ perl -e 'print sort <>' < dataUberpeachpchpchesinwarwirdwrberNoteWithout use locale, perl ignores your current locale settings. Perl comparison operators (lt, le, cmp, ge, and gt) use LC_COLLATE (when LC_ALL absented), and sort is also effected because it use cmp by default.You can get current LC_COLLATE value:$ perl -MPOSIX=setlocale -le 'print setlocale(LC_COLLATE)'en_US.UTF-8 |
_softwareengineering.264190 | Consider an^2 + bn + c. I understand that for large n, bn and c become insignificant.I also understand that for large n, the differences between 2n^2 and n^2 are pretty insignificant compared to the differences between, say n^2 and n*log(n).However, there is still an order of 2 difference between 2n^2 and n^2. Does this matter in practice? Or do people just think about algorithms without coefficients? Why? | Algorithm Analysis: In practice, do coefficients of higher order terms matter? | algorithms;algorithm analysis | null |
_unix.331904 | I have a process that runs under a nologin user (in this case Tomcat server).I would like to execute some shell commands from that process but most of them are not available apart from standard utilities like ls, date etc...In my particular case I want to use some scripts that are available in /usr/local and for normal login users it's enough to just source an init script in .bashrcsource for nologin users doesn't seem to be working as well as the . operator. I've tried adding the necessary lines to /etc/profile or /etc/bash.bashrc but that also doesn't work. Is there any other way than just copying the binaries into /bin ? I'm using Ubuntu 14.04 right now. | Executing commands from a process running under a nologin user | bash;nologin | null |
_unix.369822 | when i use nmap without sudo it show me the ports are open as nmap 192.168.1.5Host is up (0.00091s latency).Not shown: 995 filtered portsPORT STATE SERVICE80/tcp open http110/tcp open pop3143/tcp open imap993/tcp open imaps995/tcp open pop3sNmap done: 1 IP address (1 host up) scanned in 7.52 secondsbut when i use sudo before the command it show me sudo nmap 192.168.1.5Nmap scan report for 192.168.1.5Host is up (0.00025s latency).All 1000 scanned ports on 192.168.1.5 are filteredMAC Address: 08:00:27:02:14:55 (Oracle VirtualBox virtual NIC)Nmap done: 1 IP address (1 host up) scanned in 29.23 secondsso my question why the result changed and why i can't get the mac without sudomy host is macos | nmap show me differert result on the same machine | osx;nmap | null |
_softwareengineering.275578 | I am building a news app. In phone mode it should have a navigation drawer which slides out when you tap on a hamburger button or slide your finger. That navigation drawer has a fragment with static list in it.While in a tablet mode, when you rotate the screen to landscape, that fragment with the list would be permanently visible. What is the general approach to developing these kinds of apps?If I decide to make a separate layout for the tablet landscape mode without a DrawerLayout, it would probably cause an error because the Navigation Drawer fragment class is referring to a DrawerLayout in XML, and if I decide to have DrawerLayout in tablet-landscape mode and call the openDrawer method every time I rotate the screen to the landscape mode, it would overlay the main content.How should I handle it? | Building a news app for both phones and tablets | android;android development | Every time you rotate the phone, current activity is re-created. That is, onCreate() is called. Just determine whether or the device is a) Tablet / Smartphone https://stackoverflow.com/questions/9279111/determine-if-the-device-is-a-smartphone-or-tabletb) Portrait / Landscape https://stackoverflow.com/questions/3674933/find-out-if-android-device-is-portrait-or-landscape-for-normal-usageOnly after determining this should you call setContentView().Depending on the situation, inflate activity with the appropriate layout.In your case, when in landscape mode in a tablet, inflate with a layout that does not use DrawerLayout and don't expect DrawerLayout (in the corresponding Java code) because you don't need it. The required layout should just have the fragment containing the list at its left side. |
_unix.34963 | I created a small script backup_files.sh and placed it in /etc/init.d:#/bin/shlogfile=/media/verbatim/logdate >> $logfilersync -av /home/philipp/Documents /media/verbatim/ >> $logfileI would like this script to be executed whenever the computer is rebooted or shut down, so I did the following:sudo ln -s /etc/init.d/backup_files.sh /etc/rc0.d/backup_files.shsudo ln -s /etc/init.d/backup_files.sh /etc/rc6.d/backup_files.shMoreover, I made the script executable:sudo chmod +x /etc/init.d/backup_files.shI tried the script manually and it worked just fine. However, if I shutdown or reboot my computer, it is apparently not executed.Does anybody see what I'm doing wrong?Note: I'm using Xubuntu 11.10. | Running script before shutdown seemingly not working | ubuntu;init script;sysvinit | Finally found out that I had to give them particular file names:sudo ln -s /etc/init.d/backup_files.sh /etc/rc0.d/K10backup_files.shsudo ln -s /etc/init.d/backup_files.sh /etc/rc6.d/K10backup_files.shThe scripts in /etc/rc0.d and /etc/rc6.d are executed at the time of shutdown and reboot respectively. The scripts with their name starting with capital k are executed with an argument stop while those starting with capital S are executed with argument start. Moreover the execution of files is done in lexicographical order.The files in these runlevels are named as:[K | S] + nn + [string]nn -> a two digit numberstring -> must be a lowercase stringMore about linux runlevels can be found here |
_unix.246425 | It is reported that one of my linux vm is cpu overloaded on some previous time. What is the standard procedure to diagnose that which process or user causes the cpu overload? | How to find root cause of NetIq Overall CPU overloaded in Linux | linux | null |
_webapps.8524 | I'm a user of Google Apps for receiving my email in. My inbox is the Catch all for my domain which is very convenient in the way I would like to use it.In some special cases I would like to bounce an email that is sent to me with an indication of no such email address. Is there a way (plugin?) to do that from the Google Apps interface? | Bouncing emails from Google Apps (Gmail)? | email;google apps;email bounces | My suggestion: create a [email protected] account, and suspend it. Later, add as many aliases as needed for that account.Worked like a charm for me, with the following return message:Delivery to the following recipient failed permanently:[email protected] details of permanent failure: Google tried to deliver your message, but it was rejected by the recipient domain. We recommend contacting the other email provider for further information about the cause of this error. The error that the other server returned was: 550 550 5.2.1 The email account that you tried to reach is disabled. o68si156962yhm.44 (state 14).Only problem with that is o68si156962yhm.44 if googled leads you right to this page.... |
_unix.147296 | We have a startup script that is symbolicly linked to /etc/rc0.d/K01ourapp. Apparently, it is not working as expected during shutdown.The script actually does a few echo calls that may help in troubleshooting. Where does that output get logged (if anywhere)?I am using RHEL5. | If a start-up script in `init.d` has standard output, where is that logged if anywhere? | rhel;logs;init script | Strings sent to the standard output go to /dev/console (most often you can see them on your screen, but not always). To log these messages, you can use bootlogd, which, as described in its man page, runs in the background and copies all strings sent to the /dev/console device to a logfile, and the default logfile is /var/log/boot. |
_webmaster.20105 | I'm using FeedBurner as the public-facing feed for the Ask Different Podcast. Recently Stack Exchange has set up a Blog Overflow blog for Ask Different, and I'd like to move the source of the FeedBurner feed from an unofficial WordPress instance we set up to the official blog.However, when I tested this a few days ago with a test account I found that once the feed switched over iTunes thought that the podcasts were all brand new. I want to avoid annoying our subscribers and make the move silently and transparently behind the scenes.How does iTunes determine whether an RSS item is the same as one it already has?Is there a way in WordPress to modify this information? | Migrating the source of a FeedBurner podcast feed from one WordPress to another | rss;wordpress;feedburner | OPTION 1: You could set the URLs of your existing posts on the new WordPress blog to point to the locations on the old WordPress blog, using the linked list plugin. This modifies the permalinks used in the updated feed so that they match those in the old feed; iTunes shouldn't see them as new items.OPTION 2:You could set the FeedBurner feed to use a filtered version of the new WordPress feed that displays only new posts. Here's how:On the new WordPress blog:Create a category called 'old' (or similar).Note the category ID, which can be obtained by browsing to Posts > Categories, then clicking the category you created, and looking for &tag_ID=4 in your browser's address bar.Set all of your old posts to use the 'old' category.In the FeedBurner admin area:Set http://yournewURL.com/?cat=-99&feed=rss2 as the 'Original Feed' address. Replace the 99 with the category ID you noted in step two above, and be sure to include the minus sign before it. This creates a feed that excludes all posts in the 'old' category.iTunes should now see only new episodes that you publish, not older ones. One caveat is that new subscribers won't see anything at all until you next publish something. It's up to you to decide if this is better or worse than old subscribers having to redownload episodes they've already listened to. (I'd suggest that it's slightly better if you have a lot of subscribers, especially if you consider that the feed will soon fill up after you've published a few new episodes.) |
_unix.72176 | With passwd -S user_name one can find out, if an account is locked, but is there a way to find out when it was locked and who it locked?Further links:https://serverfault.com/a/485760/78439Disable a user's login without disabling the account | How to find out out WHEN an user account was locked | security;login;accounts | null |
_unix.387890 | I'm working a lot with netcat recently to test a server, and having use of the up arrow to repeat previous commands would be extremely helpful. Right now however, it only enters ^[[A. Is there any way I can change this behavior? | Using up arrow to get previous command in netcat | netcat | null |
_codereview.173101 | I was working on the USACO problem arithmetic progression.You can see the problem (and a solution) here - http://massivealgorithms.blogspot.com/2015/08/arithmeticprogressions-codetrick.htmlMy code successfully runs for the first 7 test cases. However, once it reaches test case 8 (22,250) it times out.What modifications should I make to make my code more efficent? Most solutions I found online were also o(m^2*n) complexity, so I'm not sure what I need to change.Here is my code: //#include stdafx.h #include <iostream> #include <fstream> #include <string> #include <algorithm> #include <vector> using namespace std;int main(){ ofstream fout(ariprog.out); ifstream fin(ariprog.in); int n, m; fin >> n >> m; int bisquare[125001] = {}; for (int a = 0; a <= m; a++) { for (int b = a; b <= m; b++) { bisquare[(a*a) + (b*b)] = 1; } } int max = 2 * m*m; int value; bool tb = false; pair<int, int> all[125001]; int yeah = 0; for (int s = 0; s <= max/2; s++) { for (int i = 1;i<=max/2; i++) { for (int x = 0; x < n; x++) { value = s + x*i; if (value > max) { tb = true; break; } if (!bisquare[value]) break; if (bisquare[value] && x==n-1) { all[yeah] = make_pair(i,s); yeah++; } } if (tb) { tb = false; break; } } } sort(all,all+yeah); for (int i = 0; i < yeah; i++) { fout << all[i].second << << all[i].first << endl; } if (all[0].first == 0) { fout << NONE << endl; }} | USACOs Arithmetic Progression | c++;programming challenge;time limit exceeded | null |
_webmaster.34617 | When the googlebot visits our sites it seemingly tries to visit urls that do not exist resulting in exception being thrown. The url is is like http://ourdomain/thepage.aspx/x/8/x/ etc.x stands for no value in our application. It seems like googlebot seems which parameters it can use, because the urls are no link from the page.Is there any way to control this behaviour? | How do I stop googlebot from guessing urls parameters | google;search engines;google search | null |
_codereview.167264 | This is code for a simple calculator. Can someone review it, so I can know if there is something wrong? I also want to know if I can link a keybinding to a JButton so I don't have to write an actionlistner for a JButton enterBut. I already tested it several times and it works fine.Also, someone told me yesterday that I shouldn't use a foreach loop to assign a value to my null Button array, and instead I need to use a for loop. Can someone explain why? Also, if there is a way to get rid all of the if statements in the calculate method, please tell me.import java.awt.BorderLayout;import java.awt.Dimension;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import javax.swing.AbstractAction;import javax.swing.ActionMap;import javax.swing.InputMap;import javax.swing.JButton;import javax.swing.JComponent;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.JTextField;import javax.swing.KeyStroke;class Window6 { private JFrame frame = new JFrame(); private JTextField screen = new JTextField(); private final String[] numberText = {7,8,9,4,5,6,1,2,3,0,.,c}; private final String[] functionText = {+, -, *, /}; private final JButton numberButton[] = new JButton[numberText.length]; private final JButton functionButton[] = new JButton[functionText.length]; private JButton equalBut = new JButton(=); private JPanel numberPanel = new JPanel(); private JPanel functionPanel = new JPanel(); private JPanel panel = new JPanel(); public Window6() { JPanel temp = new JPanel(); numberPanel.setLayout(new GridLayout(4,3)); functionPanel.setLayout(new GridLayout(2, 2)); int index = 0; for(JButton x : functionButton) { x = new JButton(); x.setText(functionText[index]); x.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JButton temp = (JButton)e.getSource(); screen.setText(screen.getText() + temp.getText()); } }); functionPanel.add(x); index++; } index =0; InputMap im = equalBut.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false), submit); ActionMap ap = equalBut.getActionMap(); ap.put(submit, new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { calculate(); } }); equalBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { calculate(); } }); for(JButton x : numberButton) { x = new JButton(); x.setText(numberText[index]); x.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JButton temp = (JButton)e.getSource(); if(!c.equals(temp.getText())) { screen.setText(screen.getText() + temp.getText()); } else { screen.setText(); } } }); numberPanel.add(x); index++; } temp.setLayout(new GridLayout(2, 1)); temp.add(this.functionPanel); temp.add(this.equalBut); screen.setPreferredSize(new Dimension(200,100)); frame.add(screen, BorderLayout.NORTH); panel.setLayout(new GridLayout(1,2)); panel.add(numberPanel); panel.add(temp); frame.add(panel, BorderLayout.CENTER); frame.setSize(300, 400); frame.setVisible(true); } private void calculate() { String str = screen.getText(); String number[] = str.split([+||\\-||*||/]); int index = number[0].length(); String sign = str.substring(index, index + 1); System.out.println(sign); if (-.equals(sign)) { try { float x = Float.parseFloat(number[0]); float y = Float.parseFloat(number[1]); screen.setText(String.valueOf(x - y)); } catch (Exception e){ screen.setText(Please enter numbers); } } else if (+.equals(sign)) { try { float x = Float.parseFloat(number[0]); float y = Float.parseFloat(number[1]); screen.setText(String.valueOf(x + y)); } catch (Exception e){ screen.setText(Please enter numbers); } } else if (*.equals(sign)) { try { float x = Float.parseFloat(number[0]); float y = Float.parseFloat(number[1]); screen.setText(String.valueOf(x * y)); } catch (Exception e){ screen.setText(Please enter numbers); } } else if (/.equals(sign)) { try { float x = Float.parseFloat(number[0]); float y = Float.parseFloat(number[1]); screen.setText(String.valueOf(x / y)); } catch (Exception e){ screen.setText(Please enter numbers); } } }}public class hw6 { public static void main(String args[]) { new Window6(); }} | Simple calculator about keybinding | java;beginner | Thank you for sharing your code![Is] there is a way to get rid all of the if statements in the calculate method?This program lags a clear MVC hierarchy. This results in a somwhat procedural approach in the calculate() where you mix business behavior with access to View elements.A proper OO approach would start with the function buttons. The actions they trigger have the same interface (2 numbers input, one number output). But each of them causes a different calculation aka different behavior. In OOP different behavior means different classes:interface CalculatorFunction{ float caculate(float a, float b);}class FunctionAdd implements CalculatorFunction{ float caculate(float summandA, float summandB){ return summandA + summandB; }}class OperationFunction implements CalculatorFunction{ float caculate(float minuend, float subtrahend){ return minuend-subtrahend; }}// same for other functionsIn your Model layer you should create a variable holding an instance of this interface: privat static final CalculatorFunction NO_CALCULATION = (a,b)->throw new IlligelArgumentException(no operation selected); private CalculatorFunction function = NO_CALCULATION;Having This you need to assign each function button its action individually: JButton buttonAdd = new JButton(new AbstractAction(+){ public void actionPerformed(ActionEvent e) { function = new FunctionAdd(); operandA = operandAccumilator; operandAccumilator.clear(); } }); JButton buttonSubtract = new JButton(new AbstractAction(-){ public void actionPerformed(ActionEvent e) { function = new FunctionSubtract(); operandA = operandAccumilator; operandAccumilator.clear(); } });// same for other functionsObviosly this leads to some code duplication, so we extract the parts that change to local variables: String operator = +; CalculatorFunction buttonFunction = new FunctionAdd(); JButton buttonAdd = new JButton(new AbstractAction(operator){ public void actionPerformed(ActionEvent e) { function = buttonFunction; operandA = operandAccumilator; operandAccumilator.clear(); } }); operator = -; buttonFunction = new FunctionSubtract(); JButton buttonAdd = new JButton(new AbstractAction(operator){ public void actionPerformed(ActionEvent e) { function = buttonFunction; operandA = operandAccumilator; operandAccumilator.clear(); } });// same for other functionsnow we can extract the identical repeated code into a parameterized method:private JButton configureButton(String operator, CalculatorFunction buttonFunction){ return new JButton(new AbstractAction(operator){ public void actionPerformed(ActionEvent e) { function = buttonFunction; operandA = operandAccumilator; operandAccumilator.clear(); } }); }and use that in the gui setup:JButton buttonAdd = configureButton(+, new FunctionAdd());JButton buttonSubtract = configureButton(-, new FunctionSubtract());// same for other functionsIn consequence the method calculate change to: try { float x = Float.parseFloat(number[0]); float y = Float.parseFloat(number[1]); screen.setText(String.valueOf(function.caculate(x,y))); } catch (Exception e){ screen.setText(Please enter numbers); }That's all, no more code in calculate ...whats operandA and OperandAccumilator I can't find it any where in your code user7639356These are (new) member variables. The Number buttons are expected to add individual digits to operandAccumilator. if I use keyboard then it wouldn't work, though. user7639356Neither would have your original code.Either way you have to convert the user input (given by GUI or command line) into model data. Usually it is easier to do with an OO approach than with the procedural solution you came up with. |
_webmaster.86587 | We've recently migrated an old custom cms site to Umbraco at the same domain. Google Webmaster Tool is reporting 1000s of Not Found errors from the old 404 page in the format error/404?aspxerrorpath=/path/to/old/url.Does this mean that Google has historically indexed all these pages (ie before switching to Umbraco)? Searching for these urls produces no results.Do we need to take any action (such as 410'ing pages which match this pattern) or will the new site returning a 404 be enough? | Should I 410 old 404 pages? | 404 | Does this mean that Google has historically indexed all these pages (ie before switching to Umbraco)?Not necessarily, although it would appear to suggest that the old site (incorrectly) redirected to the error page, rather than serving it directly (as with ErrorDocument etc). And Google has helpfully remembered this.Do we need to take any action (such as 410'ing pages which match this pattern)You don't need to do anything. There's no SEO penalty for having a stack of 404s if these are indeed genuine 404s.However, it can be annoying to have Google's Search Console (formerly GWT) report polluted by all these 404s, since you might miss the ones that really matter. So, you could return a 410 Gone instead - this sends a stronger signal to Google that these URLs really are gone and not coming back, so in time they will hopefully be dropped completely. |
_vi.8733 | I need to be break it to you guys, I use emacs. But just for one little thing.Recently I've been working with a good deal of Japanese people (the company is Japanese) and I got some idea of the language, moreover sometimes I need to write something in Japanese. I do not have a Japanese keyboard and I need to convert some form of romaji (Japanese written in latin letters). At first I used google translated but then I learned about emacs's japanese mode. Here is a screenshot of it:(forgive my Japanese please)emacs does this with the help of the skk dictionary with some customisations for the actual typing (lisp/international/ja-dic-cvn.el, lisp/international/ja-dic-utl.el and lisp/international/kkc.el in emacs code). Everything happens in UTF-8, the above screenshot is emacs running inside a UTF-8 terminal.Is there a viable way to perform this in Vim? I'm hoping someone wrote an interface to SKK already, since my Japanese is definitely not good enough to read its documentation.Or maybe, is there a different method to write Japanese text in Vim? | Can I write Japanese (SKK) text in Vim? | unicode;keyboard layout;text generation | OK, this took several days of struggle against the skk.vim plugin mentioned by @SatoKatsura. All the documentation is in Japanese therefore I still do not know of most of its features, and, certainly, there are better ways to accomplish SKK conversion (Henkan in Japanese) in Vim than the one presented here. Yet, it works well enough to be comparable to emacs' SKK mode.First of all you need to donwload the SKK dictionary. Any of them would be enough but I suggests the large dictionary for the sake of completeness. The dictionary comes in the EUC-JP encoding, therefore we need to convert it:gunzip SKK-JISYO.L.gziconv -f euc-jp -t utf-8 SKK-JISYO.L > skk-jisyo-utf-8.lIf your Vim has the +iconv feature the iconv utility should be available on your machine.The SKK dictionary is in the correct format to be used as a thesaurus, therefore we will set that in Vim and use <c-x><c-t> to perform thesaurus completion. Every line in the SKK dictionary looks as follows:<kana entry> / <kanji entry> / <kanji entry> / ...y / / /Now, we only need to write the <kana entry> part and Vim will be capable of completing the rest for us.skk.vim can write in Kana in insert-mode. It can write in both Hiragana and Katakana but the SKK dictionary has entries in Hiragana only. Therefore we add a Toogle function wrapper around skk.vim to use either Hiragana or Katakana when in insert-mode. When we want SKK completion we must be in Hiragana mode (this is analogous to emacs's SKK mode).Here is what I wrote in my .vimrc to wrap skk.vim and use the SKK dictionary as a thesaurus:let g:skk_initial_mode = 'hira'let g:skk_script = '~/vim/skk/skk.vim'set completeopt=menuone,previewset thesaurus=~/vim/skk/skk-jisyo-utf-8.lfunction! ToogleMode() if 'hira' ==# g:skk_initial_mode let g:skk_initial_mode = 'kata' else let g:skk_initial_mode = 'hira' endif execute source . g:skk_scriptendfunctionTo enter Kana mode you press <c-j> to complete a Kanji you need to press <c-j> to exit Kana mode and then <c-x><c-t> to bring up thesaurus completion.And here is how it looks (the text is exactly the same as in the question):Disadvantages and quirks:Since we are using Vim's thesaurus we need to add spaces between words. This is not needed in emacs's SKK becuase it keeps a selection trailing behind (see the screenshot in the question).This code is terribly hacky, I just cannot understand about 70% of skk.vim because I'm unable to read the documentation. There certainly are better ways to perform this.You need to exit the Kana mode to perform the thesaurus completion, in Kana mode <c-x><c-t> does not work as expected. |
_datascience.701 | I have generated a dataset of pairwise distances as follows:id_1 id_2 dist_12id_2 id_3 dist_23I want to cluster this data so as to identify the pattern. I have been looking at Spectral clustering and DBSCAN, but I haven't been able to come to a conclusion and have been ambiguous on how to make use of the existing implementations of these algorithms. I have been looking at Python and Java implementations so far.Could anyone point me to a tutorial or demo on how to make use of these clustering algorithms to handle the situation in hand? | Clustering pair-wise distance dataset | data mining;clustering;dbscan | In the scikit-learn implementation of Spectral clustering and DBSCAN you do not need to precompute the distances, you should input the sample coordinates for all id_1 ... id_n. Here is a simplification of the documented example comparison of clustering algorithms:import numpy as npfrom sklearn import clusterfrom sklearn.preprocessing import StandardScaler## Prepare the dataX = np.random.rand(1500, 2)# When reading from a file of the form: `id_n coord_x coord_y`# you will need this call instead:# X = np.loadtxt('coords.csv', usecols=(1, 2))X = StandardScaler().fit_transform(X)## Instantiate the algorithmsspectral = cluster.SpectralClustering(n_clusters=2, eigen_solver='arpack', affinity=nearest_neighbors)dbscan = cluster.DBSCAN(eps=.2)## Use the algorithmsspectral_labels = spectral.fit_predict(X)dbscan_labels = dbscan.fit_predict(X) |
_softwareengineering.347660 | I am familiar with the Traveling Salesman Problem, and many of the various approaches to solving it.But is there a name for the following problem:Given an existing (solved) tour and a new city, insert the new city into the tour (at the start, between any two existing cities, or at the end), such that the total increase in distance is minimized.The brute-force solution is simple - looping through the entire route to find the smallest increase in distance. This is not unlike the insertion method for solving the TSP. But I'm having trouble coming up with an optimized solution for this new problem, or figuring out how I might apply an existing heuristic to the problem.Is there a name for this particular problem? Everything I can find for the TSP has to do with solving the original tour, but doesn't cover a solution for adding a city to an established tour. For the aforementioned solved tour, it may or may not be optimized, but in either case it cannot be changed. It might be perfect, or be a jumbled rats' nest. The only change is adding the new city, wherever it satisfies the problem statement.EDIT #1There seems to be a misunderstanding with the original question. The only answer so far assumes an optimized initial route, which potentially will not be the case (it almost certainly will not be).Using the same problem statement as before: Assume the given route is not optimized. Instead, the nodes in the route have been set to a schedule, where they need to be visited at particular times, or in a particular order. The given route cannot be changed, save for the insertion of the new node at the optimal (or near-optimal) location.An extension of the problem could be:Given multiple routes and a new node, insert the new node into one of the routes (at the start, between any two existing nodes, at the end), such that the total increase in distance is minimized.Looking at this newest presentation, I cannot see how having 100 routes with 50 nodes would be any different than having one route with 5000 nodes. Similarly, scaling should be identical between the two (adding a new route of 50 nodes, or adding 50 nodes to the one route).At any rate, I've been told this can have sub-linear scaling, with the appropriate heuristics applied to it. | Traveling Salesman-esque: Adding a city to already solved tour? | algorithms | null |
_codereview.131998 | I have an object which stores an app configuration in an associative array, as this:[ 'Database' => [ 'DB_SERVER' => 'localhost' 'DB_NAME' => 'adbname' 'DB_USER' => 'theuser' 'DB_PASS' => 'thepass' ]]And a function, get(), which receives a variable number of arguments and returns the configuration value for this parameters. For example, Config::get('Database','DB_PASS') will return 'thepass'. This is an excerpt of the code:class Config{ protected static $values; ... public static function get() { $val = &self::$values; $argList = func_get_args(); for ($i = 0; $i < count($argList); $i++) { $val = &$val[$argList[$i]]; if(empty($val)) break; } return (is_null($val)?:$val); }}Is there a more elegant / efficient way of accessing the value? | Access an associative array value given an array of keys in PHP | php | null |
_cs.72525 | Some definitions: Consider the unweighted directed graph $G$, where each node is uniquely represented by an $n$-bit vector of $0$'s and $1$'s. Now consider this scenario: we want to 'shrink the dimension' of the index vectors for all nodes. For example, originally, some node has the index vector $\langle 0, 1, 1, 0 \rangle$ (so $n=4$), and we want to shrink the dimension to 2 by removing, for example, the first and third bit. Then the index for this node becomes $\langle x, 1, x, 0 \rangle$, where $x$ represents the removed bits. $x$'s are considered the same bit. If in the original graph, the bitstrings differ only in these two bits, the two nodes will be merged as the same node after the 'shrinking'. The edges are changed such that the new graph $G'$ contains an edge $(u,v)$ if and only if there were an nodes $u',v'$ 'shrunk' into $u,v$ such that $(u',v')$ is an edge in $G$.My problem: For a fixed source node $s$ and an arbitrary node $u$, we consider the shortest path between them: the distance of the node $u$ from $s$. Our objective is to minimized the longest such distance. Naturally, after the shrinking, the shortest paths can be different. Note that shrinkage can only decrease the objective value if not preserve the value as before shrinkage.Now suppose we need to shrink $k$ bits out of the total $n$-bit vector and want to maximize the objective value from the source node in the new graph. How to decide which $k$ bits should we choose?The decision version of the problem is Given a graph $G = (V, E)$ as described above, a source node $s \in V$, an integer $k$ and an integer $C$, is there a 'shrinkage' of at most $k$ bits that creates a graph of objective value greater than $C$?I have a feeling this is NP-hard, but failed to prove it by reducing it to some previous problems.Any suggestions on the algorithms, reference literature, or refining my lousy descriptions are appreciated! | Longest path in a *shrinked* graph | algorithms;graphs;graph theory;np hard | null |
_softwareengineering.177762 | This approach is pretty much the accepted way to do anything in our company. A simple example : when a piece of data for a customer is requested from a service, we fetch all the data for that customer(relevant part to the service) and save it in a in-memory dictionary then serve it from there on following requests(we run singleton services). Any update goes to DB, then updates the in memory dictionary. It seems all simple and harmless but as we implement more complicated business rules the cache gets out of sync and we have to deal with hard to find bugs. Sometimes we defer writing to database, keeping new data in cache till then. There are cases when we store millions of rows in memory because the table has many relations to other tables and we need to show aggregate data quickly. All this cache handling is a big part of our codebase and I sense this is not the right way to do it. All of this juggling adds too much noise to the code and it makes it hard to understand the actual business logic. However I don't think we can serve data in a reasonable amount of time if we have to hit the database every time.I am unhappy about the current situation but I don't have a better alternative. My only solution would be to use NHibernate 2nd level cache but I have nearly no experience with it. I know many campanies use Redis or MemCached heavily to gain performance but I have no idea how I would integrate them into our system. I also don't know if they can perform better than in-memory data structures and queries. Are there any alternative approaches that I should look into? | Caching by in-memory dictionaries. Are we doing it all wrong? | caching | null |
_codereview.144304 | I am a beginner in Zend Framework 3 and I want to hear your opinions about the code that I wrote. I don't know how exactly I can connect forms, and validators together that the code will be quite nice and readable.Register method public function registerAction() { $form = $this->form; $viewModel = new ViewModel(['form' => $form]); $prg = $this->prg('users', false); if ($prg instanceof \Zend\Http\PhpEnvironment\Response) return $prg; elseif ($prg === false) return $viewModel; $loginExistsValidator = new NoRecordExists( [ 'table' => 'users', 'field' => 'login', 'adapter' => $this->command->getAdapter() ] ); $loginExistsValidator->setMessage('Istnieje ju uytkownik o podanym loginie'); $emailExistsValidator = new NoRecordExists( [ 'table' => 'users', 'field' => 'email', 'adapter' => $this->command->getAdapter() ] ); $emailExistsValidator->setMessage('Ten email jest ju zajty...'); $form->setInputFilter(new UsersFilter()); $form->getInputFilter()->get('login')->getValidatorChain()->attach($loginExistsValidator); $form->getInputFilter()->get('email')->getValidatorChain()->attach($emailExistsValidator); $form->setData($prg); if (!$form->isValid()) return $viewModel; $users = $this->command->addUser($form->getData()); $viewModel->setTemplate('users/register/registerSukcesfull'); return ['users' => $users]; }usersFilter <?php/** * Created by PhpStorm. * User: Patryk * Date: 2016-10-09 * Time: 12:19 */namespace Users\Filters;use Users\Services\RegisterServices;use Zend\Filter\Callback;use Zend\Filter\StringTrim;use Zend\InputFilter\InputFilter;use Zend\Validator\Db\NoRecordExists;use Zend\Validator\Db\RecordExists;use Zend\Validator\EmailAddress;use Zend\Validator\Regex;use Zend\Validator\StringLength;class UsersFilter extends InputFilter{ public function __construct() { $this->add([ 'name' => 'login', 'required' => true, 'filters' => [ [ 'name' => StringTrim::class ] ], 'validators' => [ [ 'name' => StringLength::class, 'options' => [ 'min' => 5 ] ], ], ] ); $this->add([ 'name' => 'password', 'required' => true, 'validators' => [ [ 'name' => StringLength::class, 'options' => [ 'min' => 12 ] ], ], ] ); $this->add([ 'name' => 'email', 'required' => true, 'validators' => [ [ 'name' => EmailAddress::class, 'options' => [ 'domains' => true ] ] ] ]); }} | Zend Framework Form Validation Example | beginner;php;form;zend framework | null |
_cs.12041 | So basically L satisfies the conditions of the pumping lemma for CFL's but is not a CFL (that is possible according to the definition of the lemma). | Example of a non-context free language that nonetheless CAN be pumped? | formal languages;context free;pumping lemma | The classical example is $L = \{ a^i b^j c^k : i,j,k \text{ all different} \}$. Wise shows in his paper A strong pumping lemma for context-free languages that neither the Bar-Hillel pumping lemma nor Parikh's theorem (stating that the set of lengths of words in a context-free language is semi-linear) can be used to prove that $L$ is not context-free. Other tricks like intersecting with a regular language also don't help. (Ogden's lemma, a generalization of the Bar-Hillel pumping lemma, does prove that $L$ is not context-free.) He also provides an alternative pumping lemma which is equivalent to context-freeness (for computable languages), and uses it to prove that $L$ is not context-free.Wise's pumping lemma states that a language $L$ is context-free if and only if there is an (unrestricted) grammar $G$ generating $L$ and an integer $k$ such that whenever $G$ generates a sentential form $s$ (so $s$ can include non-terminals) of length $|s| > k$, we can write $s = uvxyz$ where $x,vy$ are non-empty, $|vxy| \leq k$, and there is a non-terminal $A$ such that $G$ generates $uAz$ and $A$ generates both $vAy$ and $x$.By repeatedly applying the condition in the lemma, Wise is able to prove that $L$ is not context-free, but the details are somewhat complicated. He also gives an even more complicated equivalent condition, and uses it to prove that the language $\{ a^n b a^{nm} : n,m > 0 \}$ cannot be written as a finite intersection of context-free languages.If you cannot access Wise's paper (it's behind a paywall), there's a typewritten version which came out as an Indiana university technical report.A non-context-free language which satisfies the pumping condition of Ogden's lemma is given by Johnsonbaugh and Miller, Converse of pumping lemmas, and attributed there to Boasson and Horvath, On languages satisfying Ogden's lemma. The language in question is$$ \begin{align*}L' &= \bigcup_{n \geq 1} (e^+a^+d^+)^n(e^+b^+d^+)^n(e^+c^+d^+)^n\\ &\cup (a+b+c+d)\Sigma^* \cup \Sigma^*(a+b+c+e) \cup \Sigma^*(ed+d(a+b+c)+(a+b+c)e)\Sigma^*.\end{align*} $$We can write $L' = L_1 \cup L_2$, corresponding to the two different lines. Note that $L_1 \cap L_2 = \emptyset$ and that $L_2$ is regular. Ogden's lemma can be used to prove that $L_1$ is not context-free, and so neither is $L'$, but it cannot be used directly to show that $L'$ is not context-free. |
_softwareengineering.347920 | On Azure, Session Management can be done using Redis Cache. But this is not truly stateless. Is there a way to make a Web App in general, truly stateless?If yes, what pattern to follow specific to Azure cloud? | How to make Azure Web App stateless | web applications;azure;session | null |
_unix.148853 | Using ssh from BusyBox, I cannot remove symlinks: after rebooting the device, symlinks re-appear. ls -la shows that symlinks have been removed, but after rebooting device they re-appear again.Those symlinks already existed beforehand, created at installing the firmware.$ rm uw_cert.cerI tried to remove uw_cert.cer and uw_key_prv.bin, but it reappears after reboot. The other files can be removed without problem.<root@fwre:/nvram/1/security> ls -latotal 5drwxr-xr-x 3 root 0 0 Jan 1 00:00 .drwxr-xr-x 5 root 0 0 Jan 1 00:05 ..-rwxrwxrwx 1 root 0 905 Jan 1 00:06 cm_cert.cerdrwxr-xr-x 2 root 0 0 Jan 1 00:00 downloadlrwxrwxrwx 1 root 0 25 Jan 1 00:00 uw_cert.cer -> /nvram/fw/bpi/uw_cert.cerlrwxrwxrwx 1 root 0 28 Jan 1 00:00 uw_key_prv.bin -> /nvram/fw/bpi/uw_key_prv.bin-rwxrwxrwx 1 root 0 1052 Jan 1 00:06 mfg_cert.cer-rwxrwxrwx 1 root 0 140 Jan 1 00:02 mfg_key_pub.binlrwxrwxrwx 1 root 0 37 Jan 1 00:00 root_pub_key.bin -> /etc/docsis/security/root_pub_key.binmount output:<root@fware:/var/tmp> mountrootfs on / type rootfs (rw)/dev/root on / type squashfs (ro)proc on /proc type proc (rw)ramfs on /var type ramfs (rw)sysfs on /sys type sysfs (rw)tmpfs on /dev type tmpfs (rw)devpts on /dev/pts type devpts (rw)/dev/mtdblock4 on /nvram type jffs2 (rw)EDIT:df /nvram/1/securityFilesystem 1K-blocks Used Available Use% Mounted on/dev/mtdblock4 320 256 64 80% /nvramcat /proc/mountsrootfs / rootfs rw 0 0/dev/root / squashfs ro 0 0proc /proc proc rw 0 0ramfs /var ramfs rw 0 0sysfs /sys sysfs rw 0 0tmpfs /dev tmpfs rw 0 0devpts /dev/pts devpts rw 0 0/dev/mtdblock4 /nvram jffs2 rw 0 0 | Canot remove symlinks: after reboot, symlinks re-appear | linux;shell;ssh;embedded;busybox | the filesystem you are trying to remove symlink from is probably an initramfs which is loaded on ram at boot, so the one you are modifying is the ram copy of the initial ram disk, which is discarded at shutdown.If you want to modify the ramdisk file, you need additional information. Which bootloader are you using? From which device? Can you access the kernel file and the ramdisk? Which kernel command line do you have? (use cat /proc/cmdline to discover)?I found this page that explains how to put a ramdisk image on a u-boot device. However I couldn't find a way to download the original ramdisk to your computer, so that you can edit.Please be careful that if you provide an invalid ramdisk your system could become unbootable. I don't know much about that specific architecture, so I can't suggest you a proven safe strategy. You would have your best chances if you ask another question about how to modify the initial ramdisk for a U-boot embedded modem (in this question you asked about symlinks so people who know about u-boot would probably overlook this completely) |
_softwareengineering.283069 | I am currently trying to design an interface for a WebService that can access several MySQL databases. There will be 4 operations available, Add(), Read(), Update() and Delete().The WebService just needs to assemble an SQL statement based on the called method and execute it on the target database. But now I am struggling to find a good method signature that provides all needed information to the WebService and is simple to use. So if I want to assemble an INSERT statement when the Add() method was called, I don't know how I can pass all the column information with the corresponding values and types. For example a .NET DateTime should be stored with the MySQL data type for date/time. So I'd need some kind of wrapper object that check the properties via reflection to get the type.Here are some thoughts:Add(String db, String table, Dictionary<String, object> dataSet);Read(String db, String table, String column, filter?);Update(String db, String table, String idToReplace, Dictionary<String, object> dataSet);Delete(String db, String table, String idToDelete);I am not sure how to specify a filter possibility for the SELECT statement in the Read() method. In addition I don't know how to pass parameter information in the Add() and Update() methods. I don't want to save only string values in the db, I'd like to have passed some type information so that the WebService can match them to the corresponding MySQL data types. | Design interface for WebService to access several MySQL databases | design;mysql;interfaces | null |
_unix.368339 | I create a file (output) from another file (input) using awk (skipping the header): awk 'NR==1{next} $3==1 {print $1\t$2}' input > outputI then have header information I can only calculate afterwards, which I add using sed:sed -i 1s/^/head1\thead2\n/ outputHowever, the sed is pretty slow, I'm wondering if there is a better way of doing it? Like saving the awk result and then writing the file after I have the header information? | How to add a header to the output of an awk command afterwards? | text processing;awk | After more googling, I found this question:Change the header in a huge file without rewriting the whole file. To prevent having to rewrite the entire file when adding in the header, I printed a dummy header of a minimum amount of bytes (by padding with zeros) while creating the file: awk 'NR==1{print dummyhead100\tdummyhead20000; next} $3==1 {print $1\t$2}' input > outputI then make a file (or string variable) with the new head as header.tsv, and replace the dummy header in-place (after making sure the dummy and new headers are the same number of bytes) using dd: dd conv=notrunc obs=1 if=header.tsv of=outputThis way output is edited in-place, and I don't have to wait for the whole file to be copied, or have to keep it in memory. |
_unix.127235 | The default journal mode for Ext4 is data=ordered, which, per the documentation, means that All data are forced directly out to the main file system prior to its metadata being committed to the journal.However, there is also the data=journal option, which means that All data are committed into the journal prior to being written into the main file system. Enabling this mode will disable delayed allocation and O_DIRECT support.My understanding of this is that the data=journal mode will journal all data as well as metadata, which, on the face of it, appears to mean that this is the safest option in terms of data integrity and reliability, though maybe not so much for performance.Should I go with this option if reliability is of the utmost concern, but performance much less so? Are there any caveats to using this option?For background, the system in question is on a UPS and write caching is disabled on the drives. | Is data=journal safer for Ext4 as opposed to data=ordered? | ext4 | Yes, data=journal is the safest way of writing data to disk. Since all data and metadata are written to the journal before being written to disk, you can always replay interrupted I/O jobs in the case of a crash. It also disables the delayed allocation feature, which may lead to data loss.The 3 modes are presented in order of safeness in the manual:data=journaldata=ordereddata=writebackThere's also another option which may interest you:commit=nrsec (*) Ext4 can be told to sync all its data and metadata every 'nrsec' seconds. The default value is 5 seconds.The only known caveat is that it can become terribly slow. You can reduce the performance impact by disabling the access time update with the noatime option. |
_unix.210544 | Can someone please tell me how to logout and log back in again via the command line so that I can apply a new group's settings to a user. To put this in perspective, assume that I am currently logged in as testuseraccount, and then I issue the commands below into the terminal.suusermod -aG sudo testuseraccountSo I believe by typing su this logs me into root (but just within the shell). So how do I logout of root, then logout of testuseraccount & sign back in (in order to apply the sudo group to testusersaccount) via the terminal? | How To Logout and Apply New Group Settings | login;group;session | You cannot change existing processes' group id, which means one way is to restart them. Child processes inherit the parent's group id, so programs you start in your deskop environment (menu...) you cannot influence.Within a given shell, use the newgrp command to start a new shell with the new effective group id:> iduid=1000(user) gid=100(users) groups=100(users),92(audio)> newgrp audio> iduid=1000(user) gid=92(audio) groups=92(audio),100(users)Any process started from this shell will have the new effective group id (audio in this case).If you have added a new user to a group this will again take effect after the user starts a new process.As a consequence, if you wish to start a new X (graphical login) session, you need to exit the previous session completely, then start the new session by logging in. Logging back in without interaction after logging out is not intended to be possible by the login screen (by XDM/GDM/KDM) unless passwordless login is enabled (which no-one recommends). One reason is that during logout, all processes of the user are to be terminated, so no process is left to initiate logging you in.Workarounds may be created but will be ugly, I expect. |
_softwareengineering.230086 | I am still very confused as to why and when to use Dependency Injection. If anyone could explain maybe using the below example that would be great, any other explanations would be appreciated. Lets say I am creating a web-app that will save movie reviews written in C# with ASP.NET MVC 5. If I have the following Model code,namespace MovieReviewProject.Models { public class MovieReviews { [Key] public int ReviewID_int{ get; set; } /// <summary> /// Submitter email address /// </summary> public string EmailAddress_str{ get; set; } /// <summary> /// Movie name /// </summary> public string MoveName_str{ get; set; } /// <summary> /// The review /// </summary> public string Review_str { get; set; } /// <summary> /// The submission date from /// </summary> public DateTime SubmissionDate_dt { get; set; } /// <summary> /// The movie rating /// </summary> public int Rating_int { get; set; } }}how would a class that provides the Controller with the List of all the reviews, adds an average for a movie, and more look like? I know that DI is mostly used to allow for easier unit testing but other than that what are the perks to it? Is it worth going through old projects and make sure all the providers are using this principal? | Help With Dependency Injection | c#;mvc;asp.net mvc;dependency injection;inversion of control | null |
_unix.373930 | My wish is that I would have the ability to enlarge and reduce the size of the terminal (I use terminator) at will. For example, that by giving the command resize 600-400, I can resize my terminator window.Is it possible? And if terminator is not capable of it, is there any other terminal that can do that? | Changing size of terminator from command line | shell;gnome terminator | null |
_unix.116439 | Recently had a LVM'd CentOS 6.5 install get accidentally cold-shutdown. On bootup, it says that the home partition need fscking:/dev/mapper/vg_myserver-lv_home: Block bitmap for group 3072 is not in group. (block 3335668205)/dev/mapper/vg_myserver-lv_home: UNEXPECTED INCONSISTENCY; RUN fsck MANUALLY....but I guess the root partition is OK, since it gives me a shell there. So we run e2fsck -b 32768 /dev/mapper/vg_myserver/lv_home and after saying Yes to various fixes, on Pass 5 it just prints endless numbers to the screen, very fast. Once in a while it will print them in neat columns, and if these are block numbers, after a couple hours we are still nowhere near the first 2% being done of our 1.2 TB LV.I read that you can use cleap_mmp with tune2fs, but upon trying that, it doesn't accept cleap_mmp nor list it among valid options.My question is, how does everyone deal with a corrupt ext4 fs without weeks of downtime? Does everyone have this dilemma, or weeks of downtime vs rebuilding your server / lost data? If so why does anyone use or recommend the use of ext4? Is there some trick I'm missing that would let me target the specific block/group it's complaining about, so we can get on with it and mount the home fs again? | targeting a specific block with e2fsck to shorten wait | linux;centos;lvm;ext4;fsck | Run e2fsck -y to say yes to all questions automatically instead of having to manually say yes a million times. |
_codereview.83452 | I created a simple program that allows you to create and play MIDI sounds.I've used the MVC approach and Id like to know if there are any improvements to be made regarding the design and structure of the classes? Have I used a constants class correctly? I also feel that the checkBoxArrayin the Midi class should be in a separate class. Should it be?Please also let me know of any improvements to be made on the readability and general layout of the program.For those interested, I've updated my code with the advice given on this thread: Simple Java MIDI player followupBeatBox (main class)package BeatBox;public class BeatBox { GUI gui; Midi midi; public BeatBox(){ midi = new Midi(); gui = new GUI(midi); midi.setUpMidi(); } public static void main(String[] args) { new BeatBox(); }}GUI classpackage BeatBox;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.*;public class GUI { private Midi midi; public GUI(Midi midi){ this.midi = midi; buildGUI(); } // buildGUI - creates the GUI for the beat box program void buildGUI(){ JFrame frame = new JFrame(Cyber BeatBox); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setMinimumSize(new Dimension(600, 350)); JPanel panel = new JPanel(new BorderLayout()); panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); frame.setContentPane(panel); // Instrument names Box nameBox = new Box(BoxLayout.Y_AXIS); for(int i = 0; i < BeatBoxConstants.NUM_INSTRUMENTS; i++){ nameBox.add(new Label(BeatBoxConstants.instrumentNames[i])); } // Check box GridLayout grid = new GridLayout(16, 16); grid.setVgap(0); grid.setHgap(2); JPanel checkBoxPanel = new JPanel(grid); for(int i = 0; i < BeatBoxConstants.NUM_INSTRUMENTS; i++){ for(int j = 0; j < BeatBoxConstants.NUM_BEATS; j++) { JCheckBox checkBox = new JCheckBox(); checkBoxPanel.add(checkBox); midi.checkBoxArray[i][j] = checkBox; } } // Buttons JPanel buttonsPanel = new JPanel(); buttonsPanel.setLayout(new BoxLayout(buttonsPanel, BoxLayout.Y_AXIS)); JButton startButton = new JButton(Start); JButton pauseButton = new JButton(Pause); startButton.addActionListener(new StartButtonListener()); pauseButton.addActionListener(new GUI.PauseButtonListener()); buttonsPanel.add(startButton); buttonsPanel.add(pauseButton); // Add everything to the frame frame.add(BorderLayout.WEST, nameBox); frame.add(BorderLayout.CENTER, checkBoxPanel); frame.add(BorderLayout.EAST, buttonsPanel); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } // LISTENERS private class StartButtonListener implements ActionListener{ @Override public void actionPerformed(ActionEvent ev){ midi.buildTrackAndStart(); midi.startSequencer(); } } private class PauseButtonListener implements ActionListener{ @Override public void actionPerformed(ActionEvent ev){ midi.pauseSequencer(); } }}Midi class (used to create the sounds)package BeatBox;import javax.sound.midi.*;import javax.swing.JCheckBox;public class Midi { private Sequencer sequencer; private Sequence seq; private Track track; JCheckBox[][] checkBoxArray = new JCheckBox[BeatBoxConstants.NUM_INSTRUMENTS][BeatBoxConstants.NUM_BEATS]; // buildTrackAndStart - used to create and begin playing the newly created track void buildTrackAndStart(){ try { seq.deleteTrack(track); track = seq.createTrack(); makeTrack(); sequencer.setSequence(seq); sequencer.setLoopCount(Sequencer.LOOP_CONTINUOUSLY); }catch(InvalidMidiDataException invalidMidiDataException){ invalidMidiDataException.printStackTrace(); } } // makeBeat - this creates the noteOn and noteOff beats private void makeBeat(int key, int tick) throws InvalidMidiDataException{ track.add(makeEvent(144, 9, key, 100, tick)); track.add(makeEvent(128, 9, key, 100, tick + 2)); } // makeEvent - creates the notes for the track private MidiEvent makeEvent(int comd, int chan, int one, int two, int tick) throws InvalidMidiDataException{ ShortMessage a = new ShortMessage(); a.setMessage(comd, chan, one, two); return new MidiEvent(a, tick); } // makeTrack - creates the sound track based on the check boxes selected by the user private void makeTrack() throws InvalidMidiDataException{ for(int i = 0; i < BeatBoxConstants.NUM_INSTRUMENTS; i++){ for(int j = 0; j < BeatBoxConstants.NUM_BEATS; j++){ if(checkBoxArray[i][j].isSelected()){ makeBeat(BeatBoxConstants.instruments[i], j); } } } // Added to ensure that beat box completes the whole 16 beats before it loops again track.add(makeEvent(192, 9, 1, 0, BeatBoxConstants.NUM_BEATS - 1)); } // setUpMidi - this sets up the sound system for the user to edit void setUpMidi(){ try { sequencer = MidiSystem.getSequencer(); sequencer.open(); seq = new Sequence(Sequence.PPQ, 4); track = seq.createTrack(); }catch(InvalidMidiDataException invalidMidiDataException){ invalidMidiDataException.printStackTrace(); }catch(MidiUnavailableException midiUnavailableException){ midiUnavailableException.printStackTrace(); } } // startSequencer - starts playing the sequencer void startSequencer(){ sequencer.start(); } // pauseSequencer - pauses the sequencer. This does not stop the sound, rather it pauses it. void pauseSequencer(){ sequencer.stop(); }}BeatBoxConstants (holds static info to be used by the other classes)package BeatBox;public class BeatBoxConstants { static final String[] instrumentNames = {Bass Drum, Closed Hi-Hat, Open Hi-Hat, Acoustic Snare, Crash Cymbal, Hand Clap, High Tom, Hi Bongo, Maracas, Whistle, Low Conga, Cowbell, Vibraslap, Low-mid Tom, High Agogo, Open Hi Conga}; static final int[] instruments = {35, 42, 46, 38, 49, 39, 50, 60, 70, 72, 64, 56, 58, 47, 67, 63}; static final int NUM_BEATS = 16; static final int NUM_INSTRUMENTS = instrumentNames.length;} | Simple Java MIDI player | java;object oriented;mvc;swing;audio | Disclaimer: I don't really know that much about music, so some of my assumptions might be wrong.Have I used a constants class correctly? I wouldn't say so. I would only use a constants class for things which are not part of the state of any objects, and which do not expose the inner workings of objects (eg a debug field, database credentials, fixed strings for user output, etc). The numbers in instruments (which should be all upper case) seem to be random numbers (as in, they are not numbers a musician would recognize, but numbers that are specific to your program). They also seem to interact with instrumentNames, which is not good (see below).NUM_INSTRUMENTS isn't really needed at all. NUM_BEATS is the only value that I might leave in a constants class.Id like to know if there are any improvements to be made regarding the design and structure of the classes? One thing that directly jumped out at me is that it's really hard to see how you make the sounds of different instruments. It seems to depend on the passed key in makeBeat(int key, int tick). The call of that depends on the order of instruments in the instruments constant, and that it is in the correct order regarding instrumentNames, and displayed in the same order inside the GUI. It's never a good idea to put that much weight on the order of different lists being correct (because those lists work independently of each other).I would introduce an explicit Instrument class, which has a name and a key (if key is the technical term).I would then pack the whole tick thing into a class as well (because of my lack of music knowledge it's hard to say how. Some ideas: Could a list of ticks be part of an instrument? Or could there be TickLists which each own one instrument?).I also feel that the checkBoxArray in the Midi class should be in a separate class. Should it be?Yes. Your Midi class is basically your model and controller, but it definitely isn't your GUI, so it shouldn't have JCheckBoxs. Instead, it should have the Instrument/TickList structure described above, which it can then expose to the GUI.Misca reset button would be great for usability, and should be easy to add. don't import *, instead make all your imports explicit, so readers know what classes you use.use JavaDoc style method comments (they are easier to read as they make input parameters and output explicit, and they can be displayed in IDE tooltips, published on the web, etc).Naming: seq can be a bit confusing, as it's unclear if it is sequencer or sequence; I would just write it out. At first, I thought comd is some music term, but as it stands for command, just write it out as well. Same for chan (channel). |
_softwareengineering.176429 | Steve Yegge's The Pinoccio Problem describes a very special type of program: one that not only fulfills the original purpose of its creators, but also is capable of performing arbitrary, user-defined computations.They typically also host a console, by which one can reprogram the software on runtime, maybe persisting the modifications.I find this problem very hard to reason about - there seems to be a conflict between implementing the 'core modules' of a program, and making the system really implementation-agnostic (i.e. no functionality is hard-coded).So, how to architecture such a program - what techniques can help? Is it a well-studied topic? | Designing extensible, interactive systems | architecture;extensibility | null |
_unix.297214 | Somewhat along the lines of this question, How to mount multiple directories on the same partition? but my situation is different.I have a 2 small partitions that I'm using for two variants of linux and one large partition that I'm using as the home for both. I'd like to move the /usr folder from one of the variants to that same partition.Any suggestions of how to accomplish this? | How can I mount /usr on another partition but use a folder called /usr on that partition instead of using / as /usr? | linux;ubuntu;filesystems;partition;disk usage | There is no generic way to directly mount a subtree of a filesystem. But you can mount the whole filesystem somewhere, and then copy a subtree of the mount with a bind mount.mount /dev/foobar /media/foobarmount --bind /media/foobar/usr /usrIn fstab syntax:/dev/foobar /media/foobar auto defaults 0 2/media/foobar/usr /usr bind bind |
_unix.18266 | I know VSZ in ps is for the total address space allocated for the app and is sometimes aliased as vsize (mentioned in man page of ps on linux), but what's the definition of VSIZE in top? This top output from iPhone is different from the top on Linux: PID COMMAND %CPU TIME #TH #PRTS #MREGS RPRVT RSHRD RSIZE VSIZE 1875 emma 0.0% 0:30.83 7 139 932 17868K 5328K 29M 181Mroot# ps -eo pid,rss,vsz|grep 1875 1875 29324 441324 | Why the value of VSIZE in top is different from the value of VSZ (Virtual set size) in ps? | osx;ps;top;iphone;ios | null |
_unix.351614 | cat <file1>name=HOST2WWN=50.01.43.80.29.6A.84.82WWN=50.01.43.80.29.6A.84.89WWN=50.01.43.80.29.6A.84.8AobjectID=LU.R800.57488.43objectID=LU.R800.57488.44objectID=LU.R800.57489.44name=HOST3WWN=50.01.43.80.28.55.99.5CWWN=50.01.43.80.28.55.99.5DobjectID=LU.R800.57488.45objectID=LU.R800.57488.46objectID=LU.R800.57488.47objectID=LU.R800.5748A.47name=HOST2WWN=50.01.43.80.29.6A.84.87WWN=50.01.43.80.29.6A.84.88objectID=LU.R800.57486.41objectID=LU.R800.57486.42objectID=LU.R800.57486.43I need output to be like this. can someone assist in shellHOST2 50.01.43.80.29.6A.84.82 LU.R800.57488.43HOST2 50.01.43.80.29.6A.84.82 LU.R800.57488.44HOST2 50.01.43.80.29.6A.84.82 LU.R800.57489.44HOST2 50.01.43.80.29.6A.84.89 LU.R800.57488.43HOST2 50.01.43.80.29.6A.84.89 LU.R800.57488.44HOST2 50.01.43.80.29.6A.84.89 LU.R800.57489.44HOST2 50.01.43.80.29.6A.84.8A LU.R800.57488.43HOST2 50.01.43.80.29.6A.84.8A LU.R800.57488.44HOST2 50.01.43.80.29.6A.84.8A LU.R800.57489.44HOST3 50.01.43.80.28.55.99.5C LU.R800.57488.45HOST3 50.01.43.80.28.55.99.5C LU.R800.57488.46HOST3 50.01.43.80.28.55.99.5C LU.R800.57488.47HOST3 50.01.43.80.28.55.99.5C LU.R800.5748A.47HOST3 50.01.43.80.28.55.99.5D LU.R800.57488.45HOST3 50.01.43.80.28.55.99.5D LU.R800.57488.46HOST3 50.01.43.80.28.55.99.5D LU.R800.57488.47HOST3 50.01.43.80.28.55.99.5D LU.R800.5748A.47HOST2 50.01.43.80.29.6A.84.87 LU.R800.57486.41HOST2 50.01.43.80.29.6A.84.87 LU.R800.57486.42HOST2 50.01.43.80.29.6A.84.87 LU.R800.57486.43HOST2 50.01.43.80.29.6A.84.88 LU.R800.57486.41HOST2 50.01.43.80.29.6A.84.88 LU.R800.57486.42HOST2 50.01.43.80.29.6A.84.88 LU.R800.57486.43 | formatting data in shell script | shell script;text processing | null |
_codereview.69892 | A loan calculator has to be created for the proNetBank. Method of processing the loan is as follows:Vehicle loan is given for a period of three to seven years depending on the customers preference. the current interest rate is 20% per annum. The minimum loan amount is lkr 500,000 and the maximum loan amount is 7,000,000 , in addition maximum that could be obtained also depends on the category of the vehicle as below.Brand new or unregistered vehicles. Up to 100% of the vehicle value -vehicles within 6 years of 1st registration. Up to 85% of vehicle value hybrid brand new and unregistered vehicles within 2 years of manufacturing. Up to 85% of the vehicle value.The application should obtain the necessary inputs using appropriate controls and calculate and display the installment value.So I wrote my code:Private Sub RadioButton2_CheckedChanged(sender As Object, e As EventArgs) Handles rbVeh5yrs.CheckedChanged If rbVeh5yrs.Checked = True Then txtBorrow.Visible = True lblBorrowingAmount.Text = Enter the amount you want to borrow Else txtBorrow.Visible = False lblBorrowingAmount.Text = End IfEnd SubPrivate Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click If txtBorrow.Text = Then MessageBox.Show(Pls Enter the amount you want to borrow) Else intBorrow = txtBorrow.Text If intBorrow < 500000 Then MessageBox.Show(Lowest Amount which can be borrow is RS.500000) ElseIf intBorrow > 7000000 Then MessageBox.Show(Maximum amount which can be borrowed is RS.7000000) End If End If intBorrow = txtBorrow.Text If rbVeh5yrs.Checked = True Then decVehicle = intBorrow * 0.8 decInterestPay = (decVehicle + (decVehicle * 0.2 * decYear)) decInstallment = decInterestPay / decMonthly lblMonthlyPayment.Text = Monthly Installments & decInstallment End If If rbBN.Checked = True Then decVehicle = intBorrow decInterestPay = (decVehicle + (decVehicle * 0.2 * decYear)) decInstallment = decInterestPay / decMonthly lblMonthlyPayment.Text = Monthly Installments & decInstallment End If If rbHybrid.Checked = True Then decVehicle = intBorrow * 0.8 decInterestPay = (decVehicle + (decVehicle * 0.2 * decYear)) decInstallment = decInterestPay / decMonthly lblMonthlyPayment.Text = Monthly Installments & decInstallment End IfEnd SubPrivate Sub RadioButton1_CheckedChanged(sender As Object, e As EventArgs) Handles rbBN.CheckedChanged If rbBN.Checked = True Then txtBorrow.Visible = True lblBorrowingAmount.Text = Enter the amount you want to borrow Else txtBorrow.Visible = False lblBorrowingAmount.Text = End IfEnd SubPrivate Sub rbHybrid_CheckedChanged(sender As Object, e As EventArgs) Handles rbHybrid.CheckedChanged If rbHybrid.Checked = True Then txtBorrow.Visible = True lblBorrowingAmount.Text = Enter the amount you want to borrow Else txtBorrow.Visible = False lblBorrowingAmount.Text = End IfEnd SubPrivate Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click Close()End SubPrivate Sub rb3Years_CheckedChanged(sender As Object, e As EventArgs) Handles rb3Years.CheckedChanged If rb3Years.Checked = True Then decYear = 3 decMonthly = 36 End IfEnd SubPrivate Sub rb4Years_CheckedChanged(sender As Object, e As EventArgs) Handles rb4Years.CheckedChanged If rb4Years.Checked = True Then decYear = 4 decMonthly = 36 End IfEnd SubPrivate Sub rb5Years_CheckedChanged(sender As Object, e As EventArgs) Handles rb5Years.CheckedChanged If rb5Years.Checked = True Then decYear = 5 decMonthly = 48 End IfEnd SubPrivate Sub rb6Years_CheckedChanged(sender As Object, e As EventArgs) Handles rb6Years.CheckedChanged If rb6Years.Checked = True Then decYear = 6 decMonthly = 60 End IfEnd SubPrivate Sub rb7Years_CheckedChanged(sender As Object, e As EventArgs) Handles rb7Years.CheckedChanged If rb7Years.Checked = True Then decYear = 7 decMonthly = 72 End IfEnd SubCan you check it and tell me whether it is good enough? If there is room for improvement, please let me know. | Vehicle Loan Calculator | vb.net;finance | null |
_unix.63299 | I need to sort a file based on the number of chars in the first column.I have no idea on how to go about this. (On Linux, so sed/awk/sort is available).An example:.abs is bla bla 12.abc is bla se 23 bla.fe is bla bla bla.jpg is pic extension.se is for swedish domainswhat I want is to sort these lines, based on the length of the first column in each line.Some of the lines start with 4 characters, some start with 3, or 2. I want the result to be something like:.fe is bla bla bla.se is for swedish domains.abs is bla bla 12.abc is bla se 23 bla.jpg is pic extensionIs this even possible? | sort a file based on length of the column/row | text processing;sed;grep;awk;sort | null |
_webapps.100038 | I am trying to build a filter functionality within Spreadsheets itself.The sheet looks as follows:The function looks as follows:=IF(and(I4=ALL, I6=ALL, I8=ALL, I10=ALL), query(Vastgoedbeheerders!1:1000,select A, B, C, D, E, F, G , 2),IF(and(I4<>ALL, I6=ALL, I8=ALL, I10=ALL), query(Vastgoedbeheerders!1:1000,select A, B, C, D, E, F, G where C=&I4& , 2),IF(and(I4=ALL, I6<>ALL, I8=ALL, I10=ALL), query(Vastgoedbeheerders!1:1000,select A, B, C, D, E, F, G where G=&I6& , 2),IF(and(I4=ALL, I6=ALL, I8<>ALL, I10=ALL), query(Vastgoedbeheerders!1:1000,select A, B, C, D, E, F, G where H=&I8& , 2),IF(and(I4=ALL, I6=ALL, I8=ALL, I10<>ALL), query(Vastgoedbeheerders!1:1000,select A, B, C, D, E, F, G where J=&I10& , 2),IF(and(I4<>ALL, I6<>ALL, I8=ALL, I10=ALL), query(Vastgoedbeheerders!1:1000,select A, B, C, D, E, F, G where C=&I4& and G=&I6& , 2),IF(and(I4=ALL, I6<>ALL, I8<>ALL, I10=ALL), query(Vastgoedbeheerders!1:1000,select A, B, C, D, E, F, G where G=&I6& and H=&I8& , 2),IF(and(I4=ALL, I6=ALL, I8<>ALL, I10<>ALL), query(Vastgoedbeheerders!1:1000,select A, B, C, D, E, F, G where H=&I8& and J=&I10& , 2),IF(and(I4<>ALL, I6=ALL, I8=ALL, I10<>ALL), query(Vastgoedbeheerders!1:1000,select A, B, C, D, E, F, G where C=&I4& and J=&I10& , 2),IF(and(I4<>ALL, I6=ALL, I8<>ALL, I10=ALL), query(Vastgoedbeheerders!1:1000,select A, B, C, D, E, F, G where C=&I4& and H=&I8& , 2),IF(and(I4=ALL, I6<>ALL, I8=ALL, I10<>ALL), query(Vastgoedbeheerders!1:1000,select A, B, C, D, E, F, G where G=&I6& and J=&I10& , 2),IF(and(I4<>ALL, I6<>ALL, I8<>ALL, I10=ALL), query(Vastgoedbeheerders!1:1000,select A, B, C, D, E, F, G where C=&I4& and G=&I6& and H=&I8& , 2),IF(and(I4=ALL, I6<>ALL, I8<>ALL, I10<>ALL), query(Vastgoedbeheerders!1:1000,select A, B, C, D, E, F, G where G=&I6& and H=&I8& and J=&I10& , 2),IF(and(I4<>ALL, I6=ALL, I8<>ALL, I10<>ALL), query(Vastgoedbeheerders!1:1000,select A, B, C, D, E, F, G where C=&I4& and H=&I8& and J=&I10& , 2),IF(and(I4<>ALL, I6<>ALL, I8=ALL, I10<>ALL), query(Vastgoedbeheerders!1:1000,select A, B, C, D, E, F, G where C=&I4& and G=&I6& and J=&I10& , 2),IF(and(I4<>ALL, I6<>ALL, I8<>ALL, I10<>ALL), query(Vastgoedbeheerders!1:1000,select A, B, C, D, E, F, G where C=&I4& and G=&I6& and H=&I8& and J=&I10& , 2)))))))))))))))))For some reason it results into:Error Array result was not expanded because it overwrites data in A5.I don't know what to change in the function in order for it to get it working correctly, any help would be appreciated! | Filtering Functionality results in Array result was not expanded because it overwrites data in A5 | google spreadsheets;worksheet function | null |
_unix.294388 | I've noticed that some Linux configuration files (e.g. /etc/samba/smb.conf) expect you to enter the actual settings (key value pairs) in a particular section of the file such as [global].I'm looking for a terminal tool/command which allows you to append lines to a specific section of a specific configuration file. Example:configadd FILE SECTION LINEconfigadd /etc/samba/smb.conf '[global]' my new line | Appending a line to a [section] of a config file | command line;text processing;configuration;samba | You can do the task by sed directly, for example:sed '/^\[global\]/a\my new line' /etc/samba/smb.confNOTE: This is not a solution because such line can be in config already. So firstly you should to test whether is the line present. |
_unix.291065 | I try to duplicate a video file x times from the command line by using a for loop, I've tried it like this, but it does not work:for i in {1..100}; do cp test.ogg echo test$1.ogg; done | Duplicate file x times in command shell | shell;files;file copy | Your shell code has two issues:The echo should not be there.The variable $i is mistyped as $1 in the destination file name.To make a copy of a file in the same directory as the file itself, use cp thefile thecopyIf you insert anything else in there, e.g.cp thefile theotherthing thecopythen it is assumed that you'd like to copy thefile and theotherthing into the directory called thecopy.In your case, it specifically looks for a file called test.ogg and one named echo to copy to the directory test$1.ogg.The $1 will most likely expand to an empty string. This is why, when you delete the echo from the command, you get test.ogg and test.ogg are the same files; the command being executed is essentiallycp test.ogg test.oggThis is probably a mistyping.In the end, you want something like this:for i in {1..100}; do cp test.ogg test$i.ogg; doneOr, as an alternativei=0while (( i++ < 100 )); do cp test.ogg test$i.oggdone |
_webmaster.20729 | I manage a domain which is an umbrella domain - it is used in marketing/advertising a product around the world. When users visit the domain the site re-directs them to a sub-domain specifically for their territory.No one territory is more important than another, and they show different content (all relating to the same product, but different sites) in their subdomains.Currently, when Google crawls the main page (because Googlebot is in the US) it sees the US site. This isn't ideal as people searching from outside the US get the US site in their search results. I am thinking that I should make a generic page just for search engines which shows links to all the territory subdomains, so that no-one sees the wrong content in google's results.However Google's guidance states: Make pages primarily for users, not for search engines. Don't deceive your users or present different content to search engines than you display to users, which is commonly referred to as cloaking.and alsoAvoid doorway pages created just for search engines, or other cookie cutter approaches such as affiliate programs with little or no original content.from Google webmaster guidelinesSo - would I be doing the right thing with my search engine only page?Thanks. | Should I make a search-engine only page for my domain (which re-directs visitors depending on geographic location)? | google;search engines | I think you have a lot of solutions to solve this issue and these are some:Simply report your domains/subdomains to Google with Google Webmaster tools and with the use of sitemapsPut in every homepage of your domains/subdomains a little div which has the links to the other country's domains/subdomains. This solution will be useful also in this case: A man who is english is connected from France (or his browser, for some reason, is setted to french as locale). Now your website is going to redirect him to the french version but it should redirect the user to the us/en version. Thanks to the div, he could go to the right website. |
_unix.74531 | I have a file where it contains a list of search patterns (searchPattern.txt). Its contents is similar to the contents below where there are 3000+ of them.123456234567345678...What I wanted to do is to use grep and search directories using the patterns listed in the file if they exist. It would be similar to this kind of command but instead of one search string there are many and its listed in a file.grep searchPattern.txt diagnostics*Although the command above doesn't work its just an idea as to what I wanted to happen.Can this be done with grep? If it can't be done can someone suggest a better way to do this? | Grep to search directories for patterns inside a text file | linux;command line;grep | Try this one:grep -r -f /path/to/pattern/file diagnostics* |
_codereview.111814 | I wrote a python script that converts English to Entean language from an anime called The Devil is a part timer. I am sloppy at coding and know that the script can be made better.In the anime, the language in Ente Isla is called Entean, which is basically most of the consonants in the English alphabet switched around. Vowels and the consonants 'L', 'N', 'Q' keep their original position. ABCDEFGHIJKLMNOPQRSTUVWXYZ is changed to AZYXEWVTISRLPNOMQKJHUGFDCB. For example, 'human' is 'tupan', and 'world' becomes 'foklx'. Here is the code:alphabet = ABCDEFGHIJKLMNOPQRSTUVWXYZ.lower()switched = AZYXEWVTISRLPNOMQKJHUGFDCB.lower()usr_txt = input(Enter Englsih text:)print(usr_txt)def get_letter(eng_letter): if alphabet.find(letter): if eng_letter.isupper(): alpha_place = alphabet.find(letter.lower()) return(switched[alpha_place].upper()) else: alpha_place = alphabet.find(letter.lower()) return(switched[alpha_place]) else: return(eng_letter)ent_word = ent_output = for word in usr_txt.split( ): ent_word = for letter in word: ent_letter = get_letter(letter) ent_word += ent_letter ent_output += + ent_wordprint(ent_output.strip())If you interested the updated code can be found at https://github.com/Logmytech/English-to-Entean | Translating from English to Entean | python;strings;python 3.x;caesar cipher | The most idiomatic Python solution would be to use the str.translate() function, which solves exactly this problem.I don't see any reason to split the input into words, then join the results back together. Just translate the entire string at once (where space maps to itself). |
_cstheory.8694 | Unique SAT ={$\phi$| $\phi$ has unique satisfying assignment } represents an important class of computational problems. I recall reading that P=NP iff Unique SAT is in P (I don't remember where I read it. Notice that Unique SAT is CoNP-hard and Unique SAT= SAT\ Double SAT where Double Sat={$\phi$| $\phi$ has two or more satisfying assignments}) I'm looking for an efficiently computable function $f(s_n)= \phi$ such that formula $\phi$ is uniquely satisfied by assignment $s_n$ where $n$ is the number of variables.Also, Can $f$ be made a bijection? Edit 1: Input is a binary string $s_n$, output is a 3SAT formula in CNF.Basically, I'm looking for an efficient algorithm that computes $f$. Ideally, such algorithm would allows us to construct hard instances for Unique SAT.EDIT 2: I'm seeking an algorithm that is able to generate all uniquely staisfiable instances not just the easy cases given so far. | Constructing uniquely satisfiable formulas | cc.complexity theory;unique solution | If I understand your question correctly, you're looking for ways to generate lots of non-trivial uniquely satisfiable 3SAT instances.There's a tension between your desire to find a way to generate all uniquely satisfiable instances and your desire to find a way to generate hard uniquely satisfiable instances. For the moment let's ignore your uniqueness condition. Then I know there has been some work on this problem, e.g., see this paper by Achlioptas et al. You might think that they proceed by generating random clauses and discarding the clauses that are inconsistent with a randomly chosen but fixed assignment. But although this method will in principle generate every satisfiable instance (with some probability), it tends to produce instances that are easy to solve. To get hard instances, Achlioptas et al. adopt the approach of picking some known hard problem and generating instances based on that. I suspect that a similar dilemma will arise for uniquely satisfiable instances. My guess is that a randomized method that generates every uniquely satisfiable instance with some probability will tend to produce easily solved instances. If you want hard instances, your best bet is probably to pick some cryptographic problem (where the unique solution is the cryptographic secret, e.g., a factorization) and generate instances based on that. |
_unix.18824 | I have been trying to get my .htaccess file to work on my localhost. I know that the file works because it is on my server and works. However it doesn't seem to be working locally.I have followed the tutorials I could find to set overrides to all, below is my /etc/apache2/sites-available/default file start:<VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www <Directory /> Options FollowSymLinks AllowOverride All </Directory> <Directory /var/www/> Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny allow from all </Directory>This is the code in the same directory for my nibble site:<VirtualHost *:80> ServerName nibble.local DocumentRoot /var/www/nibble_framework/web/ <Directory /var/www/nibble_framework/web/> AllowOverride All Options Indexes FollowSymLinks MultiViews Allow from All </Directory> RewriteLog /var/www/rewrite.log ErrorLog /var/log/apache2/error.log</VirtualHost>I have enabled this site using a2ensite and restarted apache. I have also added the site to my hosts file: 127.0.0.1 nibble.localI have enabled mod rewrite using a2enmod and restarted/reloaded apache multiple times. $ a2enmod rewrite Module rewrite already enabledMy .htaccess file is in /var/www/nibble_framework/web/.htaccess and has the following code: Options +FollowSymLinks +ExecCGI <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([^/]*)/?.*$ - [E=FILE:%{DOCUMENT_ROOT}/$1.php] RewriteCond %{ENV:FILE} !^$ RewriteCond %{ENV:FILE} -f RewriteRule ^([^/]*)/?(.*)$ $1.php?url=$2 [QSA,L] RewriteCond %{ENV:FILE} !^$ RewriteCond %{ENV:FILE} !-f RewriteRule ^(.*)$ index.php?url=$1 [QSA,L] </IfModule>When I do a print_r($_REQUEST), it is allways an empty array even when the url is poplulated by a long string.Does anyone have any idea why this might be failing?Edit:apache2 access log:~$ tail -f /var/log/apache2/access.log::1 - - [16/Aug/2011:07:32:39 +0100] OPTIONS * HTTP/1.0 200 152 - Apache/2.2.16 (Ubuntu) (internal dummy connection)::1 - - [16/Aug/2011:07:32:39 +0100] OPTIONS * HTTP/1.0 200 152 - Apache/2.2.16 (Ubuntu) (internal dummy connection)::1 - - [16/Aug/2011:07:32:39 +0100] OPTIONS * HTTP/1.0 200 152 - Apache/2.2.16 (Ubuntu) (internal dummy connection)::1 - - [16/Aug/2011:07:32:40 +0100] OPTIONS * HTTP/1.0 200 152 - Apache/2.2.16 (Ubuntu) (internal dummy connection)::1 - - [16/Aug/2011:07:32:40 +0100] OPTIONS * HTTP/1.0 200 152 - Apache/2.2.16 (Ubuntu) (internal dummy connection)::1 - - [16/Aug/2011:07:32:40 +0100] OPTIONS * HTTP/1.0 200 152 - Apache/2.2.16 (Ubuntu) (internal dummy connection)::1 - - [16/Aug/2011:07:32:40 +0100] OPTIONS * HTTP/1.0 200 152 - Apache/2.2.16 (Ubuntu) (internal dummy connection)::1 - - [16/Aug/2011:07:32:40 +0100] OPTIONS * HTTP/1.0 200 152 - Apache/2.2.16 (Ubuntu) (internal dummy connection)::1 - - [16/Aug/2011:07:32:40 +0100] OPTIONS * HTTP/1.0 200 152 - Apache/2.2.16 (Ubuntu) (internal dummy connection)::1 - - [16/Aug/2011:07:32:40 +0100] OPTIONS * HTTP/1.0 200 152 - Apache/2.2.16 (Ubuntu) (internal dummy connection) | Localhost .htaccess not working on Ubuntu | apache httpd;htaccess | I suspect your VirtualHost is not getting processed correctly, which would then not set AllowOverride for the get requests. First your /etc/hosts file should look like this..127.0.0.1 localhost localhost.localdomain127.0.1.1 nibble.localSecond, You must have that interface set for namebased vhosts. You did not specify if you have it currently set. Usually its set in the main apache config, I'm guessing ubuntu/debian has that file located /etc/apache2/apache2.conf.Make sure this line is set somewhere in that file,NameVirtualHost *:80Once you make these changes, restart apachesudo /etc/init.d/apache2 restartNoe test it out, remember you only set that hosts entry locally. So as is this will only work correctly when requested from localhost. If you get stuck, or it doesn't work, post the relevant lines from /var/log/apache2/error.log |
_unix.311921 | Condition: controlling 3D Image output of test code by mouse cause all CPUs to 100%; differential solutions do not help; no clicking of mouse on imageMotivation: to understand why mouse activates 3D Image process even when no evaluation of the notebook in Debian Mathematica Fig. 1 My Desktop where trying to overlay the figure and delete it causes the CPUs to max; doing Clear[data] before that does not help I need the notebook but the object keeps locking its use. Test code(* system info for WRI *)SystemInformation[] (* http://mathematica.stackexchange.com/q/38305/9815 *)data = Table[ Exp[-3 (x^2 + y^2 + z^2)], {x, -1., 1, .01}, {y, -1., 1, .01}, {z, -1., 1, .01}];Image3D[data, ClipRange -> {{100, 200}, {0, 200}, {100, 200}}, ColorFunction -> Automatic] (* default colour function *)System characteristicsmasi@masi:~$ glxinfo | grep OpenGLOpenGL vendor string: VMware, Inc.OpenGL renderer string: Gallium 0.4 on llvmpipe (LLVM 3.5, 256 bits)OpenGL version string: 3.0 Mesa 10.3.2OpenGL shading language version string: 1.30OpenGL context flags: (none)OpenGL extensions:masi@masi:~$ echo $LD_LIBRARY_PATHmasi@masi:~$ Mathematica startup option as instructed by Wolfram but still unsuccessful outputI runmasi@masi:~$ rm .Mathematica/ masi@masi:~$ suroot@masi:/home/masi# rm -r /usr/share/Mathematica/Do clean start masi@masi:~$ mathematica -cleanstartGet a new university licence for Mathematica and activateStart mathematica with the optionmathematica -mesaI contacted Wolfram student support with a link to this thread, waiting their answer for three days. OS: Debian 8.5Linux kernel: 4.6 of backports set up as described hereGraphics: modesetting set up as described in the thread How Smooth is Upgrading Linux kernel in Debian 8.5?Mathematica: 11 student editionMathematica documentation: How can I address broken 3D graphics on Linux with certain graphics cardsHardware: Asus Zenbook UX303UADifferential solutions: Clear[data], Quit kernel in Menu Evaluation | Why Mouse Activates 3D Image in non-evaluated NB of Debian Mathematica? | debian;monitoring;mouse;3d;mathematica | This was a bug in Mathematica 11.0.0 in Debian. Their testing was mostly in Mint Linux, where they did not obverse the problems. I posted a report about the case to Mathematica, where they promptly reacted and fixed the case. The new release Mathematica 11.0.1 is significantly better in Debian 8.5. |
_scicomp.5068 | I was looking at a book of FEM on problems of Diffusion-Transport.$$-div(\mu \nabla u) + b \cdot \nabla u + \gamma u = f \qquad in~\Omega$$$$u = 0 \qquad in~\partial\Omega\text{ (in the boundaries)}$$It says that if $\displaystyle \frac{|b|}{\mu} \gg 1$ then the problem is a problem dominated by transport.Taking some stuff from the previous chapter, more precisely the Galerking analysis of stability and convergence, and the approximation of the error, we have$$\displaystyle M \cong \mu + |b| \qquad \textrm{continuity constant}$$$$\alpha = \mu \qquad \textrm{coercivity constant}$$Then it has$$\displaystyle \frac{M}{\alpha} \cong1+\frac{|b|}{\mu} \gg 1$$As a consequence of that, it concludes that, the estimation of the error is$$\displaystyle ||u -u_h|| C\frac{M}{\alpha}h^r|u|_{H^{r+1}(\Omega)}$$which tell us that the Galerkin's method could give unsatisfactory results if the space step $h$ isn't small enough.I Can't understand how can it conclude such thing. Any idea? Please, do not give complex explanations, I'm just trying to understand this FEM stuff, I'm a computer science student more than a math one. | Diffusion-Transport problem FEM | finite element;error estimation | If you follow the analysis until the last equation, then you can see the problem. You write:$|| u-u_h|| \le C \frac{M}{\alpha} h^r |u|_{H^{r+1}(\Omega)}$which from the expression just above it could also be written as$|| u-u_h|| \le C \left(1+\frac{|b|}{\mu}\right) h^r |u|_{H^{r+1}(\Omega)}$Now say you want to solve a problem for a fixed mesh size. In the first problem $|b|=\mu$, then you have$|| u-u_h|| \le 2C h^r |u|_{H^{r+1}(\Omega)}$Now you move to the next problem and the transport is strong compared to diffusion, $|b|=10^4 \mu$.$|| u-u_h|| \le 10^4 C h^r |u|_{H^{r+1}(\Omega)}$So on a mesh with fixed size, the second solution is orders of magnitude worse. The only way to improve it is to decrease $h$ to an amount that resolves the transport scale (counteracting the huge constant). |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.