id
stringlengths
5
27
question
stringlengths
19
69.9k
title
stringlengths
1
150
tags
stringlengths
1
118
accepted_answer
stringlengths
4
29.9k
_softwareengineering.57547
we have a cross-platform middleware product which we typically end up customizing/bug fixing on a per client basis. In some cases, providing updates as often as once/twice per week.We have a lot of trouble efficiently managing and releasing the updates to our clients.I've done some digging, but I can't find anything to specifically address this problem.Can anyone share their experiences - how do you deal with this scenario, or do you know of a good software delivery cms?
How do you manage frequent software releases to multiple clients?
management;builds;release
null
_unix.251709
Is there a way to backup all my programs, software, maybe even libraries and their data on a Linux system like it is for apps and their data on rooted Android with TitaniumBackup?I'd like to backup all my current programs in files and activate them on another Linux system again.
How can I backup all my software in files to reinstall on another Linux system?
package management;backup
Backing up system files on UNIX type systems is generally not done on a file by file basis.If you are trying to migrate a system to new hardware, just boot the old machine with a live image such as knoppix and use dd to image your hard drive partitions to a remote machine over the network or to an external hard drive. Then you can boot the live image on the new machine and use dd to write the disk images to the new partitions. Note that the new machine will have the same configuration as the old machine, so if you are trying to clone a system while leaving the old system up then you will need to change a few configuration settings such as the hostname and any static IP addresses. Depending on what software you are using there may be other small changes that you need to make if both of the systems are to be used concurrently.If fully cloning a system is not what you are after, and the new system is the same Linux distribution as the old system, then use the package manager to get a list of installed software. That list can then be used by the package manager on the new system to install all of the software and libraries. After that just copy the data and configuration files from the old machine to the new one. Here is a URL describing this process for various distributions.Any software that was installed without using the package manager will need to be copied manually. In which case scp or rsync are the tools you are looking for. Such software is usually installed in /opt (for older legacy software) or under /usr/local/. You could clone the whole system this way, but if you miss anything important you will run into issues (hence why the previous two methods I mentioned are preferred). On Debian based distributions all of the important files should be contained in the following folders: /bin, /etc, /home, /lib, /lib64, /lib32, /opt (if it isn't empty), /root, /srv, /sbin, /usr, and /var. It is also a good idea to boot from a live image to do this as well since it will ensure that none of the files are being modified (especially in /var/log) while you are trying to copy them. This would look something like:rsync --progress -a -r /bin /etc /home /lib /lib64 /lib32 /opt /root /srv /sbin /usr /var [email protected]:/
_computergraphics.5072
I'm currently enrolled in an entry level Computer Graphics class, and as I'm studying for my final, I realize I have a question regarding the Cohen-Sutherland line clipping algorithm. I understand the basics of the algorithm, such as how to compute the 4-bit outcodes associated with each region and the test conditions for the endpoints of a line segment, but where I'm struggling is how to determine what the worst case scenario is for the algorithm.I've had the following question on both my midterm and a homework assignment: Draw two line segments (one with a positive slope and one with a negative slope) that reflect the worst case scenarios for the corresponding checking order. The following image file shows what the checking order was for each question, along with my original answers to the questions followed by the correct answers. If anyone could point me in the right direction, it would be greatly appreciated. The only answer from my professor I received when asking for an explanation was the worst case has to do with the checking order, and that answers absolutely nothing for me.
Worst Case Scenario for Cohen-Sutherland Line Clipping Algorithm
clipping
null
_unix.232290
I've been trying to build and install GNU Icecat from source on Arch linux using yaourt, but I've recieved errors during the build relating to the Infinality font set. I came across this page from the arch wiki which suggested that I could build the package in a clean chroot using the devtools package, which I have successfully done using the extra-x86_64-build build script.However, what the page is missing is any info on how to install the package to my main root from there. Any Ideas?
Arch - How do Install a package made in a clean chroot?
arch linux;compiling;chroot
null
_webmaster.15035
I'm really a newbie about this issues so excuse me if this is a rather dumb question, I'm trying to point a domain a client of mine bought to a sub-domain of mine, they're both from different companies, I'm not looking for a redirect but instead let's say his domain is www.clientdomain.com and mine is www.mydoamin.com I need to point dev.clientdomain.com to test.mydomain.com for example keeping the URL as it is, so when I visit the 'about' page it'd be dev.clientdomain.com/about instead of test.mydomain.com/about.I hope it makes some sense, I have seen this done before but have no idea if its using .htaccess files or changing some configuration options in the host control panel, if so I assume each host has their way of doing this so a general example would be great to point me in the right direction.Thanks in advance!
How to point a domain to another subdomain?
web hosting;domains;subdomain;nameserver
null
_unix.210065
INPUT: <a href=docs/2015-05-foobar/foobar.sh>foobar.sh</a>OUTPUT<a href=foobar.sh>foobar.sh</a>Question: How can I remove the docs/2015-05-foobar/ ? The string could vary between the 's
How to truncate a HTML link?
sed
null
_codereview.74803
I wrote the below enum from which I need to extract the name and its value:public enum UserEnum { TreeUser(/tree), ParentUser(/parent); private String value; UserEnum(String value) { this.value = value; } public String value() { return value; }}This is the way I am using the above UserEnum in my code base:// extract TreeUserString nameOfTree = UserEnum.TreeUser.name();String valueOfTree = UserEnum.TreeUser.value();// extract ParentUser String nameOfParent = UserEnum.ParentUser.name();String valueOfParent = UserEnum.ParentUser.value(); // and I am using UserEnum this way as well to make name1=value1,name2=value2 String mapping = UserEnum.TreeUser.name() + = + UserEnum.TreeUser.value() + , + UserEnum.ParentUser.name() + = + UserEnum.ParentUser.value(); I am opting for a review to see whether I can simplify anything in my enum.
Extracting name and value from the enum
java;enum
Not sure about the usage of nameOfTree , nameOfParent and same for the value. But one thing to simplify your mapping and provide a representation for your enum is:public String toString(){ return this.name() + = + this.value()}// and mapping cna be written as.String mapping = UserEnum.TreeUser.toString() + , + UserEnum.ParentUser.toString();String mapping = UserEnum.TreeUser + , + UserEnum.ParentUser; // toString() is called implictly.
_unix.107720
I have been able to make a phone calls using the SIP client Pjsua from one Linux computer to another one. In case you have not heard of this user agent, explaining it's functionality is quite easy. It uses IP and port number of each linux to create a unique ID and then calling to this specific ID is possible.Now I have not studied port forwarding thoroughly but I suppose what it does is to forward whatever data that comes in, to another port or IP and port.So I thought to myself, if my calling application is using ports and IPs to send and receive voice, I should be able to forward those specific ports to a second or third port (or IP and port) and listen to the conversation on a third computer.So here is what I did.Supposing that machine Linux A has the following identification info: IP:192.168.1.11` `UDP port# : 1111The second machine Linux B has the following identification: IP:192.168.1.22` `UDP port# : 2222If I do the following using iptables I should be able to hear that side of the conversation which is being received on Linux B on a 3rd system, Linux C .The third machine, Linux C has the following identification info: IP:192.168.1.33` `UDP port# : 3333To achieve this, I tried running this command on Linux B:$ iptables -t nat -A PREROUTING -p udp --dport 2222 -j DNAT--to-destination 192.168.1.33:3333 //forward port 2222 to Linux C on port 3333And ran this command on Linux C:$ aplay | nc -l -u 3333 //listen on the specified UDP port However I don't hear anything on Linux C.Can anyone tell me why this is not working? Other strategies to do something like this are also welcome.
listen to a conversation using port forwarding
linux;iptables;port forwarding;udp;sip
null
_webmaster.36278
I am planning to move several websites to a new hosting provider - keeping the same URL but will resolve to different IP addresses. For example, some sites are Canadian content-only sites, hosted on .CA domains sitting on Canadian IP addresses. I want to move these to Amazon servers which have US IP addresses.The domain names will remain the same. (1) What is the SEO impact of this? (2) Will the site lose some ranking if the sites are moved to a new IP address (Canadian or not), and if so, what is the cleanest way of accomplishing this (some kind of 301's)?
What is the SEO impact of moving my domain to another IP address and what is the right way of doing this?
seo;ip address;ranking;google ranking
null
_codereview.152010
Here is my code for Tarjan's strongly connected component algorithm. Please point out any bugs, performance/space (algorithm time/space complexity) optimization or code style issues.from collections import defaultdictclass SccGraph: def __init__(self, vertex_size): self.out_neighbour = defaultdict(list) self.vertex = set() self.visited = set() self.index = defaultdict(int) self.low_index = defaultdict(int) self.global_index = 0 self.visit_stack = [] self.scc = [] def add_edge(self, from_node, to_node): self.vertex.add(from_node) self.vertex.add(to_node) self.out_neighbour[from_node].append(to_node) def dfs_graph(self): for v in self.vertex: if v not in self.visited: self.dfs_node(v) def dfs_node(self, v): # for safe protection if v in self.visited: return self.index[v] = self.global_index self.low_index[v] = self.global_index self.global_index += 1 self.visit_stack.append(v) self.visited.add(v) for n in self.out_neighbour[v]: if n not in self.visited: self.dfs_node(n) self.low_index[v] = min(self.low_index[v], self.low_index[n]) elif n in self.visit_stack: self.low_index[v] = min(self.low_index[v], self.index[n]) result = [] if self.low_index[v] == self.index[v]: w = self.visit_stack.pop(-1) while w != v: result.append(w) w = self.visit_stack.pop(-1) result.append(v) self.scc.append(result)if __name__ == __main__: g = SccGraph(5) # setup a graph 1->2->3 and 3 -> 1 which forms a scc # setup another two edges 3->4 and 4->5 g.add_edge(1,2) g.add_edge(2,3) g.add_edge(3,1) g.add_edge(3,4) g.add_edge(4,5) g.dfs_graph() print g.scc
Tarjan's strongly connected component finding algorithm
python;algorithm;python 2.7;graph
null
_unix.84771
Can someone please tell me how to uninstall Aptana from ubuntu 12.04 LTS? I followed these instructions, in summary:Install the prerequisites with apt-get install.Download Aptana StudioExtract Aptana Studiosudo unzip [name of Aptana Studio ZIP file here].zip -d /optAdd the menu shortcutwget http://www.samclarke.com/wp-content/uploads/2012/04/AptanaStudio3.desktopsudo mv AptanaStudio3.desktop /usr/share/applications/AptanaStudio3.desktop
Uninstall Aptana from Ubuntu
ubuntu;software installation
null
_unix.350081
I have configured auditd to track some sensitive files on my system. Now I would to have a script that will be called each time auditd writes a line, with the $1 argument of that script being the line added.From what I read in the manual auditd has no such option.Is there a way to do this anyway?If I'll have a cron script running every minute, I will have a problem defining it on which lines it should work (which lines are new? if any?)
how to run a script on auditd events?
linux audit;events
Using the tail command like so:tail -Fn0 /var/log/audit/audit.log | /sbin/scriptand /sbin/script is like so:while IFS= read -r line; do #something to do with $line variable when it comesdone
_webapps.17307
I love SkyDrive, but find it frustrating when I want to attach a file that's on my SkyDrive to a new Hotmail message. I have to download the SkyDrive file to my computer and then attach the file to the email.Is there a way to cut out the middle man and just attach the file directly from SkyDrive?
Attaching SkyDrive files to Hotmail emails
outlook.com;attachment;onedrive
You can't do this. What you can do is share the document or file you would otherwise send as an attachment.Tick the checkbox next to the document filenameClick the Share link on the sidebarFrom the Share dialog that pops up with various options, you can share directly with another person by emailing them.Or you can click Get a link and select one of the options available:View onlyView and editMake it public!Then include the link in the body of your email.
_unix.346437
Is it possible to add SELinux policy rule to restrict an application to a specific virtual or physical memory address range? If so, which SELinux policy rule allows for a memory range to be specify? Thanks.
Is it possible to add SELinux policy rule to restrict an application to a memory address range?
linux;security;selinux
null
_unix.276005
I use MATE on Fedora. At some point, the behavior of scrollbars on many applications has changed. When I click below a scrollbar, now the scrollbar jumps to where I clicked. Previously, it used to page down by one page (if I clicked anywhere below the current location of the scrollbar).I preferred the old behavior. When on a very long page, the new behavior tends to make the scrollbar almost unusable: I can't control where I click precisely enough to control where the page jumps to.Is there a way to regain the previous behavior? In other words, is there a way to make clicking on a scrollbar, below the current location of the scroll, to cause the window to go down by one page, rather than jumping to where I clicked?This difference is most noticeable in Firefox, but is not limited solely to Firefox; it affects other applications, too.
Scrollbar moves to where I click
mouse;gtk;scrolling
null
_unix.315002
I noticed that my vi editor changes inodes when editing files, except when that file is under /tmp. Why is this?
VI editor changes and does not change inodes of files when editing files under /tmp
centos;vi;inode
null
_unix.17067
# which mkdir/bin/mkdir# which mkdi# How can I get the path of the e.g.: mkdir's binary without knowing the name of the binary file? (command). So that which mkdi would output the /bin/mkdir too.
which with a little grep-like solution?
bash;shell;wildcards;path
In zsh:echo $path/mkdi*(N)In other shells, for human consumption:set -f; IFS=:for x in $PATH; do set +f; ls $x/mkdi* 2>/dev/null; done
_unix.146296
I know that in ~/.bashrc one must not put spaces around = signs in assignment:$ tail -n2 ~/.bashrc alias a=echo 'You hit a!'alias b = echo 'You hit b!'$ aYou hit a!$ bb: command not foundI'm reviewing the MySQL config file /etc/my.cnf and I've found this:tmpdir=/mnt/ramdiskkey_buffer_size = 1024Minnodb_buffer_pool_size = 512Mquery_cache_size=16MHow might I verify that the spaces around the = signs are not a problem?Note that this question is not specific to the /etc/my.cnf file, but rather to *NIX config files in general. My first inclination is to RTFM but in fact man mysql makes no mention of the issue and if I need to go hunting online for each case, I'll never get anywhere. Is there any convention or easy way to check? As can be seen, multiple people have edited this file (different conventions for = signs) and I can neither force them all to use no spaces, nor can I go crazy checking everything that may have been configured and may or may not be correct.EDIT: My intention is to ensure that currently-configured files are done properly. When configuring files myself, I go with the convention of whatever the package maintainer put in there.
When are spaces around the = sign forbidden?
configuration;file format
I'll answer that in a more general way - looking a bit at the whole Unix learning experience. In your example you use two tools, and see the language is similar. It just unclear when to use what exactly. Of course you can expect there is a clear structure, so you ask us to explain that.The case with the space around = is only and example - there are lot's of similar-but-bot-quite cases.There has to be a logic in it, right?!The rules how to write code for some tool, shell, database etc only depend on what this particular tool requires. That means that the tools are completely independent, technically. The logical relation that I think you expect simply does not exist. The obvious similarity of the languages you are seeing are not part of the programm implementation. The similarity exist because developers had agreed how to do it when they wrote it down for a particular program. But humans can agree only partially. The relation you are seeing is a cultural thing - it's neither part of the implementation, nor in the definition of the language.So, now that we have handeled the theory, what to do in practise?A big step is to accept that the consistency you expected does not exist - which is much easier when understanding the reasons - I hope the theory part helps with this.If you have two tools, that do not use the same configuration language (eg. both bash scripting), knowing the details of the syntax of one does not help much with understanding the other;So, indeed, you will have to look up details independently. Make sure you know where you find the reference documentation for each.On the positive side, there is some consistency where you did not expect it: in the context of a single tool (or different tools using the same language), you can be fairly sure the syntax is consistent.In your mysql example, that means you can assume that all lines have the same rule. So the rule is space before and after = is not relevant.There are wide differences in how hard it is to learn or use the configuration- or scripting language of a tool.It can be some like List foo values in cmd-foo.conf, one per line..It can be a full scripting language that is used elsewhere too. Then you have a powerful tool to write configuration - and in some cases that's just nice, in others you will really need that.Complex tools, or large famillies of related tools sometimes just use very complex special configuration file syntax - (some famous examples are sendmail and vim).Others use a general scripting language as base, and extend that language to support the special needs, some times in complex ways, as the language allows. That would be a very specific case of a domain-specific language (DSL).
_webmaster.105717
My domains are managed on Google but my site is hosted on AWS. I want to point both my root my-company.com and the www subdomain www.my-company.com to an AWS Load Balancer, which has an address, not an IP.Although I am allowed to add a Custom CNAME Resource Record for the www subdomain and it points to the LB address without any problems, I am not allowed to make the root record a CNAME record nor am I allowed to have the root A Record point to the LB address. It seems I have no way to point my root domain to an AWS Load Balancer.I tried looking into forwarding the domain to the www subdomain which works, but Google warns that then both the root and www records will be removed, so that would break the www forward to my LB.I thought to create a subdomain prod.my-company.com and use domain forwarding to point both root and and www to prod (Google says that domain forwarding will not affect any subdomains accept www) but this will not work because it will forward users to prod.my-company.com. I tried using AWS Route53 and was thinking of adding an NS record for root but Google also doesn't allow NS records for root!Any thoughts on how to make this work?
Cannot forward root domain managed by Google Domains to AWS Load Balancer
domains;subdomain;amazon aws;domain forwarding;google domains
This is a limitation in the fundamental design of DNS itself. Adding a CNAME at the apex of a domain is essentially invalid because it leads to an illogical set of consequences.This is why Route 53 created A-Record Aliases -- to work around exactly this issue. Instead of an external referral, like a CNAME does, Alias records are an internal referral -- Route 53 looks up the record using an internal lookup from its own database, returning what is essentially a dynamically populated A record.One option is to use a service like http://wwwizer.com, which gives you an A record for your example.com that simply returns a redirect to www.example.com. (To be clear, this isn't a recommendation or endorsement; I have no affiliation with this service and don't use it, but have seen it mentioned in this context.) The www record, of course, works fine with a CNAME.Another option is to move the hosting of your DNS to Route 53 but not the domain registration. If your domain is registered with Google, you can retain the registration there, but host the records on Route 53... but this is not done by creating NS records. The process appears to be documented here.The cost of Route 53 seems low enough to consider insignificant in this configuration, since they don't bill you for DNS queries that reach Alias records, when the Alias record terminates on ELB, CloudFront, or S3.
_codereview.163532
I created code for inserting and retrieving data from a specific table. I tried to optimize it and make it as beautiful and easy to read as I can, but maybe (almost certainly) I'm missing something.It works well, but I wonder if I did all right? Have I forgotten about something?public class EpgManager {private DatabaseHandler db;private List<JSONEpgManagerModel> jsonEpgManagerModel;private EPGManagerEvent epgManagerEvent;private SQLiteDatabase sqlDB;private List<EPGModel> singleEpgChannel;private List<EPGFullRowModel> fullRowModelList = new ArrayList<>();public EpgManager(Context context, EPGManagerEvent epgManagerEvent) { db = new DatabaseHandler(context); sqlDB = db.getWritableDatabase(); this.epgManagerEvent = epgManagerEvent;}/** * Method: Serializes Json String into Object of type JsonEpgManagementModel * <ul> * <li>Creates a sql insert query</li> * <li>Cleans epg_table</li> * <li>Loads data from JSON</li> * <li>Calls the {@link #epgManagerEvent onEpgUpdated} to show completion</li> * </ul> * * @param JSON epg json array */public void updateEpgTable(final String JSON, final HashMap<String, Integer> channelNumberMap, final HashMap<String, String> channelImageMap) { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { sqlDB.delete(db.EPG_TABLE, null, null); try { jsonEpgManagerModel = Arrays .asList(new Gson().fromJson(JSON, JSONEpgManagerModel[].class)); } catch (Exception e) { e.printStackTrace(); } writeEPGTable(jsonEpgManagerModel, channelNumberMap, channelImageMap); return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); epgManagerEvent.onEpgUpdated(); } }.execute();}/** * Method: Inserts rows into epg_table * * @param jsonEpgManagerModel Serialized EPG Model * @param channelNumberMap Channel ID and Channel Number HashMap * @param channelImageMap Channel ID and Channel Image HashMap */private void writeEPGTable(List<JSONEpgManagerModel> jsonEpgManagerModel, HashMap<String, Integer> channelNumberMap, HashMap<String, String> channelImageMap) { String epgSqlInsertStatement = INSERT INTO + db.EPG_TABLE + ( + db.KEY_EPG_ID + , + db.KEY_EPG_DATE + , + db.KEY_EPG_DATE_MILLISECONDS + , + db.KEY_EPG_DISPLAY_TIME + , + db.KEY_EPG_TITLE + , + db.KEY_EPG_DESCRIPTION + , + db.KEY_EPG_IMAGE_URL + , + db.KEY_EPG_DURATION + , + db.KEY_EPG_CHANNEL_ID + , + db.KEY_EPG_CHANNEL_NUMBER + , + db.KEY_EPG_CHANNEL_IMAGE_LINK + ) + values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);; sqlDB.beginTransaction(); SQLiteStatement sqLiteStatement = sqlDB.compileStatement(epgSqlInsertStatement); for (int i = 0; i < jsonEpgManagerModel.size(); i++) { for (int k = 0; k < jsonEpgManagerModel.get(i).getEPGList().size(); k++) { ChannelPrograms epgProgram = jsonEpgManagerModel.get(i).getEPGList().get(k); sqLiteStatement.bindString(1, epgProgram.getEpgId()); sqLiteStatement.bindString(2, epgProgram.getEpgDate()); sqLiteStatement.bindLong(3, getDateInMilliseconds(epgProgram.getEpgDate())); sqLiteStatement.bindString(4, epgProgram.getEpgDisplayTime()); sqLiteStatement.bindString(5, epgProgram.getEpgTitle()); sqLiteStatement.bindString(6, epgProgram.getEpgDescription()); sqLiteStatement.bindString(7, epgProgram.getEpgImageUrl()); sqLiteStatement.bindString(8, epgProgram.getEpgDuration()); sqLiteStatement.bindString(9, jsonEpgManagerModel.get(i).getEpgChannelId()); sqLiteStatement.bindString(10, + channelNumberMap.get(jsonEpgManagerModel.get(i).getEpgChannelId())); sqLiteStatement.bindString(11, + channelImageMap.get(jsonEpgManagerModel.get(i).getEpgChannelId())); sqLiteStatement.executeInsert(); sqLiteStatement.clearBindings(); } } sqlDB.setTransactionSuccessful(); sqlDB.endTransaction();}/** * Method returns list of epg channels and programs in order to build the epg * <ul> * <li>Gets rows from channel_table</li> * <li>Gets rows from epg_table by channel_table channel_id</li> * <li>Populates list of EPGFullRowModel class</li> * </ul> * * @return EPG Screen data list of type EPGFullRowModel */public List<EPGFullRowModel> getAllChannelPrograms() { List<EPGModel> epgProgramList = new ArrayList<>(); Cursor channelCursor = sqlDB.query(db.CHANNEL_TABLE, new String[] {db.KEY_CHANNEL_ID, db.KEY_CHANNEL_IMG_LINK, db.KEY_CHANNEL_NUMBER}, null, null, null, null, null); Cursor epgCursor; while (channelCursor.moveToNext()) { epgCursor = sqlDB.query(db.EPG_TABLE, null, db.KEY_EPG_CHANNEL_ID + =?, new String[] {channelCursor.getString(0)}, null, null, db.KEY_EPG_DATE_MILLISECONDS + ASC); while (epgCursor.moveToNext()) { epgProgramList.add( new EPGModel( epgCursor.getString(1),epgCursor.getString(2), epgCursor.getString(3),epgCursor.getString(4), epgCursor.getString(5),epgCursor.getString(6), epgCursor.getString(7),epgCursor.getString(8), epgCursor.getString(9),channelCursor.getString(2), epgCursor.getString(1) ) ); } fullRowModelList.add(new EPGFullRowModel( new ChannelModel(channelCursor.getString(0), channelCursor.getString(1), Integer.valueOf(channelCursor.getString(2))), epgProgramList)); epgCursor.close(); epgProgramList = new ArrayList<>(); } channelCursor.close(); return fullRowModelList;}/** * Method returns list of epg programs in order to build the single channel epg * * @param channelId Channel unique id * @return Single epg row list of type EPGModel */public List<EPGModel> getSingleChannelPrograms(String channelId) { Cursor cursor = sqlDB .query(db.EPG_TABLE, null, db.KEY_EPG_CHANNEL_ID + =?, new String[] {channelId}, null, null, db.KEY_EPG_DATE_MILLISECONDS + ASC, null); singleEpgChannel = new ArrayList<>(); Log.e(CURSOR , String.valueOf(cursor.getCount())); if (cursor.moveToFirst()) { do { singleEpgChannel.add( new EPGModel(cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getString(6), cursor.getString(7), cursor.getString(8), cursor.getString(9), cursor.getString(10), cursor.getString(11))); } while (cursor.moveToNext()); } cursor.close(); return singleEpgChannel;}/** * Method transforms the date of string into long of milliseconds * * @param date Epg program date * @return Milliseconds */private long getDateInMilliseconds(String date) { date = date.replaceAll(T, ); date = date.replaceAll(Z, ); SimpleDateFormat simpleDateFormat = new SimpleDateFormat(yyyy-MM-dd HH:mm:ss); Calendar calendar = Calendar.getInstance(); try { calendar.setTime(simpleDateFormat.parse(date)); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); } catch (ParseException e) { e.printStackTrace(); } return calendar.getTimeInMillis();}}
Code for writing and reading from the database
java;android;sqlite
null
_softwareengineering.257266
This started out as a SO question but I realized that it is quite unconventional and based on the actual description on the websites, it might be better suited to programmers.se since the question has a lot of conceptual weight. I have been learning clang LibTooling and it is a very powerful tool capable of exposing the entire nitty gritty of the code in a friendly way, that is, in a semantic way, and not by guessing either. If clang can compile your code, then clang is certain about the semantics of every single character inside that code. Now allow me to step back for a moment. There are many practical problems that arise when one engages in C++ template metaprogramming (and especially when venturing beyond templates into the territory of clever albeit terrifying macros). To be honest, to many programmers, myself included, many of the ordinary uses of templates are also somewhat terrifying. I guess a good example would be compile-time strings. This is a question that is over a year old now, but it is clear that C++ as of right now does not make this easy for mere mortals. While looking at these options isn't quite enough to induce nausea for me, it nevertheless leaves me unconfident about being able to produce magical, maximally efficient machine code to suit whatever fancy application I have for my software. I mean, let's face it, folks, strings are pretty simple and basic. Some of us just want a convenient way to emit machine code that has certain strings baked in significantly more than we do get when coding it the straightforward way. In our C++ code. Enter clang and LibTooling, which exposes the abstract syntax tree (AST) of the source code and allows a simple custom C++ application to correctly and reliably manipulate raw source code (using Rewriter) alongside a rich semantic object-oriented model of everything in the AST. It handles a lot of things. It knows about the macro expansions, and lets you follow those chains. Yes, I am talking about source-to-source code transformation or translation. My fundamental thesis here is that clang now enables us to create executables which themselves can function as the ideal custom preprocessor stages to our C++ software, and we can implement these metaprogramming stages with C++. We are simply constrained by the fact that this stage must take input which is valid C++ code and produce as output more valid C++ code. Plus whatever other constraints your build system applies. The input has to be at least very close to valid C++ code because, after all, clang is the compiler front-end and we are just poking around and being creative with its API. I do not know if there is any provision for being able to define new syntax to use, but clearly we have to develop the ways to properly parse it and add it to the clang project in order to do this. To expect any more is to have something in the clang project that is out of scope. Not a problem. I would imagine that some no-op macro functions can handle this task. Another way to look at what I'm describing is to implement metaprogramming constructs using runtime C++ by manipulating the AST of our source code (thanks to clang and its API) instead of implementing them using the more limited tools available in the language itself. This has clear compilation performance benefits as well (template-heavy headers slow compilation proportionally to how often you use them. Lots of compiled stuff then gets carefully matched up and thrown away by the linker). This does, however, come at the cost of introducing an additional step or two in the build process and also in the requirement of writing some (admittedly) somewhat more verbose software (but at least it is straightforward runtime C++) as part of our tool. That isn't the whole picture. I am pretty certain that there is a much larger space of functionality that can be had from generating code that is extremely difficult or impossible with core language features. In C++ you can write a template or a macro or a crazy combination of both, but in a clang tool you can modify classes and functions in ANY way that you can achieve with C++, at runtime, while having full access to the semantic content, in addition to template and macros and everything else.So, I'm wondering about why everybody isn't already doing this. Is it that this functionality from clang is so new and nobody is familiar with the huge class hierarchy of clang's AST? That can't be it.Perhaps I am just underestimating the difficulty of this a little bit, but doing compile-time string manipulation with a clang tool is nearly criminally simple. It's verbose, but it's insanely straightforward. All that's needed are a bunch of no-op macro functions that map to actual real std::string operations. The clang plugin implements this by fetching all the relevant no-op macro calls, and performs the operations with strings. This tool is then inserted as a part of the build process. During build, these no-op macro function calls are automatically evaluated into their results, and then inserted back as plain old compile-time strings in the program. The program can then be compiled as usual. In fact this resulting program is also much more portable as a result, not requiring a fancy new compiler supporting C++11.
C++: Metaprogramming with a compiler API rather than with C++ features
c++;c++11;meta programming;clang
Yes, Virginia, there is a Santa Claus.The notion of using programs to modify programs has been around a long time. The original idea came from John von Neumann in the form of stored-program computers. But machine code modifying machine code in arbitrary ways is pretty inconvenient. People generally want to modify source code. This is mostly realized in the form of program transformation systems (PTS).PTS generally offer, for at least one programming language, the ability to parse to ASTs, manipulate that AST, and regenerate valid source text. If in fact you dig around, for most mainstream languages, somebody has built such a tool (Clang is an example for C++, the Java compiler offers this capability as an API, Microsoft offers Rosyln, Eclipse's JDT, ...) with a procedural API that is actually pretty useful. For the broader community, almost every language-specific community can point to something like this, implemented with various levels of maturity (usually modest, many just parsers producing ASTs). Happy metaprogramming.[There's a reflection-oriented community that tries to do metaprogramming from inside the programming language, but only achieve runtime behaviour modifiation, and only to the extent that the language compilers made some information available by reflection. With the exception of LISP, there are always details about the program that are not available by reflection (Luke, you need the source) that always limit what reflection can do.]The more interesting PTS do this for arbitrary languages (you give the tool a language description as a configuration parameter, including at a minimum the BNF). Such PTS also allow you to do source to source transformation, e.g., specify patterns directly using the surface syntax of the targeted language; using such patterns, you can code fragments of interest, and/or find and replace code fragments. This is far more convenient than the programming API, because you don't have to know every microscopic details about the ASTs to do most of your work. Think of this as meta-metaprogramming :-} A downside: unless the PTS offers various kinds of useful static analyses (symbol tables, control and data flow analyses), it is hard to write really interesting transformations this way, because you need to check types and verify information flows for most practical tasks. Unfortunately, this capability is in fact rare in the general PTS. (It is always unavailable with the ever-proposed If I just had a parser... See my bio for a longer discussion of Life After Parsing).There's a theorem that says if you can do string rewriting [thus tree rewriting] you can do arbitrary transformation; and thus a number of PTS lean on this to claim you can metaprogram anything with just the tree rewrites they offer. While the theorem is satisfying in the sense you are now sure you can do anything, it is unsatisfying in the same way that a Turing Machine's ability to do anything doesn't make programming a Turing Machine the method of choice. (The same holds true for systems with just procedural APIs, if they will let you make arbitrary changes to the AST [and in fact I think this is not true of Clang]).What you want is the best of both worlds, a system that offers you the generality of the language-parameterized type of PTS (even handling multiple languages), with the additional static analyses, the ability to mix source-to-source transformations with procedural APIs. I only know of two that do this:Rascal (MPL) MetaProgramming Languageour DMS Software Reengineering ToolkitUnless you want the write the language descriptions and static analyzers yourself (for C++ this is a tremendous amount of work, which is why Clang was constructed both as a compiler and as general procedural metaprogramming foundation), you will want a PTS with mature language descriptions already available. Otherwise you will spend all your time configuring the PTS, and none doing the work you actually wanted to do. [If you pick a random, non-mainstream language, this step is very hard to avoid].Rascal tries to do this by co-opting OPP (Other People's Parsers) but that doesnt help with the static analysis part. I think they have Java pretty well in hand, but I'm very sure they don't do C or C++. But, its a academic research tool; hard to blame them.I emphasize, our [commercial] DMS tool does have Java, C, C++ full front ends available. For C++, it covers almost everything in C++14 for GCC and even Microsoft's variations (and we are polishing now), macro expansion and conditional management, and method-level control and data flow analysis. And yes, you can specify grammar changes in a practical way; we built a custom VectorC++ system for a client that radically extended C++ to use what amount to F90/APL data-parallel array operations. DMS has been used to carry out other massive metaprogramming tasks on large C++ systems (e.g., application architectural reshaping). (I am the architect behind DMS).Happy meta-metaprogramming.
_unix.368202
I have a simple task that I can do with multiple lines but I wanted to run this through just 1 cron job as 1 line, and not have 12 separate lines. Here is the setup: Have one folder on an image processing share that gets images and moves them to 12 different folders depending on location and other things. Folder names are 1a, 2a, 3a, 4a, 5a, 6a, etc. to 12a. Folders 1a-6a need to go to a mounted drive on dr01 and folders 7a-12a need to go to a mounted folder named dr02. Each of the #a folders have a lot of subfolders and files inside. So, I want to rsync ../images/1a to ..DR01/1a twice a day. I can do this for each folder individually with: rsync -avh --remove-source-files /images/1a/ /usr/local/blah/dr02/1a/I wish that I could just sync the entire directory, but since half of the files are going to one share and the other half to another, I have to break them up. Is there a better way to do this without having to create 12 rsync jobs to sync each folder? Is there a way to group them in the rsync line or something like that? I used to use union-fs to fuse the DRs together, but that is no longer a working option. Thanks in advance for any tips that can help me resolve this issue.
Rsync multiple directories in one line
rsync
Something like this might work for you, assuming a shell that can expand {x..y} type constructs. (Test it from the command-line by prefixing the entire line with echo.)rsync -avh --remove-source-files /images/{1..6}a /mnt/dr01/rsync -avh --remove-source-files /images/{7..12}a /usr/local/blah/dr02/
_webapps.50183
A friend of mine who went on an exchange to Denmark asked me for help, because sometimes he just wants to see movies in Spanish, or at least with the subtitles in Spanish. But he said that every movie he sees has the subtitles in Danish and he cannot change the language. Is there any way to ask Netflix to change the language? Or at least to trick it to believe he is in a Spanish speaking country? As you know, using proxies would be unacceptably slow.So the questions would be: Is there a video-ready hide-my-ip software out there? Is there any other faster way to do this? Thanks in advance.
Netflix forced language localisation
localization;netflix
Has he tried VPN like hide my ass: http://vpnverge.com/truths-about-hidemyass/ or DNS service like smartyDNS?
_unix.102575
I am using a motherboard based on this architecture.http://www.intel.com/content/www/us/en/intelligent-systems/navy-pier/embedded-intel-atom-n270-with-mobile-intel-945gse-express-chipset.htmlI need the linux driver for Intel 82801GB I/O Controller Hub (Intel ICH7). I find only windows drivers for this chipset. Any pointers would be useful.The actual issue I am facing is as described below.Issue: Secondary hard disk failure leads to OS Stall..Motherboard : Quanmax KEMX 2030Operating System: Debian 2.6.32-31Our Setup and Application Description: On the KEMX 2030 motherboard, we connect two HDDs each at SATA 0 and SATA 1. SATA 0 is connected to a HDD(primary) which is loaded with Debian Linux OS. SATA 1 is connected to a HDD(secondary) which does not have any OS but has data storage partitions. Our application runs on the primary HDD and we copy certain critical files from primary to secondary HDD periodically for backup purposes.Problem Description: A faulty secondary HDD results in primary HDD Operating system stalling and freezing. There are two cases that we have witnessed in our field deploymentsWhen the secondary HDD has developed bad sectors, whenever a file copy operation is performed from primary to secondary, the primary OS will start throwing DRDY UNC errors in its kernel log. UNC means uncorrectable sectors. The OS is not able to recover from this scenario and the whole system freezes and every application running on the primary HDD will become dead slow because the sata bus is choked.When the sata data cable to the secondary HDD is faulty or of low quality, the primary OS will start throwing DRDY ICRC errors in its kernel log. ICRC means CRC errors in the data transmission. Even in this case, the primary OS freezes.Question is that why should the primary OS freeze when the secondary HDD goes bad. Is it because the SATA bus is getting choked? We want the primary HDD not to be affected because of secondary HDD failures.In order to isolate the problem and we did the following test. With a regular PC motherboard, we connected the same primary and secondary(faulty) drive to simulate the case. On simulating, we found that the linux kernel detects the same DRDY UNC/ICRC errors and in a matter of about 2 minutes, it is able to make the secondary HDD as read only and prevents further damage. The primary OS does not get choked at all. This PC motherboard also had a similar SATA 0 and SATA 1 to which we connected the same HDDs. We could not understand how the PC motherboard handled the scenario better. This test proved that the OS is doing it job on the PC motherboard, but on the KEMX motherboard it does not. Quanmax architecture is as shown in the picture below . Do I need a specific I/O controller driver to address this issue?Further debugging it, we found that irrespective of we connecting the secondary hard disk on SATA 0 or SATA 1 port, linux is able to scan for the secondary hard disk only on SCSI /HOST 0 port. If we do a scan on SCSI/HOST 1, the secondary HDD is not getting detected. Does this mean, the SATA bus is multiplexed into SCSI HOST 0? On the contrary, in the case of regular PC motherboards, we noticed that the scan has to be performed on the respective SCSI/HOST port for the secondary HDD to be detected.Following is the lspci output on the Quanmax KEMX board.debian:~# lspci00:00.0 Host bridge: Intel Corporation Mobile 945GME Express Memory Controller Hub (rev 03)00:02.0 VGA compatible controller: Intel Corporation Mobile 945GME Express Integrated Graphics Controller (rev 03)00:02.1 Display controller: Intel Corporation Mobile 945GM/GMS/GME, 943/940GML Express Integrated Graphics Controller (rev 03)00:1b.0 Audio device: Intel Corporation N10/ICH 7 Family High Definition Audio Controller (rev 02)00:1c.0 PCI bridge: Intel Corporation N10/ICH 7 Family PCI Express Port 1 (rev 02)00:1d.0 USB Controller: Intel Corporation N10/ICH 7 Family USB UHCI Controller #1 (rev 02)00:1d.1 USB Controller: Intel Corporation N10/ICH 7 Family USB UHCI Controller #2 (rev 02)00:1d.2 USB Controller: Intel Corporation N10/ICH 7 Family USB UHCI Controller #3 (rev 02)00:1d.3 USB Controller: Intel Corporation N10/ICH 7 Family USB UHCI Controller #4 (rev 02)00:1d.7 USB Controller: Intel Corporation N10/ICH 7 Family USB2 EHCI Controller (rev 02)00:1e.0 PCI bridge: Intel Corporation 82801 Mobile PCI Bridge (rev e2)00:1f.0 ISA bridge: Intel Corporation 82801GBM (ICH7-M) LPC Interface Bridge (rev 02)00:1f.2 IDE interface: Intel Corporation 82801GBM/GHM (ICH7 Family) SATA IDE Controller (rev 02)00:1f.3 SMBus: Intel Corporation N10/ICH 7 Family SMBus Controller (rev 02)01:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168B PCI Express Gigabit Ethernet controller (rev 02)debian:~#Following is the lspci output on the regular PC motherboard.debian:~# lspci00:00.0 Host bridge: Intel Corporation 82G33/G31/P35/P31 Express DRAM Controller (rev 02)00:01.0 PCI bridge: Intel Corporation 82G33/G31/P35/P31 Express PCI Express Root Port (rev 02)00:02.0 VGA compatible controller: Intel Corporation 82G33/G31 Express Integrated Graphics Controller (rev 02)00:19.0 Ethernet controller: Intel Corporation 82562V-2 10/100 Network Connection (rev 02)00:1a.0 USB Controller: Intel Corporation 82801I (ICH9 Family) USB UHCI Controller #4 (rev 02)00:1a.1 USB Controller: Intel Corporation 82801I (ICH9 Family) USB UHCI Controller #5 (rev 02)00:1a.2 USB Controller: Intel Corporation 82801I (ICH9 Family) USB UHCI Controller #6 (rev 02)00:1a.7 USB Controller: Intel Corporation 82801I (ICH9 Family) USB2 EHCI Controller #2 (rev 02)00:1b.0 Audio device: Intel Corporation 82801I (ICH9 Family) HD Audio Controller (rev 02)00:1d.0 USB Controller: Intel Corporation 82801I (ICH9 Family) USB UHCI Controller #1 (rev 02)00:1d.1 USB Controller: Intel Corporation 82801I (ICH9 Family) USB UHCI Controller #2 (rev 02)00:1d.2 USB Controller: Intel Corporation 82801I (ICH9 Family) USB UHCI Controller #3 (rev 02)00:1d.7 USB Controller: Intel Corporation 82801I (ICH9 Family) USB2 EHCI Controller #1 (rev 02)00:1e.0 PCI bridge: Intel Corporation 82801 PCI Bridge (rev 92)00:1f.0 ISA bridge: Intel Corporation 82801IR (ICH9R) LPC Interface Controller (rev 02)00:1f.2 IDE interface: Intel Corporation 82801IR/IO/IH (ICH9R/DO/DH) 4 port SATA IDE Controller (rev 02)00:1f.3 SMBus: Intel Corporation 82801I (ICH9 Family) SMBus Controller (rev 02)00:1f.5 IDE interface: Intel Corporation 82801I (ICH9 Family) 2 port SATA IDE Controller (rev 02)The difference is that regular PC motherboard has ICH9 family and Quanmax KEMX has ICH7 family.Following is the kernel log which shows ata_piix version 2.13 is the driver which is being used. Does this version of the driver have a bug?2013 Nov 21 17:14:19::kernel::[ 1.569271] ata_piix 0000:00:1f.2: version 2.132013 Nov 21 17:14:19::kernel::[ 1.569315] ata_piix 0000:00:1f.2: PCI INT B -> GSI 19 (level, low) -> IRQ 192013 Nov 21 17:14:19::kernel::[ 1.569405] ata_piix 0000:00:1f.2: MAP [ P0 P2 IDE IDE ]2013 Nov 21 17:14:19::kernel::[ 1.569697] ata_piix 0000:00:1f.2: setting latency timer to 642013 Nov 21 17:14:19::kernel::[ 1.576892] scsi0 : ata_piix2013 Nov 21 17:14:19::kernel::[ 1.581480] scsi1 : ata_piix2013 Nov 21 17:14:19::kernel::[ 1.584880] ata1: SATA max UDMA/133 cmd 0x1f0 ctl 0x3f6 bmdma 0xffa0 irq 142013 Nov 21 17:14:19::kernel::[ 1.584952] ata2: PATA max UDMA/100 cmd 0x170 ctl 0x376 bmdma 0xffa8 irq 152013 Nov 21 17:14:19::kernel::[ 1.756783] ata1.00: ATA-8: ST320LT012-9WS14C, 0001SDM1, max UDMA/1332013 Nov 21 17:14:19::kernel::[ 1.756860] ata1.00: 625142448 sectors, multi 16: LBA48 NCQ (depth 0/32)2013 Nov 21 17:14:19::kernel::[ 1.757445] ata1.01: ATA-8: ST320LT012-9WS14C, 0001SDM1, max UDMA/1332013 Nov 21 17:14:19::kernel::[ 1.757517] ata1.01: 625142448 sectors, multi 16: LBA48 NCQ (depth 0/32)2013 Nov 21 17:14:19::kernel::[ 1.772546] ata1.00: configured for UDMA/1332013 Nov 21 17:14:19::kernel::[ 1.789555] ata1.01: configured for UDMA/1332013 Nov 21 17:14:19::kernel::[ 1.789846] scsi 0:0:0:0: Direct-Access ATA ST320LT012-9WS14 0001 PQ: 0 ANSI: 52013 Nov 21 17:14:19::kernel::[ 1.790422] scsi 0:0:1:0: Direct-Access ATA ST320LT012-9WS14 0001 PQ: 0 ANSI: 52013 Nov 21 17:14:19::kernel::[ 1.814269] sd 0:0:0:0: [sda] 625142448 512-byte logical blocks: (320 GB/298 GiB)2013 Nov 21 17:14:19::kernel::[ 1.814370] sd 0:0:0:0: [sda] 4096-byte physical blocks2013 Nov 21 17:14:19::kernel::[ 1.814658] sd 0:0:1:0: [sdb] 625142448 512-byte logical blocks: (320 GB/298 GiB)2013 Nov 21 17:14:19::kernel::[ 1.814755] sd 0:0:1:0: [sdb] 4096-byte physical blocks2013 Nov 21 17:14:19::kernel::[ 1.814998] sd 0:0:0:0: [sda] Write Protect is off2013 Nov 21 17:14:19::kernel::[ 1.815068] sd 0:0:0:0: [sda] Mode Sense: 00 3a 00 002013 Nov 21 17:14:19::kernel::[ 1.815165] sd 0:0:0:0: [sda] Write cache: enabled, read cache: enabled, doesn't support DPO or FUA2013 Nov 21 17:14:19::kernel::[ 1.815268] sd 0:0:1:0: [sdb] Write Protect is off2013 Nov 21 17:14:19::kernel::[ 1.815339] sd 0:0:1:0: [sdb] Mode Sense: 00 3a 00 002013 Nov 21 17:14:19::kernel::[ 1.815452] sd 0:0:1:0: [sdb] Write cache: enabled, read cache: enabled, doesn't support DPO or FUA2013 Nov 21 17:14:19::kernel::[ 1.816076] sda:2013 Nov 21 17:14:19::kernel::[ 1.828670] sdb: sda1 sda2 sda3 < sdb1 sdb2 < sda5 sdb5 sda6 >2013 Nov 21 17:14:19::kernel::[ 1.921110] sdb6 >2013 Nov 21 17:14:19::kernel::[ 1.922236] sd 0:0:1:0: [sdb] Attached SCSI disk2013 Nov 21 17:14:19::kernel::[ 1.922571] sd 0:0:0:0: [sda] Attached SCSI disk
Debian driver needed for Intel ICH7M SouthBridge I/O controller
linux kernel;drivers;sata;libata
null
_codereview.140390
This header implements a very simple set of C (only) functions for logging.This is part of a larger collection of utility functions aimed to be used during the development process, meaning that they are intended to provide quick, easy to use solutions that could be replaced in the production code if needed.To ease with reading the code, I've removed the (rather verbose) comments with the documentation. You can find it in the README.md file here.Beside the printf()-like functions, there are a couple of functions that may be used for testing and debugging purpose.I'm very interested in any feedback you may have, especially in the area of usability.#ifndef UTL_H#define UTL_H#include <stdio.h>#include <stdlib.h>#include <stdint.h>#include <string.h>#include <stdarg.h>#include <stddef.h>#include <time.h>#include <ctype.h>#ifndef UTL_NOLOG#define logprintf(...) utl_log_printf(__VA_ARGS__)#define logclose() utl_log_close(LOG STOP)#define logopen(f,m) utl_log_open(f,m)#ifndef NDEBUG #define logcheck(e) utl_log_check(!!(e),#e,__FILE__,__LINE__)#define logassert(e) utl_log_assert(!!(e),#e,__FILE__,__LINE__)#define logdebug logprintf#else #define logcheck(e) utl_log_one()#define logassert(e) ((void)0)#define logdebug(...) ((void)0)#endif #define _logprintf(...) ((void)0)#define _logdebug(...) ((void)0)#define _logcheck(...) utl_log_one()#define _logassert(...) ((void)0)#define _logopen(f,m) ((void)0)#define _logclose() ((void)0)void utl_log_close(char *msg);void utl_log_open(char *fname, char *mode);int utl_log_check(int res, char *test, char *file, int line);void utl_log_assert(int res, char *test, char *file, int line);void utl_log_printf(char *format, ...);int utl_log_one(void);#ifdef UTL_MAINstatic FILE *utl_log_file = NULL;void utl_log_close(char *msg){ if (msg) logprintf(msg); if (utl_log_file && utl_log_file != stderr) fclose(utl_log_file); utl_log_file = NULL;}void utl_log_open(char *fname, char *mode){ char md[2]; md[0] = (mode && *mode == 'w')? 'w' : 'a'; md[1] = '\0'; utl_log_close(NULL); utl_log_file = fopen(fname,md); logprintf(LOG START);}void utl_log_printf(char *format, ...){ va_list args; char log_tstr[32]; time_t log_time; if (!utl_log_file) utl_log_file = stderr; time(&log_time); strftime(log_tstr,32,%Y-%m-%d %X,localtime(&log_time)); fprintf(utl_log_file,%s ,log_tstr); va_start(args, format); vfprintf(utl_log_file, format, args); va_end(args); fputc('\n',utl_log_file); fflush(utl_log_file);}int utl_log_check(int res, char *test, char *file, int line){ logprintf(CHK %s (%s) %s:%d, (res?PASS:FAIL), test, file, line); return res;}void utl_log_assert(int res, char *test, char *file, int line){ if (!utl_log_check(res,test,file,line)) { logprintf(CHK EXITING ON FAIL); logclose(); exit(1); }}int utl_log_one() {return 1;} /* to avoid warnings */#endif /* UTL_MAIN */#endif /* UTL_NOLOG */#endif /* UTL_H */
Simple logging library in C
c;library;logging
null
_unix.101172
I'd like to put two strings in two different variables. Let's take a small example. after a simple grep, I got this :$ grep nl.*acc.*bas :ABAS01=...ABAS02=...I'd like to have two variables, one containing ABAS01, and the other containing ABAS02.How can I do this ? I guess a loop can be used to go through all the results from my query, then I could do a cut -d= -f1 to retrieve the name of the variables. How can I do this ?
Looping through commands' results, KSH script
ksh;string
If it's AT&T or zsh implementations of ksh:cmd | { IFS== read -r var1 x && IFS== read -r var2 x; }
_vi.6650
I have vim set to relative line numbering withset numberset relativenumberFor some reason, every now and then, for some unknown reason, relative line numbering seems to turn off (or is stuck to the top of the buffer) in particular splits (though still active in other splits). Does anyone have any idea why this might be happening? This is my full .vimrc as it currently standsexecute pathogen#infect()if has('unix') set t_Co=256endif Vundle stuffset nocompatiblefiletype offset rtp+=~/.vim/bundle/Vundle.vimcall vundle#begin()Plugin 'VundleVim/Vundle.vim'call vundle#end()filetype plugin indent on Hard Mode Plugin autocmd VimEnter,BufNewFile,BufReadPost * silent! call HardMode() Other stuffset numberset noerrorbells Turn off the annoying error soundsset relativenumber Turn relative line numbering onset laststatus=2 Always keep the status line onset wildmenu Create graphical menu when tab completing file paths Syntasticlet syntastic_always_populate_loc_list = 1let g:syntastic_auto_loc_list = 1let g:syntastic_check_on_open = 1let g:syntastic_check_on_wq = 0let g:syntastic_mode_map = { 'mode': 'passive', 'active_filetypes': [],'passive_filetypes': [] } Turn it off for nowSearchingset incsearch Search as characters are enteredset ignorecase Ignore case when searchingset smartcase If a pattern contains an uppercase letter, it will match case sensitive, otherwise it will be case insensitive Setup foldingset foldenable Turn folding onset foldlevelstart=1set foldmethod=syntax Backupsset nobackupset nowritebackup Visual elementsset cursorline Creates a highlight on the line containing the cursor Set Colourscheme from the ./vim/color directorycolorscheme valloric Override colours in scheme set belowhighlight cursorline ctermbg=17 Ident guideslet g:indent_guides_auto_colors = 0let g:indent_guides_start_level = 2let g:indent_guides_guide_size = 1 let g:indent_guides_enable_on_vim_startup = 1highlight IndentGuidesEven ctermbg=22highlight IndentGuidesOdd ctermbg=28 Identing and tabsset autoindentset smartindentset tabstop=3 Number of visual spaces to visually display hard tabs withset softtabstop=3 Number of spaces inserted with the tab key if expandtab is onset shiftwidth=3set expandtab Turn all presses of the tab key into spaces Keymapsmap = :set foldlevel+=1<CR>map - :set foldlevel-=1<CR> Swap filesset backupdir=~/.vim/backup//set directory=~/.vim/swap//set undodir=~/.vim/undo//
Why does relative line numbering sometimes turn off
vimrc;line numbers
null
_unix.246587
Is there any way to assign ''linux core numbers'' to specific real cores?I'm working with an asymmetric architecture, so not all cores are the same, and I want to assign specific cores number to each core.Suppose my processor has 6 cores, two of them of type ARM-A57 and the other fours of type ARM-A53, and I want to map the cpu0, cpu1 (linux virtual cores) with the ARM-57 cores, and cpu2-cpu5 to the ARM-53 cores.At this moment, kernel 4.2.0 assigns cpu0, cpu3-cpu5 to ARM-53 cores, and cpu1-cpu2 to ARM-57 cores (no sense).
Assign virtual core number to specific real core
linux;kernel;cpu;cpu frequency
null
_unix.365886
If I do /usr/bin/which --all git, it shows me all the occurrences of git in my $PATH, where the first line shows the effective one.From the below picture, the git version in /home/kmodi/stowed/bin/git is the effective one.Now I wanted to know the true file names of the results. So for /home/kmodi/stowed/bin/git, which is a symlink, I wanted to know what that pointed to.Doing /usr/bin/which --all git | xargs \ls -Fpl shows the symlink reference. But the output is confusing.. the original order of listed files is not retained! So now looking at that output (below), one might think that the version in /cad/.. is the effective git binary path.Is there a way to make xargs retain that order?If it matters, I am using tcsh shell.Thanks to the tip from John about -n 1, I finally have a solution that I like. It is messy.. those quotes! (thanks to tcsh), but it works.alias whichall '/usr/bin/which --all \!* \\ | xargs -n 1 \ls -Fpl --color=always \\ | awk -v OFS= '''{$1=$2=$3=$4=$5=$6=$7=$8=; print $0}''' \\ | \sed '''/^$/d'''; \\ 'Now whichall git gives:
Is it possible for ls to maintain the order of its inputs
ls;xargs
The xargs command did maintain the order of it's arguments - but it passed all of them to one instance of ls, which gave you output in alphabetical order, which it does by default. To get the behavior you want, add a -n 1 argument to the xargs command to pass only one line of output to ls at a time, or if using the GNU implementation of ls, add a -U option to tell it not to sort the list of files.Behavior of ls:$ ls -lad /usr/bin /etcdrwxr-xr-x. 146 root root 12288 May 18 09:46 /etcdr-xr-xr-x. 2 root root 57344 Dec 12 15:30 /usr/bin
_softwareengineering.261714
IN view of creating a MIS (Management Information System) one architectural/design issue that's confronting us is managing allocation for set of employees.Scenario:Employees get allocated to projects and hence get their time (in full or part) for a duration is allocated to a specific task.How can this be represented in DB and Programing model?Example:Employee E1 is allocated to 2 projects P1 and P2P1 start date is: 10 Jan 2014 and End date is: 20 Mar 2014P2 start date is: 15 FEB 2014 and End date is: 1 MAY 2014.E1 gets allocated to P1 for 0.5 (50%) from 20 JAN to 20 FEB 2014 and then again gets allocated 0.75 (75%) from 1 MAR to 20 MAR 2014.Now let's consider a scenario where the same employee needs to get allocated 100% to project P2. Based on a DB model or programming model (say Java) I should be able to make the following interpretations:1> E1 is only available 50% for the time period 15 to 20 FEB 2014.2> E1 is available 100% for the time period 20 FEB to 1 MAR 2014.3> E1 is available 25% for the period 1 MAR to 20 MAR 2014.4> E1 is available 100% for the period 20 MAR to 1 MAY 2014.I am assuming I will have to maintain the allocation details for each employee in a DB and it's equivalent Java data structures. The problem is we are unable to come up with a structure/ER model that can accommodate such details.I am assuming similar problems are nothing new and open source/projects will already be there.Question:1> Can anyone please suggest approach for problem like this?2> is there any references/links you can provide that will help me a better design.
Managing allocation calendars for an employee set
design;database design;orm
null
_codereview.9077
I did this code for somebody but need it to be double checked before I pass it onto them. Code seems fine but I need someone to confirm I have coded the crossover methods correctly.Would be great if somebody that is familiar with genetic algorithms and crossover methods, could confirm that I have the correct logic and code behind each crossover method. //one crossover point is selected, string from beginning of chromosome to the //crossover point is copied from one parent, the rest is copied from the second parent // One-point crossoverpublic void onePointCrossover(Individual indi) { if (SGA.rand.nextDouble() < pc) { // choose the crossover point int xoverpoint = SGA.rand.nextInt(length); int tmp; for (int i=xoverpoint; i<length; i++){ tmp = chromosome[i]; chromosome[i] = indi.chromosome[i]; indi.chromosome[i] = tmp; } } }//two crossover point are selected, binary string from beginning of chromosome to//the first crossover point is copied from one parent, the part from// the first to the second crossover point is copied from the second parent// and the rest is copied from the first parent// Two-point crossover public void twoPointCrossover(Individual indi) { if (SGA.rand.nextDouble() < pc) { // choose the crossover point int xoverpoint = SGA.rand.nextInt(length); int xoverpoint2 = SGA.rand.nextInt(length); int tmp; //swap if (xoverpoint > xoverpoint2){ tmp = xoverpoint; xoverpoint = xoverpoint2; xoverpoint2 = tmp; } for (int i=xoverpoint; i<xoverpoint2; i++){ tmp = chromosome[i]; chromosome[i] = indi.chromosome[i]; indi.chromosome[i] = tmp; } } } // For each gene, createa random number in [0,1]. If // the number is less than 0.5, swap the gene values in // the parents for this gene; otherwise, no swapping // Uniform Crossover public void UniformCrossover(Individual indi) { if (SGA.rand.nextDouble() < pc) { for (int i= 1; i<length; i++){ boolean tmp = SGA.rand.nextFloat() < 0.5; if(tmp){ chromosome[i] = indi.chromosome[i]; } } }Parent 1 = chromosome Parent 2= indi.chromosomeI am turning the parents into children inplace.
Confirm code is correct - crossover methods in Java
java;algorithm
null
_unix.35059
I want to monitor CPU usage, disk read/write usage for a particular process, say ./myprocess.To monitor CPU top command seems to be a nice option and for read and write iotop seems to be a handy one. For example to monitor read/write for every second i use the command iotop -tbod1 | grep myprocess.My difficulty is I just want only three variables to store, namely read/sec, write/sec, cpu usage/sec. Could you help me with a script that combines the outputs the above said three variables from top and iotop to be stored into a log file?Thanks!
script for logging all the stats for a particular process
shell script;centos;monitoring;cpu;io
null
_unix.373977
I have a BareOS director I'm trying to start on Debian 8, and when it starts up I get the following error:-- Logs begin at Wed 2017-06-28 16:36:57 UTC, end at Wed 2017-06-28 16:50:26 UTC. --Jun 28 16:44:40 bareOSdirector systemd[1]: Starting LSB: Bareos Director...Jun 28 16:44:41 bareOSdirector bareos-dir[9337]: Checking Configuration and Database connection ...Jun 28 16:44:41 bareOSdirector su[9340]: Successful su for bareos by rootJun 28 16:44:41 bareOSdirector su[9340]: + ??? root:bareosJun 28 16:44:41 bareOSdirector su[9340]: pam_unix(su:session): session opened for user bareos by (uid=0)Jun 28 16:44:41 bareOSdirector bareos-dir[9337]: BAREOS interrupted by signal 11: Segmentation violationJun 28 16:44:41 bareOSdirector bareos-dir[9342]: BAREOS interrupted by signal 11: Segmentation violationJun 28 16:44:41 bareOSdirector bareos-dir[9337]: Kaboom! bareos-dir, bareos-dir got signal 11 - Segmentation violation. Attempting traceback.Jun 28 16:44:41 bareOSdirector bareos-dir[9337]: Kaboom! exepath=/usr/sbin/Jun 28 16:44:41 bareOSdirector bareos-dir[9337]: Calling: /usr/sbin/btraceback /usr/sbin/bareos-dir 9342 /var/lib/bareosJun 28 16:44:41 bareOSdirector bareos-dir[9337]: It looks like the traceback worked...Jun 28 16:44:41 bareOSdirector bareos-dir[9337]: Dumping: /var/lib/bareos/bareos-dir.9342.bactraceJun 28 16:44:41 bareOSdirector su[9340]: pam_unix(su:session): session closed for user bareosJun 28 16:44:41 bareOSdirector systemd[1]: Started LSB: Bareos Director.It appears that it is related to the configuration in some way:Okay I found more details here:vagrant@bareOSdirector:~$ /usr/sbin/bareos-dir -t -d 200 -u bareos -g bareosbareos-dir (10): dird.c:243-0 Debug level = 200bareos-dir (100): parse_conf.c:151-0 config file = /etc/bareos/bareos-dir.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/bareos-dir.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/bareos-dir.confbareos-dir (100): lex.c:250-0 open config file: |find /etc/bareos/director.d -name '*.conf' -type f -exec echo @{} ;bareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/pool-Scratch.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/pool-Scratch.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/fileset-SelfTest.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/fileset-SelfTest.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/messages-Daemon.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/messages-Daemon.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/job-lampdir-fd-RestoreFiles.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/job-lampdir-fd-RestoreFiles.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/fileset-Catalog.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/fileset-Catalog.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/pool-Differential.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/pool-Differential.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/fileset-bacula_files_backup.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/fileset-bacula_files_backup.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/schedule-WeeklyCycle.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/schedule-WeeklyCycle.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/storage-File.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/storage-File.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/job-lampdir-fd-BaculaDirectorDirFiles.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/job-lampdir-fd-BaculaDirectorDirFiles.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/pool-Full.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/pool-Full.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/messages-standard.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/messages-standard.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/fileset-LinuxAll.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/fileset-LinuxAll.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/pool-Incremental.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/pool-Incremental.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/catalog-MyCatalog.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/catalog-MyCatalog.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/job-lampdir-fd-BackupCatalog.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/job-lampdir-fd-BackupCatalog.confbareos-dir (100): lex.c:250-0 open config file: |find /etc/bareos/clients.d -name '*.conf' -type f -exec echo @{} ;bareos-dir (100): lex.c:356-0 glob /etc/bareos/clients.d/lampdir-fd.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/clients.d/lampdir-fd.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/bareos-dir.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/bareos-dir.confbareos-dir (100): lex.c:250-0 open config file: |find /etc/bareos/director.d -name '*.conf' -type f -exec echo @{} ;bareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/pool-Scratch.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/pool-Scratch.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/fileset-SelfTest.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/fileset-SelfTest.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/messages-Daemon.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/messages-Daemon.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/job-lampdir-fd-RestoreFiles.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/job-lampdir-fd-RestoreFiles.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/fileset-Catalog.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/fileset-Catalog.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/pool-Differential.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/pool-Differential.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/fileset-bacula_files_backup.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/fileset-bacula_files_backup.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/schedule-WeeklyCycle.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/schedule-WeeklyCycle.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/storage-File.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/storage-File.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/job-lampdir-fd-BaculaDirectorDirFiles.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/job-lampdir-fd-BaculaDirectorDirFiles.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/pool-Full.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/pool-Full.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/messages-standard.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/messages-standard.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/fileset-LinuxAll.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/fileset-LinuxAll.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/pool-Incremental.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/pool-Incremental.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/catalog-MyCatalog.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/catalog-MyCatalog.confbareos-dir (100): lex.c:356-0 glob /etc/bareos/director.d/job-lampdir-fd-BackupCatalog.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/director.d/job-lampdir-fd-BackupCatalog.confbareos-dir (200): runscript.c:334-0 runscript: debugbareos-dir (200): runscript.c:335-0 --> RunScriptbareos-dir (200): runscript.c:336-0 --> Command=/usr/lib/bareos/scripts/make_catalog_backup.pl MyCatalogbareos-dir (200): runscript.c:337-0 --> Target=%cbareos-dir (200): runscript.c:338-0 --> RunOnSuccess=1bareos-dir (200): runscript.c:339-0 --> RunOnFailure=0bareos-dir (200): runscript.c:340-0 --> FailJobOnError=1bareos-dir (200): runscript.c:341-0 --> RunWhen=2bareos-dir (200): runscript.c:334-0 runscript: debugbareos-dir (200): runscript.c:335-0 --> RunScriptbareos-dir (200): runscript.c:336-0 --> Command=/usr/lib/bareos/scripts/delete_catalog_backupbareos-dir (200): runscript.c:337-0 --> Target=%cbareos-dir (200): runscript.c:338-0 --> RunOnSuccess=1bareos-dir (200): runscript.c:339-0 --> RunOnFailure=0bareos-dir (200): runscript.c:340-0 --> FailJobOnError=0bareos-dir (200): runscript.c:341-0 --> RunWhen=1bareos-dir (100): lex.c:250-0 open config file: |find /etc/bareos/clients.d -name '*.conf' -type f -exec echo @{} ;bareos-dir (100): lex.c:356-0 glob /etc/bareos/clients.d/lampdir-fd.conf: 1 filesbareos-dir (100): lex.c:250-0 open config file: /etc/bareos/clients.d/lampdir-fd.confBAREOS interrupted by signal 11: Segmentation violationKaboom! bareos-dir, bareos-dir got signal 11 - Segmentation violation. Attempting traceback.Kaboom! exepath=/usr/sbin/Calling: /usr/sbin/btraceback /usr/sbin/bareos-dir 10692 /var/lib/bareos/usr/sbin/btraceback: 94: /usr/sbin/btraceback: cannot create /var/lib/bareos/bareos.10692.traceback: Permission deniedcat: /var/lib/bareos/bareos.10692.traceback: No such file or directoryIt looks like the traceback worked...Dumping: /var/lib/bareos/bareos-dir.10692.bactraceAttempt to dump locksAttempt to dump current JCRs. njcrs=0It appears that the last file processed is /etc/bareos/clients.d/lampdir-fd.conf :Client { Name = lampdir-fd Address = localhost FDPort = 9102 Password = blah Catalog = MyCatalog FileRetention = 30 days JobRetention = 6 months AutoPrune = true HeartbeatInterval = 1 minute}Not certain what the issue with it is...
BAREOS 16.2.4 interrupted by signal 11: Segmentation violation in Debian 8?
debian;segmentation fault;bareos
null
_cogsci.8209
What I get from Trevarthen's theory of innate intersubjectivity (2010) and the theory of theory of mind (Perner, 1999) is that they don't agree.A considerable number of studies in theory of mind development suggest that infants are cognitively egocentric, that is they cannot understand that others may have different thoughts, feelings and points of view than they do until the age of 3 or 4 when a shift in cognitive development occurs.Trevarthen on the other hand states that a newborn's view of the world is already intersubjective, that is a newborn can share parts of his/her inner world (thoughts, feelings) with other people and sense other people's intentions.I was having a disagreement with my developmental psychology professor who thought they were reconcilable if one does a proper conceptual analysis of the statements of each theory and the methods and data that they use to formulate their theories, but she did not get any more specific as to what can be defined alternatively and how can this be done to avoid conflict.Any thoughts on that?
Are innate intersubjectivity and theory of mind opposing theories or are they reconcilable?
cognitive psychology;developmental psychology;theory of the mind
null
_unix.41260
I have the mapping shown below, in my ~/.vimrc. However, this mapping also hijacks the Enter key. So, whenever I hit Enter it executes the tabedit % command. I am using gvim 7.3nnoremap <C-m> :tabedit %<CR>Can anyone fix this so that it doesn't hijack the Enter key.
Vim mapping behaving strangely
vim
< C-m> maps to the enter key (C-M and CR both do); it's not hijacking it, you're telling it to run :tabedit % every time you hit enter. I would suggest a different mapping.See :h key-notation for more information.
_unix.376153
I find myself using bash more often than not on remote machines even though fish is my preferred shell. Fish has small, but nice feature that when you hit Ctrl+C something like this happens:if command running send SIGINTelse clear line (don't start a new one)It would be nice to be able to do this in bash too.I imagine it would involve trapping SIGINT, which comes from stty being configured to send it once Ctrl+C is hit, but I haven't found out how to execute the pseudo-code above.What I've triedtrap 'tput dl1' SIGINT which clears the line, but still continues to start a new line/prompt (it's like hitting enter on an empty prompt) and does so only if I've not navigated in history :\
How can one override bash Ctrl+C to be more fish-like
bash;configuration;tty;fish;stty
null
_unix.347219
I have a win10 pc and I'm trying to set up a dual boot with Ubuntu using a pen drive with grub. The problem is when I select install Ubuntu from grub menu it has the same effect as if I click to boot Ubuntu directly from my pen drive, so the installation is not initialized but the Ubuntu SO is booted from my pen drive. Am I missing something here? Any tips? Thanks!
Grub bypass Ubuntu installation
ubuntu;grub2
null
_softwareengineering.197707
In my PHP web page (index.php), I have a simple script that calls a page class, and then builds the page from it.Index.php executes methods within an instance of the 'page' class, such as add_to_body(bla bla bla). It can then call a build() method, where the page class will return a string with the user input and some other HTML elements pre-added in, that index.php can echo. Essentially the page class is a template of sorts. I'm trying to have some kind of MVC hierarchy here (I'm a student learning about programming 'best practices' in my own time), my question is: would 'index.php' be a view? Or, would the instance of the page class be the view (as it constructs the page, but it doesn't actually show it, it returns a string), or: would the 'page' class be a controller? Also, is a view 'allowed' to talk to (eg: get data from) a controller (for example: by calling a method that controller owns)? Many thanks for your help!
MVC View Question
php;mvc;web
null
_cs.54741
Suppose that you have a large dictionary with spellings and pronounciations of foreign words, and you want to find a set of pronunciation rules. They should have the simplest form: a sequence of letters to a sequence of sounds.For example, in French, c [k], i [i] and ci [si].The rules may be long: tion [sj] (instead of [tj]).They may be rare: [a] is used only in a dozen of words.They may be both: aill [aj] (as a-ill, instead of ai-ll [l]).Fortunately, such rules are rare enough: for the most part, the letters are pronounced by itself, even most of them in complicated rules. For examples, cercle [skl] instead of [kkl]: the algorithm should notice the corresponding sounds in the middle of the word.Maybe, there is a standard algorithm to extract candidates for such rules? I would like to have an explicit list of rules, rather than a method predicting pronunciation.
Algorithm to find pronounciation rules
algorithms;machine learning;data mining;computational linguistics
Broadly, I can see two possible approaches: machine learning, or data miningMachine learningYou could look into using machine learning to learn a transducer that transforms the input sequence (the letters in the word) to the output sequence (the pronunciation). This approach doesn't try to find an explicit set of rules; it just tries to find a method that is effective in practice at producing the right pronunciation.You could try training a recurrent neural network (RNN), and/or a LSTM network. LSTM's have been effective at related tasks, and since you have a large training set, they might possibly be effective here. Bi-directional RNN's/LSTM's might be worth exploring.Data miningAlternatively, you could use data mining techniques to try to find an explicit set of rules that seem to have good support among your dictionary.This problem fits into the general area of sequence mining (also known as sequential pattern mining) and association rule learning. I think it might be fruitful to try applying one of the algorithms from that field, to your problem.In your case, you could consider each possible substring of the word or pronunciation to be a possible item, and your goal is to find rules of the form $x \Rightarrow y$, where $x$ is a substring of the word and $y$ is a substring of the pronunciation. This is a special case of itemset mining, where your itemsets are restricted to have size 1. You could then adapt any standard itemset algorithm (e.g., Apriori, FP-growth) to this problem.For instance, here is an adaptation of Apriori. You consider all possible rules of the form $x \Rightarrow y$, where $x$ and $y$ are length 1. For each, you compute their support or some probabilistic measure of the strength of the association (e.g., out of all words that contain $x$, what fraction contain $y$?). Discard all candidate rules for which this metric is below some threshold. Then, try all extensions of this rule by extending either $x$ or $y$ by one character to the left or right side of it; this gives you a bunch more candidates. For each such candidate, compute the metric and discard those that are below the threshold. Keep expanding your set of candidates until no new candidates can be identified. This is basically a form of breadth-first search. Finally, at the end, prune your rules by eliminating rules with a containment relationship (e.g., if you have a rule $x \Rightarrow y$, then you might want to remove all other rules of the form $x' \Rightarrow y'$ where $x'$ is a substring of $x$ and $y'$ is a substring of $y$).You could also consider similar tweaks to FP-growth.However, it's not clear to me how well a data mining-based approach will work: while it does consider order to some extent, it doesn't take into account the position within the word, and it doesn't consider whether a set of rules fully covers all of the characters in the word, and it doesn't take into account rule overlap (e.g., $x_1 \Rightarrow y_1$ and $x_2 \Rightarrow y_2$ where $x_1,x_2$ overlap partially).
_softwareengineering.246648
I'm in a situation at work where I have to transfer responsibility of a large code base that I inherited, re-factored and enhanced to another developer. This is the first time that I have to do such a thing and although I always thought it would be trivial the actual steps I have to follow seem vague.The code base I maintain is a module that includes a lot of stuff such asA persistence layerA service layerA presentation layer which sadly has a lots of business code in itAn interface for module interactionI also have very good knowledge of the business assumptions made when it was developed as well as its technical foundation.I know that I can go with my mind's flow and give it my best but I prefer to do it in the most professional manner I can. So, I would like to ask you for advice on how I should approach this situation. Are there any standard procedures and good practices that I could follow?
How to transfer code responsibility to another developer
teamwork;knowledge transfer;code ownership
null
_codereview.69324
Here is my JSON in which I have only three reportRecords just for demonstration purpose but in general sometimes we are getting pretty huge JSON, then it doesn't have three reportRecords only, it has large number of reportRecords.{ parentRecords:{ reportRecords:[ { min:1.0, max:1.0, avg:1.0, count:18, sumSq:18.0, stddev:0.0, median:1.0, percentileMap:{ 95:1 }, metricName:TotalCount, dimensions:{ env:prod, pool:hawk, Name:CORE_utrade11, Type:Error }, value:18.0 }, { min:1.0, max:1.0, avg:1.0, count:25968842, sumSq:2.5968842E7, stddev:0.0, median:1.0, percentileMap:{ 95:1 }, metricName:TotalCount, dimensions:{ env:prod, pool:hawk, Name:ResponseHeaders, Type:ConnectionPool }, value:2.5968842E7 }, { min:1.0, max:1.0, avg:1.0, count:44, sumSq:44.0, stddev:0.0, median:1.0, percentileMap:{ 95:1 }, metricName:TotalCount, dimensions:{ env:prod, pool:hawk, Name:read-lookup, Type:ClientPool }, value:44.0 } ] }, minRecordsMap:{ }}Now I am trying to serialize above JSON to extract those reportRecords whose Type is ClientPool and ConnectionPool only so I don't want to load everything in memory. And I am thinking to use GSON Streaming for this and I got below code working fine.private static final List<String> metricsToExtract = Arrays.asList(ClientPool, ConnectionPool);// does this have to be static final?private static final GsonBuilder gsonBuilder = new GsonBuilder();public static void main(String[] args) { String urlA = urlA; String urlB = urlB; try { List<HostClientMetrics> clientMetrics = loadMetrics(urlA); clientMetrics.addAll(loadMetrics(urlB)); } catch (Exception ex) { ex.printStackTrace(); }}private static List<HostClientMetrics> loadMetrics(String url) { Gson gson = gsonBuilder.create(); List<HostClientMetrics> metrics = new ArrayList<HostClientMetrics>(); try { InputStream input = new URL(url).openStream(); JsonReader reader = new JsonReader(new InputStreamReader(input, UTF-8)); reader.beginObject(); String jsonTag = null; while (reader.hasNext()) { jsonTag = reader.nextName(); if (parentRecords.equals(jsonTag)) { reader.beginObject(); while (reader.hasNext()) { jsonTag = reader.nextName(); if (reportRecords.equals(jsonTag)) { reader.beginArray(); while (reader.hasNext()) { HostClientMetrics hostClientMetrics = gson.fromJson(reader, HostClientMetrics.class); for (String extract : metricsToExtract) { if (extract.equals(HostClientMetrics.getDimensions().getType())) { metrics.add(HostClientMetrics); } } } reader.endArray(); } } reader.endObject(); } else if (minRecordsMap.equals(jsonTag)) { reader.beginObject(); // skip reader.endObject(); } } reader.endObject(); reader.close(); return metrics; } catch (Exception ex) { System.out.println(ex: + ex); } return metrics;}HostClientMetricspublic class HostClientMetrics { private String metricName; private Map<String, Integer> percentileMap; private String median; private String stddev; private String sumSq; private String count; private String avg; private String max; private String min; public String getMetricName() { return metricName; } public Map<String, Integer> getPercentileMap() { return percentileMap; } public String getMedian() { return median; } public String getStddev() { return stddev; } public String getSumSq() { return sumSq; } public String getCount() { return count; } public String getAvg() { return avg; } public String getMax() { return max; } public String getMin() { return min; } public Dimensions getDimensions() { return dimensions; } public Dimensions dimensions; public static class Dimensions { private String env; private String pool; @SerializedName(Name) private String name; @SerializedName(Type) private String type; public String getEnv() { return env; } public String getPool() { return pool; } public String getName() { return name; } public String getType() { return type; } }}I'd like to improve this in any way using GSON Streaming. I need to extract those reportRecords whose Type is ClientPool and ConnectionPool only.
Serializing big JSON using GSON without loading everything in memory
java;performance;json;serialization
There is no point for printing an exception, it would be better if you can rethrow it, wrap it into an unchecked exception and throw it.catch (Exception ex) { throw new RuntimeException}The reader will not be closed if an exception occurred while parsing the json, Java 7 supports try-with-resources statement, this will close the resources for you in a safe way try(JsonReader reader = new JsonReader(new InputStreamReader(input, UTF-8)){ ....}catch(Exception e){ throw new RuntimeException(e);}If you aren't using Java 7 then you can go with the try-catch-finally approach.JsonReader reader = new JsonReader(new InputStreamReader(input, UTF-8));try{}catch(Exception e){throw new RuntimeException(e1);} finally{ try{ reader.close(); }catch(Exception e1){ throw new RuntimeException(e1); }}It's ugly isn't it? But it's the only way if you running java 6 or lower versionsExtract you constants into variablespublic static final REPORT_RECORDS_TAG_NAME = reportRecords;There is no point for declaring jsonTag string and initializing it into null outside the loop. String jsonTag = reader.nextName();In your HostClientMetrics class everything is declared as a String where Java has a type system, count for instance should have a numerical type
_cstheory.4246
Yesterday, I discussed with one of my EE friends. She asked me an interesting problem and I simplify it by ignoring the bandwidth cost and model as following:Given a graph $G=(V,E)$ with its path set $P=\{P_1,P_2,\ldots, P_m\}$ where $P_i$ is a path between two points in $V$. A path $P_i$ is colored by red if only and only if one of it's edges is colored by red, i.e. $P^c=red$; otherwise $P_i$ is colored by blue, i.e. $P^c=blue$. Find a subset $P_s\subseteq P$ s.t. 1) If for every $j$ color all edges in $G$ by blue except only one $e_j\in E$ by red, there is a subset $P_s' =\{P_1,P_2,\ldots,P_t\}$ in $P_s$ such that $f(P_1^c,\ldots,P_t^c)=e_j$ where f() is one-to-one mapping; 2) minimize the size of the result set $P_s$.My questions are:1) is there any similar work done in TCS?2) is there any similar work done in graph theory?3)2) is there any similar work done in networks?3) any discussions about this problem are welcome.
Is any related work to this m-trails problem ?
ds.algorithms;graph theory;graph algorithms
null
_codereview.83463
My problem is in writing a function reverse(s) that reverses the character string s, a line at a time. My code here works, I write the line and it reverses the line. Is it a good solution?#include <stdio.h>#include <stdlib.h>#define MAX 1000void reverse(char cad[] ,char cadenita[],int i);int main() { int a ,i ; char cad[MAX] = {0,0}; char cadenita[MAX]; i= 0; while ((a = getchar()) != EOF) { if (a != '\n') { cad[i] = a; ++i; } else { cad[i] = '\0' ; reverse(cad , cadenita, i); printf(%s\n,cadenita); i = 0; } } return (EXIT_SUCCESS);}void reverse(char s[] ,char svol[], int i) { int a =0 ; // i is the amount characters in s while ((svol[a] = s[i-1]) != '\0' ){ ++a; --i; } } Also in this part of code while ((svol[a] = s[i-1]) != '\0' ){ . If I change to ((svol[a] = s[i-1]) != '\n' ) it still works and gives the same result, but why? I think there is an issue. Can you explain? Also, where does it break?
A function that reverses a string of characters
c;strings
A smarter use of getchar()I don't recommend using getchar() to read one character at a time, since you are really interested more in lines. However, if you do use getchar(), you might as well use it more effectively, by writing the string in reverse to begin with.#include <stdio.h>#define MAX 1000int main() { char cadena[MAX]; do { int i; cadena[i = MAX - 1] = '\0'; while (i > 0) { int c = getchar(); if (c == EOF) { return 0; } else if (c == '\n') { break; } else { cadena[--i] = c; } } puts(cadena + i); } while (1);}
_unix.283316
This is CentOS 7 running in Docker. Silent install doesn't show anything in /tmp/state.xml. When I remove silent install and enable X11 for the installer Window, I can see that the installer is stuck at this step.Have tried installing JDK 8 and setting $JAVA_HOME to no avail.Downloaded the 64-bit Linux installer. I shouldn't need to install ia32-libs according to this: RedHat-based 64bit distributions should contain ia32-libs automatically and the 32bit bundles should start without any error. http://wiki.netbeans.org/FaqUnableToPrepareBundledJdk Configuring the installer...Searching for JVM on the system...Preparing bundled JVM ...
NetBeans 8.1 installer stuck on 64-bit RHEL 7
centos;docker
null
_unix.43063
After using linux for a month or two, I know what I'm doing now.When creating programs, using whatever language, I've obviously been using code like this:$ python test.pyAnd so if I wanted test.py to read a given file, I would have to use:$ python test.py something.fileWhat I'd like to do now, it try and create a command line application, so I can use$ myapp something.fileA program like the python in $ python test.py, or the nano in $ nano program.plBut where on earth do I start building applications like these? A bit of web trawling has got me nowhere.If you can tell me yourself that would be great, but I'll readily accept a bunch of links.I'm totally open if there's more than one way, I don't really mind what language (an excuse to learn another!) or whatever.
Where to start creating CLI applications?
command line;application
null
_codereview.143595
I wrote this sparse linked list insert function, and there are nine return statements. Is this a code smell? Is this badly implemented? I fear that it's hard to read, or hard to maintain./* NOT BUGS, TESTED AND WORKS CORRECTLY * insert an element into a list * list is ordered using pos * if position pos is already occupied, the value of the node * should be updated with val * if val=0, then the element should be deleted * return 0 if operation is succesfull * 1 if malloc failed */int insert_element(ElementNode_handle *list_handle, int pos, int data){ /*Record the head*/ ElementNode *current = *list_handle; /* If data is 0, stop */ if (data == 0) { return 1; } /* If list is empty, crate new list*/ if (current == NULL) { /* Create new list */ ElementNode *new_node = make_node(pos, data); /* Malloc fail check*/ if (new_node == NULL) { return 0; } new_node->data = data; new_node->pos = pos; *list_handle = new_node; return 1; } /* If head pos == pos, replace and done*/ if (current->pos == pos) { current->data = data; return 1; } else if (current->pos > pos) { /* Create new node between current and next */ ElementNode *new_node = make_node(pos, data); if (new_node == NULL) { return 0; } new_node->next = current; *list_handle = new_node; return 1; } /*Walk the list, until next hits the end*/ while (current->next != NULL) { if (current->next->pos == pos) { /* If next pos equals post, replace, done*/ current->next->data = data; return 1; } else if (current->next->pos > pos) { /* Create new node between current and next */ ElementNode *new_node = make_node(pos, data); if (new_node == NULL) { return 0; } ElementNode *next = current->next; current->next = new_node; new_node->next = next; return 1; } /*walk the list*/ current = current->next; } /* Append to the tail */ ElementNode *new_node = make_node(pos, data); if (new_node == NULL) { return 0; } current->next = new_node; return 1;}=== EDIT ===Refactored based on @user1118321/** * @brief insert an element into a list * @details * list is ordered using pos if position * pos is already occupied, the value of * the node should be updated with data * @param p_list_handle Opaque pointer to list * @param pos Position to insert * @param data data at position * @return 0 = success, 1 = failed */int insert_element(ElementNode_handle *p_list_handle, int pos, int data){ /*Record the head*/ ElementNode *current = *p_list_handle; /*Record previous*/ ElementNode *previous = NULL; /*End result*/ int result = -1; if (data == 0) { delete_element(p_list_handle, pos); return 0; } if (current == NULL) { return make_list(p_list_handle, pos, data); } while ((current != NULL) && (result == -1)) { if (current->pos == pos) { current->data = data; result = 0; } else if (current->pos > pos) { ElementNode *new_node = make_node(pos, data); if (new_node == NULL) { result = 1; } if (previous == NULL) { *p_list_handle = new_node; } else { previous->next = new_node; } new_node->next = current; result = 0; } previous = current; current = current->next; } if (result == -1) { ElementNode *new_node = make_node(pos, data); if (new_node == NULL) { result = 0; } previous->next = new_node; } return result;}
Sparse linked list insert function
c;linked list
This is a good question. Code smells tend to be subtle, and I think you're right to ask about this code. In my opinion, yes, it's a code smell. There's a general rule that programmers are taught to only have a single return statement in their functions in order to reduce the amount of spaghetti code we write. It's a good rule of thumb, but it can be taken too far. It often makes sense to have an early return when the inputs are invalid, or there's no action to take. That can actually make the code clearer.That said, I think your code has a little of both. It has a few reasonable early returns and a several unnecessary ones. I also think the code could be restructured to make it shorter without reducing its readability. (And actually, your code's readability is pretty good.) Here are my suggestions:Comments Are Out of DateIt looks like the comment at the top of the function doesn't match the implementation. It mentions a parameter named val, but there's no val in the code. I assume it means data. And if that is correct, then the comment is still wrong in that it says that when val (data) is 0, the node at pos should be deleted, but it isn't. You just return 1 at that point. So at least make the comments match the code.Early ReturnsAs mentioned above, I think early returns are fine. If a value of 0 for data means do nothing, then the first return is fine. The next 2 are OK, but could be improved. I would do that by making a function for creating a new list. (Another good rule of thumb is to only do allocations in a single function and have all other functions that need to allocate memory call that function.) I would make a function like this:int create_list(Elementnode_Handle *list_handle, const int pos, const int data){ /* Create new list */ ElementNode *new_node = make_node(pos, data); /* Malloc fail check*/ if (new_node == NULL) { return 0; } new_node->data = data; new_node->pos = pos; *list_handle = new_node; return 1;}Then, I would make your second check look like this:if (current == NULL){ return create_list(list_handle, pos, data);}That improves the readability a lot, and reduces those 2 early returns into 1.Don't Repeat YourselfThe next thing the code does is checks the head node of the list to see if either pos matches the first node, or is at an earlier position than the first node. Then it goes into a loop and checks the exact same condition for every other node in the list (at least until it finds the right spot). You can rearrange your loop so that you don't need the extra copy for the first node. I'd do it something like this:ElementNode *nextNode = current;ElementNode *prevNode = NULL;while (nextNode != NULL){ if (nextNode->pos == pos) { nextNode->data = data; return 1; } else if (nextNode->pos > pos) { /* Create new node between current and next */ ElementNode *new_node = make_node(pos, data); if (new_node == NULL) { return 0; } if (prevNode == NULL) { *list_handle = new_node; } else { prevNode->next = new_node; } new_node->next = nextNode; return 1; } prevNode = nextNode; nextNode = nextNode->next;}Note: I haven't actually run the above code, so double-check it to make sure I didn't mess up the insertion. But the point remains that you can eliminate the first copy of those checks.You could further reduce the number of early returns by doing something like the following before the loop:int result = -1;while ((nextNode != NULL) && (result == -1)){ // ... loop from above, but set result to 0 or 1 // instead of returning 0 or 1}// If we didn't find the node in the list, append it to the endif (result == -1){ ElementNode *new_node = make_node(pos, data); if (new_node == NULL) { return 0; } prevNode->next = new_node;}return result;That will eliminate 3 other early returns.Make Unchanging Arguments constOne last thing. Since you never change the value of pos or data in your function, you should mark them as const. That tells both the compiler and the reader that the function does not modify them either locally or alter their values upon return of the function. That can make it easier to understand a function's purpose at a glance.
_cogsci.16254
At a hospital I work in (as a new psychiatry trainee), some admitted patients - especially those with conversion disorder - are made by psychologists to:Stop meeting their friends or familySpend the entire day in isolation on their bedsOnly eat simple (but not aversive) food such as bread with milk.This treatment lasts for weeks. They call it extinction therapy. However, in attempts of finding scientific evidence relating to this practice, I looked it up online and couldn't find any references to extinction therapy.My question is:Is the above psychological management a known and named concept? If so, what is it called?
What is the name for the psychological therapy involving socially isolating a patient?
psychiatry
null
_codereview.144376
This post elaborates on NBA*: Very efficient bidirectional heuristic search algorithm in Java. I have made the following changes:Added an explicit type for representing digraph paths: DirectedGraphPath.If the target node is unreachable from the source node, a TargetUnreachableException is thrown instead of returning a sentinel value representing a nonexistent path.HeapEntry removed from AbstractPathfinder and moved into the package net.coderodde.graph.pathfinding.support, where it is declared as package-private.ZeroHeuristicFunction is removed and a lambda is used instead.HeuristicFunction is annotated as @FunctionalInterface.The source and target nodes in the demonstration are chosen to be as far from each other as feasible.Minor improvements in the Demo.An optimality related bug fixed.NBAStarPathfinder.javapackage net.coderodde.graph.pathfinding.support;import java.util.Arrays;import java.util.HashMap;import java.util.HashSet;import java.util.Map;import java.util.Objects;import java.util.PriorityQueue;import java.util.Set;import net.coderodde.graph.DirectedGraph;import net.coderodde.graph.DirectedGraphWeightFunction;import net.coderodde.graph.pathfinding.AbstractPathfinder;import net.coderodde.graph.pathfinding.DirectedGraphPath;import net.coderodde.graph.pathfinding.HeuristicFunction;import net.coderodde.graph.pathfinding.TargetUnreachableException;/** * This pathfinding algorithm is due to Wim Pijls and Henk Post in Yet another * bidirectional algorithm for shortest paths. 15 June 2009. * <p> * <b>This class is not thread-safe.</b> If you need it in different threads, * make sure each thread has its own object of this class. * * @author Rodion rodde Efremov * @version 1.61 (Oct 13, 2016) */public final class NBAStarPathfinder extends AbstractPathfinder { private final HeuristicFunction heuristicFunction; private final PriorityQueue<HeapEntry> OPENA = new PriorityQueue<>(); private final PriorityQueue<HeapEntry> OPENB = new PriorityQueue<>(); private final Map<Integer, Integer> PARENTSA = new HashMap<>(); private final Map<Integer, Integer> PARENTSB = new HashMap<>(); private final Map<Integer, Double> DISTANCEA = new HashMap<>(); private final Map<Integer, Double> DISTANCEB = new HashMap<>(); private final Set<Integer> CLOSED = new HashSet<>(); private double fA; private double fB; private double bestPathLength; private Integer touchNode; private Integer sourceNode; private Integer targetNode; public NBAStarPathfinder(DirectedGraph graph, DirectedGraphWeightFunction weightFunction, HeuristicFunction heuristicFunction) { super(graph, weightFunction); this.heuristicFunction = Objects.requireNonNull(heuristicFunction, The input heuristic function is null.); } @Override public DirectedGraphPath search(int sourceNode, int targetNode) { if (sourceNode == targetNode) { return new DirectedGraphPath(Arrays.asList(sourceNode)); } init(sourceNode, targetNode); while (!OPENA.isEmpty() && !OPENB.isEmpty()) { if (OPENA.size() < OPENB.size()) { expandInForwardDirection(); } else { expandInBackwardDirection(); } } if (touchNode == null) { throw new TargetUnreachableException(graph, sourceNode, targetNode); } return tracebackPath(touchNode, PARENTSA, PARENTSB); } private void expandInForwardDirection() { Integer currentNode = OPENA.remove().getNode(); if (CLOSED.contains(currentNode)) { return; } CLOSED.add(currentNode); if (DISTANCEA.get(currentNode) + heuristicFunction.estimateDistanceBetween(currentNode, targetNode) >= bestPathLength || DISTANCEA.get(currentNode) + fB - heuristicFunction.estimateDistanceBetween(currentNode, sourceNode) >= bestPathLength) { // Reject the 'currentNode'. } else { // Stabilize the 'currentNode'. for (Integer childNode : graph.getChildrenOf(currentNode)) { if (CLOSED.contains(childNode)) { continue; } double tentativeDistance = DISTANCEA.get(currentNode) + weightFunction.get(currentNode, childNode); if (!DISTANCEA.containsKey(childNode) || DISTANCEA.get(childNode) > tentativeDistance) { DISTANCEA.put(childNode, tentativeDistance); PARENTSA.put(childNode, currentNode); HeapEntry e = new HeapEntry( childNode, tentativeDistance + heuristicFunction .estimateDistanceBetween(childNode, targetNode)); OPENA.add(e); if (DISTANCEB.containsKey(childNode)) { double pathLength = tentativeDistance + DISTANCEB.get(childNode); if (bestPathLength > pathLength) { bestPathLength = pathLength; touchNode = childNode; } } } } } if (!OPENA.isEmpty()) { fA = OPENA.peek().getDistance(); } } private void expandInBackwardDirection() { Integer currentNode = OPENB.remove().getNode(); if (CLOSED.contains(currentNode)) { return; } CLOSED.add(currentNode); if (DISTANCEB.get(currentNode) + heuristicFunction.estimateDistanceBetween(currentNode, sourceNode) >= bestPathLength || DISTANCEB.get(currentNode) + fA - heuristicFunction.estimateDistanceBetween(currentNode, targetNode) >= bestPathLength) { // Reject the node 'currentNode'. } else { for (Integer parentNode : graph.getParentsOf(currentNode)) { if (CLOSED.contains(parentNode)) { continue; } double tentativeDistance = DISTANCEB.get(currentNode) + weightFunction.get(parentNode, currentNode); if (!DISTANCEB.containsKey(parentNode) || DISTANCEB.get(parentNode) > tentativeDistance) { DISTANCEB.put(parentNode, tentativeDistance); PARENTSB.put(parentNode, currentNode); HeapEntry e = new HeapEntry(parentNode, tentativeDistance + heuristicFunction .estimateDistanceBetween(parentNode, sourceNode)); OPENB.add(e); if (DISTANCEA.containsKey(parentNode)) { double pathLength = tentativeDistance + DISTANCEA.get(parentNode); if (bestPathLength > pathLength) { bestPathLength = pathLength; touchNode = parentNode; } } } } } if (!OPENB.isEmpty()) { fB = OPENB.peek().getDistance(); } } private void init(Integer sourceNode, Integer targetNode) { OPENA.clear(); OPENB.clear(); PARENTSA.clear(); PARENTSB.clear(); DISTANCEA.clear(); DISTANCEB.clear(); CLOSED.clear(); double totalDistance = heuristicFunction.estimateDistanceBetween(sourceNode, targetNode); fA = totalDistance; fB = totalDistance; bestPathLength = Double.MAX_VALUE; touchNode = null; this.sourceNode = sourceNode; this.targetNode = targetNode; OPENA.add(new HeapEntry(sourceNode, fA)); OPENB.add(new HeapEntry(targetNode, fB)); PARENTSA.put(sourceNode, null); PARENTSB.put(targetNode, null); DISTANCEA.put(sourceNode, 0.0); DISTANCEB.put(targetNode, 0.0); }}AStarPathfinder.javapackage net.coderodde.graph.pathfinding.support;import java.util.HashMap;import java.util.HashSet;import java.util.Map;import java.util.Objects;import java.util.PriorityQueue;import java.util.Set;import net.coderodde.graph.DirectedGraph;import net.coderodde.graph.DirectedGraphWeightFunction;import net.coderodde.graph.pathfinding.AbstractPathfinder;import net.coderodde.graph.pathfinding.DirectedGraphPath;import net.coderodde.graph.pathfinding.HeuristicFunction;import net.coderodde.graph.pathfinding.TargetUnreachableException;public final class AStarPathfinder extends AbstractPathfinder { private final HeuristicFunction heuristicFunction; private final PriorityQueue<HeapEntry> OPEN = new PriorityQueue<>(); private final Set<Integer> CLOSED = new HashSet<>(); private final Map<Integer, Double> DISTANCE = new HashMap<>(); private final Map<Integer, Integer> PARENTS = new HashMap<>(); public AStarPathfinder(DirectedGraph graph, DirectedGraphWeightFunction weightFunction, HeuristicFunction heuristicFunction) { super(graph, weightFunction); this.heuristicFunction = Objects.requireNonNull(heuristicFunction, The input heuristic function is null.); } @Override public DirectedGraphPath search(int sourceNodeId, int targetNodeId) { init(sourceNodeId); while (!OPEN.isEmpty()) { Integer currentNodeId = OPEN.remove().getNode(); if (currentNodeId.equals(targetNodeId)) { return tracebackPath(currentNodeId, PARENTS); } if (CLOSED.contains(currentNodeId)) { continue; } CLOSED.add(currentNodeId); for (Integer childNodeId : graph.getChildrenOf(currentNodeId)) { if (CLOSED.contains(childNodeId)) { continue; } double tentativeDistance = DISTANCE.get(currentNodeId) + weightFunction.get(currentNodeId, childNodeId); if (!DISTANCE.containsKey(childNodeId) || DISTANCE.get(childNodeId) > tentativeDistance) { DISTANCE.put(childNodeId, tentativeDistance); PARENTS.put(childNodeId, currentNodeId); OPEN.add( new HeapEntry( childNodeId, tentativeDistance + heuristicFunction .estimateDistanceBetween(childNodeId, targetNodeId))); } } } throw new TargetUnreachableException(graph, sourceNodeId, targetNodeId); } private void init(int sourceNodeId) { OPEN.clear(); CLOSED.clear(); PARENTS.clear(); DISTANCE.clear(); OPEN.add(new HeapEntry(sourceNodeId, 0.0)); PARENTS.put(sourceNodeId, null); DISTANCE.put(sourceNodeId, 0.0); }}DijkstraPathfinder.javapackage net.coderodde.graph.pathfinding.support;import net.coderodde.graph.DirectedGraph;import net.coderodde.graph.DirectedGraphWeightFunction;import net.coderodde.graph.pathfinding.AbstractPathfinder;import net.coderodde.graph.pathfinding.DirectedGraphPath;public final class DijkstraPathfinder extends AbstractPathfinder { private final AStarPathfinder finderImplementation; public DijkstraPathfinder(DirectedGraph graph, DirectedGraphWeightFunction weightFunction) { this.finderImplementation = new AStarPathfinder(graph, weightFunction, (a, b) -> { return 0.0; }); } @Override public DirectedGraphPath search(int sourceNodeId, int targetNodeId) { return finderImplementation.search(sourceNodeId, targetNodeId); }}HeapEntry.javapackage net.coderodde.graph.pathfinding.support;/** * This class implements an entry for {@link java.util.PriorityQueue}. * * @author Rodion rodde Efremov * @version 1.6 (Oct 13, 2016) */final class HeapEntry implements Comparable<HeapEntry> { private final int nodeId; private final double distance; // The priority key. public HeapEntry(int nodeId, double distance) { this.nodeId = nodeId; this.distance = distance; } public int getNode() { return nodeId; } public double getDistance() { return distance; } @Override public int compareTo(HeapEntry o) { return Double.compare(distance, o.distance); }}EuclideanHeuristicFunction.javapackage net.coderodde.graph.pathfinding.support;import java.util.Objects;import net.coderodde.graph.pathfinding.DirectedGraphNodeCoordinates;import net.coderodde.graph.pathfinding.HeuristicFunction;/** * This class implements a heuristic function that returns the Euclidean * distance between two given nodes. * * @author Rodion rodde Efremov * @version 1.6 (Oct 6, 2016) */public class EuclideanHeuristicFunction implements HeuristicFunction { private final DirectedGraphNodeCoordinates coordinates; public EuclideanHeuristicFunction(DirectedGraphNodeCoordinates coordinates) { this.coordinates = Objects.requireNonNull(coordinates, The input coordinate map is null.); } /** * {@inheritDoc } */ @Override public double estimateDistanceBetween(int nodeId1, int nodeId2) { return coordinates.get(nodeId1).distance(coordinates.get(nodeId2)); }}HeuristicFunction.javapackage net.coderodde.graph.pathfinding;/** * This interface defines the API for heuristic functions used in pathfinding. * * @author Rodion rodde Efremov * @version 1.6 (Oct 6, 2016) */@FunctionalInterfacepublic interface HeuristicFunction { /** * Provides an optimistic (underestimated) distance between {@code nodeId1} * and {@code nodeId2} using a specific distance metric. * * @param nodeId1 the first node. * @param nodeId2 the second node. * @return a shortest path estimate between the two input nodes. */ public double estimateDistanceBetween(int nodeId1, int nodeId2);}TargetUnreachableException.javapackage net.coderodde.graph.pathfinding;import net.coderodde.graph.DirectedGraph;public class TargetUnreachableException extends RuntimeException { private final DirectedGraph graph; private final Integer sourceNode; private final Integer targetNode; public TargetUnreachableException(DirectedGraph graph, Integer sourceNode, Integer targetNode) { this.graph = graph; this.sourceNode = sourceNode; this.targetNode = targetNode; } public DirectedGraph getGraph() { return graph; } public int getSourceNode() { return sourceNode; } public int getTargetNode() { return targetNode; } @Override public String toString() { return ' + targetNode + ' is not reachable from ' + sourceNode + '.; }}DirectedGraphPath.javapackage net.coderodde.graph.pathfinding;import java.util.ArrayList;import java.util.List;import net.coderodde.graph.DirectedGraphWeightFunction;/** * This class implements a type for representing paths in directed graphs. * * @author Rodion rodde Efremov * @version 1.6 (Oct 16, 2016) */public final class DirectedGraphPath { /** * The actual list of nodes on a path. */ private final List<Integer> path; public DirectedGraphPath(List<Integer> path) { checkNotEmpty(path); this.path = new ArrayList<>(path); } public int getNode(int index) { return path.get(index); } public int getNumberOfNodes() { return path.size(); } public int getNumberOfEdges() { return path.size() - 1; } public double getCost(DirectedGraphWeightFunction weightFunction) { double cost = 0.0; for (int i = 0; i < path.size() - 1; ++i) { cost += weightFunction.get(path.get(i), path.get(i + 1)); } return cost; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || !o.getClass().equals(getClass())) { return false; } return path.equals(((DirectedGraphPath) o).path); } @Override public String toString() { StringBuilder sb = new StringBuilder([); String separator = ; for (Integer node : path) { sb.append(separator).append(node); separator = , ; } return sb.append(']').toString(); } private void checkNotEmpty(List<Integer> path) { if (path.isEmpty()) { throw new IllegalArgumentException( The input path is not allowed to be empty.); } }}DirectedGraphNodeCoordinates.javapackage net.coderodde.graph.pathfinding;import java.awt.geom.Point2D;import java.util.HashMap;import java.util.Map;/** * This class allows mapping each graph node to its coordinates on a * two-dimensional plane. * * @author Rodion rodde Efremov * @version 1.6 (Oct 6, 2016) */public class DirectedGraphNodeCoordinates { /** * Maps each node to its coordinates. */ private final Map<Integer, Point2D.Double> map = new HashMap<>(); /** * Associates the coordinates {@code point} to the node {@code nodeId}. * * @param nodeId the node to map. * @param point the coordinates to associate to the node. */ public void put(int nodeId, Point2D.Double point) { map.put(nodeId, point); } /** * Return the point of the input node. * * @param nodeId the node whose coordinates to return. * @return the coordinates. */ public Point2D.Double get(int nodeId) { return map.get(nodeId); }}AbstractPathfinder.javapackage net.coderodde.graph.pathfinding;import java.util.ArrayList;import java.util.Collections;import java.util.List;import java.util.Map;import java.util.Objects;import net.coderodde.graph.DirectedGraph;import net.coderodde.graph.DirectedGraphWeightFunction;/** * This abstract class defines some facilities shared by pathfinding algorithms * and API for using them. * * @author Rodion rodde Efremov * @version 1.6 (Oct 6, 2016) */public abstract class AbstractPathfinder { /** * The graph to search in. */ protected final DirectedGraph graph; /** * The weight function to use. */ protected final DirectedGraphWeightFunction weightFunction; protected AbstractPathfinder(DirectedGraph graph, DirectedGraphWeightFunction weightFunction) { this.graph = Objects.requireNonNull(graph, The input graph is null.); this.weightFunction = Objects.requireNonNull(weightFunction, The input weight function is null.); } protected AbstractPathfinder() { this.graph = null; this.weightFunction = null; // Compiler requires this initialization. } /** * Searches and returns a shortest path starting from the node * {@code sourceNodeId} and leading to {@code targetNodeId}. * * @param sourceNodeId the source node. * @param targetNodeId the target node. * @return a shortest path of nodes from source node to target node * including the terminal nodes. */ public abstract DirectedGraphPath search(int sourceNodeId, int targetNodeId); /** * Reconstructs a shortest path from the data structures maintained by a * <b>bidirectional</b> pathfinding algorithm. * * @param touchNodeId the node where the two search frontiers agree. * @param PARENTSA the parent map in the forward search direction. * @param PARENTSB the parent map in the backward search direction. * @return the shortest path object. */ protected DirectedGraphPath tracebackPath(int touchNodeId, Map<Integer, Integer> PARENTSA, Map<Integer, Integer> PARENTSB) { List<Integer> path = new ArrayList<>(); Integer currentNodeId = touchNodeId; while (currentNodeId != null) { path.add(currentNodeId); currentNodeId = PARENTSA.get(currentNodeId); } Collections.<Integer>reverse(path); if (PARENTSB != null) { currentNodeId = PARENTSB.get(touchNodeId); while (currentNodeId != null) { path.add(currentNodeId); currentNodeId = PARENTSB.get(currentNodeId); } } return new DirectedGraphPath(path); } /** * Reconstructs a shortest path from the data structures maintained by a * unidirectional pathfinding algorithm. * * @param targetNodeId the target node. * @param PARENTS the parents map. * @return the shortest path object */ protected DirectedGraphPath tracebackPath(int targetNodeId, Map<Integer, Integer> PARENTS) { return tracebackPath(targetNodeId, PARENTS, null); }}DirectedGraph.javapackage net.coderodde.graph;import java.util.Collections;import java.util.HashMap;import java.util.HashSet;import java.util.Map;import java.util.Set;/** * This class implements a directed graph data structure via adjacency lists. * This implementation represents each graph node as an unique integer. * * @author Rodion rodde Efremov * @version 1.61 (Oct 13, 2016) */public class DirectedGraph { /** * This map maps each directed graph node to the list of its child nodes. */ private final Map<Integer, Set<Integer>> childMap = new HashMap<>(); /** * This map maps each directed graph node to the list of its parent nodes. */ private final Map<Integer, Set<Integer>> parentMap = new HashMap<>(); /** * Adds a new node represented by integer {@code nodeId} to this graph if * it is not yet present in it. * * @param nodeId the node to add. */ public void addNode(int nodeId) { childMap .putIfAbsent(nodeId, new HashSet<>()); parentMap.putIfAbsent(nodeId, new HashSet<>()); } /** * Creates a directed arc <tt>(tailNodeId, headNodeId)</tt> if it is not yet * present in the graph. * * @param tailNodeId the tail node of the arc. * @param headNodeId the head node of the arc. */ public void addArc(int tailNodeId, int headNodeId) { childMap .get(tailNodeId).add(headNodeId); parentMap.get(headNodeId).add(tailNodeId); } /** * Returns the view of all the nodes in this graph. * * @return the set of all nodes. */ public Set<Integer> getNodeSet() { return Collections.unmodifiableSet(childMap.keySet()); } /** * Returns the set of all child nodes of the given node {@code nodeId}. * * @param nodeId the node whose children to return. * @return the set of child nodes of {@code nodeId}. */ public Set<Integer> getChildrenOf(int nodeId) { return Collections.<Integer>unmodifiableSet(childMap.get(nodeId)); } /** * Returns the set of all parent nodes of the given node {@code nodeId}. * * @param nodeId the node whose parents to return. * @return the set of parent nodes of {@code nodeId}. */ public Set<Integer> getParentsOf(int nodeId) { return Collections.<Integer>unmodifiableSet(parentMap.get(nodeId)); }}DirectedGraphWeightFunction.javapackage net.coderodde.graph;import java.util.HashMap;import java.util.Map;/** * This class maps directed arcs to their weights. An arc weight is not allowed * to be a <tt>NaN</tt> value or negative. * * @author Rodion rodde Efremov * @vesion 1.6 (Oct 6, 2016) */public class DirectedGraphWeightFunction { /** * Maps the arcs to the arc weights. */ private final Map<Integer, Map<Integer, Double>> map = new HashMap<>(); /** * Associates the weight {@code weight} with the arc * <tt>(tailNodeId, headNodeId)</tt>. * * @param tailNodeId the starting node of the arc. * @param headNodeId the ending node of the arc. * @param weight the arc weight. */ public void put(int tailNodeId, int headNodeId, double weight) { checkWeight(weight); map.putIfAbsent(tailNodeId, new HashMap<>()); map.get(tailNodeId).put(headNodeId, weight); } /** * Returns the weight of the given arc. * * @param tailNodeId the starting node (tail node) of the arc. * @param headNodeId the ending node (head node) of the arc. * @return */ public double get(int tailNodeId, int headNodeId) { return map.get(tailNodeId).get(headNodeId); } private void checkWeight(double weight) { if (Double.isNaN(weight)) { throw new IllegalArgumentException(The input weight is NaN.); } if (weight < 0.0) { throw new IllegalArgumentException( The input weight is negative: + weight + .); } }}Demo.javaimport java.awt.geom.Point2D;import java.util.ArrayList;import java.util.List;import java.util.Random;import net.coderodde.graph.DirectedGraph;import net.coderodde.graph.DirectedGraphWeightFunction;import net.coderodde.graph.pathfinding.AbstractPathfinder;import net.coderodde.graph.pathfinding.DirectedGraphNodeCoordinates;import net.coderodde.graph.pathfinding.DirectedGraphPath;import net.coderodde.graph.pathfinding.HeuristicFunction;import net.coderodde.graph.pathfinding.support.AStarPathfinder;import net.coderodde.graph.pathfinding.support.DijkstraPathfinder;import net.coderodde.graph.pathfinding.support.EuclideanHeuristicFunction;import net.coderodde.graph.pathfinding.support.NBAStarPathfinder;/** * This class contains a demonstration program comparing performance of three * point-to-point shortest path algorithms: * <ol> * <li>A*,</li> * <li>Dijkstra's algorithm</li> * <li>NBA*, New Bidirectional A*.</li> * </ol> * * @author Rodion rodde Efremov * @version 1.61 (Oct 16, 2016) */public class Demo { private static final int NODES = 100_000; private static final int ARCS = 500_000; private static final double PLANE_WIDTH = 1000.0; private static final double PLANE_HEIGHT = 1000.0; public static void main(String[] args) { long seed = System.nanoTime(); Random random = new Random(seed); System.out.println(Seed = + seed); long start = System.currentTimeMillis(); DirectedGraph graph = getRandomGraph(NODES, ARCS, random); DirectedGraphNodeCoordinates coordinates = getCoordinates(graph, PLANE_WIDTH, PLANE_HEIGHT, random); DirectedGraphWeightFunction weightFunction = getWeightFunction(graph, coordinates); Integer sourceNodeId = getSource(graph, coordinates); Integer targetNodeId = getTarget(graph, coordinates); long end = System.currentTimeMillis(); System.out.println(Created the graph data structures in + (end - start) + milliseconds.); System.out.println(Source: + sourceNodeId); System.out.println(Target: + targetNodeId); System.out.println(); HeuristicFunction hf = new EuclideanHeuristicFunction(coordinates); AbstractPathfinder finder1 = new AStarPathfinder(graph, weightFunction, hf); AbstractPathfinder finder2 = new DijkstraPathfinder(graph, weightFunction); AbstractPathfinder finder3 = new NBAStarPathfinder(graph, weightFunction, hf); DirectedGraphPath path1 = benchmark(finder1, sourceNodeId, targetNodeId); DirectedGraphPath path2 = benchmark(finder2, sourceNodeId, targetNodeId); DirectedGraphPath path3 = benchmark(finder3, sourceNodeId, targetNodeId); boolean agreed = path1.equals(path2) && path1.equals(path3); if (agreed) { System.out.println(Algorithms agree: true); } else { System.out.println(Algorithms DISAGREED!); System.out.println(A* path length: + path1.getCost(weightFunction)); System.out.println(Dijkstra path length: + path2.getCost(weightFunction)); System.out.println(NBA* path length: + path3.getCost(weightFunction)); } } private static DirectedGraphPath benchmark(AbstractPathfinder pathfinder, int sourceNode, int targetNode) { long start = System.currentTimeMillis(); DirectedGraphPath path = pathfinder.search(sourceNode, targetNode); long end = System.currentTimeMillis(); System.out.println(pathfinder.getClass().getSimpleName() + in + (end - start) + milliseconds.); System.out.println(path); System.out.println(); return path; } private static DirectedGraph getRandomGraph(int nodes, int arcs, Random random) { DirectedGraph graph = new DirectedGraph(); for (int id = 0; id < nodes; ++id) { graph.addNode(id); } List<Integer> graphNodeList = new ArrayList<>(graph.getNodeSet()); while (arcs-- > 0) { Integer tailNodeId = choose(graphNodeList, random); Integer headNodeId = choose(graphNodeList, random); graph.addArc(tailNodeId, headNodeId); } return graph; } private static DirectedGraphNodeCoordinates getCoordinates(DirectedGraph graph, double planeWidth, double planeHeight, Random random) { DirectedGraphNodeCoordinates coordinates = new DirectedGraphNodeCoordinates(); for (Integer nodeId : graph.getNodeSet()) { coordinates.put(nodeId, randomPoint(planeWidth, planeHeight, random)); } return coordinates; } private static DirectedGraphWeightFunction getWeightFunction(DirectedGraph graph, DirectedGraphNodeCoordinates coordinates) { DirectedGraphWeightFunction weightFunction = new DirectedGraphWeightFunction(); for (Integer nodeId : graph.getNodeSet()) { Point2D.Double p1 = coordinates.get(nodeId); for (Integer childNodeId : graph.getChildrenOf(nodeId)) { Point2D.Double p2 = coordinates.get(childNodeId); double distance = p1.distance(p2); weightFunction.put(nodeId, childNodeId, 1.2 * distance); } } return weightFunction; } private static Point2D.Double randomPoint(double width, double height, Random random) { return new Point2D.Double(width * random.nextDouble(), height * random.nextDouble()); } private static <T> T choose(List<T> list, Random random) { return list.get(random.nextInt(list.size())); } private static Integer getClosestTo(DirectedGraph graph, DirectedGraphNodeCoordinates coordinates, Point2D.Double point) { double bestDistance = Double.POSITIVE_INFINITY; Integer bestNode = null; for (Integer node : graph.getNodeSet()) { Point2D.Double nodePoint = coordinates.get(node); if (bestDistance > nodePoint.distance(point)) { bestDistance = nodePoint.distance(point); bestNode = node; } } return bestNode; } private static Integer getSource(DirectedGraph graph, DirectedGraphNodeCoordinates coordinates) { return getClosestTo(graph, coordinates, new Point2D.Double()); } private static Integer getTarget(DirectedGraph graph, DirectedGraphNodeCoordinates coordinates) { return getClosestTo(graph, coordinates, new Point2D.Double(PLANE_WIDTH, PLANE_HEIGHT)); }}Performance figuresA typical run of the demonstration might output something like this:Seed = 380420829228515Created the graph data structures in 6350 milliseconds.Source: 58350Target: 45998AStarPathfinder in 996 milliseconds.[58350, 69183, 24066, 12240, 79684, 33326, 53655, 74615, 97690, 28336, 45998]DijkstraPathfinder in 5025 milliseconds.[58350, 69183, 24066, 12240, 79684, 33326, 53655, 74615, 97690, 28336, 45998]NBAStarPathfinder in 29 milliseconds.[58350, 69183, 24066, 12240, 79684, 33326, 53655, 74615, 97690, 28336, 45998]Algorithms agree: trueCritique requestI would like to hear anything you can tell me, especially:API designModularityNamingCoding conventionsEfficiencyJavadoc
NBA*: Very efficient bidirectional heuristic search algorithm in Java - follow-up
java;algorithm;graph;pathfinding;a star
null
_cs.35873
I'm wondering if there is some formalization, type theoretical analysis, or similar for data structures that automatically splice in an associative way. Barring a perfect citation, I'd be interested to know if there are other keywords I should be looking for in this space.Examples are particularly common in term-rewriting languages, such as Tuples and Matricies in Purelang or Sequence in Mathematica.I'm also interested in one particularly challenging question with these constructs: How should quoting (to prevent splicing) be represented and handled?
Is there a formalization of automatic-splicing data structures?
data structures;type theory
null
_unix.268464
What's the simplest way to express allow all connections to the local lan for iptables output?Including connections to 192.*, 172.*, 10.*, etc.Can all of this compressed within a single rule?
iptables - How to allow all connections to the local lan?
iptables
null
_softwareengineering.224033
Let's say in some reason all objects are created this way $obj = CLASS::getInstance(). Then we inject dependencies using setters and perform starting initialization using $obj->initInstance(); Are there any real troubles or situations, which can't be solved, if we won't use constructors at all?P.s. the reason to create object this way, is that we can replace class inside getInstance() according to some rules.I'm working in PHP, if that matter
Can we live without constructors?
object oriented design;class design
null
_softwareengineering.312702
I'm trying to figure out a way to handle default variable values when making functions without side effects and have ended up with the following: function getDefaultSeparator() { return ':';}function process(input, separator) { var separator = separator || getDefaultSeparator(); // Use separator in some logic return output;}The default separator will be used in other functions and I only want to define it in one place. If this is a pure function, what is the difference from just using a global DEFAULT_SEPARATOR constant instead?
Is a function getting a value from another function considered pure?
javascript;functional programming;functions
null
_cs.54063
i'm studying an algorithms designing and analysis , and i've question about Big-theta how can i prove that nlogn is not (n) without using limits ?
how to prove that nlogn is not (n) without using limits?
algorithms;complexity theory;algorithm analysis;asymptotics
null
_webmaster.106728
We changed the sites UI, CMS, link structure. Also Bought a new and better domain name. After we completed everything. We did below step by step;Created a new web application for old.com/page1.html to new.com/page1.html 301 redirection.Used webmmaster tools for 301 redirection.Sent new sitemaps a long with robots.txtAlthough we've got a custom title,meta descrpition and meta keywords for every page, Google takes a piece of sentece from content and uses it for MetaDescription. This is a big problem for our potential clicks on SERP. What should we do for getting back MetaDescription?The old site is : indirimkodlari.gen.trThe new site : indirimkodu.gen.trGoogle still shows the old url and right meta description with it.The new domain name with randomly scraped on Google search of site.com/urlSolutionLooking at Google's search cache by using view source shows we used the wrong field from database for MetaDescription! Changed it, fixed, and solved!.
Google doesn't use meta description on SERP
seo;google search;serps;meta description
null
_codereview.28870
The file is quite long, 1000 LOC so I want to separate it into smaller files.https://github.com/anvoz/world-js/blob/v1.0/js/world.core.jsHere is a brief version of the code:(function(window, undefined) { var WorldJS = window.WorldJS = function() { // WorldJS Constructor this.nextSeedId = 1; this.Statistic = { population: 0 }; this.Knowledge = { completed: [], gain: function(world) { /* ... */ } }; } WorldJS.prototype.someMethods = function() {}; var Seed = WorldJS.prototype.Seed = function() { // Seed Constructor }; Seed.prototype.someMethods = function() {};})(window);// Create a worldvar world = new WorldJS();// Create a seedvar seed = new world.Seed();Seems like I was right with the Seed class. So I can put Seed in a new file. Like this:(function(window, undefined) { var WorldJS = window.WorldJS; var Seed = WorldJS.prototype.Seed = function() { // Seed Constructor }; Seed.prototype.someMethods = function() {};})(window);How can I put the Knowledge property to a new file? Is it a good practice if I change Knowledge to a class just like the Seed class and use a new lowercase property to hold data like this:world.knowledge = new world.Knowledge();
Separate a module into smaller parts
javascript
I don't see the advantage of adding Seed and Knowledge into the prototype of World (unless you've got more code to tell me otherwise). If you don't need anything from the instance at all, then you don't need them in the instance. You can put them like static members instead.With that, you can do what jQuery did. jQuery's jQuery and $ point to a constructor function that builds jQuery objects. That's why you can do jQuery() and $(). But in JS, functions are objects and like any other object, you can add properties. It's the same reason why you can also do jQuery.each or $.each. Basically they made their constructor their namespace as well.So you can do the following to World:(function(window){ var World = window.World = function(){/*World constructor code*/}; World.prototype.someFn = function(){/*...*/};}(window));And like how non-instance jQuery plugins extend (and yes, you can place this in another file. Just make sure the World library is loaded first):(function(World){ //This part would be synonymous to $.somePlugin = function(){...} var Seed = World.Seed = function(){/*Seed constructor code*/}; Seed.prototype.someFn = function(){/*...*/};}(World));To use them:var myWorld = new World(); //Using World as a constructorvar mangoSeed = new World.Seed(); //Using World to access the Seed constructor
_unix.83897
How can I do a screencast (having a video file out from my screen output) without X server? I mean, purely from the tty, no KDE, no LXDE, no Xorg beneath them. Like if I were in single-user mode.
How can I screencast purely from the tty?
video
Recordscreen.pyRecordscreen.py sounds like what you're looking for. You can download and install it like so:$ wget http://www.davidrevoy.com/data/documents/recordscreen_12-04.zip$ unzip recordscreen_12-04.zip$ rm recordscreen_12-04.zip$ chmod +x recordscreen.pyThere are a few dependencies that it requires:$ sudo apt-get install wget libav-tools ffmpeg libavc1394-0 libavformat-extra-53 \ libavfilter2 libavutil-extra-51 mencoder libavahi-common-dataRun it like this:$ ./recordscreen.pyttyrecYou can use ttyrec to also accomplish this.For example, to record:$ ttyrec...(In the executed shell, do whatever you want and exit)...Or this, to record just a command running:$ ttyrec -e command...(command specified by -e option will be executed) ...You can then use ttyplayback to play back your recording:$ ttyplay ttyrecord There are some sample videos here in this articled titled: ttyrec > script on Linuxaria.
_codereview.158678
I'm writing a C++ high precision library based on GMP, sample code(files which have to be added to project)://biginteger.cc#include biginteger.h#include <cstdlib>#include <iostream>#include <tuple>#include <gmp.h>void biginteger::deleteBiginteger(){std::cout << sprzatam bigintegera; std::cout << std::endl;mpz_clear(x);}void biginteger::printbiginteger(){gmp_printf(%Zd\n, this->x); //std::cout <<std::endl; } // overloaded += operators biginteger& biginteger::operator += (const unsigned long long int& a){ mpz_add_ui(this->x, x, a); return *this; }biginteger& biginteger::operator += (const signed long int& a){ if (a < 0) { signed long int tmp1 = -a; unsigned long long int tmp2 = tmp1; mpz_sub_ui(this->x, x, tmp2); return *this;}else{ unsigned long long int t1 = (unsigned long long int) a; mpz_add_ui(this->x, x, t1); return *this;}}biginteger& biginteger::operator += (const biginteger& a){mpz_add(this->x, this->x, a.x);return *this;}//biginteger.h#ifndef biginteger_h#define biginteger_h#include <cstdlib>#include <iostream>#include <tuple>#include <gmp.h> class biginteger{ public: mpz_t x; biginteger(mpz_t n){ mpz_init(x); mpz_set(x, n); } biginteger(unsigned long long int a){ mpz_init(x); mpz_set_ui(x, a); } biginteger(signed long int a){ mpz_init(x); mpz_set_si(x, a); }biginteger(int a){ mpz_init(x); mpz_set_si(x, a);}biginteger(const char *str, int base){ mpz_init_set_str(x, str, base);} void deleteBiginteger();void printbiginteger();biginteger& operator += (const unsigned long long int& a);biginteger& operator += (const signed long int& a);biginteger& operator += (const biginteger& a);Those two files are just sample code, is there any way to improve performance of this?
Wrapper for GMP in C++
c++;performance;integer;wrapper
null
_reverseengineering.10722
While reversing a C++ program compiled with g++, I've seen a _ZNSs4_Rep20_S_empty_rep_storageE being used. Running it through c++filt shows that before mangling it's a: std::basic_string<char, std::char_traits<char>, std::allocator<char> >::_Rep::_S_empty_rep_storageBut what is this _S_empty_rep_storage used for? I included an assembly snippet below where it's used:mov rax, cs:_ZNSs4_Rep20_S_empty_rep_storageE_ptr...add rax, 18h...mov [rsp+328h+var_308], raxmov [rsp+328h+var_2F8], raxmov [rsp+328h+var_2E8], rax...lea r14, [rsp+328h+var_308]lea rsi, [rsp+328h+var_2D8] ; std::string *mov rdi, r14 ; thiscall __ZNSs4swapERSs ; std::string::swap(std::string &)lea rdi, [rsp+328h+var_2D8] ; thislea r13, [rsp+328h+var_2F8]lea r12, [rsp+328h+var_2E8]call __ZNSsD1Ev ; std::string::~string()So my question is: What's the purpose of _S_empty_rep_storage here? Also why are var_308, var_2f8 and var_2e8 lea'd into r12-14? These registers are not used later on.
What is _S_empty_rep_storage used for in this code?
disassembly
Check the comments at the beginning of libstdc++'s basic_string.h to see how GCC's std::string works.Basically, _S_empty_rep_storage is a pre-initialized (in fact, zeroed out) representation of an empty string, used to initialize the string in a default constructor. So var_308, var_2F8 and var_2E8 are three std::string objects, initialized to an empty string.As for r12-r14, they seem to be used as temporary variables. We can at leas see that r14 is used to initialize rdi - the this pointer for the std::string::swap() call, so presumably r12 and r13 are also used later.
_unix.4569
I have an operation using cut that I would like to assign result to a variablevar4=echo ztemp.xml |cut -f1 -d '.'I get the error:ztemp.xml is not a commandThe value of var4 never gets assigned; I'm trying to assign it the output of:echo ztemp.xml | cut -f1 -d '.'How can I do that?
Storing output of command in shell variable
command line;bash;scripting;shell script;coreutils
You'll want to modify your assignment to read:var4=$(echo ztemp.xml | cut -f1 -d '.')The $() construct is known as command susbtitution.
_softwareengineering.270697
In Pattern Oriented Software Architecture - Vol 1 (p. 131), the author said that View is responsible for creating Controller. But in Head First Design Patterns (p. 562) it is the Controller that creates the View. In some other references I see that nor View niether Controller create each other. Only Controller has a reference of View and/or vice versa.What's your opinion about this? Does this depend?
Model-View-Controller: who creates whom?
design patterns;mvc;architectural patterns
Well, I can only assume this changes along different platforms.On the android library, you create the view from the controller. i.e., in your Activity you call setContentView... to awake you XML (The view) and create it.On the other hand, in the iOS world, you would ask the View (storyboard or .xib file) to awake (Actually you ask the system to go to the app's bundle, get the View and create it) itself up, than it will awake your controller (e.g., myView) and awakeFromNib will be called...I might not be precise about the small details, but you can see that different platforms would create this connection in slightly different ways, depends on the architecture.
_unix.126201
When I run apropos or man -k in bash, it always returns the same item (at least one) twice:QuestionWhy is it doing this; and would it indicate that there's a possible configuration issue with my system?I'm using OSX.
Apropos always returns several duplicate matches from whatis
osx;man
From this link titled: Subject: Re: omitting duplicates in apropos andapropos-list - msg#00017, I found the information below.Because a symbol might be available by way of more than one inheritance path, apropos might print information about the same symbol more than once, or apropos-list might return a list containing duplicate symbols.I also found from this link titled: duplicate entires for apropos after 5.0.7 MP5 (Linux & Unix Question), which contained the below piece of information. I straightened out this problem by running makewhatis
_unix.370216
I'm trying to setup grub to boot from encrypted /boot on BTRFS based RAID1 array. However, I'm cannot find a way to force grub to unlock both disks. GRUB asks for key twice to unlock /boot, but I don't know how to ask it to unlock two cryptdevices after that. Here the boot process:Unlock /dev/sda2:Unlock /dev/sdb2:grub asks for /dev/sdb2 passwordand fails since /dev/mapper/root1 is not foundHere is how relevant parts of config files look like:/etc/default/grub.cfg:...GRUB_CMDLINE_LINUX_DEFAULT=cryptdevice=/dev/sda2:root1 cryptkey=rootfs:/cryptfile.bin cryptdevice=/dev/sdb2:root2 cryptkey=rootfs:/cryptfile.bin root=/dev/mapper/root1 rootfstype=btrfs rootflags=device/dev/mapper/root1,device=/dev/mapper/root2,defaultsGRUB_ENABLE_CRYPTODISK=y...Disk partitioning looks like:/sda /sda1 - SWAP /sda2 - dmcrypt /root1 - / (RAID1)/sdb /sdb1 - SWAP /sdb2 - dmcrypt /root2 - / (RAID1)Any help please?
Grub with encrypted /boot and / on btrfs RAID1?
linux;grub;btrfs;disk encryption;whole drive encryption
Working advice from reddit:Find the encrypt boot hook (the one that is bundled inside your initramfs)copy it and create encrypt2 from it. Remove some sanitation lines from it (like clearing some files or folders)add encrypt2 to your hooks (mkinitcpio.conf(5)), encrypt2_* arguments to your kernel cmdline, rebuild the initramfs.reboot?
_unix.22854
How can I create a script that automatically switches windows? I'm trying to do the same thing Alt+Tab does.
How to switch X windows from the command-line?
terminal;keyboard;keyboard shortcuts
Sounds like you're looking for wmctrl - see here for more examples.Edit: Your window manager/desktop environment has to be standards compliant (EWMH). And here are more examples.
_codereview.149562
I need to create this eventEmitter class with the functions listed below. I think I could clean the code a little but don't really know where to start.var eventEmitter =function (){ this.listeners = 0; this.events = {}; return this;};eventEmitter.prototype.on = function(ev, cb) { if (typeof ev !== 'string') throw new TypeError(Event should be type string, index.js, 6); if (typeof cb !== 'function' || cb === null || cb === undefined) throw new TypeError(callback should be type function, index.js, 7); if (this.events[ev]){ this.events[ev].push(cb); } else { this.events[ev] = [cb]; } this.listeners ++; return this;};eventEmitter.prototype.emit = function(eventType) { if (typeof eventType !== 'string') throw new TypeError(Event type should be type string, index.js, 6); var handlerFunctions = this.events[eventType]; if (handlerFunctions) { var self = this; for (var i = 0; i < handlerFunctions.length; i++) { var handler = handlerFunctions[i]; if (arguments.length > 0) { var args = Array.prototype.slice.call(arguments).slice(1, arguments.length); handler.apply(self, args); } else{ handler.call(self); } } } return this;};eventEmitter.prototype.off = function(eventType, handlers) { if ( arguments.length > 0 && (eventType === 'undefined' || typeof eventType !== 'string')) throw TypeError('listener must be a function'); if (arguments.length > 1) { if ( typeof handlers !== 'function' || handlers === 'undefined') throw TypeError('handler must be a function string or object'); } switch(arguments.length) { case 0: this.listeners = 0; this.events = {}; break; case 1: if (this.events[eventType]) { this.listeners = this.listeners - this.events[eventType].length; delete this.events[eventType]; } break; case 2: if (this.events[eventType]) { for (var i = 0; i < this.events[eventType].length; i++) { if (handlers.toString() == this.events[eventType][i].toString()){ this.events[eventType].splice( i, 1 ); this.listeners --; i --; } } } break; } return this;};module.exports = eventEmitter;
Event emitter in JavaScript without using Node's built in class or any additional libraries
javascript;object oriented;event handling
Constructors should be PascalCase, i.e. EventEmitter - not eventEmitter. Of course, EventEmitter is the exact name of Node's own implementation, so I'd pick something else.Don't hardcode file and line number in errors. Those get added automatically, which is the whole point. And besides, if you hardcode them, you'll have to keep them up to date (line numbers are already misleading), etc.. It's interpreter-generated metadata, not data.Also, this a minor thing but don't use should in an error description. You're throwing an error because, something must be something - not just because it ought to. So event names must be strings, and listeners must be functions.Don't bother with maintaining the listeners count manually. You can just do this (ES6 syntax, but you can translate it):Object.keys(this.events).reduce((count, key) => count + this.events[key].length, 0);// => number of listener functionsYou can add that as a getter function with Object.defineProperty or just have a getListenerCount method. If you add it as a method you can even choose to only get the count for a named event, i.e. getListenerCount('someEventName').This:if (typeof cb !== 'function' || cb === null || cb === undefined)is very redundant. The only thing that matters is whether cb is a function. Doesn't matter if it's null or undefined - it's still not a function.You don't need to return this if you intend to use a function as a constructor. You can, but you don't need to.Here's a quick refactoring based on the points above:function EventBase() { this.events = {};};EventBase.prototype = { on: function (event, listener) { if (typeof event !== 'string') throw new TypeError(Event must be a string); if (typeof event !== 'string') throw new TypeError(Listener must be a function); this.events[event] || (this.events[event] = []); this.events[event].push(listener); }, off: function (event, listener) { if (arguments.length === 0) { // remove all listeners this.events = {}; return; } if (!this.events[event]) { // return if there's no event by the given name return; } if (arguments.length === 1) { // remove all listeners for the given event delete this.events[event]; return; } // remove specific listener this.events[event] = this.events[event].filter(function (func) { return func !== listener; }); }, emit: function (event) { if (!this.events[event]) { // return if there's no event by the given name return; } // get args var args = [].slice.call(arguments, 1); // invoke listeners this.events[event].forEach(listener => listener.apply(this, args)); }, getListenerCount: function (event) { // get total number of listeners if (arguments.length === 0) { return Object.keys(this.events).reduce((count, key) => count + this.getListenerCount(key), 0); } // return zero for non-existing events if (!this.events[event]) { return 0; } // return count for specific event return this.events[event].length; }};
_cstheory.25985
We know from Church's theorem that determining first order satisfiability is undecidable in general, but there are several techniques we can use to determine first order satisfiability. The most obvious is to search for a finite model. However, there are a number of statements in first order logic that we can demonstrate have no finite models. For instance, any domain in which an injective and non-surjective function operates is infinite. How do we demonstrate satisfiability for first order statements where there aren't finite models or the existence of finite models is unknown? In automated theorem proving we can determine satisfiability several ways:We can negate the sentence, and search for a contradiction. If one is found, we prove first order validity of the statement and thus satisfiability.We use saturation with resolution and run out of inferences. More often than not, we will have an infinite amount of inferences to make, so this isn't dependable.We can use forcing, which assumes the existence of a model and also the consistency of the theory.I don't know of anyone implementing forcing as a mechanized technique for automated theorem proving, and it doesn't look easy, but I'm interested if it's been done or attempted, as it's been used to prove independence for a number of statements in set theory, which itself has no finite models. Are there other techniques known for searching for first order satisfiability that are applicable for automated reasoning or has anyone worked on an automated forcing algorithm?
First order satisfiability that doesn't have finite models
reference request;lo.logic;automated theorem proving
Here's an amusing approach by Brock-Nannestad and Schrmann:Truthful Monadic AbstractionsThe idea is to try to translate first-order sentences into monadic first-order logic, by forgetting some of the arguments. Certainly the translation isn't complete: there are some consistent sentences which become inconsistent after translation.However, monadic first order logic is decidable. One can therefore verify if the translation $\overline F$ of a formula $F$ is consistent:$$ \overline F\not\vdash\bot$$can be checked by a decision procedure, and implies$$ F\not\vdash\bot$$Which implies that $F$ has a model, by the completeness theorem.This theme can apply somewhat more generally: identify a decidable sub-logic of your problem, then translate your problem into it, in a way that preserves truth. In particular modern SMT solvers like Z3 have gotten astonishingly good at proving satisfiability of formulas with quantifiers (by default $\Sigma^0_1$, but can perform well on $\Pi^0_2$ formulas).Forcing seems to be far out of reach of automated methods at the present.
_cs.41099
I have a tentative understanding of modal logic. Can anyone explain modal logic as it is used in computer science?
The use of modal logic in computer science
logic;modal logic
null
_unix.171258
this problem occurs on Debian jessie x86 with systemd. It leads to an incomplete boot sequence on init 2 because network-manager won't start. it leaves the whole system unusableNetworkManager[785]: segfault at e7394845 ip b74ab7a1 sp b7548810 error 7 in libgnutls-deb0.so.28.41.0[b746f000+13a000]
segfault in libgnutls - Debian won't complete boot
debian;init;segmentation fault
Turned out, I interrupted an upgrade process earlier. I manually reinstalled the network manager package.
_codereview.24869
I have a simple two-class hierarchy to represent U.S. ZIP (12345) and ZIP+4 (12345-1234) codes. To allow clients to allow both types for a field/parameter or restrict it to one type or the other, the specific types inherit from a common generic ZipCode interface.Update: A ZIP code is five digits. A ZIP+4 code consists of the primary five-digit ZIP code plus a four-digit plus-4 (+4) code. You can create a ZIP+4 from a regular ZIP and get the primary ZIP from a ZIP+4. Thus, the interface which the two classes implement knows about the two classes, and they know about each other.interface ZipCode boolean isPlusFour() ZipPlusFour plusFour(String code) Zip primary() boolean hasSamePrimary(ZipCode other)class Zip implements ZipCode String codeclass ZipPlusFour implements ZipCode Zip primary String plusFourCodeIntroducing Null Object PatternTo avoid duplicating code that checks for null values throughout the application, I would like to introduce the Null Object pattern. However, I'm afraid the only way to do so that supports the features above is to add three new classes instead of just one:class NullZipCode implements ZipCodeclass NullZip extends Zipclass NullZipPlusFour extends ZipPlusFourWorse, since the last two extend concrete classes they will need to pass special values to their superclass that will pass validation but not block the possibility of using real values. For example, NullZip would call super(00000).Here are my main questions, though please don't hesitate to throw out any suggestions you have.Is there a way to solve this with just one new class to cover all bases?Is it worth extracting interfaces from Zip and ZipPlusFour so that NullZip won't extend the concrete Zip implementation (same for ZipPlusFour)?ZipCode Zip NullZip RealZipAnother option is to forego separate classes altogether and check for a special value in Zip and ZipPlusFour to signify a missing ZIP code.class Zip boolean isNone() { return code.equals(00000); } boolean hasSamePrimary(ZipCode other) { if (isNone() || other.isNone()) return false; else return code.equals(other.primary().code); }At least the complicated checks are encapsulated in these classes which is the whole point of introducing the pattern. The downside is that this logic can be more fragile than inheritance. Is this a good trade-off?
Null Object pattern with simple class hierarchy
java;design patterns;polymorphism;null
null
_codereview.25763
I had my original threading code which worked well, but since my tasks were shortlived, I decided to use thread pools through ExecutorService.This was my original codepublic class MyRun implements Runnable{ private Socket socket = null; public MyRun(Socket s) { socket = s; thread = new Thread(this, SocketThread); thread.start(); } public void run() { // My actual thread code }}My main program...ss = new ServerSocket(port);....MyRun st = null;while (!stop){ st = new MyRun(ss.accept()); st = null;}New codepublic MyRun(Socket s){ socket = s; thread = new Thread(this, SocketThread);}run() left unchangedChanged Main programprivate static ExecutorService execService = Executors.newCachedThreadPool();........while (!stop){ execService.execute(new MyRun(ss.accept()));}Changed code seems to be working fine, but I just want to make sure there is nothing I am missing. I want all threads to execute simultaneously.
Moving from normal threads to ExecutorService thread pools in java
java;multithreading
A few simple remarks :thread = new Thread(this, SocketThread); is no longer needed in MyRun, since the ExecutorService is the one creating and managing the Threads.you will want to call execService.shutDown() to properly clean up the resources of the executorService.
_softwareengineering.211197
My team is writing a compiler for a domain-specific language (DSL) which will be integrated into an IDE. Right now, we are focused on the analysis phase of the compiler. We are not using any existing parser-generators (such as ANTLR) because we need real-time performance and highly detailed error/warning/message information. We haveclasses, each of which represents a node in the concrete syntax tree for the language, as well asclasses which act as annotations for each node (i.e., for errors and additional information), as well asinternal classes which build and manipulate the concrete syntax tree (i.e., lexer, parser, cache for strings, syntax visitors).We are trying to decide on an overall strategy for organizing our tests. Our company is pushing behavior-driven development (BDD) and domain-driven design (DDD). Although we are building a DSL for our companys domain, the domain of the compiler is a programming language.We are still in the process of building the compiler and have some tests already. We are aiming to have 100% statement coverage.We currently have tests in which we input source code to the syntax tree builder, and then run a verification on each property of every node of the resultant syntax tree to make sure that the expected information (line number, relevant error(s), child/parent tokens, width of token, type of token, etc.). Now, since each node is its own class, and certain annotations and errors attached to a node are separate classes, this test ends up referencing many classes.We currently have tests for certain classes such as the lexer in which we can isolate the input (a string) and the output (a list of tokens) from other classes (e.g., the classes for the nodes of the syntax tree). These tests are more granular.Now, the tests in the paragraph immediately above can be put in correspondence with the class under test (e.g., lexer, string cache). However, the tests from the second paragraph above really test the whole analysis phase of the compiler; that is, each test can have well over 300 assertions for the syntax tree, given the input source code. The tests are for the behavior of the analysis phase.Is this an appropriate testing strategy? If not, what should we be doing differently? What organization strategy should we use for our tests?
How to use BDD to unit test a compiler?
unit testing;compiler;domain driven design;bdd
> Is this an appropriate testing strategy?No, because the your subdomain is a DSL (a kind of programming language) and your compiler is part of an implementation detail for the use case that allows to automate actions/workflows in this domain using the DSL.Since I do not know how your DSL looks like I assume that you have concepts like loop, condition, statement, variable using the example for(int i=1;i =< 10;i++) {subtask();}Using a bdd-gherkin like language you could write something likeas a automation useri want to have a for loop with startvalue, endvalue, loopincrementso that i can repeat subtasks several times.given startvalue=1and endvalue = 10and loopinclrement = 1when i execute for(int i=%startvalue%;i =< %endvalue %;i+=%loopinclrement%)then the subtask should have been executet 10 times.This is quite a lot of work to prove that your compiler works as expected. > If not, what should we be doing differently? > What organization strategy should we use for our tests?I would create a big repository of examples for input with corresponding output.The automated test would iterate through the examples and verify that the compiler output matches the expected output.Example: if your invoice/order-related dsl compiles to java a repository entry would look like: example: loop over orderentries dsl-source: foreach orderitem in orders do calculateTaxes(orderitem) expected errormessage: none expected java output: for(OrderItemType orderitem : orders) {calculateTaxes(orderitem);} example: loop with syntax errors dsl-source: foreach orderitem in orders expected errormessage: missing do-keyword in line 1 expected java output: noneSo instead of writing a lot of code to fit bdd you simply have to add examples of hardcoded input/output values.
_webmaster.11073
Some acquaintances of mine inherited a website running a custom wordpress template and the previous owner asked them to take over and to get it set up on their own server. I was asked to assist since I was the only one they knew with some technical skills.The previous site owner send me a backup of the web files and the mySQL database and recommended using site5.com for hosting.I got the files installed, things seemed to be OK and we were then ready to transfer the DNS.The domain is registered through GoDaddy and the prior owner issued a transfer to me, I got signed up accepted the domain and then went in and set the nameservers per site5 instructions: dns.site5.com and dns2.site5.comI expected that this was all that would be required and would just wait for the dns entries to update.However, at present when I browse or ping the Website. I get Server not Found.Is there anything else that I should have done or am I just in DNS Limbo?WHOIS.NET reports that it is registered to me and has the nameservers correct.You'll have to excuse me, while I've set up several websites internally at my work, this is the first time I've worked on an internet website.Thanks for any help you can offer.
Having trouble moving Website
wordpress;dns;godaddy;nameserver
Can you see your site on site5.com's IP address? Did they give you a temporary url so that you can test it prior to the nameserver change?Have site5/you setup your account so that there are records pointing to your site? If you haven't transferred the domain in to site5 or set up the domain in their backstage their nameservers won't know about your site. Could you give us the url so we can have a look?
_cs.2985
On Wikipedia, an implementation for the bottom-up dynamic programming scheme for the edit distance is given. It does not follow the definition completely; inner cells are computed thus:if s[i] = t[j] then d[i, j] := d[i-1, j-1] // no operation requiredelse d[i, j] := minimum ( d[i-1, j] + 1, // a deletion d[i, j-1] + 1, // an insertion d[i-1, j-1] + 1 // a substitution )}As you can see, the algorithm always chooses the value from the upper-left neighbour if there is a match, saving some memory accesses, ALU operations and comparisons. However, deletion (or insertion) may result in a smaller value, thus the algorithm is locally incorrect, i.e. it breaks with the optimality criterion. But maybe the mistake does not change the end result -- it might be cancelled out.Is this micro-optimisation valid, and why (not)?
Micro-optimisation for edit distance computation: is it valid?
algorithms;dynamic programming;string metrics;correctness proof;program optimization
I don't think that the algorithm is flawed. If two strings are matched, we compare first its last two characters (and then recurse). If they are the same, we can match them to get an optimal alignment. For example, consider the strings test and testat. If you don't match the two last ts, than one of the ts remains unmatched, since otherwise your matching would look like this:This is impossible, since the arrows are not allowed to cross. The matched t induces several inserts (green boxes in the figure), as depicted on the left:But then you can simply find an equally good alignment, depicted on the right. In both cases you match a t and you have two inserts.The argument for a substitution of one of the last ts is the same. So if you substitute one of the last ts, then you can instead match the last two t, and get a better alignment (see the picture).
_webmaster.31331
this question just came up as we recently bought content from image stock portals. Many of those altered their license agreement in favor of charging more for using in mobile apps. So instead of using their standard licenses, you need to pay an extended licenses which multiplies the fee easily by 5-10.That doesn't make sense as the mobile device is just a smaller browser and protects the content even better than a desktop computer.Are those stock agencies allowed to do that, and is it legal at all ?I am not a lawyer but I would even risk to go on with the standard license and wait to be sued in that matter.
Is it legal to charge extra fees for copyrighted content on mobile platforms?
legal;mobile;content;copyright
null
_webapps.49594
Is there a way to search for all files with a certain name in all repositories on Github? I've seen the advanced search form, but I can't see anything in there.If there isn't anything on the Github website, is there any other way to do this?I'm looking to produce various interesting statistics (a simple example is, how many README files are there on Github? But there are a broader range of questions)
Search in all Github repositories for files with a specific name
search;github
Try this:README.txt in:path(maybe you will need to click on Code on the left side of the search page)
_cstheory.19882
Given a degree $2k$ reducible polynomial $$f(x)=\sum_{i=0}^{2k}a_ix^i\in\Bbb Z[x]$$ with $$\text{gcd}(a_{2k},\dots,a_0)=1$$ that is known to be of the form $f_1(x)f_2(x)$ with $\text{deg}\big(f_i(x)\big)=\frac{\text{deg}(f(x))}{2}=k$ and each $f_i(x)$ irreducible.Can the LLL algorithm be used to factor $f(x)$ in polynomial time and what is the complexity?Note that $\text{gcd}(a_{2k},\dots,a_0)=1$ makes $f(x)$ prmitive.This answer tells that such polynomials have efficient factorization algorithms. Although the precise method is not mentioned there I belive LLL suffices and hence the question here. If LLL does do the job, can its complexity be improved from $(2k)^{6+\epsilon}$ arithmetic operations which is needed if the form of the factors are unknown.Refer here for complexity of factoring primitive polynomials with integer ocefficents where the phrase We also mention Schnhage's method using $O(n^6+n^4\log_2^2l)$ bit operations for factoring polynomials with integer coefficients ($l$ is the length of the coefficients)is used. $n$ is the degree and it corresponds to $2k$ here.
Factoring with LLL when the form of the factors is given
ds.algorithms;polynomials;algebraic complexity;factoring;lattice
Yes, assuming you want both $f_1(x)$ and $f_2(x)$ with integer coefficients.One of the reasons why LLL is so popular is precisely because it gives a polynomial time algorithm to factor polynomials with integer coefficients.For an excellent introduction, I recommend C. Yap's Fundamental Problems in Algorithmic Algebra (available online, for free), specifically chapter 9 Lattice Reduction and Applications (section 9.6). Following Yap, choose an approximation, $\alpha$, of a (complex) root for $f(x)$. Setup the lattice reduction with the following basis:$$ B_k = \begin{bmatrix} \text{Re}(\alpha^0) & \text{Re}(\alpha^1) & \text{Re}(\alpha^2) & \cdots & \text{Re}(\alpha^k) \\\text{Im}(\alpha^0) & \text{Im}(\alpha^1) & \text{Im}(\alpha^2) & \cdots & \text{Im}(\alpha^k) \\c & 0 & 0 & \cdots & 0 \\0 & c & 0 & \cdots & 0 \\0 & 0 & c & \cdots & 0 \\\vdots & \vdots & \vdots & \ddots & \vdots \\0 & 0 & 0 & \cdots & c \end{bmatrix}$$Choosing $c = 2^{-4t^3}$, with $\alpha$ to have $O(t^3)$ bits for each of the real and complex portions. Here, $t = \log ||f(x)||_{\infty}$ (that is, the cube of the number of bits of the maximum coefficient of $f(x)$).Quoted from FPiAA:Theorem 9 Given a basis $A \in \mathbb{Q}^{n \times m}$, we can compute a reduced basis $B$ with $\Lambda(A) = \Lambda(B)$ using $O(n^5(s + \log n))$ arithmetic operations, where s is the maximum bit size of entries in $A$This gives us the (polynomial) run time. Proof of correctness that for a properly setup lattice will give you the minimal factor of a reducible polynomial is a bit more involved, but please refer to theorem 14 of the same chapter to see the relation between the reduced basis and the minimal polynomial.By setting up the basis with dimension $n=k$ you can easily see the bound as roughly $O(k^5( \lg(||f(x)||_{\infty}^3) + \log n))$.Since, by assumption, you know the degree of $f_1(x)$ and $f_2(x)$, the lattice reduction algorithm only needs to be run once to find one of the two factors of $f(x)$. You can then use the discovered $f_j(x)$ to find the other by standard polynomial division.The original paper by Lenstra, Lenstra and Lovasz, Factoring polynomials with rational coefficients, is also quite readable and I found it to be a good compliment to Yap's introduction.
_unix.219909
I would like to install .rpm file using aliensudo alien --scripts /root/Disk1/oracle-xe-11.2.0-1.0.x86_64.rpmerror: incorrect format: unknown tagmkdir: cannot create directory `oracle-xe-11.2.0': File existsunable to mkdir oracle-xe-11.2.0: at /usr/share/perl5/Alien/Package.pm line 257Getting the above error.and then root@atten2015:~# sudo alien --verbose --scripts /root/Disk1/oracle-xe-11.2.0- 1.0.x86_64.rpm LANG=C rpm -qp --queryformat %{NAME} /root/Disk1/oracle-xe-11.2.0-1.0.x8 6_64.rpm LANG=C rpm -qp --queryformat %{VERSION} /root/Disk1/oracle-xe-11.2.0-1.0 .x86_64.rpm LANG=C rpm -qp --queryformat %{RELEASE} /root/Disk1/oracle-xe-11.2.0-1.0 .x86_64.rpm LANG=C rpm -qp --queryformat %{ARCH} /root/Disk1/oracle-xe-11.2.0-1.0.x8 6_64.rpm LANG=C rpm -qp --queryformat %{CHANGELOGTEXT} /root/Disk1/oracle-xe-11.2 .0-1.0.x86_64.rpm LANG=C rpm -qp --queryformat %{SUMMARY} /root/Disk1/oracle-xe-11.2.0-1.0 .x86_64.rpm LANG=C rpm -qp --queryformat %{DESCRIPTION} /root/Disk1/oracle-xe-11.2.0 -1.0.x86_64.rpm LANG=C rpm -qp --queryformat %{COPYRIGHT} /root/Disk1/oracle-xe-11.2.0-1 .0.x86_64.rpmerror: incorrect format: unknown tag LANG=C rpm -qp --queryformat %{PREFIXES} /root/Disk1/oracle-xe-11.2.0-1. 0.x86_64.rpm LANG=C rpm -qp --queryformat %{POSTIN} /root/Disk1/oracle-xe-11.2.0-1.0. x86_64.rpm LANG=C rpm -qp --queryformat %{POSTUN} /root/Disk1/oracle-xe-11.2.0-1.0. x86_64.rpm LANG=C rpm -qp --queryformat %{PREUN} /root/Disk1/oracle-xe-11.2.0-1.0.x 86_64.rpm LANG=C rpm -qp --queryformat %{PREIN} /root/Disk1/oracle-xe-11.2.0-1.0.x 86_64.rpm LANG=C rpm -qcp /root/Disk1/oracle-xe-11.2.0-1.0.x86_64.rpm rpm -qpi /root/Disk1/oracle-xe-11.2.0-1.0.x86_64.rpm LANG=C rpm -qpl /root/Disk1/oracle-xe-11.2.0-1.0.x86_64.rpm mkdir oracle-xe-11.2.0mkdir: cannot create directory `oracle-xe-11.2.0': File existsunable to mkdir oracle-xe-11.2.0: at /usr/share/perl5/Alien/Package.pm line 257
rpm file to deb Ubuntu 10.04.4 LTS
rpm
null
_cs.19848
Seemingly, a byte has established itself to be 8bit (is that correct?). RAM and NOR-flash can be normally accessed on a quite granular level, but it is up to the system architecture to determine if the smallest addressable unit is 8bit, 16bit or any other power of two bit number. Would the correct terminology be to call this word-addressable? Or asked differently, is a word the size of smallest addressable unit? Or is there some other term to describe this? Are mabye nibble, byte, word, double word all variable in bit-length and only defined by the architecture? And it is therefore only coincidence that a byte is always 8 bit? E.g. someone could design some new CPU and memory type and define her byte to be 16bit?Main question: What is the precise term for the smallest addressable memory block?Side question: What is the antonym to this word I'm looking for (e.g. used in NAND-flash)? Page-addressable, block-addressable? Are both correct or is one inprecise?
Word- or byte-addressable? Correct terminology
terminology;computer architecture;memory management;memory access
From a computer architecture point of view, and with the caveat that nomenclature sometimes varies, especially when there is a family of related architectures which has evolved for a long time, or when the marketing department decides to that the usual terms have to used in another way (either to put the product in better light by using a bigger number, or to have a simple number to differentiate more or less related products).A word has the size normally used for integer operations (often expressed as size of the integer or the general purpose registers, i.e. not address or data, internal or external buses, not address registers, not index registers). A common issue is that when an architecture is an evolution of a previous one, one often keep the term word for the initial size and one use double word or quad word for what is a word if you look at the architecture in isolation. Historically words have not always been a power of two (I know of sizes: 12, 16, 18, 24, 32, 36, 60, 64 and I don't think my knowledge is exhaustive).Word addressable means that the memory is considered as arrays of words, and thus no smaller unit has an individual addresses.A byte has various definitions. The term was introduced to mean the unit used in character encoding at a time where multi-byte encoding didn't exist. It is often used to means the smallest addressable unit for machine which are not word addressable (well as long at it is not one bit). I don't think those two definitions have ever given a different size. (nor a size different from 6 or 8 bits). For word addressable machine it often means some unit smaller than a word that the machine has some support for (for instance the PDP-10 -- a 36 bits word addressable computer -- had byte instructions which could manipulate any size from 1 to 35 or 36 bits). Nowadays it is also often 8 bits. Often several of those definitions are practically equivalent.Byte addressable characterizes machines where the memory is considered as arrays of bytes in one of the above meaning.AFAIK nibble has only been used for 4 bits quantities.E.g. someone could design some new CPU and memory type and define her byte to be 16bit?Yes, but I'm not sure if it would make much sense to do so if one keeps the CA usage to use byte for something smaller than the word. Having a word addressable 16-bit processor with no support for something smaller than a word may be a good choice for a special purpose processor.Secondarily, what is the antonym to this word I'm looking for? Page-addressable, block-addressable?Bit-addressable, byte-addressable and word-addressable are the only terms I've seen use. It doesn't make much sense to address only units bigger than the word at the architectural level. Word-addressable is nowadays only used for special purpose processors such as DSP. I don't think bit-addressability has been used for anything else than special purpose one excepted the IBM Stretch.About your new main questionWhat is the precise term for the smallest addressable memory block?I know of none used in Computer Architecture (byte has been used for something smaller in word adressable machines), but is the definition used by C for byte.
_unix.308999
I am running tmux inside gnome terminal and have been trying to use a binding to copy the contents of tmux's paste buffer to my linux X clipboard. Alot of places on the internet recommend this:bind C-c run tmux save-buffer - | xclip -i -sel clipboardThis command works perfectly from the command linetmux save-buffer - | xclip -i -sel clipboardIf I bind the shell command to a key and use it from inside tmux (using bind C-c run tmux save-buffer - | xclip -i -sel clipboard) , it does copy the tmux save-buffer to my clipboard. I.e. once I have copied some text in tmux's copy mode, using this binding will load the text into my X clipboard ready to be pasted into a browser etc.however it _also_ causes the prefix key to stop working for that terminal.If I kill the terminal with tmux running inside it and open another terminal and re-attach to tmux, the prefix key will continue working in another terminal.I also tried the following approach: Set up an executable file: /usr/local/bin/tmux_to_clip with the command in it% cat /usr/local/bin/tmux_to_clip #!/bin/bashtmux save-buffer - | xclip -i -sel clipboardand then called the command from inside tmux:run tmux_to_clipagain, it successfully copies the command to the clipboard, but again it, breaks the prefix key.How can I prevent this and get a keybinding for copying tmux save-buffer to X clipboard?
Running shell commands from inside tmux is causing Gnome terminal to break key
tmux;gnome terminal
null
_webmaster.71633
webmaster is crawling both the urls, one which is SEO friendly and the one .php urls for the same page thus showing duplicate title and description for those pages.urls of .php were changed through .htaccess file. what is the solution?
google webmaster is crawling both file urls
url;web crawlers;googlebot
null
_webmaster.84495
I call it 'Meta-jacking'.So this website I found has a meta with content= and whatever you type in the description displays your text in the content. So I took advantage of this and typed:0;//wwww.google.comhttp-equiv=refreshand sure enough it redirected to google, is this some sort of XSS?
I found some weird exploit
hacking
Yes, that's pretty much a textbook example of XSS. When a site takes input and then serves it back to you in an executable manner, the site is vulnerable because a ne'er-do-well can direct a victim to the legitimate website in such a way that malicious code is injected into the session. The user thinks they are safe because the site is legitimate, HTTPS encrypted, etc. -- but since they were sent there by a malicious source leveraging the XSS vulnerability, the session is compromised.This is exactly why we tell people not to click links in email.
_webmaster.34844
We have a site based upon Google Sites. Now we would like to create a login area (HTTPS) with a mixture of dynamic and static content. Is it a good idea to utilize Google Sites and use iFrames for the dynamic parts of the content?The reason why I like Google Sites, is that it is so easy to change content and immediately see what it will look like.
Good idea to use Google Sites for static content and custom PHP for dynamic
security;authentication;iframe;google sites
null
_computergraphics.1895
I have been working on a graphics library for some time now and have gotten to the point where I have to draw Bezier and line based fonts. Up to this point I am stuck with this:The green lines are the Bezier paths, and the white part is what gets rendered.The code I use for Beziers is here. The one for lines is here. For those who don't know that is Lua. Path rendering (lines) : 32 - 39 The algorithm is as follows:Iterating from 0 to 1 at certain intervalscalculating the x and y with this formula: (1-index)^2*x1+2*(1-index)*index*x2+index^2*x3Up to this point everything works fine. The green lines are generated using the path method.The white part is rendered in a completely different way:I get the x coordinates of the Beziers and lines at a particular Y, the put them into a table.I iterate through the table and each time I encounter a point I change the value of state. In the same for loop is also check whether state is on. If it is, I draw a pixel to the screen.To find the x values of a y, I use the getX method (line 46 in Bezier and line 31 in Line).The code I use for the drawing itself is this one:local xBuffer = {}local state = falsefor i=0,500 do for k,v in pairs(beziers) do a,b = v.getX(i) if a then xBuffer[round(a)] = 1 if b then xBuffer[round(a)] = 1 end end end for k,v in pairs(lines) do a = v.getX(i) if a then xBuffer[round(a)] = 1 end end state = false for x=0,600 do if xBuffer[x] then state = not state end if state then love.graphics.points(x,i) end endendQuick explanation: for i,v in pairs iterates through the table given as an argument to pairs. love.graphics.points(x,y) sets a point at x,y.Thanks in advance.
How should I fill a shape consisting of Bezier curves and straight lines?
rendering;algorithm;geometry;line drawing
If you are in a hurry to get your renderer working and you already have the filled polygonal routine functioning correctly, can I suggest an alternative, possibly easier approach? Though I'm not familiar with Lua, it seems you are solving for the exact intersection of a scan line with the quadratic Bezier which, though admirable, is possibly overkill.Instead, tessellate your Beziers into line segments and then throw those into the polygon scan converter. I suggest just using (recursive) binary subdivision: i.e. the quadratic Bezier with control points, $(\overline {A} , \overline {B} , \overline {C})$ can be split into two Beziers, $(\overline {A} , \overline {D} , \overline {E})$ and $(\overline {E} , \overline {F} , \overline {C})$ where$$\begin{align*} & \overline {D}=\dfrac {\overline {A}+\overline {B}} {2}\\ & \overline {E} =\dfrac {\overline {A}+2\overline {B}+\overline {C}}{4}\\ &\overline {F}=\dfrac {\overline {B}+\overline {C}} {2}\end{align*}$$(which is also great if you only have fixed point maths).IIRC, each time you subdivide, the error between the Bezier and just a straight line segment joining the end points goes down by a factor of ~4x, so it doesn't take many subdivisions before the piecewise linear approximation will be indistinguishable from the true curve. You can also use the bounding box of the control points to decide if you can skip out of the subdivision process early since that will also be a conservative bound on the curve.
_unix.56595
My friends are recommending me to use OSx for video-editing but trying to use old good OSs such as Debian and Ubuntu. How can I do chromakey -video-editing in some Unix or Linux?
Chromakey -video-editing in Unix?
ubuntu;debian;software rec;video;video editing
null
_unix.384845
Long time ago, like 20+ years, I recall running Abuse under Slackware 1.2 and having no issues whatsoever. Tried this again today and gotten this:abuse 0.8ALSA lib pulse.c:243:(pulse_connect) PulseAudio: Unable to connect: Connection refusedAbuse version 0.8Sound: Unable to open audio - No available audio deviceSound: Disabled (error)Specs : main file set to abuse.speProtocol Installed : UNIX generic TCPIPLisp: 527 symbols defined, 99 system functions, 319 pre-compiled functions(load abuse.lsp) [........................................]Engine : Registering base graphicsPalette has changed, recalculating light table...white light [...................................... ]tints [.................................. ]Video : Unable to set video mode : Couldn't set console screen infoNo sound detected. This must be a permissions issue which should be resolved with udev rules if I am not mistaken.Video mode setting issue - why?I could run it in an X terminal, but the bloody thing (KDE, not Abuse) re-arranges icons on my desktop even though I specifically lock their positions through desktop properties. So text console is the preferred method.
Running Crack Dot Com Abuse in text console: Unable to set video mode
fedora;console;graphics
null
_unix.371456
Im trying to do print last directory like below#!/bin/bashdirc=/a/b/i=3 `echo $dirc | awk -F / '{ print $i}'`which should print 'b', which is not happening.
echo $ along with variable
bash;shell script;awk;quoting
i in the AWK script is an AWK variable, not a shell variable; you need to set the AWK variable:#!/bin/bashdirc=/a/b/echo ${dirc} | awk -F / -v i=3 '{print $i}'You can specify the value of i in any way the shell understands:i=3echo ${dirc} | awk -F / -v i=${i} '{print $i}'You could also get the shell to evaluate the variable in the AWK script, but thats just looking for trouble:i=3echo ${dirc} | awk -F / {print \$${i}}
_unix.277433
I want to anonymously use Kali Linux in VirtualBox. But VirtualBox's network is also my IP address so I want to use Whonix gateway for my Kali Linux, not Whonix workstation. How do I configure Whonix gateway in Kali? How to connect Whonix gateway to Kali Linux? What's the command I should use?
How to configure Whonix gateway to Kali Linux?
kali linux;whonix
null
_softwareengineering.352866
I have couple of nested resources like Merchant, Hotel, Room. A merchant can have many hotels and similarly a hotel can have many rooms.Right now for managing these resources I doing something like:CreatePOST api/v1/merchants/11/hotelscreates a new hotel.UpdatePUT api/v1/merchants/11/hotels/42updates the given hotel.Same for read and delete.For rooms:CreatePOST api/v1/merchants/11/hotels/42/roomscreates a new room.UpdatePUT api/v1/merchants/11/hotels/42/rooms/42updates the given room etc.In future there will be more nested resources like room facilities etc. and following this scheme will turn hairy.I am in the early stage of development and I may expose these APIs for developers hence I can't change API scheme very quickly.I am in doubt from day one regarding this approach. Can I assume that each entity has unique ID (which is true for now as I am using relational database and has its own table)? If yes, then the can I use these URLs for APIs instead of above ones?POST api/v1/roomsPUT api/v1/rooms/42Etc for more nested resources.Is there any violation of semantics or standard that I may be missing? I am using similar approach in views eg. in URLs in browsers which is looking ugly too.
Unique ids for nested resources
architecture;web development;rest;domain driven design
null
_unix.364884
Lets consider an input text file like this:some text % BEGINblablafoo barblablablabla% ENDsome text and a foobar.txt file like this:2 38 9 1 2what is the simplest way using sed (maybe awk ?) to obtain this output text file:some text % BEGINblabla2 3blablablabla% END% BEGINblabla8 9blablablabla% END% BEGINblabla1 2blablablabla% ENDsome text
Duplicate and replace a pattern in a text file
text processing;awk;sed
Complex bash + sed solution:foobar_replacer.sh script:#!/bin/bashhead -n1 $2 # print the first linewhile read -r linedo sed '1d;$d;{s/^foo bar$/'$line'/g}' $2 done < $1tail -n1 $2 # print the last lineUsage:bash foobar_replacer.sh foobar.txt input.txtThe output:some text % BEGINblabla2 3blablablabla% END% BEGINblabla8 9blablablabla% END% BEGINblabla1 2blablablabla% ENDsome text sed command details:1d;$d; - delete the first and the last line from input.txts/^foo bar$/'$line'/g - substitute the line containing foo bar with next item $line from foobar.txt
_softwareengineering.22146
I have a couple of developers at my company who wish to move from programming into architecture. What are the best books out there on the theory and practice of software architecture? Include a cover picture if you can. Feel free to include general books, and also books that relate to a specific technology.
Best books on the theory and practice of software architecture?
books;architecture
(link to the book)This is a pretty good book, although it deals not with software architecture in general, but with architecture of business applications.
_unix.107582
I'm using Ubuntu and I would like to find and/or print the sudo lecture that is printed to the screen the first time a user executes a sudo command. How can I do this? I'm unable to find the lecture file.
How can I find and/or print sudo's lecture file?
sudo
null
_webmaster.11188
I am trying to re-do my portfolio website since its a pain to maintain it. Everytime I have to add a new item to it, it just takes forever and kills me. I'd like to redesign in a way that makes the workflow of adding new items smooth. I am not looking for fancy effects, just a simple website which makes it easy to people browse through my stuff.All of the pages are standalone html files. Each page has a common header and footer for navigation between pages. Right now, whenever I have to modify the content, I try to dig in which table row it is and then add content to it. (yes, I use notepad).Can someone please recommend me what would be the best way to go about it ?(PS: Please let me know if I missed out anything).
design website using header and footer template approach
html;web development;website design;headers
There are probably 1000 ways to do this which vary in cost, control and complexity.If you go to PHP or even just SSI, you can move the common parts to separate files and include them where needed, so that each page mostly consists of what is different.You can use a template system where an application like Dreamweaver maintains templates for you can each time you modify it, it will prompt you to update your other files. You have to then synchronize the changes.You can also build or buy a content management system where generates webpages for you. You fill the content in some complex entry forms, sometimes using a WYSIWYG editor, and the platform picks up changes automatically. This is an oversimplified version of what Wordpress does.
_unix.157007
I am a moderately new linux user. I changed my PC, and started using CentOS 7 from CentOS 6.So I attached my previous hard disk to my new pc to take backup of my files. Now, copying the files (and preserving the permissions and all), the files shows owner as 500 (I guess this is my previous UID). Is there any way I can change them to my new user name? I want to exclude the files which shows some other owners like 501.Edit:Example:ls -ltotal 3-rw-rw-r--. 1 500 500 210 Jan 10 2012 about.xmldrwxr-xr-x. 2 500 500 4096 May 15 2013 apachedrwxrwxr-x. 2 500 500 4096 Dec 9 2012 etcNow, I can do chown -R xyz:xyz . to make them look like:ls -ltotal 3-rw-rw-r--. 1 xyz xyz 210 Jan 10 2012 about.xmldrwxr-xr-x. 2 xyz xyz 4096 May 15 2013 apachedrwxrwxr-x. 2 xyz xyz 4096 Dec 9 2012 etc But I just want to know if there are some kind of commands which can map user 500 to user xyz.Thank you.
Change file ownership, based on previous owner
files;users;recursive;chown
If I understand you correctly, you want to change the owner of all files inside some directory (or the root) that are owned by user #500 to be owned by another user, without modifying files owned by any other user. You're in that situation because you've copied a whole directory tree from another machine, where files inside that tree were owned by many different users, but you're only interested in updating those that were owned by your user at the moment, and not any of the files that are owned by user #501 or any other.GNU chown supports an option --from=500 that you can use in combination with the -R recursive option to do this:chown -R --from=500 yourusername /path/hereThis will be the fastest option if you have GNU chown, which on CentOS you should.Alternatively can use find on any system:find /path/here -user 500 -exec chown yourusername '{}' '+'find will look at every file and directory recursively inside /path/here, matching all of those owned by user #500. With all of those files, it will execute chown yourusername file1 file2... as many times as required. After the command finishes, all files that were owned by user #500 will be owned by yourusername. You'll need to run that command as root to be able to change the file owners.You can check for any stragglers by running the same find command without a command to run:find /path/here -user 500It should list no files at this point.An important caveat: if any of the files owned by user #500 are symlinks, chown will by default change the owner of the file the symlink points at, not the link itself. If you don't trust the files you're examining, this is a security hole. Use chown -h in that case.
_webapps.893
I have two Google Analytics accounts that were created under my Google ID while I was with a former employer. Is there a way to transfer ownership of those accounts?If I can't just give those accounts to someone else then is there an easy way to recreate the accounts under a different ID without losing the history?EDIT: I have been through the process to add another administrator, and my administrator privileges have been removed, but the accounts still show up on my analytics page! I can't even delete them... Am I stuck with these accounts forever?!
Transfer ownership of Google Analytics accounts?
google analytics;account management
As of June 2017 transferring ownership of Google Analytics accounts is accomplished by adding a new user with administrative permissions, then deleting the previous user.To add a new user with administrative permissions:Click Admin at the bottom of the left navigation menu to view the Administration page.From there, select the account, then click User Management. Below the table of current users, enter an email address and check the boxes for Manage Users and Edit. (Collaborate and Read & Analyze will be selected automatically.) Then click Add.To remove a user's access to the account, edit the account permissions accordingly using the drop down menu in the user management table then save; or click delete to remove the user from the account entirely.It is also possible to move a Property from one Account to another:Select the Account that contains the property you wish to move.Select the PropertyClick Property Settings, then click Move PropertySelect destination account.Choose desired permissions settings.Click Move, then Save.
_unix.341922
If a Linux system is using more than one swap device and suspend to disk, how does one setup the resume= kernel parameter?
Linux resume when using multiple swap partitions
linux kernel;swap;power management
null
_codereview.82422
I am new to programming and want to know if this is really bad code. I know my variable names may seem arbitrary but I spent some time trying to get them right. I am struggling on that. Would you do this the same way?#include <stdio.h>#define MAXLINE 100void printHistogramHorizontally(int alphabetofline[]);int main(){ int c,i,j; int alphabetofline[25]; char line[MAXLINE]; for(j=0; j< 26; j++) alphabetofline[j] = 0; for(i=0;i < MAXLINE -1 && (c = getchar()) != EOF && c != '\n'; ++i) { line[i] = c; switch (c) { case 'a': case 'A': ++alphabetofline[0]; break; case 'b': case 'B': ++alphabetofline[1]; break; case 'c': case 'C': ++alphabetofline[2]; break; case 'd': case 'D': ++alphabetofline[3]; break; case 'e': case 'E': ++alphabetofline[4]; break; case 'f': case 'F': ++alphabetofline[5]; break; case 'g': case 'G': ++alphabetofline[6]; break; case 'h': case 'H': ++alphabetofline[7]; break; case 'i': case 'I': ++alphabetofline[8]; break; case 'j': case 'J': ++alphabetofline[9]; break; case 'k': case 'K': ++alphabetofline[10]; break; case 'l': case 'L': ++alphabetofline[11]; break; case 'm': case 'M': ++alphabetofline[12]; break; case 'n': case 'N': ++alphabetofline[13]; break; case 'o': case 'O': ++alphabetofline[14]; break; case 'p': case 'P': ++alphabetofline[15]; break; case 'q': case 'Q': ++alphabetofline[16]; break; case 'r': case 'R': ++alphabetofline[17]; break; case 's': case 'S': ++alphabetofline[18]; break; case 't': case 'T': ++alphabetofline[19]; break; case 'u': case 'U': ++alphabetofline[20]; break; case 'v': case 'V': ++alphabetofline[21]; break; case 'w': case 'W': ++alphabetofline[22]; break; case 'x': case 'X': ++alphabetofline[23]; break; case 'y': case 'Y': ++alphabetofline[24]; break; case 'z': case 'Z': ++alphabetofline[25]; break; } } if (c == '\n') { line[i] = c; ++i; } line[i] = '\0'; printf(\n%s\n, line); printHistogramHorizontally(alphabetofline); return 0; } void printHistogramHorizontally(int alphabetofline[]) { char const* alphaIndex[] = {A, B, C, D, E, F, G, H, I, J,K, L, M, N, O, P,Q, R, S, T, U, V,W, X, Y, Z }; int i, numOfX; i=numOfX=0; for( i = 0; i < 26; ++i ) { printf(%s: , alphaIndex[i]); while(numOfX < alphabetofline[i]) { printf(X); ++numOfX; } numOfX = 0; printf(\n); }}
Printing simple histogram horizontally
beginner;c;formatting
null
_codereview.62616
Given a chess coordinate as a string (e.g. a1) I'd like to transform it into a 2-D array (so, for a1 I'd like to get [1,1]).Here's what I came up with: def safe_pawns(pawns) pawns.inject([]){|res, pwn| res << [pwn.split('')[0].index(/[a-h]/) + 1, pwn.split('')[1].to_i]}end Can anyone suggest a refactoring please to make it more idiomatic Ruby?
Breaking a chess coordinate string into 2D coordinates
ruby;game;array;coordinate system
Give your code some breathing room. I.e. ) { |a, b| instead of ){|a, b|. And there's no need to put everything on one line. The way your block works right now, it'd be better to store the result of pwn.split in a variable, instead of calling split twice. (There's also no need to abbrevate pawn as pwn.)That being said, strings support array-like access, so you don't need the split at all.Judging from your code, pawns is an array. Transforming an n-element array to a new n-element array is called mapping. You're using inject which is also known as reduce (and fold in many other languages; see comments) - an operation most often used to take an n-element array and reduce it to a single value. So step 1: Use map instead of inject.I'd probably use a regex to pull the string apart. It'll double as a way to check the coordinate strings for validity (e.g. so no z9 coordinates will slip through).It's a little low-level, but we can use the fact that a is 97 in ASCII. So to get the number for a letter, we can say letter.ord - 96. You get something like this:def safe_pawns(squares) squares.map do |square| [$1.ord - 96, $2.to_i] if square.downcase =~ /^([a-h])([1-8])$/ end.compactendAlternatively, if you're sure that all the input coordinates are valid, lowercase strings already, you don't need the regex or the downcasing:def safe_pawns(squares) squares.map { |square| [square[0].ord - 96, square[1].to_i] }endAs tokland points out in the comments, we can avoid the hardcoded 96 (which isn't very self-explanatory) and instead get the letter-to-number translation by saying:square[0].ord - 'a'.ord + 1
_cogsci.4474
What are the groundbreaking works/papers/results/theories specific to Perceptual Learning within cognitive science?One paper/theory per answer please, and state why do you find this work is important to know (and ideally, not just because it has lots of citations, or because it is taught as a Cognitive Science 101 subject).The idea behind this question is to provide a rich resource of expert research and subsequent theory.
What are the groundbreaking papers on Perception Learning within Cognitive Science?
perception;reference request;learning;perceptual learning
null
_unix.368174
I need to pass credentials via curl to a database from several thousand systems, as each are updated. A team who will not be permitted the credentials shall be executing the script. Therefore, I want to hide username/password from the update team.
How can I hide credentials in a script?
bash;shell script;security;password
null
_unix.231259
Yesterday I was googling how to merge two files and came across an awk snippet.I need a simple merge, so sort -u is not the way to go, but the code below works.Could some one please explain what this awk code does?awk '!a[$0]++' file_1 file_2
Please explain this awk statement
awk
null
_codereview.70156
I was writing an application with a few Monads in a transformer stack. The top level application state resides in a TVar, and various components of the application operate on parts of it.I wrote a helper function to extract those parts:hoistStateWithLens :: S.MonadState outerState m => Simple Lens outerState innerState -> S.State innerState a -> m ahoistStateWithLens acc op = do s <- S.get let sp = s ^. acc let (res, sp') = S.runState op sp S.put (s & acc .~ sp') return resAnd I extract it from my main state as such:runWebMState :: MonadTrans t => State appState a -> t (WebM appState) arunWebMState x = let runWebMState_ :: State appState a -> WebM appState a runWebMState_ f = do appStateTVar <- ask liftIO . atomically $ do appState <- readTVar appStateTVar let (fResult, appState') = runState f appState writeTVar appStateTVar appState' return fResult in webM $ runWebMState_ xEnsuring atomic access (multiple web handlers can run at once).Using it in my application code gets pretty easy:runRandom x = runWebMState $ hoistStateWithLens gen x-- sample use of runRandomget /random $ do x <- runRandom $ state . randomR (1 :: Int,100) text . pack . show $ xI wanted to gather some feedback about the implementation and the idea itself. The whole project is OpenSource and available on GitHub.
Expressing computations on values as State
haskell;state;monads
null